Your Name 1912bcd25b
Some checks failed
Lint / build (20) (push) Has been cancelled
Playwright Tests / test (push) Has been cancelled
chore: sync all remaining local workspace changes
2026-05-08 11:26:57 +08:00

2434 lines
84 KiB
JavaScript

/*
* Extracted from browser-delivered Turbopack chunk: 5090ef85429ba5da.685e3e4591.js
* Module id: 222553
* For reading/searching only; this factory depends on the original Turbopack runtime.
*/
const moduleFactory = (e) => {
"use strict";
let t;
var n,
r,
s,
i = e.i(64879);
e.i(890478);
var a = e.i(169823),
o = e.i(316119),
l = e.i(870010),
u = e.i(153766);
let d = Symbol("Let zodToJsonSchema decide on which parser to use"),
c = {
name: void 0,
$refStrategy: "root",
basePath: ["#"],
effectStrategy: "input",
pipeStrategy: "all",
dateStrategy: "format:date-time",
mapStrategy: "entries",
removeAdditionalStrategy: "passthrough",
allowedAdditionalProperties: !0,
rejectedAdditionalProperties: !1,
definitionPath: "definitions",
target: "jsonSchema7",
strictUnions: !1,
definitions: {},
errorMessages: !1,
markdownDescription: !1,
patternStrategy: "escape",
applyRegexFlags: !1,
emailStrategy: "format:email",
base64Strategy: "contentEncoding:base64",
nameStrategy: "ref",
openAiAnyTypeName: "OpenAiAnyType",
};
function p(e, t, n, r) {
r?.errorMessages && n && (e.errorMessage = { ...e.errorMessage, [t]: n });
}
function h(e, t, n, r, s) {
(e[t] = n), p(e, t, r, s);
}
let f = (e, t) => {
let n = 0;
for (; n < e.length && n < t.length && e[n] === t[n]; n++);
return [(e.length - n).toString(), ...t.slice(n)].join("/");
};
var g = e.i(480);
function m(e) {
if ("openAi" !== e.target) return {};
let t = [...e.basePath, e.definitionPath, e.openAiAnyTypeName];
return (
(e.flags.hasReferencedOpenAiAnyType = !0),
{
$ref:
"relative" === e.$refStrategy ? f(t, e.currentPath) : t.join("/"),
}
);
}
function v(e, t) {
return Z(e.type._def, t);
}
let y = /^[cC][^\s-]{8,}$/,
_ = /^[0-9a-z]+$/,
E = /^[0-9A-HJKMNP-TV-Z]{26}$/,
b =
/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
T = () => (
void 0 === t &&
(t = RegExp(
"^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
"u",
)),
t
),
S =
/^(?:(?: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])$/,
A =
/^(([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])$/,
N = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
I =
/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
w = /^[a-zA-Z0-9_-]{21}$/,
O = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
function C(e, t) {
let n = { type: "string" };
if (e.checks)
for (let r of e.checks)
switch (r.kind) {
case "min":
h(
n,
"minLength",
"number" == typeof n.minLength
? Math.max(n.minLength, r.value)
: r.value,
r.message,
t,
);
break;
case "max":
h(
n,
"maxLength",
"number" == typeof n.maxLength
? Math.min(n.maxLength, r.value)
: r.value,
r.message,
t,
);
break;
case "email":
switch (t.emailStrategy) {
case "format:email":
x(n, "email", r.message, t);
break;
case "format:idn-email":
x(n, "idn-email", r.message, t);
break;
case "pattern:zod":
P(n, b, r.message, t);
}
break;
case "url":
x(n, "uri", r.message, t);
break;
case "uuid":
x(n, "uuid", r.message, t);
break;
case "regex":
P(n, r.regex, r.message, t);
break;
case "cuid":
P(n, y, r.message, t);
break;
case "cuid2":
P(n, _, r.message, t);
break;
case "startsWith":
P(n, RegExp(`^${R(r.value, t)}`), r.message, t);
break;
case "endsWith":
P(n, RegExp(`${R(r.value, t)}$`), r.message, t);
break;
case "datetime":
x(n, "date-time", r.message, t);
break;
case "date":
x(n, "date", r.message, t);
break;
case "time":
x(n, "time", r.message, t);
break;
case "duration":
x(n, "duration", r.message, t);
break;
case "length":
h(
n,
"minLength",
"number" == typeof n.minLength
? Math.max(n.minLength, r.value)
: r.value,
r.message,
t,
),
h(
n,
"maxLength",
"number" == typeof n.maxLength
? Math.min(n.maxLength, r.value)
: r.value,
r.message,
t,
);
break;
case "includes":
P(n, RegExp(R(r.value, t)), r.message, t);
break;
case "ip":
"v6" !== r.version && x(n, "ipv4", r.message, t),
"v4" !== r.version && x(n, "ipv6", r.message, t);
break;
case "base64url":
P(n, I, r.message, t);
break;
case "jwt":
P(n, O, r.message, t);
break;
case "cidr":
"v6" !== r.version && P(n, S, r.message, t),
"v4" !== r.version && P(n, A, r.message, t);
break;
case "emoji":
P(n, T(), r.message, t);
break;
case "ulid":
P(n, E, r.message, t);
break;
case "base64":
switch (t.base64Strategy) {
case "format:binary":
x(n, "binary", r.message, t);
break;
case "contentEncoding:base64":
h(n, "contentEncoding", "base64", r.message, t);
break;
case "pattern:zod":
P(n, N, r.message, t);
}
break;
case "nanoid":
P(n, w, r.message, t);
}
return n;
}
function R(e, t) {
return "escape" === t.patternStrategy
? (function (e) {
let t = "";
for (let n = 0; n < e.length; n++)
k.has(e[n]) || (t += "\\"), (t += e[n]);
return t;
})(e)
: e;
}
let k = new Set(
"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789",
);
function x(e, t, n, r) {
e.format || e.anyOf?.some((e) => e.format)
? (e.anyOf || (e.anyOf = []),
e.format &&
(e.anyOf.push({
format: e.format,
...(e.errorMessage &&
r.errorMessages && {
errorMessage: { format: e.errorMessage.format },
}),
}),
delete e.format,
e.errorMessage &&
(delete e.errorMessage.format,
0 === Object.keys(e.errorMessage).length &&
delete e.errorMessage)),
e.anyOf.push({
format: t,
...(n && r.errorMessages && { errorMessage: { format: n } }),
}))
: h(e, "format", t, n, r);
}
function P(e, t, n, r) {
e.pattern || e.allOf?.some((e) => e.pattern)
? (e.allOf || (e.allOf = []),
e.pattern &&
(e.allOf.push({
pattern: e.pattern,
...(e.errorMessage &&
r.errorMessages && {
errorMessage: { pattern: e.errorMessage.pattern },
}),
}),
delete e.pattern,
e.errorMessage &&
(delete e.errorMessage.pattern,
0 === Object.keys(e.errorMessage).length &&
delete e.errorMessage)),
e.allOf.push({
pattern: M(t, r),
...(n && r.errorMessages && { errorMessage: { pattern: n } }),
}))
: h(e, "pattern", M(t, r), n, r);
}
function M(e, t) {
if (!t.applyRegexFlags || !e.flags) return e.source;
let n = {
i: e.flags.includes("i"),
m: e.flags.includes("m"),
s: e.flags.includes("s"),
},
r = n.i ? e.source.toLowerCase() : e.source,
s = "",
i = !1,
a = !1,
o = !1;
for (let e = 0; e < r.length; e++) {
if (i) {
(s += r[e]), (i = !1);
continue;
}
if (n.i) {
if (a) {
if (r[e].match(/[a-z]/)) {
o
? ((s += r[e]),
(s += `${r[e - 2]}-${r[e]}`.toUpperCase()),
(o = !1))
: "-" === r[e + 1] && r[e + 2]?.match(/[a-z]/)
? ((s += r[e]), (o = !0))
: (s += `${r[e]}${r[e].toUpperCase()}`);
continue;
}
} else if (r[e].match(/[a-z]/)) {
s += `[${r[e]}${r[e].toUpperCase()}]`;
continue;
}
}
if (n.m) {
if ("^" === r[e]) {
s += `(^|(?<=[\r
]))`;
continue;
} else if ("$" === r[e]) {
s += `($|(?=[\r
]))`;
continue;
}
}
if (n.s && "." === r[e]) {
s += a
? `${r[e]}\r
`
: `[${r[e]}\r
]`;
continue;
}
(s += r[e]),
"\\" === r[e]
? (i = !0)
: a && "]" === r[e]
? (a = !1)
: a || "[" !== r[e] || (a = !0);
}
try {
new RegExp(s);
} catch {
return (
console.warn(
`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`,
),
e.source
);
}
return s;
}
function L(e, t) {
if (
("openAi" === t.target &&
console.warn(
"Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.",
),
"openApi3" === t.target &&
e.keyType?._def.typeName === g.ZodFirstPartyTypeKind.ZodEnum)
)
return {
type: "object",
required: e.keyType._def.values,
properties: e.keyType._def.values.reduce(
(n, r) => ({
...n,
[r]:
Z(e.valueType._def, {
...t,
currentPath: [...t.currentPath, "properties", r],
}) ?? m(t),
}),
{},
),
additionalProperties: t.rejectedAdditionalProperties,
};
let n = {
type: "object",
additionalProperties:
Z(e.valueType._def, {
...t,
currentPath: [...t.currentPath, "additionalProperties"],
}) ?? t.allowedAdditionalProperties,
};
if ("openApi3" === t.target) return n;
if (
e.keyType?._def.typeName === g.ZodFirstPartyTypeKind.ZodString &&
e.keyType._def.checks?.length
) {
let { type: r, ...s } = C(e.keyType._def, t);
return { ...n, propertyNames: s };
}
if (e.keyType?._def.typeName === g.ZodFirstPartyTypeKind.ZodEnum)
return { ...n, propertyNames: { enum: e.keyType._def.values } };
if (
e.keyType?._def.typeName === g.ZodFirstPartyTypeKind.ZodBranded &&
e.keyType._def.type._def.typeName ===
g.ZodFirstPartyTypeKind.ZodString &&
e.keyType._def.type._def.checks?.length
) {
let { type: r, ...s } = v(e.keyType._def, t);
return { ...n, propertyNames: s };
}
return n;
}
let D = {
ZodString: "string",
ZodNumber: "number",
ZodBigInt: "integer",
ZodBoolean: "boolean",
ZodNull: "null",
},
j = (e, t) => {
let n = (
e.options instanceof Map ? Array.from(e.options.values()) : e.options
)
.map((e, n) =>
Z(e._def, {
...t,
currentPath: [...t.currentPath, "anyOf", `${n}`],
}),
)
.filter(
(e) =>
!!e &&
(!t.strictUnions ||
("object" == typeof e && Object.keys(e).length > 0)),
);
return n.length ? { anyOf: n } : void 0;
};
function Z(e, t, n = !1) {
let r = t.seen.get(e);
if (t.override) {
let s = t.override?.(e, t, r, n);
if (s !== d) return s;
}
if (r && !n) {
let e = U(r, t);
if (void 0 !== e) return e;
}
let s = { def: e, path: t.currentPath, jsonSchema: void 0 };
t.seen.set(e, s);
let i = ((e, t, n) => {
switch (t) {
case g.ZodFirstPartyTypeKind.ZodString:
return C(e, n);
case g.ZodFirstPartyTypeKind.ZodNumber:
let r = { type: "number" };
if (!e.checks) return r;
for (let t of e.checks)
switch (t.kind) {
case "int":
(r.type = "integer"), p(r, "type", t.message, n);
break;
case "min":
"jsonSchema7" === n.target
? t.inclusive
? h(r, "minimum", t.value, t.message, n)
: h(r, "exclusiveMinimum", t.value, t.message, n)
: (t.inclusive || (r.exclusiveMinimum = !0),
h(r, "minimum", t.value, t.message, n));
break;
case "max":
"jsonSchema7" === n.target
? t.inclusive
? h(r, "maximum", t.value, t.message, n)
: h(r, "exclusiveMaximum", t.value, t.message, n)
: (t.inclusive || (r.exclusiveMaximum = !0),
h(r, "maximum", t.value, t.message, n));
break;
case "multipleOf":
h(r, "multipleOf", t.value, t.message, n);
}
return r;
case g.ZodFirstPartyTypeKind.ZodObject:
return (function (e, t) {
let n = "openAi" === t.target,
r = { type: "object", properties: {} },
s = [],
i = e.shape();
for (let e in i) {
let a = i[e];
if (void 0 === a || void 0 === a._def) continue;
let o = (function (e) {
try {
return e.isOptional();
} catch {
return !0;
}
})(a);
o &&
n &&
("ZodOptional" === a._def.typeName &&
(a = a._def.innerType),
a.isNullable() || (a = a.nullable()),
(o = !1));
let l = Z(a._def, {
...t,
currentPath: [...t.currentPath, "properties", e],
propertyPath: [...t.currentPath, "properties", e],
});
void 0 !== l && ((r.properties[e] = l), o || s.push(e));
}
s.length && (r.required = s);
let a = (function (e, t) {
if ("ZodNever" !== e.catchall._def.typeName)
return Z(e.catchall._def, {
...t,
currentPath: [...t.currentPath, "additionalProperties"],
});
switch (e.unknownKeys) {
case "passthrough":
return t.allowedAdditionalProperties;
case "strict":
return t.rejectedAdditionalProperties;
case "strip":
return "strict" === t.removeAdditionalStrategy
? t.allowedAdditionalProperties
: t.rejectedAdditionalProperties;
}
})(e, t);
return void 0 !== a && (r.additionalProperties = a), r;
})(e, n);
case g.ZodFirstPartyTypeKind.ZodBigInt:
let s = { type: "integer", format: "int64" };
if (!e.checks) return s;
for (let t of e.checks)
switch (t.kind) {
case "min":
"jsonSchema7" === n.target
? t.inclusive
? h(s, "minimum", t.value, t.message, n)
: h(s, "exclusiveMinimum", t.value, t.message, n)
: (t.inclusive || (s.exclusiveMinimum = !0),
h(s, "minimum", t.value, t.message, n));
break;
case "max":
"jsonSchema7" === n.target
? t.inclusive
? h(s, "maximum", t.value, t.message, n)
: h(s, "exclusiveMaximum", t.value, t.message, n)
: (t.inclusive || (s.exclusiveMaximum = !0),
h(s, "maximum", t.value, t.message, n));
break;
case "multipleOf":
h(s, "multipleOf", t.value, t.message, n);
}
return s;
case g.ZodFirstPartyTypeKind.ZodBoolean:
return { type: "boolean" };
case g.ZodFirstPartyTypeKind.ZodDate:
return (function e(t, n, r) {
let s = r ?? n.dateStrategy;
if (Array.isArray(s))
return { anyOf: s.map((r, s) => e(t, n, r)) };
switch (s) {
case "string":
case "format:date-time":
return { type: "string", format: "date-time" };
case "format:date":
return { type: "string", format: "date" };
case "integer":
var i = t,
a = n;
let o = { type: "integer", format: "unix-time" };
if ("openApi3" === a.target) return o;
for (let e of i.checks)
switch (e.kind) {
case "min":
h(o, "minimum", e.value, e.message, a);
break;
case "max":
h(o, "maximum", e.value, e.message, a);
}
return o;
}
})(e, n);
case g.ZodFirstPartyTypeKind.ZodUndefined:
return { not: m(n) };
case g.ZodFirstPartyTypeKind.ZodNull:
return "openApi3" === n.target
? { enum: ["null"], nullable: !0 }
: { type: "null" };
case g.ZodFirstPartyTypeKind.ZodArray:
let i;
return (
(i = { type: "array" }),
e.type?._def &&
e.type?._def?.typeName !== g.ZodFirstPartyTypeKind.ZodAny &&
(i.items = Z(e.type._def, {
...n,
currentPath: [...n.currentPath, "items"],
})),
e.minLength &&
h(i, "minItems", e.minLength.value, e.minLength.message, n),
e.maxLength &&
h(i, "maxItems", e.maxLength.value, e.maxLength.message, n),
e.exactLength &&
(h(
i,
"minItems",
e.exactLength.value,
e.exactLength.message,
n,
),
h(
i,
"maxItems",
e.exactLength.value,
e.exactLength.message,
n,
)),
i
);
case g.ZodFirstPartyTypeKind.ZodUnion:
case g.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
if ("openApi3" === n.target) return j(e, n);
let a =
e.options instanceof Map
? Array.from(e.options.values())
: e.options;
if (
a.every(
(e) =>
e._def.typeName in D &&
(!e._def.checks || !e._def.checks.length),
)
) {
let e = a.reduce((e, t) => {
let n = D[t._def.typeName];
return n && !e.includes(n) ? [...e, n] : e;
}, []);
return { type: e.length > 1 ? e : e[0] };
}
if (
a.every(
(e) => "ZodLiteral" === e._def.typeName && !e.description,
)
) {
let e = a.reduce((e, t) => {
let n = typeof t._def.value;
switch (n) {
case "string":
case "number":
case "boolean":
return [...e, n];
case "bigint":
return [...e, "integer"];
case "object":
if (null === t._def.value) return [...e, "null"];
default:
return e;
}
}, []);
if (e.length === a.length) {
let t = e.filter((e, t, n) => n.indexOf(e) === t);
return {
type: t.length > 1 ? t : t[0],
enum: a.reduce(
(e, t) =>
e.includes(t._def.value) ? e : [...e, t._def.value],
[],
),
};
}
} else if (a.every((e) => "ZodEnum" === e._def.typeName))
return {
type: "string",
enum: a.reduce(
(e, t) => [
...e,
...t._def.values.filter((t) => !e.includes(t)),
],
[],
),
};
return j(e, n);
case g.ZodFirstPartyTypeKind.ZodIntersection:
let o, l, u;
return (
(o = [
Z(e.left._def, {
...n,
currentPath: [...n.currentPath, "allOf", "0"],
}),
Z(e.right._def, {
...n,
currentPath: [...n.currentPath, "allOf", "1"],
}),
].filter((e) => !!e)),
(l =
"jsonSchema2019-09" === n.target
? { unevaluatedProperties: !1 }
: void 0),
(u = []),
o.forEach((e) => {
if ((!("type" in e) || "string" !== e.type) && "allOf" in e)
u.push(...e.allOf),
void 0 === e.unevaluatedProperties && (l = void 0);
else {
let t = e;
if (
"additionalProperties" in e &&
!1 === e.additionalProperties
) {
let { additionalProperties: n, ...r } = e;
t = r;
} else l = void 0;
u.push(t);
}
}),
u.length ? { allOf: u, ...l } : void 0
);
case g.ZodFirstPartyTypeKind.ZodTuple:
return e.rest
? {
type: "array",
minItems: e.items.length,
items: e.items
.map((e, t) =>
Z(e._def, {
...n,
currentPath: [...n.currentPath, "items", `${t}`],
}),
)
.reduce((e, t) => (void 0 === t ? e : [...e, t]), []),
additionalItems: Z(e.rest._def, {
...n,
currentPath: [...n.currentPath, "additionalItems"],
}),
}
: {
type: "array",
minItems: e.items.length,
maxItems: e.items.length,
items: e.items
.map((e, t) =>
Z(e._def, {
...n,
currentPath: [...n.currentPath, "items", `${t}`],
}),
)
.reduce((e, t) => (void 0 === t ? e : [...e, t]), []),
};
case g.ZodFirstPartyTypeKind.ZodRecord:
return L(e, n);
case g.ZodFirstPartyTypeKind.ZodLiteral:
let d;
return "bigint" != (d = typeof e.value) &&
"number" !== d &&
"boolean" !== d &&
"string" !== d
? { type: Array.isArray(e.value) ? "array" : "object" }
: "openApi3" === n.target
? { type: "bigint" === d ? "integer" : d, enum: [e.value] }
: { type: "bigint" === d ? "integer" : d, const: e.value };
case g.ZodFirstPartyTypeKind.ZodEnum:
return { type: "string", enum: Array.from(e.values) };
case g.ZodFirstPartyTypeKind.ZodNativeEnum:
let c, f, y;
return (
(c = e.values),
{
type:
1 ===
(y = Array.from(
new Set(
(f = Object.keys(e.values)
.filter((e) => "number" != typeof c[c[e]])
.map((e) => c[e])).map((e) => typeof e),
),
)).length
? "string" === y[0]
? "string"
: "number"
: ["string", "number"],
enum: f,
}
);
case g.ZodFirstPartyTypeKind.ZodNullable:
if (
[
"ZodString",
"ZodNumber",
"ZodBigInt",
"ZodBoolean",
"ZodNull",
].includes(e.innerType._def.typeName) &&
(!e.innerType._def.checks || !e.innerType._def.checks.length)
)
return "openApi3" === n.target
? { type: D[e.innerType._def.typeName], nullable: !0 }
: { type: [D[e.innerType._def.typeName], "null"] };
if ("openApi3" === n.target) {
let t = Z(e.innerType._def, {
...n,
currentPath: [...n.currentPath],
});
return t && "$ref" in t
? { allOf: [t], nullable: !0 }
: t && { ...t, nullable: !0 };
}
let _ = Z(e.innerType._def, {
...n,
currentPath: [...n.currentPath, "anyOf", "0"],
});
return _ && { anyOf: [_, { type: "null" }] };
case g.ZodFirstPartyTypeKind.ZodOptional:
if (n.currentPath.toString() === n.propertyPath?.toString())
return Z(e.innerType._def, n);
let E = Z(e.innerType._def, {
...n,
currentPath: [...n.currentPath, "anyOf", "1"],
});
return E ? { anyOf: [{ not: m(n) }, E] } : m(n);
case g.ZodFirstPartyTypeKind.ZodMap:
if ("record" === n.mapStrategy) return L(e, n);
return {
type: "array",
maxItems: 125,
items: {
type: "array",
items: [
Z(e.keyType._def, {
...n,
currentPath: [...n.currentPath, "items", "items", "0"],
}) || m(n),
Z(e.valueType._def, {
...n,
currentPath: [...n.currentPath, "items", "items", "1"],
}) || m(n),
],
minItems: 2,
maxItems: 2,
},
};
case g.ZodFirstPartyTypeKind.ZodSet:
let b;
return (
(b = {
type: "array",
uniqueItems: !0,
items: Z(e.valueType._def, {
...n,
currentPath: [...n.currentPath, "items"],
}),
}),
e.minSize &&
h(b, "minItems", e.minSize.value, e.minSize.message, n),
e.maxSize &&
h(b, "maxItems", e.maxSize.value, e.maxSize.message, n),
b
);
case g.ZodFirstPartyTypeKind.ZodLazy:
return () => e.getter()._def;
case g.ZodFirstPartyTypeKind.ZodPromise:
return Z(e.type._def, n);
case g.ZodFirstPartyTypeKind.ZodNaN:
case g.ZodFirstPartyTypeKind.ZodNever:
return "openAi" === n.target
? void 0
: { not: m({ ...n, currentPath: [...n.currentPath, "not"] }) };
case g.ZodFirstPartyTypeKind.ZodEffects:
return "input" === n.effectStrategy ? Z(e.schema._def, n) : m(n);
case g.ZodFirstPartyTypeKind.ZodAny:
case g.ZodFirstPartyTypeKind.ZodUnknown:
return m(n);
case g.ZodFirstPartyTypeKind.ZodDefault:
return { ...Z(e.innerType._def, n), default: e.defaultValue() };
case g.ZodFirstPartyTypeKind.ZodBranded:
return v(e, n);
case g.ZodFirstPartyTypeKind.ZodReadonly:
case g.ZodFirstPartyTypeKind.ZodCatch:
return Z(e.innerType._def, n);
case g.ZodFirstPartyTypeKind.ZodPipeline:
if ("input" === n.pipeStrategy) return Z(e.in._def, n);
if ("output" === n.pipeStrategy) return Z(e.out._def, n);
let T = Z(e.in._def, {
...n,
currentPath: [...n.currentPath, "allOf", "0"],
}),
S = Z(e.out._def, {
...n,
currentPath: [...n.currentPath, "allOf", T ? "1" : "0"],
});
return { allOf: [T, S].filter((e) => void 0 !== e) };
case g.ZodFirstPartyTypeKind.ZodFunction:
case g.ZodFirstPartyTypeKind.ZodVoid:
case g.ZodFirstPartyTypeKind.ZodSymbol:
default:
return;
}
})(e, e.typeName, t),
a = "function" == typeof i ? Z(i(), t) : i;
if ((a && G(e, t, a), t.postProcess)) {
let n = t.postProcess(a, e, t);
return (s.jsonSchema = a), n;
}
return (s.jsonSchema = a), a;
}
let U = (e, t) => {
switch (t.$refStrategy) {
case "root":
return { $ref: e.path.join("/") };
case "relative":
return { $ref: f(t.currentPath, e.path) };
case "none":
case "seen":
if (
e.path.length < t.currentPath.length &&
e.path.every((e, n) => t.currentPath[n] === e)
)
return (
console.warn(
`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`,
),
m(t)
);
return "seen" === t.$refStrategy ? m(t) : void 0;
}
},
G = (e, t, n) => (
e.description &&
((n.description = e.description),
t.markdownDescription && (n.markdownDescription = e.description)),
n
);
function F(e) {
return e.pipe(
(0, u.catchError)((e) => {
if (
null !== e &&
"object" == typeof e &&
"name" in e &&
"ZodError" === e.name
)
return l.EMPTY;
throw e;
}),
);
}
var $ = class extends i.HttpAgent {
runtimeUrl;
credentials;
transport;
singleEndpointUrl;
constructor(e) {
const t = e.runtimeUrl ? e.runtimeUrl.replace(/\/$/, "") : void 0,
n = e.transport ?? "rest",
r =
"single" === n
? (t ?? e.runtimeUrl ?? "")
: `${t ?? e.runtimeUrl}/agent/${encodeURIComponent(e.agentId ?? "")}/run`;
if (!r)
throw Error(
"ProxiedCopilotRuntimeAgent requires a runtimeUrl when transport is set to 'single'.",
);
super({ ...e, url: r }),
(this.runtimeUrl = t ?? e.runtimeUrl),
(this.credentials = e.credentials),
(this.transport = n),
"single" === this.transport &&
(this.singleEndpointUrl = this.runtimeUrl);
}
abortRun() {
if (!this.agentId || !this.threadId || "u" < typeof fetch) return;
if ("single" === this.transport) {
if (!this.singleEndpointUrl) return;
let e = new Headers({
...this.headers,
"Content-Type": "application/json",
});
fetch(this.singleEndpointUrl, {
method: "POST",
headers: e,
body: JSON.stringify({
method: "agent/stop",
params: { agentId: this.agentId, threadId: this.threadId },
}),
...(this.credentials ? { credentials: this.credentials } : {}),
}).catch((e) => {
console.error(
"ProxiedCopilotRuntimeAgent: stop request failed",
e,
);
});
return;
}
if (!this.runtimeUrl) return;
let e = `${this.runtimeUrl}/agent/${encodeURIComponent(this.agentId)}/stop/${encodeURIComponent(this.threadId)}`,
t =
"u" > typeof window && window.location
? window.location.origin
: "http://localhost",
n = new URL(this.runtimeUrl, t);
fetch(new URL(e, n).toString(), {
method: "POST",
headers: { "Content-Type": "application/json", ...this.headers },
...(this.credentials ? { credentials: this.credentials } : {}),
}).catch((e) => {
console.error("ProxiedCopilotRuntimeAgent: stop request failed", e);
});
}
connect(e) {
if ("single" === this.transport) {
if (!this.singleEndpointUrl)
throw Error("Single endpoint transport requires a runtimeUrl");
let t = this.createSingleRouteRequestInit(e, "agent/connect", {
agentId: this.agentId,
});
return F(
(0, i.transformHttpEventStream)(
(0, i.runHttpRequest)(this.singleEndpointUrl, t),
),
);
}
return F(
(0, i.transformHttpEventStream)(
(0, i.runHttpRequest)(
`${this.runtimeUrl}/agent/${this.agentId}/connect`,
this.requestInit(e),
),
),
);
}
run(e) {
if ("single" === this.transport) {
if (!this.singleEndpointUrl)
throw Error("Single endpoint transport requires a runtimeUrl");
let t = this.createSingleRouteRequestInit(e, "agent/run", {
agentId: this.agentId,
});
return F(
(0, i.transformHttpEventStream)(
(0, i.runHttpRequest)(this.singleEndpointUrl, t),
),
);
}
return F(super.run(e));
}
clone() {
let e = super.clone();
return (
(e.runtimeUrl = this.runtimeUrl),
(e.credentials = this.credentials),
(e.transport = this.transport),
(e.singleEndpointUrl = this.singleEndpointUrl),
e
);
}
createSingleRouteRequestInit(e, t, n) {
let r;
if (!this.agentId)
throw Error(
"ProxiedCopilotRuntimeAgent requires agentId to make runtime requests",
);
let s = super.requestInit(e),
i = new Headers(s.headers ?? {});
if (
(i.set("Content-Type", "application/json"),
i.set("Accept", i.get("Accept") ?? "text/event-stream"),
"string" == typeof s.body)
)
try {
r = JSON.parse(s.body);
} catch (e) {
console.warn(
"ProxiedCopilotRuntimeAgent: failed to parse request body for single route transport",
e,
),
(r = void 0);
}
let a = { method: t };
return (
n && Object.keys(n).length > 0 && (a.params = n),
void 0 !== r && (a.body = r),
{
...s,
headers: i,
body: JSON.stringify(a),
...(this.credentials ? { credentials: this.credentials } : {}),
}
);
}
},
V = class {
_agents = {};
localAgents = {};
remoteAgents = {};
_runtimeUrl;
_runtimeVersion;
_runtimeConnectionStatus = q.Disconnected;
_runtimeTransport = "rest";
_audioFileTranscriptionEnabled = !1;
constructor(e) {
this.core = e;
}
get agents() {
return this._agents;
}
get runtimeUrl() {
return this._runtimeUrl;
}
get runtimeVersion() {
return this._runtimeVersion;
}
get runtimeConnectionStatus() {
return this._runtimeConnectionStatus;
}
get runtimeTransport() {
return this._runtimeTransport;
}
get audioFileTranscriptionEnabled() {
return this._audioFileTranscriptionEnabled;
}
initialize(e) {
(this.localAgents = this.assignAgentIds(e)),
this.applyHeadersToAgents(this.localAgents),
(this._agents = this.localAgents);
}
setRuntimeUrl(e) {
let t = e ? e.replace(/\/$/, "") : void 0;
this._runtimeUrl !== t &&
((this._runtimeUrl = t), this.updateRuntimeConnection());
}
setRuntimeTransport(e) {
this._runtimeTransport !== e &&
((this._runtimeTransport = e), this.updateRuntimeConnection());
}
setAgents__unsafe_dev_only(e) {
Object.entries(e).forEach(([e, t]) => {
t && this.validateAndAssignAgentId(e, t);
}),
(this.localAgents = e),
(this._agents = { ...this.localAgents, ...this.remoteAgents }),
this.applyHeadersToAgents(this._agents),
this.notifyAgentsChanged();
}
addAgent__unsafe_dev_only({ id: e, agent: t }) {
this.validateAndAssignAgentId(e, t),
(this.localAgents[e] = t),
this.applyHeadersToAgent(t),
(this._agents = { ...this.localAgents, ...this.remoteAgents }),
this.notifyAgentsChanged();
}
removeAgent__unsafe_dev_only(e) {
delete this.localAgents[e],
(this._agents = { ...this.localAgents, ...this.remoteAgents }),
this.notifyAgentsChanged();
}
getAgent(e) {
if (e in this._agents) return this._agents[e];
(void 0 === this.runtimeUrl ||
(this.runtimeConnectionStatus !== q.Disconnected &&
this.runtimeConnectionStatus !== q.Connecting)) &&
console.warn(`Agent ${e} not found`);
}
applyHeadersToAgent(e) {
e instanceof i.HttpAgent && (e.headers = { ...this.core.headers });
}
applyHeadersToAgents(e) {
Object.values(e).forEach((e) => {
this.applyHeadersToAgent(e);
});
}
applyCredentialsToAgent(e) {
e instanceof $ && (e.credentials = this.core.credentials);
}
applyCredentialsToAgents(e) {
Object.values(e).forEach((e) => {
this.applyCredentialsToAgent(e);
});
}
async updateRuntimeConnection() {
if ("u" > typeof window) {
if (!this.runtimeUrl) {
(this._runtimeConnectionStatus = q.Disconnected),
(this._runtimeVersion = void 0),
(this._audioFileTranscriptionEnabled = !1),
(this.remoteAgents = {}),
(this._agents = this.localAgents),
await this.notifyRuntimeStatusChanged(q.Disconnected),
await this.notifyAgentsChanged();
return;
}
(this._runtimeConnectionStatus = q.Connecting),
await this.notifyRuntimeStatusChanged(q.Connecting);
try {
let e = await this.fetchRuntimeInfo(),
{ version: t, ...n } = e,
r = this.core.credentials;
(this.remoteAgents = Object.fromEntries(
Object.entries(n.agents).map(([e, { description: t }]) => {
let n = new $({
runtimeUrl: this.runtimeUrl,
agentId: e,
description: t,
transport: this._runtimeTransport,
credentials: r,
});
return this.applyHeadersToAgent(n), [e, n];
}),
)),
(this._agents = { ...this.localAgents, ...this.remoteAgents }),
(this._runtimeConnectionStatus = q.Connected),
(this._runtimeVersion = t),
(this._audioFileTranscriptionEnabled =
e.audioFileTranscriptionEnabled ?? !1),
await this.notifyRuntimeStatusChanged(q.Connected),
await this.notifyAgentsChanged();
} catch (n) {
(this._runtimeConnectionStatus = q.Error),
(this._runtimeVersion = void 0),
(this._audioFileTranscriptionEnabled = !1),
(this.remoteAgents = {}),
(this._agents = this.localAgents),
await this.notifyRuntimeStatusChanged(q.Error),
await this.notifyAgentsChanged();
let e = n instanceof Error ? n.message : JSON.stringify(n);
a.logger.warn(
`Failed to load runtime info (${this.runtimeUrl}/info): ${e}`,
);
let t = n instanceof Error ? n : Error(String(n));
await this.core.emitError({
error: t,
code: Y.RUNTIME_INFO_FETCH_FAILED,
context: { runtimeUrl: this.runtimeUrl },
});
}
}
}
async fetchRuntimeInfo() {
if (!this.runtimeUrl) throw Error("Runtime URL is not set");
let e = this.core.headers,
t = this.core.credentials,
n = { ...e };
if ("single" === this._runtimeTransport) {
n["Content-Type"] || (n["Content-Type"] = "application/json");
let e = await fetch(this.runtimeUrl, {
method: "POST",
headers: n,
body: JSON.stringify({ method: "info" }),
...(t ? { credentials: t } : {}),
});
if ("ok" in e && !e.ok)
throw Error(
`Runtime info request failed with status ${e.status}`,
);
return await e.json();
}
let r = await fetch(`${this.runtimeUrl}/info`, {
headers: n,
...(t ? { credentials: t } : {}),
});
if ("ok" in r && !r.ok)
throw Error(`Runtime info request failed with status ${r.status}`);
return await r.json();
}
assignAgentIds(e) {
return (
Object.entries(e).forEach(([e, t]) => {
t && this.validateAndAssignAgentId(e, t);
}),
e
);
}
validateAndAssignAgentId(e, t) {
if (t.agentId && t.agentId !== e)
throw Error(
`Agent registration mismatch: Agent with ID "${t.agentId}" cannot be registered under key "${e}". The agent ID must match the registration key or be undefined.`,
);
t.agentId || (t.agentId = e);
}
async notifyRuntimeStatusChanged(e) {
await this.core.notifySubscribers(
(t) =>
t.onRuntimeConnectionStatusChanged?.({
copilotkit: this.core,
status: e,
}),
"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):",
);
}
async notifyAgentsChanged() {
await this.core.notifySubscribers(
(e) =>
e.onAgentsChanged?.({
copilotkit: this.core,
agents: this._agents,
}),
"Subscriber onAgentsChanged error:",
);
}
},
z = class {
_context = {};
constructor(e) {
this.core = e;
}
get context() {
return this._context;
}
addContext({ description: e, value: t }) {
let n = (0, o.randomUUID)();
return (
(this._context[n] = { description: e, value: t }),
this.notifySubscribers(),
n
);
}
removeContext(e) {
delete this._context[e], this.notifySubscribers();
}
async notifySubscribers() {
await this.core.notifySubscribers(
(e) =>
e.onContextChanged?.({
copilotkit: this.core,
context: this._context,
}),
"Subscriber onContextChanged error:",
);
}
},
H = class {
_suggestionsConfig = {};
_suggestions = {};
_runningSuggestions = {};
constructor(e) {
this.core = e;
}
initialize(e) {
for (let t of e) this._suggestionsConfig[(0, o.randomUUID)()] = t;
}
addSuggestionsConfig(e) {
let t = (0, o.randomUUID)();
return (
(this._suggestionsConfig[t] = e),
this.notifySuggestionsConfigChanged(),
t
);
}
removeSuggestionsConfig(e) {
delete this._suggestionsConfig[e],
this.notifySuggestionsConfigChanged();
}
reloadSuggestions(e) {
this.clearSuggestions(e);
let t = this.core.getAgent(e);
if (!t) return;
let n = t.messages?.length ?? 0,
r = !1;
for (let t of Object.values(this._suggestionsConfig)) {
if (
(void 0 !== t.consumerAgentId &&
"*" !== t.consumerAgentId &&
t.consumerAgentId !== e) ||
!this.shouldShowSuggestions(t, n)
)
continue;
let s = (0, o.randomUUID)();
K(t)
? (r || ((r = !0), this.notifySuggestionsStartedLoading(e)),
this.generateSuggestions(s, t, e))
: "suggestions" in t && this.addStaticSuggestions(s, t, e);
}
}
clearSuggestions(e) {
let t = this._runningSuggestions[e];
if (t) {
for (let e of t) e.abortRun();
delete this._runningSuggestions[e];
}
(this._suggestions[e] = {}), this.notifySuggestionsChanged(e, []);
}
getSuggestions(e) {
return {
suggestions: Object.values(this._suggestions[e] ?? {}).flat(),
isLoading: (this._runningSuggestions[e]?.length ?? 0) > 0,
};
}
async generateSuggestions(e, t, n) {
let r;
try {
let s = this.core.getAgent(t.providerAgentId ?? "default");
if (!s)
throw Error(
`Suggestions provider agent not found: ${t.providerAgentId}`,
);
let i = this.core.getAgent(n);
if (!i) throw Error(`Suggestions consumer agent not found: ${n}`);
((r = s.clone()).threadId = e),
(r.messages = JSON.parse(JSON.stringify(i.messages))),
(r.state = JSON.parse(JSON.stringify(i.state))),
(this._suggestions[n] = {
...(this._suggestions[n] ?? {}),
[e]: [],
}),
(this._runningSuggestions[n] = [
...(this._runningSuggestions[n] ?? []),
r,
]),
r.addMessage({
id: e,
role: "user",
content: `Suggest what the user could say next. Provide clear, highly relevant suggestions by calling the \`copilotkitSuggest\` tool.
Provide at least ${t.minSuggestions ?? 1} and at most ${t.maxSuggestions ?? 3} suggestions.
The user has the following tools available: ${JSON.stringify(this.core.buildFrontendTools(n))}.
${t.instructions}`,
}),
await r.runAgent(
{
context: Object.values(this.core.context),
forwardedProps: {
...this.core.properties,
toolChoice: {
type: "function",
function: { name: "copilotkitSuggest" },
},
},
tools: [B],
},
{
onMessagesChanged: ({ messages: t }) => {
this.extractSuggestions(t, e, n, !0);
},
},
);
} catch (e) {
console.warn("Error generating suggestions:", e);
} finally {
this.finalizeSuggestions(e, n);
let t = this._runningSuggestions[n];
if (r && t) {
let e = t.filter((e) => e !== r);
(this._runningSuggestions[n] = e),
0 === e.length &&
(delete this._runningSuggestions[n],
await this.notifySuggestionsFinishedLoading(n));
}
}
}
finalizeSuggestions(e, t) {
let n = this._suggestions[t],
r = n?.[e];
if (n && r && r.length > 0) {
let s = r
.filter((e) => "" !== e.title || "" !== e.message)
.map((e) => ({ ...e, isLoading: !1 }));
s.length > 0 ? (n[e] = s) : delete n[e];
let i = Object.values(this._suggestions[t] ?? {}).flat();
this.notifySuggestionsChanged(t, i, "finalized");
}
}
extractSuggestions(e, t, n, r) {
let s = e.findIndex((e) => e.id === t);
if (-1 == s) return;
let i = [];
for (let t of e.slice(s + 1))
if ("assistant" === t.role && t.toolCalls) {
for (let e of t.toolCalls)
if ("copilotkitSuggest" === e.function.name) {
let t = (0, o.partialJSONParse)(
Array.isArray(e.function.arguments)
? e.function.arguments.join("")
: e.function.arguments,
);
if (t && "object" == typeof t && "suggestions" in t) {
let e = t.suggestions;
if (Array.isArray(e))
for (let t of e)
t &&
"object" == typeof t &&
"title" in t &&
i.push({
title: t.title ?? "",
message: t.message ?? "",
isLoading: !1,
});
}
}
}
r && i.length > 0 && (i[i.length - 1].isLoading = !0);
let a = this._suggestions[n];
if (a) {
a[t] = i;
let e = Object.values(this._suggestions[n] ?? {}).flat();
this.notifySuggestionsChanged(n, e, "suggestions changed");
}
}
async notifySuggestionsConfigChanged() {
await this.core.notifySubscribers(
(e) =>
e.onSuggestionsConfigChanged?.({
copilotkit: this.core,
suggestionsConfig: this._suggestionsConfig,
}),
"Subscriber onSuggestionsConfigChanged error:",
);
}
async notifySuggestionsChanged(e, t, n = "") {
await this.core.notifySubscribers(
(n) =>
n.onSuggestionsChanged?.({
copilotkit: this.core,
agentId: e,
suggestions: t,
}),
`Subscriber onSuggestionsChanged error: ${n}`,
);
}
async notifySuggestionsStartedLoading(e) {
await this.core.notifySubscribers(
(t) =>
t.onSuggestionsStartedLoading?.({
copilotkit: this.core,
agentId: e,
}),
"Subscriber onSuggestionsStartedLoading error:",
);
}
async notifySuggestionsFinishedLoading(e) {
await this.core.notifySubscribers(
(t) =>
t.onSuggestionsFinishedLoading?.({
copilotkit: this.core,
agentId: e,
}),
"Subscriber onSuggestionsFinishedLoading error:",
);
}
shouldShowSuggestions(e, t) {
let n = e.available;
if (!n)
if (K(e)) return t > 0;
else return 0 === t;
switch (n) {
case "disabled":
default:
return !1;
case "before-first-message":
return 0 === t;
case "after-first-message":
return t > 0;
case "always":
return !0;
}
}
addStaticSuggestions(e, t, n) {
let r = t.suggestions.map((e) => ({ ...e, isLoading: !1 }));
this._suggestions[n] = { ...(this._suggestions[n] ?? {}), [e]: r };
let s = Object.values(this._suggestions[n] ?? {}).flat();
this.notifySuggestionsChanged(n, s, "static suggestions added");
}
};
function K(e) {
return "instructions" in e;
}
let B = {
name: "copilotkitSuggest",
description: "Suggest what the user could say next",
parameters: {
type: "object",
properties: {
suggestions: {
type: "array",
description: "List of suggestions shown to the user as buttons.",
items: {
type: "object",
properties: {
title: {
type: "string",
description:
"The title of the suggestion. This is shown as a button and should be short.",
},
message: {
type: "string",
description:
"The message to send when the suggestion is clicked. This should be a clear, complete sentence and will be sent as an instruction to the AI.",
},
},
required: ["title", "message"],
},
},
},
required: ["suggestions"],
},
};
var J = class {
_tools = [];
constructor(e) {
this.core = e;
}
get tools() {
return this._tools;
}
initialize(e) {
this._tools = e;
}
addTool(e) {
-1 !==
this._tools.findIndex(
(t) => t.name === e.name && t.agentId === e.agentId,
)
? a.logger.warn(
`Tool already exists: '${e.name}' for agent '${e.agentId || "global"}', skipping.`,
)
: this._tools.push(e);
}
removeTool(e, t) {
this._tools = this._tools.filter((n) =>
void 0 !== t
? n.name !== e || n.agentId !== t
: !(n.name === e && !n.agentId),
);
}
getTool(e) {
let { toolName: t, agentId: n } = e;
if (n) {
let e = this._tools.find((e) => e.name === t && e.agentId === n);
if (e) return e;
}
return this._tools.find((e) => e.name === t && !e.agentId);
}
setTools(e) {
this._tools = [...e];
}
async connectAgent({ agent: e }) {
try {
await e.detachActiveRun(),
e.setMessages([]),
e.setState({}),
e instanceof i.HttpAgent && (e.headers = { ...this.core.headers });
let t = await e.connectAgent(
{
forwardedProps: this.core.properties,
tools: this.buildFrontendTools(e.agentId),
},
this.createAgentErrorSubscriber(e),
);
return this.processAgentResult({ runAgentResult: t, agent: e });
} catch (r) {
let t = r instanceof Error ? r : Error(String(r)),
n = {};
throw (
(e.agentId && (n.agentId = e.agentId),
await this.core.emitError({
error: t,
code: Y.AGENT_CONNECT_FAILED,
context: n,
}),
r)
);
}
}
async runAgent({ agent: e, forwardedProps: t }) {
e.agentId && this.core.suggestionEngine.clearSuggestions(e.agentId),
e instanceof i.HttpAgent && (e.headers = { ...this.core.headers });
try {
let n = await e.runAgent(
{
forwardedProps: { ...this.core.properties, ...t },
tools: this.buildFrontendTools(e.agentId),
context: Object.values(this.core.context),
},
this.createAgentErrorSubscriber(e),
);
return this.processAgentResult({ runAgentResult: n, agent: e });
} catch (r) {
let t = r instanceof Error ? r : Error(String(r)),
n = {};
throw (
(e.agentId && (n.agentId = e.agentId),
await this.core.emitError({
error: t,
code: Y.AGENT_RUN_FAILED,
context: n,
}),
r)
);
}
}
async processAgentResult({ runAgentResult: e, agent: t }) {
let { newMessages: n } = e,
r = t.agentId,
s = !1;
for (let e of n)
if ("assistant" === e.role) {
for (let i of e.toolCalls || [])
if (
-1 ===
n.findIndex((e) => "tool" === e.role && e.toolCallId === i.id)
) {
let n = this.getTool({
toolName: i.function.name,
agentId: t.agentId,
});
if (n)
(await this.executeSpecificTool(n, i, e, t, r)) && (s = !0);
else {
let n = this.getTool({ toolName: "*", agentId: t.agentId });
n &&
(await this.executeWildcardTool(n, i, e, t, r)) &&
(s = !0);
}
}
}
return s
? await this.runAgent({ agent: t })
: (this.core.suggestionEngine.reloadSuggestions(r), e);
}
async executeSpecificTool(e, t, n, r, s) {
let i;
if (e?.agentId && e.agentId !== r.agentId) return !1;
let a = "",
l = !1;
if (e?.handler) {
let o;
try {
o = JSON.parse(t.function.arguments);
} catch (r) {
let e = r instanceof Error ? r : Error(String(r));
(i = e.message),
(l = !0),
await this.core.emitError({
error: e,
code: Y.TOOL_ARGUMENT_PARSE_FAILED,
context: {
agentId: s,
toolCallId: t.id,
toolName: t.function.name,
rawArguments: t.function.arguments,
toolType: "specific",
messageId: n.id,
},
});
}
if (
(await this.core.notifySubscribers(
(e) =>
e.onToolExecutionStart?.({
copilotkit: this.core,
toolCallId: t.id,
agentId: s,
toolName: t.function.name,
args: o,
}),
"Subscriber onToolExecutionStart error:",
),
!i)
)
try {
let n = await e.handler(o, { toolCall: t, agent: r });
a = null == n ? "" : "string" == typeof n ? n : JSON.stringify(n);
} catch (r) {
let e = r instanceof Error ? r : Error(String(r));
(i = e.message),
await this.core.emitError({
error: e,
code: Y.TOOL_HANDLER_FAILED,
context: {
agentId: s,
toolCallId: t.id,
toolName: t.function.name,
parsedArgs: o,
toolType: "specific",
messageId: n.id,
},
});
}
if (
(i && (a = `Error: ${i}`),
await this.core.notifySubscribers(
(e) =>
e.onToolExecutionEnd?.({
copilotkit: this.core,
toolCallId: t.id,
agentId: s,
toolName: t.function.name,
result: i ? "" : a,
error: i,
}),
"Subscriber onToolExecutionEnd error:",
),
l)
)
throw Error(i ?? "Tool execution failed");
}
if (!i || !l) {
let s = r.messages.findIndex((e) => e.id === n.id);
if (-1 === s) return !1;
let l = {
id: (0, o.randomUUID)(),
role: "tool",
toolCallId: t.id,
content: a,
};
if ((r.messages.splice(s + 1, 0, l), !i && e?.followUp !== !1))
return !0;
}
return !1;
}
async executeWildcardTool(e, t, n, r, s) {
let i;
if (e?.agentId && e.agentId !== r.agentId) return !1;
let a = "",
l = !1;
if (e?.handler) {
let o;
try {
o = JSON.parse(t.function.arguments);
} catch (r) {
let e = r instanceof Error ? r : Error(String(r));
(i = e.message),
(l = !0),
await this.core.emitError({
error: e,
code: Y.TOOL_ARGUMENT_PARSE_FAILED,
context: {
agentId: s,
toolCallId: t.id,
toolName: t.function.name,
rawArguments: t.function.arguments,
toolType: "wildcard",
messageId: n.id,
},
});
}
let u = { toolName: t.function.name, args: o };
if (
(await this.core.notifySubscribers(
(e) =>
e.onToolExecutionStart?.({
copilotkit: this.core,
toolCallId: t.id,
agentId: s,
toolName: t.function.name,
args: u,
}),
"Subscriber onToolExecutionStart error:",
),
!i)
)
try {
let n = await e.handler(u, { toolCall: t, agent: r });
a = null == n ? "" : "string" == typeof n ? n : JSON.stringify(n);
} catch (r) {
let e = r instanceof Error ? r : Error(String(r));
(i = e.message),
await this.core.emitError({
error: e,
code: Y.TOOL_HANDLER_FAILED,
context: {
agentId: s,
toolCallId: t.id,
toolName: t.function.name,
parsedArgs: u,
toolType: "wildcard",
messageId: n.id,
},
});
}
if (
(i && (a = `Error: ${i}`),
await this.core.notifySubscribers(
(e) =>
e.onToolExecutionEnd?.({
copilotkit: this.core,
toolCallId: t.id,
agentId: s,
toolName: t.function.name,
result: i ? "" : a,
error: i,
}),
"Subscriber onToolExecutionEnd error:",
),
l)
)
throw Error(i ?? "Tool execution failed");
}
if (!i || !l) {
let s = r.messages.findIndex((e) => e.id === n.id);
if (-1 === s) return !1;
let l = {
id: (0, o.randomUUID)(),
role: "tool",
toolCallId: t.id,
content: a,
};
if ((r.messages.splice(s + 1, 0, l), !i && e?.followUp !== !1))
return !0;
}
return !1;
}
buildFrontendTools(e) {
return this._tools
.filter((t) => !1 !== t.available && (!t.agentId || t.agentId === e))
.map((e) => ({
name: e.name,
description: e.description ?? "",
parameters: (function (e) {
if (!e.parameters) return { ...X };
let t = ((e, t) => {
let n,
r,
s =
((r =
void 0 !==
(n =
"string" == typeof t
? { ...c, name: t }
: { ...c, ...t }).name
? [...n.basePath, n.definitionPath, n.name]
: n.basePath),
{
...n,
flags: { hasReferencedOpenAiAnyType: !1 },
currentPath: r,
propertyPath: void 0,
seen: new Map(
Object.entries(n.definitions).map(([e, t]) => [
t._def,
{
def: t._def,
path: [...n.basePath, n.definitionPath, e],
jsonSchema: void 0,
},
]),
),
}),
i =
"object" == typeof t && t.definitions
? Object.entries(t.definitions).reduce(
(e, [t, n]) => ({
...e,
[t]:
Z(
n._def,
{
...s,
currentPath: [
...s.basePath,
s.definitionPath,
t,
],
},
!0,
) ?? m(s),
}),
{},
)
: void 0,
a =
"string" == typeof t
? t
: t?.nameStrategy === "title"
? void 0
: t?.name,
o =
Z(
e._def,
void 0 === a
? s
: {
...s,
currentPath: [...s.basePath, s.definitionPath, a],
},
!1,
) ?? m(s),
l =
"object" == typeof t &&
void 0 !== t.name &&
"title" === t.nameStrategy
? t.name
: void 0;
void 0 !== l && (o.title = l),
s.flags.hasReferencedOpenAiAnyType &&
(i || (i = {}),
i[s.openAiAnyTypeName] ||
(i[s.openAiAnyTypeName] = {
type: [
"string",
"number",
"integer",
"boolean",
"array",
"null",
],
items: {
$ref:
"relative" === s.$refStrategy
? "1"
: [
...s.basePath,
s.definitionPath,
s.openAiAnyTypeName,
].join("/"),
},
}));
let u =
void 0 === a
? i
? { ...o, [s.definitionPath]: i }
: o
: {
$ref: [
...("relative" === s.$refStrategy ? [] : s.basePath),
s.definitionPath,
a,
].join("/"),
[s.definitionPath]: { ...i, [a]: o },
};
return (
"jsonSchema7" === s.target
? (u.$schema = "http://json-schema.org/draft-07/schema#")
: ("jsonSchema2019-09" === s.target ||
"openAi" === s.target) &&
(u.$schema =
"https://json-schema.org/draft/2019-09/schema#"),
"openAi" === s.target &&
("anyOf" in u ||
"oneOf" in u ||
"allOf" in u ||
("type" in u && Array.isArray(u.type))) &&
console.warn(
"Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.",
),
u
);
})(e.parameters, { $refStrategy: "none" });
if (!t || "object" != typeof t) return { ...X };
let { $schema: n, ...r } = t;
return (
"string" != typeof r.type && (r.type = "object"),
("object" != typeof r.properties || null === r.properties) &&
(r.properties = {}),
(function e(t) {
if (t && "object" == typeof t) {
if (Array.isArray(t)) return void t.forEach(e);
for (let n of (void 0 !== t.additionalProperties &&
delete t.additionalProperties,
Object.values(t)))
e(n);
}
})(r),
r
);
})(e),
}));
}
createAgentErrorSubscriber(e) {
let t = async (t, n, r = {}) => {
let s = { ...r };
e.agentId && (s.agentId = e.agentId),
await this.core.emitError({ error: t, code: n, context: s });
};
return {
onRunFailed: async ({ error: e }) => {
await t(e, Y.AGENT_RUN_FAILED_EVENT, { source: "onRunFailed" });
},
onRunErrorEvent: async ({ event: e }) => {
let n =
e?.rawEvent instanceof Error
? e.rawEvent
: e?.rawEvent?.error instanceof Error
? e.rawEvent.error
: void 0,
r =
"string" == typeof e?.rawEvent?.error
? e.rawEvent.error
: (e?.message ?? "Agent run error"),
s = n ?? Error(r);
e?.code && !s.code && (s.code = e.code),
await t(s, Y.AGENT_RUN_ERROR_EVENT, {
source: "onRunErrorEvent",
event: e,
runtimeErrorCode: e?.code,
});
},
};
}
};
let X = { type: "object", properties: {} };
var W = class {
stateByRun = new Map();
messageToRun = new Map();
agentSubscriptions = new Map();
constructor(e) {
this.core = e;
}
initialize() {}
subscribeToAgent(e) {
if (!e.agentId) return;
let t = e.agentId;
this.unsubscribeFromAgent(t);
let { unsubscribe: n } = e.subscribe({
onRunStartedEvent: ({ event: t, state: n }) => {
this.handleRunStarted(e, t, n);
},
onRunFinishedEvent: ({ event: t, state: n }) => {
this.handleRunFinished(e, t, n);
},
onStateSnapshotEvent: ({ event: t, input: n, state: r }) => {
this.handleStateSnapshot(e, t, n, r);
},
onStateDeltaEvent: ({ event: t, input: n, state: r }) => {
this.handleStateDelta(e, t, n, r);
},
onMessagesSnapshotEvent: ({ event: t, input: n, messages: r }) => {
this.handleMessagesSnapshot(e, t, n, r);
},
onNewMessage: ({ message: t, input: n }) => {
this.handleNewMessage(e, t, n);
},
});
this.agentSubscriptions.set(t, n);
}
unsubscribeFromAgent(e) {
let t = this.agentSubscriptions.get(e);
t && (t(), this.agentSubscriptions.delete(e));
}
getStateByRun(e, t, n) {
let r = this.stateByRun.get(e)?.get(t)?.get(n);
if (r) return JSON.parse(JSON.stringify(r));
}
getRunIdForMessage(e, t, n) {
return this.messageToRun.get(e)?.get(t)?.get(n);
}
getStatesForThread(e, t) {
return this.stateByRun.get(e)?.get(t) ?? new Map();
}
getRunIdsForThread(e, t) {
let n = this.stateByRun.get(e)?.get(t);
return n ? Array.from(n.keys()) : [];
}
handleRunStarted(e, t, n) {
if (!e.agentId) return;
let { threadId: r, runId: s } = t;
this.saveState(e.agentId, r, s, n);
}
handleRunFinished(e, t, n) {
if (!e.agentId) return;
let { threadId: r, runId: s } = t;
this.saveState(e.agentId, r, s, n);
}
handleStateSnapshot(e, t, n, r) {
if (!e.agentId) return;
let { threadId: s, runId: i } = n,
a = { ...r, ...t.snapshot };
this.saveState(e.agentId, s, i, a);
}
handleStateDelta(e, t, n, r) {
if (!e.agentId) return;
let { threadId: s, runId: i } = n;
this.saveState(e.agentId, s, i, r);
}
handleMessagesSnapshot(e, t, n, r) {
if (!e.agentId) return;
let { threadId: s, runId: i } = n;
for (let n of t.messages)
this.associateMessageWithRun(e.agentId, s, n.id, i);
}
handleNewMessage(e, t, n) {
if (!e.agentId || !n) return;
let { threadId: r, runId: s } = n;
this.associateMessageWithRun(e.agentId, r, t.id, s);
}
saveState(e, t, n, r) {
this.stateByRun.has(e) || this.stateByRun.set(e, new Map());
let s = this.stateByRun.get(e);
s.has(t) || s.set(t, new Map()),
s.get(t).set(n, JSON.parse(JSON.stringify(r)));
}
associateMessageWithRun(e, t, n, r) {
this.messageToRun.has(e) || this.messageToRun.set(e, new Map());
let s = this.messageToRun.get(e);
s.has(t) || s.set(t, new Map()), s.get(t).set(n, r);
}
clearAgentState(e) {
this.stateByRun.delete(e), this.messageToRun.delete(e);
}
clearThreadState(e, t) {
this.stateByRun.get(e)?.delete(t), this.messageToRun.get(e)?.delete(t);
}
};
let Y =
(((n = {}).RUNTIME_INFO_FETCH_FAILED = "runtime_info_fetch_failed"),
(n.AGENT_CONNECT_FAILED = "agent_connect_failed"),
(n.AGENT_RUN_FAILED = "agent_run_failed"),
(n.AGENT_RUN_FAILED_EVENT = "agent_run_failed_event"),
(n.AGENT_RUN_ERROR_EVENT = "agent_run_error_event"),
(n.TOOL_ARGUMENT_PARSE_FAILED = "tool_argument_parse_failed"),
(n.TOOL_HANDLER_FAILED = "tool_handler_failed"),
(n.TRANSCRIPTION_FAILED = "transcription_failed"),
(n.TRANSCRIPTION_SERVICE_NOT_CONFIGURED =
"transcription_service_not_configured"),
(n.TRANSCRIPTION_INVALID_AUDIO = "transcription_invalid_audio"),
(n.TRANSCRIPTION_RATE_LIMITED = "transcription_rate_limited"),
(n.TRANSCRIPTION_AUTH_FAILED = "transcription_auth_failed"),
(n.TRANSCRIPTION_NETWORK_ERROR = "transcription_network_error"),
n),
q =
(((r = {}).Disconnected = "disconnected"),
(r.Connected = "connected"),
(r.Connecting = "connecting"),
(r.Error = "error"),
r);
var Q = class {
_headers;
_credentials;
_properties;
subscribers = new Set();
agentRegistry;
contextStore;
suggestionEngine;
runHandler;
stateManager;
constructor({
runtimeUrl: e,
runtimeTransport: t = "rest",
headers: n = {},
credentials: r,
properties: s = {},
agents__unsafe_dev_only: i = {},
tools: a = [],
suggestionsConfig: o = [],
}) {
(this._headers = n),
(this._credentials = r),
(this._properties = s),
(this.agentRegistry = new V(this)),
(this.contextStore = new z(this)),
(this.suggestionEngine = new H(this)),
(this.runHandler = new J(this)),
(this.stateManager = new W(this)),
this.agentRegistry.initialize(i),
this.runHandler.initialize(a),
this.suggestionEngine.initialize(o),
this.stateManager.initialize(),
this.agentRegistry.setRuntimeTransport(t),
this.agentRegistry.setRuntimeUrl(e),
this.subscribe({
onAgentsChanged: ({ agents: e }) => {
Object.values(e).forEach((e) => {
e.agentId && this.stateManager.subscribeToAgent(e);
});
},
});
}
async notifySubscribers(e, t) {
await Promise.all(
Array.from(this.subscribers).map(async (n) => {
try {
await e(n);
} catch (e) {
console.error(t, e);
}
}),
);
}
async emitError({ error: e, code: t, context: n = {} }) {
await this.notifySubscribers(
(r) =>
r.onError?.({ copilotkit: this, error: e, code: t, context: n }),
"Subscriber onError error:",
);
}
get context() {
return this.contextStore.context;
}
get agents() {
return this.agentRegistry.agents;
}
get tools() {
return this.runHandler.tools;
}
get runtimeUrl() {
return this.agentRegistry.runtimeUrl;
}
setRuntimeUrl(e) {
this.agentRegistry.setRuntimeUrl(e);
}
get runtimeTransport() {
return this.agentRegistry.runtimeTransport;
}
setRuntimeTransport(e) {
this.agentRegistry.setRuntimeTransport(e);
}
get runtimeVersion() {
return this.agentRegistry.runtimeVersion;
}
get headers() {
return this._headers;
}
get credentials() {
return this._credentials;
}
get properties() {
return this._properties;
}
get runtimeConnectionStatus() {
return this.agentRegistry.runtimeConnectionStatus;
}
get audioFileTranscriptionEnabled() {
return this.agentRegistry.audioFileTranscriptionEnabled;
}
setHeaders(e) {
(this._headers = e),
this.agentRegistry.applyHeadersToAgents(this.agentRegistry.agents),
this.notifySubscribers(
(e) =>
e.onHeadersChanged?.({ copilotkit: this, headers: this.headers }),
"Subscriber onHeadersChanged error:",
);
}
setCredentials(e) {
(this._credentials = e),
this.agentRegistry.applyCredentialsToAgents(
this.agentRegistry.agents,
);
}
setProperties(e) {
(this._properties = e),
this.notifySubscribers(
(e) =>
e.onPropertiesChanged?.({
copilotkit: this,
properties: this.properties,
}),
"Subscriber onPropertiesChanged error:",
);
}
setAgents__unsafe_dev_only(e) {
this.agentRegistry.setAgents__unsafe_dev_only(e);
}
addAgent__unsafe_dev_only(e) {
this.agentRegistry.addAgent__unsafe_dev_only(e);
}
removeAgent__unsafe_dev_only(e) {
this.agentRegistry.removeAgent__unsafe_dev_only(e);
}
getAgent(e) {
return this.agentRegistry.getAgent(e);
}
addContext(e) {
return this.contextStore.addContext(e);
}
removeContext(e) {
this.contextStore.removeContext(e);
}
addSuggestionsConfig(e) {
return this.suggestionEngine.addSuggestionsConfig(e);
}
removeSuggestionsConfig(e) {
this.suggestionEngine.removeSuggestionsConfig(e);
}
reloadSuggestions(e) {
this.suggestionEngine.reloadSuggestions(e);
}
clearSuggestions(e) {
this.suggestionEngine.clearSuggestions(e);
}
getSuggestions(e) {
return this.suggestionEngine.getSuggestions(e);
}
addTool(e) {
this.runHandler.addTool(e);
}
removeTool(e, t) {
this.runHandler.removeTool(e, t);
}
getTool(e) {
return this.runHandler.getTool(e);
}
setTools(e) {
this.runHandler.setTools(e);
}
subscribe(e) {
return (
this.subscribers.add(e),
{
unsubscribe: () => {
this.subscribers.delete(e);
},
}
);
}
async connectAgent(e) {
return this.runHandler.connectAgent(e);
}
stopAgent(e) {
e.agent.abortRun();
}
async runAgent(e) {
return this.runHandler.runAgent(e);
}
getStateByRun(e, t, n) {
return this.stateManager.getStateByRun(e, t, n);
}
getRunIdForMessage(e, t, n) {
return this.stateManager.getRunIdForMessage(e, t, n);
}
getRunIdsForThread(e, t) {
return this.stateManager.getRunIdsForThread(e, t);
}
buildFrontendTools(e) {
return this.runHandler.buildFrontendTools(e);
}
};
let ee =
(((s = {}).InProgress = "inProgress"),
(s.Executing = "executing"),
(s.Complete = "complete"),
s);
e.s(
[
"AgentRegistry",
() => V,
"CopilotKitCore",
() => Q,
"CopilotKitCoreRuntimeConnectionStatus",
() => q,
"ProxiedCopilotRuntimeAgent",
() => $,
"ToolCallStatus",
() => ee,
],
222553,
);
};
export default moduleFactory;