cencori 1.9.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1421 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __esm = (fn, res) => function __init() {
7
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
+ };
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
22
+
23
+ // src/agents-sdk/schema.ts
24
+ function isStandard(schema) {
25
+ return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"]?.validate === "function";
26
+ }
27
+ function toJsonSchema(schema) {
28
+ if (!schema) return { type: "object", properties: {}, additionalProperties: false };
29
+ let json2;
30
+ if (isStandard(schema)) {
31
+ const std = schema["~standard"];
32
+ if (std.jsonSchema) {
33
+ json2 = std.jsonSchema.input({ target: "draft-2020-12" });
34
+ } else if (typeof schema.toJSONSchema === "function") {
35
+ json2 = schema.toJSONSchema();
36
+ } else if (std.vendor === "zod" && schema._def?.typeName) {
37
+ json2 = zod3ToJsonSchema(schema);
38
+ } else {
39
+ throw new TypeError(
40
+ `This ${std.vendor} schema can't be converted to JSON Schema. Use zod 4, a library that implements Standard JSON Schema, or pass a JSON Schema object.`
41
+ );
42
+ }
43
+ } else {
44
+ json2 = schema;
45
+ }
46
+ const { $schema: _ignored, ...rest } = json2;
47
+ return rest;
48
+ }
49
+ async function validate(schema, value, what) {
50
+ if (!schema || !isStandard(schema)) return value;
51
+ const result = await schema["~standard"].validate(value);
52
+ if (result.issues) {
53
+ throw new SchemaValidationError(what, result.issues.map((issue) => ({
54
+ message: issue.message,
55
+ path: issue.path?.map((p) => String(typeof p === "object" && p !== null && "key" in p ? p.key : p)).join(".") || void 0
56
+ })));
57
+ }
58
+ return result.value;
59
+ }
60
+ function zod3ToJsonSchema(schema) {
61
+ const def = schema._def;
62
+ const describe = (json2) => def.description ? { ...json2, description: def.description } : json2;
63
+ switch (def.typeName) {
64
+ case "ZodString":
65
+ return describe({ type: "string" });
66
+ case "ZodNumber": {
67
+ const checks = def.checks ?? [];
68
+ return describe({ type: checks.some((c) => c.kind === "int") ? "integer" : "number" });
69
+ }
70
+ case "ZodBigInt":
71
+ return describe({ type: "integer" });
72
+ case "ZodBoolean":
73
+ return describe({ type: "boolean" });
74
+ case "ZodNull":
75
+ return describe({ type: "null" });
76
+ case "ZodDate":
77
+ return describe({ type: "string", format: "date-time" });
78
+ case "ZodAny":
79
+ case "ZodUnknown":
80
+ return describe({});
81
+ case "ZodLiteral":
82
+ return describe({ const: def.value });
83
+ case "ZodEnum":
84
+ return describe({ type: "string", enum: def.values });
85
+ case "ZodNativeEnum":
86
+ return describe({ enum: Object.values(def.values) });
87
+ case "ZodArray":
88
+ return describe({ type: "array", items: zod3ToJsonSchema(def.type) });
89
+ case "ZodTuple":
90
+ return describe({ type: "array", prefixItems: def.items.map(zod3ToJsonSchema) });
91
+ case "ZodRecord":
92
+ return describe({ type: "object", additionalProperties: zod3ToJsonSchema(def.valueType) });
93
+ case "ZodUnion":
94
+ case "ZodDiscriminatedUnion": {
95
+ const options = Array.isArray(def.options) ? def.options : [...def.options.values()];
96
+ return describe({ anyOf: options.map(zod3ToJsonSchema) });
97
+ }
98
+ case "ZodNullable":
99
+ return describe({ anyOf: [zod3ToJsonSchema(def.innerType), { type: "null" }] });
100
+ case "ZodOptional":
101
+ case "ZodDefault":
102
+ case "ZodCatch":
103
+ case "ZodReadonly":
104
+ case "ZodBranded": {
105
+ const inner = zod3ToJsonSchema(def.innerType ?? def.type);
106
+ return def.description ? { ...inner, description: def.description } : inner;
107
+ }
108
+ case "ZodEffects":
109
+ return describe(zod3ToJsonSchema(def.schema));
110
+ case "ZodLazy":
111
+ return describe(zod3ToJsonSchema(def.getter()));
112
+ case "ZodObject": {
113
+ const shape = typeof def.shape === "function" ? def.shape() : def.shape;
114
+ const properties = {};
115
+ const required = [];
116
+ for (const [key, value] of Object.entries(shape)) {
117
+ properties[key] = zod3ToJsonSchema(value);
118
+ const kind = value._def.typeName;
119
+ if (kind !== "ZodOptional" && kind !== "ZodDefault") required.push(key);
120
+ }
121
+ return describe({
122
+ type: "object",
123
+ properties,
124
+ ...required.length ? { required } : {},
125
+ additionalProperties: def.unknownKeys === "passthrough"
126
+ });
127
+ }
128
+ default:
129
+ throw new TypeError(`zod type ${def.typeName} isn't supported in tool parameters. Use zod 4 or pass a JSON Schema object.`);
130
+ }
131
+ }
132
+ var SchemaValidationError;
133
+ var init_schema = __esm({
134
+ "src/agents-sdk/schema.ts"() {
135
+ "use strict";
136
+ SchemaValidationError = class extends Error {
137
+ constructor(what, issues) {
138
+ super(`${what}: ${issues.map((i) => i.path ? `${i.path}: ${i.message}` : i.message).join("; ")}`);
139
+ this.name = "SchemaValidationError";
140
+ this.issues = issues;
141
+ }
142
+ };
143
+ }
144
+ });
145
+
146
+ // src/agents-sdk/tool.ts
147
+ function stringify(value) {
148
+ if (typeof value === "string") return value;
149
+ if (value === void 0) return "";
150
+ try {
151
+ return JSON.stringify(value);
152
+ } catch {
153
+ return String(value);
154
+ }
155
+ }
156
+ function tool(options) {
157
+ if (!TOOL_NAME_PATTERN.test(options.name)) {
158
+ throw new TypeError(`Tool name "${options.name}" must be 1-64 letters, digits, _ or -.`);
159
+ }
160
+ const jsonSchema = toJsonSchema(options.parameters);
161
+ const parseArguments = async (rawArguments) => {
162
+ let parsed = {};
163
+ if (rawArguments && rawArguments.trim()) {
164
+ try {
165
+ parsed = JSON.parse(rawArguments);
166
+ } catch {
167
+ throw new SyntaxError(`The arguments for ${options.name} are not valid JSON.`);
168
+ }
169
+ }
170
+ return validate(options.parameters, parsed, `Invalid arguments for ${options.name}`);
171
+ };
172
+ return {
173
+ type: "function",
174
+ name: options.name,
175
+ description: options.description,
176
+ parameters: jsonSchema,
177
+ needsApproval: options.needsApproval ?? false,
178
+ parseArguments,
179
+ async invoke(runContext, rawArguments, callId) {
180
+ try {
181
+ const args = await parseArguments(rawArguments);
182
+ const out = await options.execute(args, runContext, { callId });
183
+ return stringify(out);
184
+ } catch (error) {
185
+ if (options.errorFunction) return options.errorFunction(error, runContext);
186
+ const message = error instanceof Error ? error.message : String(error);
187
+ return `Error running ${options.name}: ${message}`;
188
+ }
189
+ }
190
+ };
191
+ }
192
+ var TOOL_NAME_PATTERN;
193
+ var init_tool = __esm({
194
+ "src/agents-sdk/tool.ts"() {
195
+ "use strict";
196
+ init_schema();
197
+ TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
198
+ }
199
+ });
200
+
201
+ // src/widgets/spec.ts
202
+ function safeUrl(v, images) {
203
+ if (images && /^data:image\/(png|jpe?g|gif|webp|svg\+xml);base64,/i.test(v)) return v.length <= 2e5;
204
+ try {
205
+ const u = new URL(v);
206
+ return u.protocol === "https:" || !images && u.protocol === "mailto:";
207
+ } catch {
208
+ return false;
209
+ }
210
+ }
211
+ function validateWidget(input) {
212
+ const errors = [];
213
+ let nodes = 0;
214
+ if (bytes(input) > WIDGET_LIMITS.maxBytes) {
215
+ return { ok: false, errors: [`widget is larger than ${WIDGET_LIMITS.maxBytes / 1024} KB; show fewer rows or points`] };
216
+ }
217
+ const str = (v, path) => {
218
+ if (typeof v !== "string") {
219
+ errors.push(`${path}: expected a string`);
220
+ return void 0;
221
+ }
222
+ if (v.length > WIDGET_LIMITS.maxString) {
223
+ errors.push(`${path}: longer than ${WIDGET_LIMITS.maxString} characters`);
224
+ return void 0;
225
+ }
226
+ return v;
227
+ };
228
+ const action = (v, path) => {
229
+ if (!isObj(v) || typeof v.type !== "string" || !v.type.trim()) {
230
+ errors.push(`${path}: expected { type: string, payload?: object, handler?: "agent" | "client" }`);
231
+ return void 0;
232
+ }
233
+ const out = { type: v.type.slice(0, 100) };
234
+ if (v.payload !== void 0) {
235
+ if (!isObj(v.payload)) errors.push(`${path}.payload: expected an object`);
236
+ else if (bytes(v.payload) > WIDGET_LIMITS.maxPayloadBytes) errors.push(`${path}.payload: larger than 4 KB`);
237
+ else out.payload = v.payload;
238
+ }
239
+ if (v.handler !== void 0) {
240
+ if (v.handler !== "agent" && v.handler !== "client") errors.push(`${path}.handler: expected "agent" or "client"`);
241
+ else out.handler = v.handler;
242
+ }
243
+ return out;
244
+ };
245
+ const prop = (kind, v, path, depth) => {
246
+ switch (kind.k) {
247
+ case "string":
248
+ return str(v, path);
249
+ case "number":
250
+ if (typeof v !== "number" || !Number.isFinite(v)) {
251
+ errors.push(`${path}: expected a number`);
252
+ return void 0;
253
+ }
254
+ return v;
255
+ case "boolean":
256
+ if (typeof v !== "boolean") {
257
+ errors.push(`${path}: expected true or false`);
258
+ return void 0;
259
+ }
260
+ return v;
261
+ case "scalar":
262
+ if (typeof v === "number" && Number.isFinite(v)) return v;
263
+ return str(v, path);
264
+ case "enum":
265
+ if (typeof v !== "string" || !kind.values.includes(v)) {
266
+ errors.push(`${path}: expected one of ${kind.values.map((x) => `"${x}"`).join(", ")}`);
267
+ return void 0;
268
+ }
269
+ return v;
270
+ case "url": {
271
+ const s = str(v, path);
272
+ if (s === void 0) return void 0;
273
+ if (!safeUrl(s, Boolean(kind.images))) {
274
+ errors.push(`${path}: expected an https:// URL${kind.images ? " or a base64 data:image URL" : ""}`);
275
+ return void 0;
276
+ }
277
+ return s;
278
+ }
279
+ case "action":
280
+ return action(v, path);
281
+ case "children": {
282
+ if (!Array.isArray(v)) {
283
+ errors.push(`${path}: expected an array of components`);
284
+ return void 0;
285
+ }
286
+ return v.map((c, i) => node(c, `${path}[${i}]`, depth + 1)).filter(Boolean);
287
+ }
288
+ case "buttons": {
289
+ if (!Array.isArray(v)) {
290
+ errors.push(`${path}: expected an array of Button components`);
291
+ return void 0;
292
+ }
293
+ return v.map((c, i) => {
294
+ if (!isObj(c) || c.type !== "Button") {
295
+ errors.push(`${path}[${i}]: expected a Button`);
296
+ return void 0;
297
+ }
298
+ return node(c, `${path}[${i}]`, depth + 1);
299
+ }).filter(Boolean);
300
+ }
301
+ case "items": {
302
+ if (!Array.isArray(v)) {
303
+ errors.push(`${path}: expected an array of items`);
304
+ return void 0;
305
+ }
306
+ if (v.length > WIDGET_LIMITS.maxListItems) errors.push(`${path}: more than ${WIDGET_LIMITS.maxListItems} items`);
307
+ return v.slice(0, WIDGET_LIMITS.maxListItems).map((it, i) => {
308
+ const p = `${path}[${i}]`;
309
+ if (!isObj(it)) {
310
+ errors.push(`${p}: expected { title, subtitle?, value?, badge?, image?, action? }`);
311
+ return void 0;
312
+ }
313
+ const out = { title: str(it.title, `${p}.title`) ?? "" };
314
+ if (it.subtitle !== void 0) out.subtitle = str(it.subtitle, `${p}.subtitle`);
315
+ if (it.value !== void 0) out.value = typeof it.value === "number" ? String(it.value) : str(it.value, `${p}.value`);
316
+ if (it.badge !== void 0) out.badge = str(it.badge, `${p}.badge`);
317
+ if (it.badgeColor !== void 0) out.badgeColor = prop(e(...COLORS), it.badgeColor, `${p}.badgeColor`, depth);
318
+ if (it.image !== void 0) out.image = prop({ k: "url", images: true }, it.image, `${p}.image`, depth);
319
+ if (it.action !== void 0) out.action = action(it.action, `${p}.action`);
320
+ return out;
321
+ }).filter(Boolean);
322
+ }
323
+ case "options": {
324
+ if (!Array.isArray(v) || v.length === 0) {
325
+ errors.push(`${path}: expected a non-empty array of { label, value }`);
326
+ return void 0;
327
+ }
328
+ if (v.length > WIDGET_LIMITS.maxOptions) errors.push(`${path}: more than ${WIDGET_LIMITS.maxOptions} options`);
329
+ return v.slice(0, WIDGET_LIMITS.maxOptions).map((o, i) => {
330
+ if (!isObj(o)) {
331
+ errors.push(`${path}[${i}]: expected { label, value }`);
332
+ return void 0;
333
+ }
334
+ return { label: str(o.label, `${path}[${i}].label`) ?? "", value: typeof o.value === "number" ? String(o.value) : str(o.value, `${path}[${i}].value`) ?? "" };
335
+ }).filter(Boolean);
336
+ }
337
+ case "series": {
338
+ if (!Array.isArray(v) || v.length === 0) {
339
+ errors.push(`${path}: expected a non-empty array of { key, label?, color? }`);
340
+ return void 0;
341
+ }
342
+ if (v.length > WIDGET_LIMITS.maxChartSeries) errors.push(`${path}: more than ${WIDGET_LIMITS.maxChartSeries} series`);
343
+ return v.slice(0, WIDGET_LIMITS.maxChartSeries).map((s, i) => {
344
+ if (!isObj(s)) {
345
+ errors.push(`${path}[${i}]: expected { key, label?, color? }`);
346
+ return void 0;
347
+ }
348
+ const out = { key: str(s.key, `${path}[${i}].key`) ?? "" };
349
+ if (s.label !== void 0) out.label = str(s.label, `${path}[${i}].label`);
350
+ if (s.color !== void 0) out.color = prop(e(...COLORS), s.color, `${path}[${i}].color`, depth);
351
+ return out;
352
+ }).filter(Boolean);
353
+ }
354
+ case "columns": {
355
+ if (!Array.isArray(v) || v.length === 0) {
356
+ errors.push(`${path}: expected a non-empty array of { key, label, align?, format? }`);
357
+ return void 0;
358
+ }
359
+ if (v.length > WIDGET_LIMITS.maxTableColumns) errors.push(`${path}: more than ${WIDGET_LIMITS.maxTableColumns} columns`);
360
+ return v.slice(0, WIDGET_LIMITS.maxTableColumns).map((c, i) => {
361
+ const p = `${path}[${i}]`;
362
+ if (!isObj(c)) {
363
+ errors.push(`${p}: expected { key, label, align?, format? }`);
364
+ return void 0;
365
+ }
366
+ const out = { key: str(c.key, `${p}.key`) ?? "", label: str(c.label, `${p}.label`) ?? "" };
367
+ if (c.align !== void 0) out.align = prop(e("start", "end", "center"), c.align, `${p}.align`, depth);
368
+ if (c.format !== void 0) out.format = prop(e(...FORMATS), c.format, `${p}.format`, depth);
369
+ if (c.currency !== void 0) out.currency = str(c.currency, `${p}.currency`);
370
+ return out;
371
+ }).filter(Boolean);
372
+ }
373
+ case "rows":
374
+ case "data": {
375
+ const max = kind.k === "rows" ? WIDGET_LIMITS.maxTableRows : WIDGET_LIMITS.maxChartPoints;
376
+ if (!Array.isArray(v)) {
377
+ errors.push(`${path}: expected an array of objects`);
378
+ return void 0;
379
+ }
380
+ if (v.length > max) errors.push(`${path}: more than ${max} entries; aggregate or show fewer`);
381
+ return v.slice(0, max).map((r, i) => {
382
+ if (!isObj(r)) {
383
+ errors.push(`${path}[${i}]: expected an object`);
384
+ return void 0;
385
+ }
386
+ const out = {};
387
+ for (const [key, val] of Object.entries(r)) {
388
+ if (val === null || typeof val === "number" || typeof val === "boolean") out[key] = val;
389
+ else if (typeof val === "string") out[key] = val.slice(0, 500);
390
+ else errors.push(`${path}[${i}].${key}: expected a string, number, boolean or null`);
391
+ }
392
+ return out;
393
+ }).filter(Boolean);
394
+ }
395
+ }
396
+ };
397
+ function node(v, path, depth) {
398
+ if (++nodes > WIDGET_LIMITS.maxNodes) {
399
+ if (nodes === WIDGET_LIMITS.maxNodes + 1) errors.push(`widget has more than ${WIDGET_LIMITS.maxNodes} components`);
400
+ return void 0;
401
+ }
402
+ if (depth > WIDGET_LIMITS.maxDepth) {
403
+ errors.push(`${path}: nested deeper than ${WIDGET_LIMITS.maxDepth} levels`);
404
+ return void 0;
405
+ }
406
+ if (!isObj(v)) {
407
+ errors.push(`${path}: expected a component object with a "type"`);
408
+ return void 0;
409
+ }
410
+ const type = v.type;
411
+ const spec = PROPS[type];
412
+ if (typeof type !== "string" || !spec) {
413
+ errors.push(`${path}: unknown component type ${JSON.stringify(v.type)}; use one of ${WIDGET_TYPES.join(", ")}`);
414
+ return void 0;
415
+ }
416
+ const out = { type };
417
+ for (const [name, ps] of Object.entries(spec)) {
418
+ const value = v[name];
419
+ if (value === void 0 || value === null) {
420
+ if (ps.required) errors.push(`${path} (${type}): missing "${name}"`);
421
+ continue;
422
+ }
423
+ const clean = prop(ps.kind, value, `${path}.${name}`, depth);
424
+ if (clean !== void 0) out[name] = clean;
425
+ }
426
+ if (type === "Button" && out.action === void 0 && out.href === void 0 && !out.submit) {
427
+ errors.push(`${path} (Button): needs an "action", an "href", or submit: true inside a Form`);
428
+ }
429
+ if (type === "Chart" && Array.isArray(out.data) && Array.isArray(out.series)) {
430
+ const keys = new Set(out.data.flatMap((d) => Object.keys(d)));
431
+ if (keys.size > 0) {
432
+ if (!keys.has(out.x)) errors.push(`${path} (Chart): x "${out.x}" is not a key in data`);
433
+ for (const s of out.series) {
434
+ if (!keys.has(s.key)) errors.push(`${path} (Chart): series key "${s.key}" is not a key in data`);
435
+ }
436
+ }
437
+ }
438
+ return out;
439
+ }
440
+ const widget = node(input, "widget", 0);
441
+ if (errors.length > 0 || !widget) return { ok: false, errors: errors.length ? errors.slice(0, 30) : ["widget is empty"] };
442
+ return { ok: true, widget };
443
+ }
444
+ function isWidgetResult(v) {
445
+ return isObj(v) && isObj(v.widget) && typeof v.widget.type === "string";
446
+ }
447
+ var WIDGET_LIMITS, S, N, B, e, req, opt, COLORS, FORMATS, GAPS, PROPS, WIDGET_TYPES, isObj, bytes;
448
+ var init_spec = __esm({
449
+ "src/widgets/spec.ts"() {
450
+ "use strict";
451
+ WIDGET_LIMITS = {
452
+ maxBytes: 64 * 1024,
453
+ maxNodes: 400,
454
+ maxDepth: 12,
455
+ maxString: 4e3,
456
+ maxListItems: 100,
457
+ maxTableRows: 200,
458
+ maxTableColumns: 20,
459
+ maxChartPoints: 500,
460
+ maxChartSeries: 12,
461
+ maxOptions: 100,
462
+ maxPayloadBytes: 4 * 1024
463
+ };
464
+ S = { k: "string" };
465
+ N = { k: "number" };
466
+ B = { k: "boolean" };
467
+ e = (...values) => ({ k: "enum", values });
468
+ req = (kind) => ({ kind, required: true });
469
+ opt = (kind) => ({ kind });
470
+ COLORS = ["default", "muted", "accent", "success", "warning", "danger", "info"];
471
+ FORMATS = ["number", "compact", "currency", "percent", "date", "datetime"];
472
+ GAPS = ["none", "xs", "sm", "md", "lg"];
473
+ PROPS = {
474
+ Card: { title: opt(S), subtitle: opt(S), status: opt(S), children: req({ k: "children" }), actions: opt({ k: "buttons" }) },
475
+ ListView: { title: opt(S), items: req({ k: "items" }) },
476
+ Row: { children: req({ k: "children" }), gap: opt(e(...GAPS)), align: opt(e("start", "center", "end", "stretch")), justify: opt(e("start", "center", "end", "between")), wrap: opt(B) },
477
+ Col: { children: req({ k: "children" }), gap: opt(e(...GAPS)), align: opt(e("start", "center", "end", "stretch")), flex: opt(N) },
478
+ Divider: {},
479
+ Spacer: {},
480
+ Text: { value: req(S), size: opt(e("xs", "sm", "md", "lg")), weight: opt(e("normal", "medium", "semibold", "bold")), color: opt(e(...COLORS)), align: opt(e("start", "center", "end")), truncate: opt(B) },
481
+ Title: { value: req(S), size: opt(e("sm", "md", "lg", "xl")) },
482
+ Markdown: { value: req(S) },
483
+ Badge: { label: req(S), color: opt(e(...COLORS)) },
484
+ Image: { src: req({ k: "url", images: true }), alt: opt(S), aspectRatio: opt(N), fit: opt(e("cover", "contain")) },
485
+ Stat: { label: req(S), value: req({ k: "scalar" }), format: opt(e(...FORMATS)), currency: opt(S), delta: opt(N), deltaFormat: opt(e("percent", "number")), caption: opt(S) },
486
+ Chart: { chart: req(e("bar", "line", "area", "pie")), data: req({ k: "data" }), x: req(S), series: req({ k: "series" }), stacked: opt(B), height: opt(N), format: opt(e(...FORMATS)), currency: opt(S), title: opt(S) },
487
+ Table: { columns: req({ k: "columns" }), rows: req({ k: "rows" }), title: opt(S) },
488
+ Button: { label: req(S), action: opt({ k: "action" }), href: opt({ k: "url" }), variant: opt(e("primary", "secondary", "outline", "ghost", "danger")), size: opt(e("sm", "md")), block: opt(B), submit: opt(B) },
489
+ Form: { children: req({ k: "children" }), action: req({ k: "action" }), submitLabel: opt(S) },
490
+ Input: { name: req(S), label: opt(S), placeholder: opt(S), inputType: opt(e("text", "number", "email", "date", "tel", "url")), required: opt(B), defaultValue: opt({ k: "scalar" }), multiline: opt(B) },
491
+ Select: { name: req(S), label: opt(S), options: req({ k: "options" }), placeholder: opt(S), defaultValue: opt(S), required: opt(B), action: opt({ k: "action" }) },
492
+ Checkbox: { name: req(S), label: req(S), defaultChecked: opt(B) }
493
+ };
494
+ WIDGET_TYPES = Object.keys(PROPS);
495
+ isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
496
+ bytes = (v) => new TextEncoder().encode(JSON.stringify(v) ?? "").byteLength;
497
+ }
498
+ });
499
+
500
+ // src/agents-sdk/errors.ts
501
+ var AgentsError, MaxTurnsExceededError, GuardrailTripwireTriggered, CencoriRunError;
502
+ var init_errors = __esm({
503
+ "src/agents-sdk/errors.ts"() {
504
+ "use strict";
505
+ AgentsError = class extends Error {
506
+ constructor(message) {
507
+ super(message);
508
+ this.name = "AgentsError";
509
+ }
510
+ };
511
+ MaxTurnsExceededError = class extends AgentsError {
512
+ constructor(maxTurns, sessionId) {
513
+ super(`The run exceeded maxTurns (${maxTurns}) without a final answer. Raise maxTurns or check for a tool loop.`);
514
+ this.name = "MaxTurnsExceededError";
515
+ this.sessionId = sessionId;
516
+ }
517
+ };
518
+ GuardrailTripwireTriggered = class extends AgentsError {
519
+ constructor(kind, guardrail, outputInfo) {
520
+ super(`${kind === "input" ? "Input" : "Output"} guardrail "${guardrail}" tripped.`);
521
+ this.name = kind === "input" ? "InputGuardrailTripwireTriggered" : "OutputGuardrailTripwireTriggered";
522
+ this.guardrail = guardrail;
523
+ this.kind = kind;
524
+ this.outputInfo = outputInfo;
525
+ }
526
+ };
527
+ CencoriRunError = class extends AgentsError {
528
+ constructor(message, details = {}) {
529
+ super(message);
530
+ this.name = "CencoriRunError";
531
+ this.status = details.status;
532
+ this.code = details.code;
533
+ this.sessionId = details.sessionId;
534
+ }
535
+ };
536
+ }
537
+ });
538
+
539
+ // src/agents-sdk/transport.ts
540
+ function env(name) {
541
+ try {
542
+ return typeof process !== "undefined" ? process.env?.[name] : void 0;
543
+ } catch {
544
+ return void 0;
545
+ }
546
+ }
547
+ async function errorFrom(response, sessionId) {
548
+ let message = `Cencori returned ${response.status}`;
549
+ let code;
550
+ try {
551
+ const body = await response.json();
552
+ if (typeof body.error === "string") message = body.error;
553
+ else if (body.error?.message) {
554
+ message = body.error.message;
555
+ code = body.error.code;
556
+ }
557
+ } catch {
558
+ }
559
+ return new CencoriRunError(message, { status: response.status, code, sessionId });
560
+ }
561
+ async function* readSessionEvents(response) {
562
+ if (!response.body) return;
563
+ const reader = response.body.getReader();
564
+ const decoder = new TextDecoder();
565
+ let buffer = "";
566
+ let event = "message";
567
+ let data = [];
568
+ const flush = () => {
569
+ if (data.length === 0) {
570
+ event = "message";
571
+ return null;
572
+ }
573
+ const raw = data.join("\n");
574
+ data = [];
575
+ const name = event;
576
+ event = "message";
577
+ try {
578
+ return { event: name, data: JSON.parse(raw) };
579
+ } catch {
580
+ return { event: name, data: { raw } };
581
+ }
582
+ };
583
+ try {
584
+ while (true) {
585
+ const { done, value } = await reader.read();
586
+ if (done) break;
587
+ buffer += decoder.decode(value, { stream: true });
588
+ let newline;
589
+ while ((newline = buffer.indexOf("\n")) >= 0) {
590
+ const line = buffer.slice(0, newline).replace(/\r$/, "");
591
+ buffer = buffer.slice(newline + 1);
592
+ if (line === "") {
593
+ const parsed = flush();
594
+ if (parsed) yield parsed;
595
+ } else if (line.startsWith("event:")) {
596
+ event = line.slice(6).trim();
597
+ } else if (line.startsWith("data:")) {
598
+ data.push(line.slice(5).replace(/^ /, ""));
599
+ }
600
+ }
601
+ }
602
+ buffer += decoder.decode();
603
+ if (buffer.trim()) {
604
+ for (const line of buffer.split("\n")) {
605
+ if (line.startsWith("event:")) event = line.slice(6).trim();
606
+ else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
607
+ }
608
+ }
609
+ const last = flush();
610
+ if (last) yield last;
611
+ } finally {
612
+ reader.releaseLock();
613
+ }
614
+ }
615
+ var DEFAULT_BASE_URL, Transport;
616
+ var init_transport = __esm({
617
+ "src/agents-sdk/transport.ts"() {
618
+ "use strict";
619
+ init_errors();
620
+ DEFAULT_BASE_URL = "https://cencori.com";
621
+ Transport = class {
622
+ constructor(options = {}) {
623
+ const apiKey = options.apiKey ?? env("CENCORI_API_KEY");
624
+ if (!apiKey) {
625
+ throw new CencoriRunError("No Cencori API key. Pass apiKey or set CENCORI_API_KEY (a secret project key, csk_...).", { code: "missing_api_key" });
626
+ }
627
+ this.apiKey = apiKey;
628
+ this.baseUrl = (options.baseUrl ?? env("CENCORI_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
629
+ this.fetchImpl = options.fetch ?? fetch;
630
+ this.signal = options.signal;
631
+ }
632
+ async post(path, body, sessionId) {
633
+ const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
634
+ method: "POST",
635
+ headers: {
636
+ "CENCORI_API_KEY": this.apiKey,
637
+ "Content-Type": "application/json",
638
+ "Accept": "text/event-stream, application/json"
639
+ },
640
+ body: JSON.stringify(body),
641
+ signal: this.signal
642
+ });
643
+ if (!response.ok) throw await errorFrom(response, sessionId);
644
+ return response;
645
+ }
646
+ /**
647
+ * Create a session and run its first turn in one request. Servers that
648
+ * predate this answer with the plain session JSON; the turn then goes in a
649
+ * second request, as before.
650
+ */
651
+ async createSessionWithTurn(metadata, body) {
652
+ const turn = { ...body, stream: true, pause_on_tool_calls: true };
653
+ const response = await this.fetchImpl(`${this.baseUrl}/v1/sessions`, {
654
+ method: "POST",
655
+ headers: {
656
+ "CENCORI_API_KEY": this.apiKey,
657
+ "Content-Type": "application/json",
658
+ "Accept": "text/event-stream, application/json"
659
+ },
660
+ body: JSON.stringify({ metadata, turn }),
661
+ signal: this.signal
662
+ });
663
+ const headerId = response.headers.get("X-Cencori-Session-Id") ?? void 0;
664
+ if (!response.ok) throw await errorFrom(response, headerId);
665
+ if (headerId) return { sessionId: headerId, response };
666
+ const created = await response.json();
667
+ if (!created.id) throw new CencoriRunError("Cencori did not return a session id.");
668
+ return { sessionId: created.id, response: await this.turn(created.id, body) };
669
+ }
670
+ turn(sessionId, body) {
671
+ return this.post(`/v1/sessions/${encodeURIComponent(sessionId)}/turns`, {
672
+ ...body,
673
+ stream: true,
674
+ pause_on_tool_calls: true
675
+ }, sessionId);
676
+ }
677
+ resume(sessionId, actionId, toolResults, next) {
678
+ return this.post(`/v1/sessions/${encodeURIComponent(sessionId)}/approve`, {
679
+ action_id: actionId,
680
+ tool_results: toolResults,
681
+ ...next ? { next } : {}
682
+ }, sessionId);
683
+ }
684
+ };
685
+ }
686
+ });
687
+
688
+ // src/agents-sdk/run.ts
689
+ var run_exports = {};
690
+ __export(run_exports, {
691
+ RunState: () => RunState,
692
+ run: () => run
693
+ });
694
+ function toolWidget(output) {
695
+ if (!output.startsWith("{") || !output.includes('"widget"')) return null;
696
+ let parsed;
697
+ try {
698
+ parsed = JSON.parse(output);
699
+ } catch {
700
+ return null;
701
+ }
702
+ if (!isWidgetResult(parsed)) return null;
703
+ const { widget, ...rest } = parsed;
704
+ const checked = validateWidget(widget);
705
+ if (!checked.ok) {
706
+ console.warn(`[cencori/agents] A tool returned a widget that isn't valid, so it wasn't shown:
707
+ ${checked.errors.join("\n")}`);
708
+ return null;
709
+ }
710
+ const widgetId = `wgt_${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;
711
+ return {
712
+ widgetId,
713
+ widget: checked.widget,
714
+ modelOutput: JSON.stringify({ ...rest, rendered: true, widget_id: widgetId, note: "The user can see this widget now; do not repeat its contents. If the user asked for anything else, do it now with the tools it needs. Never say an action happened unless its tool returned success." })
715
+ };
716
+ }
717
+ function collectAgents(start) {
718
+ const seen = /* @__PURE__ */ new Map();
719
+ const visit = (agent) => {
720
+ if (seen.has(agent.name)) return;
721
+ seen.set(agent.name, agent);
722
+ agent.handoffs.forEach(visit);
723
+ };
724
+ visit(start);
725
+ return seen;
726
+ }
727
+ function wireTools(agent) {
728
+ const tools = agent.tools.map((t) => ({
729
+ type: "function",
730
+ function: { name: t.name, description: t.description, parameters: t.parameters },
731
+ // Only an unconditional approval is the server's to hold and record; a
732
+ // conditional one is decided here, per call.
733
+ ...t.needsApproval === true ? { needsApproval: true } : {}
734
+ }));
735
+ for (const target of agent.handoffs) {
736
+ tools.push({
737
+ type: "function",
738
+ function: {
739
+ name: Agent.handoffToolName(target),
740
+ description: target.handoffDescription ? `Hand the conversation to ${target.name}: ${target.handoffDescription}` : `Hand the conversation to the ${target.name} agent.`,
741
+ parameters: { type: "object", properties: {}, additionalProperties: false }
742
+ }
743
+ });
744
+ }
745
+ return tools;
746
+ }
747
+ function addUsage(total, usage) {
748
+ const u = usage ?? {};
749
+ return {
750
+ inputTokens: total.inputTokens + (u.input_tokens ?? 0),
751
+ outputTokens: total.outputTokens + (u.output_tokens ?? 0),
752
+ totalTokens: total.totalTokens + (u.total_tokens ?? 0)
753
+ };
754
+ }
755
+ function completedText(streamed2, data) {
756
+ if (streamed2) return streamed2;
757
+ const out = data.output;
758
+ if (typeof out?.text === "string") return out.text;
759
+ let text = "";
760
+ if (Array.isArray(out?.output)) {
761
+ for (const item of out.output) {
762
+ if (item.type !== "message" || !Array.isArray(item.content)) continue;
763
+ for (const c of item.content) {
764
+ if (c.type === "output_text" && typeof c.text === "string") text += c.text;
765
+ }
766
+ }
767
+ }
768
+ return text;
769
+ }
770
+ async function* consumeTurn(response, agentName, sessionId, items) {
771
+ let text = "";
772
+ for await (const { event, data } of readSessionEvents(response)) {
773
+ switch (event) {
774
+ case "output_text.delta": {
775
+ const delta = typeof data.delta === "string" ? data.delta : "";
776
+ if (delta) {
777
+ text += delta;
778
+ yield { type: "text_delta", delta, agentName };
779
+ }
780
+ break;
781
+ }
782
+ case "tool_call.completed": {
783
+ const out = data.output;
784
+ if (data.tool === "render_ui" && out?.ok && out.widget && out.widget_id) {
785
+ items.push({ type: "widget", agentName, callId: String(data.action_id ?? ""), widgetId: out.widget_id, widget: out.widget });
786
+ yield { type: "widget", callId: String(data.action_id ?? ""), widgetId: out.widget_id, widget: out.widget, agentName };
787
+ }
788
+ break;
789
+ }
790
+ case "turn.paused": {
791
+ const actions = Array.isArray(data.actions) ? data.actions : [{ action_id: String(data.action_id), tool: String(data.tool), arguments: JSON.stringify(data.arguments?.[String(data.tool)] ?? {}) }];
792
+ return { kind: "paused", pause: { actionId: String(data.action_id), actions, text } };
793
+ }
794
+ case "turn.completed":
795
+ return { kind: "completed", text: completedText(text, data), usage: data.usage };
796
+ case "turn.failed": {
797
+ const output = data.output;
798
+ throw new CencoriRunError(output?.error ?? "The turn failed.", { code: "turn_failed", sessionId });
799
+ }
800
+ case "error": {
801
+ const err = data.error ?? data;
802
+ throw new CencoriRunError(err.message ?? "The turn failed.", { code: err.code, sessionId });
803
+ }
804
+ default:
805
+ break;
806
+ }
807
+ }
808
+ throw new CencoriRunError("The turn ended without a result.", { code: "stream_ended", sessionId });
809
+ }
810
+ async function* runLoop(startAgent, input, options) {
811
+ const transport = new Transport(options);
812
+ const agents = collectAgents(startAgent);
813
+ const maxTurns = options.maxTurns ?? DEFAULT_MAX_TURNS;
814
+ const items = [];
815
+ const contextFor = (agent2, sessionId2) => {
816
+ const ctx = {
817
+ context: options.context,
818
+ sessionId: sessionId2,
819
+ agentName: agent2.name,
820
+ signal: options.signal
821
+ };
822
+ Object.defineProperty(ctx, "__runOptions", { value: options, enumerable: false });
823
+ return ctx;
824
+ };
825
+ const nextFor = async (agent2, sessionId2) => ({
826
+ instructions: await agent2.resolveInstructions(contextFor(agent2, sessionId2)) ?? "",
827
+ model: agent2.model,
828
+ tools: wireTools(agent2),
829
+ metadata: { sdk: "cencori/agents", agent: agent2.name }
830
+ });
831
+ let agent;
832
+ let sessionId;
833
+ let turnsUsed;
834
+ let usage;
835
+ let response;
836
+ let pending;
837
+ let resumedState;
838
+ if (input instanceof RunState) {
839
+ resumedState = input;
840
+ const found = agents.get(input.agentName);
841
+ if (!found) throw new AgentsError(`The run state belongs to agent "${input.agentName}", which isn't reachable from "${startAgent.name}".`);
842
+ agent = found;
843
+ sessionId = input.sessionId;
844
+ turnsUsed = input.turnsUsed;
845
+ usage = input.usage;
846
+ pending = input.pending;
847
+ } else {
848
+ agent = startAgent;
849
+ turnsUsed = 0;
850
+ usage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
851
+ sessionId = options.sessionId ?? "";
852
+ const runContext = contextFor(agent, sessionId);
853
+ for (const guardrail of agent.inputGuardrails) {
854
+ const verdict = await guardrail.execute({ input, agent, runContext });
855
+ if (verdict.tripwireTriggered) throw new GuardrailTripwireTriggered("input", guardrail.name, verdict.outputInfo);
856
+ }
857
+ yield { type: "agent_updated", agent };
858
+ turnsUsed++;
859
+ const firstTools = wireTools(agent);
860
+ const firstTurn = {
861
+ input,
862
+ model: agent.model,
863
+ instructions: await agent.resolveInstructions(runContext),
864
+ tools: firstTools.length ? firstTools : void 0,
865
+ ...agent.outputType ? { response_format: { type: "json_schema", json_schema: { name: "final_output", schema: toJsonSchema(agent.outputType) } } } : {},
866
+ ...agent.modelSettings.temperature !== void 0 ? { temperature: agent.modelSettings.temperature } : {},
867
+ ...agent.modelSettings.maxTokens !== void 0 ? { max_output_tokens: agent.modelSettings.maxTokens } : {},
868
+ ...agent.modelSettings.reasoningEffort ? { reasoning_effort: agent.modelSettings.reasoningEffort } : {},
869
+ ...options.memory ? { memory: options.memory } : {},
870
+ ...options.user ? { user: options.user } : {},
871
+ ...agent.widgets ? { widgets: true } : {},
872
+ metadata: { sdk: "cencori/agents", agent: agent.name }
873
+ };
874
+ if (sessionId) {
875
+ response = await transport.turn(sessionId, firstTurn);
876
+ } else {
877
+ const created = await transport.createSessionWithTurn({
878
+ ...options.metadata ?? {},
879
+ sdk: "cencori/agents",
880
+ agent: startAgent.name
881
+ }, firstTurn);
882
+ sessionId = created.sessionId;
883
+ response = created.response;
884
+ }
885
+ }
886
+ while (true) {
887
+ if (response) {
888
+ const outcome = yield* consumeTurn(response, agent.name, sessionId, items);
889
+ response = void 0;
890
+ if (outcome.kind === "completed") {
891
+ usage = addUsage(usage, outcome.usage);
892
+ let finalOutput = outcome.text;
893
+ if (agent.outputType) {
894
+ let parsed;
895
+ try {
896
+ parsed = JSON.parse(outcome.text);
897
+ } catch {
898
+ throw new CencoriRunError(`${agent.name} did not return valid JSON for its outputType.`, { code: "invalid_output", sessionId });
899
+ }
900
+ finalOutput = await validate(agent.outputType, parsed, `${agent.name}'s output`);
901
+ }
902
+ items.push({ type: "message", agentName: agent.name, text: outcome.text });
903
+ const runContext2 = contextFor(agent, sessionId);
904
+ for (const guardrail of agent.outputGuardrails) {
905
+ const verdict = await guardrail.execute({ output: finalOutput, agent, runContext: runContext2 });
906
+ if (verdict.tripwireTriggered) throw new GuardrailTripwireTriggered("output", guardrail.name, verdict.outputInfo);
907
+ }
908
+ return { finalOutput, sessionId, lastAgent: agent, interruptions: [], state: void 0, newItems: items, usage };
909
+ }
910
+ pending = outcome.pause;
911
+ if (outcome.pause.text) items.push({ type: "message", agentName: agent.name, text: outcome.pause.text });
912
+ for (const action of outcome.pause.actions) {
913
+ items.push({ type: "tool_call", agentName: agent.name, callId: action.action_id, toolName: action.tool, arguments: action.arguments });
914
+ yield { type: "tool_call", callId: action.action_id, toolName: action.tool, arguments: action.arguments, agentName: agent.name };
915
+ }
916
+ }
917
+ if (!pending) throw new AgentsError("Nothing to continue.");
918
+ const runContext = contextFor(agent, sessionId);
919
+ const toolsByName = new Map(agent.tools.map((t) => [t.name, t]));
920
+ const handoffsByName = new Map(agent.handoffs.map((a) => [Agent.handoffToolName(a), a]));
921
+ const interruptions = [];
922
+ for (const action of pending.actions) {
923
+ const t = toolsByName.get(action.tool);
924
+ if (!t || resumedState?.decision(action.action_id)) continue;
925
+ let needs = action.needs_approval === true || t.needsApproval === true;
926
+ if (!needs && typeof t.needsApproval === "function") {
927
+ try {
928
+ needs = await t.needsApproval(runContext, await t.parseArguments(action.arguments), action.action_id);
929
+ } catch {
930
+ needs = false;
931
+ }
932
+ }
933
+ if (needs) {
934
+ interruptions.push({ type: "tool_approval", callId: action.action_id, toolName: action.tool, arguments: action.arguments, agentName: agent.name });
935
+ }
936
+ }
937
+ if (interruptions.length > 0) {
938
+ const state = new RunState({ sessionId, agentName: agent.name, turnsUsed, usage, pending });
939
+ yield { type: "interruption", interruptions };
940
+ return { finalOutput: void 0, sessionId, lastAgent: agent, interruptions, state, newItems: items, usage };
941
+ }
942
+ if (turnsUsed >= maxTurns) throw new MaxTurnsExceededError(maxTurns, sessionId);
943
+ let handoffTo;
944
+ const results = await Promise.all(pending.actions.map(async (action) => {
945
+ const target = handoffsByName.get(action.tool);
946
+ if (target) {
947
+ if (handoffTo && handoffTo !== target) {
948
+ return { action, output: `Not transferred: the conversation already went to ${handoffTo.name}.` };
949
+ }
950
+ handoffTo = target;
951
+ return { action, output: `Transferred to ${target.name}. You are now ${target.name}; continue the conversation.` };
952
+ }
953
+ const decision = resumedState?.decision(action.action_id);
954
+ if (decision && !decision.approved) {
955
+ return { action, output: `The user rejected this call${decision.message ? `: ${decision.message}` : "."} Don't retry it.` };
956
+ }
957
+ const t = toolsByName.get(action.tool);
958
+ if (!t) return { action, output: `Error: there is no tool named ${action.tool}.` };
959
+ return { action, output: await t.invoke(runContext, action.arguments, action.action_id) };
960
+ }));
961
+ for (const result of results) {
962
+ const { action } = result;
963
+ if (handoffsByName.has(action.tool)) continue;
964
+ const shown = toolWidget(result.output);
965
+ if (shown) {
966
+ result.output = shown.modelOutput;
967
+ items.push({ type: "widget", agentName: agent.name, callId: action.action_id, widgetId: shown.widgetId, widget: shown.widget });
968
+ yield { type: "widget", callId: action.action_id, widgetId: shown.widgetId, widget: shown.widget, agentName: agent.name };
969
+ }
970
+ const output = result.output;
971
+ items.push({ type: "tool_output", agentName: agent.name, callId: action.action_id, toolName: action.tool, output });
972
+ yield { type: "tool_output", callId: action.action_id, toolName: action.tool, output, agentName: agent.name };
973
+ }
974
+ let next;
975
+ if (handoffTo) {
976
+ const from = agent.name;
977
+ agent = handoffTo;
978
+ next = await nextFor(agent, sessionId);
979
+ items.push({ type: "handoff", from, to: agent.name });
980
+ yield { type: "handoff", from, to: agent.name };
981
+ yield { type: "agent_updated", agent };
982
+ }
983
+ turnsUsed++;
984
+ resumedState = void 0;
985
+ response = await transport.resume(
986
+ sessionId,
987
+ pending.actionId,
988
+ results.map(({ action, output }) => ({ action_id: action.action_id, output })),
989
+ next
990
+ );
991
+ pending = void 0;
992
+ }
993
+ }
994
+ function run(agent, input, options = {}) {
995
+ if (options.stream) return streamed(agent, input, options);
996
+ return (async () => {
997
+ const loop = runLoop(agent, input, options);
998
+ while (true) {
999
+ const step = await loop.next();
1000
+ if (step.done) return step.value;
1001
+ }
1002
+ })();
1003
+ }
1004
+ function streamed(agent, input, options) {
1005
+ const loop = runLoop(agent, input, options);
1006
+ let resolve;
1007
+ let reject;
1008
+ const completed = new Promise((res, rej) => {
1009
+ resolve = res;
1010
+ reject = rej;
1011
+ });
1012
+ completed.catch(() => {
1013
+ });
1014
+ let started = false;
1015
+ const events = async function* () {
1016
+ if (started) throw new AgentsError("A streamed run can be iterated once.");
1017
+ started = true;
1018
+ try {
1019
+ while (true) {
1020
+ const step = await loop.next();
1021
+ if (step.done) {
1022
+ resolve(step.value);
1023
+ return;
1024
+ }
1025
+ yield step.value;
1026
+ }
1027
+ } catch (error) {
1028
+ reject(error);
1029
+ throw error;
1030
+ }
1031
+ };
1032
+ let iterator;
1033
+ return {
1034
+ [Symbol.asyncIterator]() {
1035
+ iterator ?? (iterator = events());
1036
+ return iterator;
1037
+ },
1038
+ get completed() {
1039
+ if (!started) {
1040
+ void (async () => {
1041
+ try {
1042
+ for await (const _event of this) {
1043
+ }
1044
+ } catch {
1045
+ }
1046
+ })();
1047
+ }
1048
+ return completed;
1049
+ },
1050
+ async *toTextStream() {
1051
+ for await (const event of this) {
1052
+ if (event.type === "text_delta") yield event.delta;
1053
+ }
1054
+ }
1055
+ };
1056
+ }
1057
+ var RunState, DEFAULT_MAX_TURNS;
1058
+ var init_run = __esm({
1059
+ "src/agents-sdk/run.ts"() {
1060
+ "use strict";
1061
+ init_spec();
1062
+ init_agent();
1063
+ init_errors();
1064
+ init_schema();
1065
+ init_transport();
1066
+ RunState = class _RunState {
1067
+ /** @internal */
1068
+ constructor(init) {
1069
+ this.sessionId = init.sessionId;
1070
+ this.agentName = init.agentName;
1071
+ this.turnsUsed = init.turnsUsed;
1072
+ this.usage = init.usage;
1073
+ this.pending = init.pending;
1074
+ this.decisions = new Map(Object.entries(init.decisions ?? {}));
1075
+ }
1076
+ approve(item) {
1077
+ this.decisions.set(typeof item === "string" ? item : item.callId, { approved: true });
1078
+ }
1079
+ /** The model is told the call was rejected, with your message if given. */
1080
+ reject(item, options = {}) {
1081
+ this.decisions.set(typeof item === "string" ? item : item.callId, { approved: false, message: options.message });
1082
+ }
1083
+ /** @internal */
1084
+ decision(callId) {
1085
+ return this.decisions.get(callId);
1086
+ }
1087
+ toJSON() {
1088
+ return {
1089
+ v: 1,
1090
+ sessionId: this.sessionId,
1091
+ agentName: this.agentName,
1092
+ turnsUsed: this.turnsUsed,
1093
+ usage: this.usage,
1094
+ pending: this.pending,
1095
+ decisions: Object.fromEntries(this.decisions)
1096
+ };
1097
+ }
1098
+ static fromJSON(json2) {
1099
+ const data = typeof json2 === "string" ? JSON.parse(json2) : json2;
1100
+ if (data?.v !== 1 || !data.sessionId || !data.pending) throw new AgentsError("Not a cencori/agents run state.");
1101
+ return new _RunState(data);
1102
+ }
1103
+ };
1104
+ DEFAULT_MAX_TURNS = 10;
1105
+ }
1106
+ });
1107
+
1108
+ // src/agents-sdk/agent.ts
1109
+ function toolSafe(name) {
1110
+ const safe = name.toLowerCase().replace(/[^a-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "");
1111
+ return safe || "agent";
1112
+ }
1113
+ var DEFAULT_MODEL, Agent;
1114
+ var init_agent = __esm({
1115
+ "src/agents-sdk/agent.ts"() {
1116
+ "use strict";
1117
+ init_tool();
1118
+ DEFAULT_MODEL = "gpt-oss-120b";
1119
+ Agent = class _Agent {
1120
+ constructor(options) {
1121
+ if (!options.name?.trim()) throw new TypeError("An agent needs a name.");
1122
+ if (options.model !== void 0 && !options.model.trim()) throw new TypeError(`Agent "${options.name}" needs a model.`);
1123
+ this.name = options.name;
1124
+ this.instructions = options.instructions;
1125
+ this.model = options.model ?? DEFAULT_MODEL;
1126
+ this.tools = options.tools ?? [];
1127
+ this.handoffs = options.handoffs ?? [];
1128
+ this.handoffDescription = options.handoffDescription;
1129
+ this.outputType = options.outputType;
1130
+ this.modelSettings = options.modelSettings ?? {};
1131
+ this.inputGuardrails = options.inputGuardrails ?? [];
1132
+ this.outputGuardrails = options.outputGuardrails ?? [];
1133
+ this.widgets = options.widgets ?? false;
1134
+ const names = /* @__PURE__ */ new Set();
1135
+ for (const t of [...this.tools.map((t2) => t2.name), ...this.handoffs.map((a) => _Agent.handoffToolName(a))]) {
1136
+ if (names.has(t)) throw new TypeError(`Agent "${this.name}" has two tools named "${t}".`);
1137
+ names.add(t);
1138
+ }
1139
+ }
1140
+ /** A copy with some options changed. */
1141
+ clone(overrides) {
1142
+ return new _Agent({
1143
+ name: this.name,
1144
+ instructions: this.instructions,
1145
+ model: this.model,
1146
+ tools: this.tools,
1147
+ handoffs: this.handoffs,
1148
+ handoffDescription: this.handoffDescription,
1149
+ outputType: this.outputType,
1150
+ modelSettings: this.modelSettings,
1151
+ inputGuardrails: this.inputGuardrails,
1152
+ outputGuardrails: this.outputGuardrails,
1153
+ widgets: this.widgets,
1154
+ ...overrides
1155
+ });
1156
+ }
1157
+ /** The tool name a handoff to this agent goes by. */
1158
+ static handoffToolName(agent) {
1159
+ const name = `transfer_to_${toolSafe(agent.name)}`.slice(0, 64);
1160
+ if (!TOOL_NAME_PATTERN.test(name)) throw new TypeError(`Can't make a handoff tool name for "${agent.name}".`);
1161
+ return name;
1162
+ }
1163
+ /** Instructions for this run, resolving a function if given. */
1164
+ async resolveInstructions(runContext) {
1165
+ if (typeof this.instructions === "function") return this.instructions(runContext);
1166
+ return this.instructions;
1167
+ }
1168
+ /**
1169
+ * Use this agent as a tool of another: it runs on its own (in its own
1170
+ * session) and returns its final answer, while the calling agent keeps the
1171
+ * conversation. Compare handoffs, where this agent would take it over.
1172
+ */
1173
+ asTool(options = {}) {
1174
+ const agent = this;
1175
+ return tool({
1176
+ name: options.toolName ?? toolSafe(this.name).slice(0, 64),
1177
+ description: options.toolDescription ?? this.handoffDescription ?? `Ask the ${this.name} agent.`,
1178
+ parameters: {
1179
+ type: "object",
1180
+ properties: { input: { type: "string", description: `What to ask ${this.name}.` } },
1181
+ required: ["input"],
1182
+ additionalProperties: false
1183
+ },
1184
+ async execute(args, runContext) {
1185
+ const { run: run2 } = await Promise.resolve().then(() => (init_run(), run_exports));
1186
+ const { input } = args;
1187
+ const inherited = runContext.__runOptions;
1188
+ const result = await run2(agent, input, {
1189
+ // Same transport as the calling run: key, endpoint and any custom fetch.
1190
+ apiKey: inherited?.apiKey,
1191
+ baseUrl: inherited?.baseUrl,
1192
+ fetch: inherited?.fetch,
1193
+ user: inherited?.user,
1194
+ ...options.runOptions,
1195
+ context: runContext.context,
1196
+ signal: runContext.signal,
1197
+ metadata: { parent_session_id: runContext.sessionId, ...inherited?.metadata ?? {} }
1198
+ });
1199
+ return result.finalOutput;
1200
+ }
1201
+ });
1202
+ }
1203
+ };
1204
+ }
1205
+ });
1206
+
1207
+ // src/agents-sdk/index.ts
1208
+ var agents_sdk_exports = {};
1209
+ __export(agents_sdk_exports, {
1210
+ Agent: () => Agent,
1211
+ AgentsError: () => AgentsError,
1212
+ CencoriRunError: () => CencoriRunError,
1213
+ DEFAULT_MODEL: () => DEFAULT_MODEL,
1214
+ GuardrailTripwireTriggered: () => GuardrailTripwireTriggered,
1215
+ MaxTurnsExceededError: () => MaxTurnsExceededError,
1216
+ RunState: () => RunState,
1217
+ SchemaValidationError: () => SchemaValidationError,
1218
+ WIDGET_TYPES: () => WIDGET_TYPES,
1219
+ createAgentChatHandler: () => createAgentChatHandler,
1220
+ isWidgetResult: () => isWidgetResult,
1221
+ run: () => run,
1222
+ toAgentChatStream: () => toAgentChatStream,
1223
+ tool: () => tool,
1224
+ validateWidget: () => validateWidget
1225
+ });
1226
+ module.exports = __toCommonJS(agents_sdk_exports);
1227
+ init_agent();
1228
+ init_tool();
1229
+ init_run();
1230
+ init_errors();
1231
+ init_schema();
1232
+
1233
+ // src/agents-sdk/chat.ts
1234
+ init_errors();
1235
+ init_run();
1236
+
1237
+ // src/agent-chat/protocol.ts
1238
+ init_transport();
1239
+ function formatWidgetAction(action) {
1240
+ const payload = action.payload && Object.keys(action.payload).length > 0 ? ` ${JSON.stringify(action.payload)}` : "";
1241
+ const label = action.label ? ` ("${action.label}")` : "";
1242
+ return `[The user used the widget${label}: action "${action.type}"${payload}]`;
1243
+ }
1244
+ function encodeAgentChatEvent(e2) {
1245
+ return `event: ${e2.event}
1246
+ data: ${JSON.stringify(e2.data)}
1247
+
1248
+ `;
1249
+ }
1250
+
1251
+ // src/agents-sdk/chat.ts
1252
+ var MAX_MESSAGE = 32e3;
1253
+ function createAgentChatHandler(agent, options = {}) {
1254
+ const { context, user, authorizeSession, secret, ...runOptions } = options;
1255
+ return async (req2) => {
1256
+ let body;
1257
+ try {
1258
+ body = await req2.json();
1259
+ } catch {
1260
+ return json(400, "The request body must be JSON.");
1261
+ }
1262
+ const signingKey = secret ?? env2("CENCORI_AGENT_CHAT_SECRET") ?? runOptions.apiKey ?? env2("CENCORI_API_KEY");
1263
+ if (!signingKey) return json(500, "Set CENCORI_API_KEY (or pass secret) to serve an agent chat.");
1264
+ let input;
1265
+ let sessionId;
1266
+ if (body.approval) {
1267
+ const verified = await verifyState(body.approval.state, signingKey);
1268
+ if (!verified) return json(400, "The approval state is not valid.");
1269
+ const state = RunState.fromJSON(verified);
1270
+ for (const [callId, decision] of Object.entries(body.approval.decisions ?? {})) {
1271
+ if (decision?.approved) state.approve(callId);
1272
+ else state.reject(callId, { message: typeof decision?.message === "string" ? decision.message.slice(0, 500) : void 0 });
1273
+ }
1274
+ input = state;
1275
+ sessionId = state.sessionId;
1276
+ } else {
1277
+ const text = typeof body.message === "string" && body.message.trim() ? body.message : body.action && typeof body.action.type === "string" ? formatWidgetAction(body.action) : "";
1278
+ if (!text) return json(400, "Send a message, an action or an approval.");
1279
+ if (text.length > MAX_MESSAGE) return json(413, "The message is too long.");
1280
+ input = text;
1281
+ sessionId = typeof body.sessionId === "string" && body.sessionId ? body.sessionId : void 0;
1282
+ }
1283
+ if (sessionId && authorizeSession && !await authorizeSession(sessionId, req2)) {
1284
+ return json(403, "This conversation belongs to someone else.");
1285
+ }
1286
+ const streamed2 = run(agent, input, {
1287
+ ...runOptions,
1288
+ stream: true,
1289
+ ...sessionId && typeof input === "string" ? { sessionId } : {},
1290
+ context: context ? await context(req2) : void 0,
1291
+ user: user ? await user(req2) : void 0,
1292
+ signal: req2.signal
1293
+ });
1294
+ return new Response(toAgentChatStream(streamed2, { secret: signingKey }), {
1295
+ headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache, no-transform", Connection: "keep-alive" }
1296
+ });
1297
+ };
1298
+ }
1299
+ function toAgentChatStream(streamed2, options) {
1300
+ const encoder = new TextEncoder();
1301
+ return new ReadableStream({
1302
+ async start(controller) {
1303
+ const send = (e2) => controller.enqueue(encoder.encode(encodeAgentChatEvent(e2)));
1304
+ try {
1305
+ for await (const e2 of streamed2) {
1306
+ switch (e2.type) {
1307
+ case "agent_updated":
1308
+ send({ event: "agent", data: { name: e2.agent.name } });
1309
+ break;
1310
+ case "text_delta":
1311
+ send({ event: "text", data: { delta: e2.delta, agent: e2.agentName } });
1312
+ break;
1313
+ case "tool_call":
1314
+ send({ event: "tool_call", data: { callId: e2.callId, name: e2.toolName, arguments: e2.arguments, agent: e2.agentName } });
1315
+ break;
1316
+ case "tool_output":
1317
+ send({ event: "tool_output", data: { callId: e2.callId, name: e2.toolName, output: e2.output, agent: e2.agentName } });
1318
+ break;
1319
+ case "widget":
1320
+ send({ event: "widget", data: { id: e2.widgetId, callId: e2.callId, widget: e2.widget, agent: e2.agentName } });
1321
+ break;
1322
+ case "handoff":
1323
+ send({ event: "handoff", data: { from: e2.from, to: e2.to } });
1324
+ break;
1325
+ case "interruption":
1326
+ break;
1327
+ }
1328
+ }
1329
+ const result = await streamed2.completed;
1330
+ if (result.state) {
1331
+ send({
1332
+ event: "approval",
1333
+ data: {
1334
+ sessionId: result.sessionId,
1335
+ state: await signState(JSON.stringify(result.state), options.secret),
1336
+ items: result.interruptions.map((i) => ({ callId: i.callId, toolName: i.toolName, arguments: i.arguments, agentName: i.agentName }))
1337
+ }
1338
+ });
1339
+ } else {
1340
+ send({ event: "done", data: { sessionId: result.sessionId } });
1341
+ }
1342
+ } catch (error) {
1343
+ const message = error instanceof GuardrailTripwireTriggered ? "That request was blocked." : error instanceof Error ? error.message : "The agent failed.";
1344
+ const code = error?.code ?? (error instanceof AgentsError ? error.name : void 0);
1345
+ send({ event: "error", data: { message, ...code ? { code } : {} } });
1346
+ } finally {
1347
+ controller.close();
1348
+ }
1349
+ }
1350
+ });
1351
+ }
1352
+ var b64url = (bytes2) => {
1353
+ let s = "";
1354
+ for (const b of bytes2) s += String.fromCharCode(b);
1355
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1356
+ };
1357
+ var fromB64url = (s) => {
1358
+ const bin = atob(s.replace(/-/g, "+").replace(/_/g, "/"));
1359
+ return Uint8Array.from(bin, (c) => c.charCodeAt(0));
1360
+ };
1361
+ async function hmac(data, secret) {
1362
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(`cencori-agent-chat:${secret}`), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
1363
+ return new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(data)));
1364
+ }
1365
+ async function signState(json2, secret) {
1366
+ const payload = b64url(new TextEncoder().encode(json2));
1367
+ return `${payload}.${b64url(await hmac(payload, secret))}`;
1368
+ }
1369
+ async function verifyState(token, secret) {
1370
+ if (typeof token !== "string" || token.length > 512e3) return null;
1371
+ const [payload, signature] = token.split(".");
1372
+ if (!payload || !signature) return null;
1373
+ const expected = await hmac(payload, secret);
1374
+ let given;
1375
+ try {
1376
+ given = fromB64url(signature);
1377
+ } catch {
1378
+ return null;
1379
+ }
1380
+ if (given.length !== expected.length) return null;
1381
+ let diff = 0;
1382
+ for (let i = 0; i < given.length; i++) diff |= given[i] ^ expected[i];
1383
+ if (diff !== 0) return null;
1384
+ try {
1385
+ return new TextDecoder().decode(fromB64url(payload));
1386
+ } catch {
1387
+ return null;
1388
+ }
1389
+ }
1390
+ function json(status, message) {
1391
+ return new Response(JSON.stringify({ error: { message } }), { status, headers: { "Content-Type": "application/json" } });
1392
+ }
1393
+ function env2(name) {
1394
+ try {
1395
+ return typeof process !== "undefined" ? process.env?.[name] : void 0;
1396
+ } catch {
1397
+ return void 0;
1398
+ }
1399
+ }
1400
+
1401
+ // src/agents-sdk/index.ts
1402
+ init_spec();
1403
+ // Annotate the CommonJS export names for ESM import in node:
1404
+ 0 && (module.exports = {
1405
+ Agent,
1406
+ AgentsError,
1407
+ CencoriRunError,
1408
+ DEFAULT_MODEL,
1409
+ GuardrailTripwireTriggered,
1410
+ MaxTurnsExceededError,
1411
+ RunState,
1412
+ SchemaValidationError,
1413
+ WIDGET_TYPES,
1414
+ createAgentChatHandler,
1415
+ isWidgetResult,
1416
+ run,
1417
+ toAgentChatStream,
1418
+ tool,
1419
+ validateWidget
1420
+ });
1421
+ //# sourceMappingURL=index.js.map