cencori 1.10.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.
@@ -26,24 +26,24 @@ function isStandard(schema) {
26
26
  }
27
27
  function toJsonSchema(schema) {
28
28
  if (!schema) return { type: "object", properties: {}, additionalProperties: false };
29
- let json;
29
+ let json2;
30
30
  if (isStandard(schema)) {
31
31
  const std = schema["~standard"];
32
32
  if (std.jsonSchema) {
33
- json = std.jsonSchema.input({ target: "draft-2020-12" });
33
+ json2 = std.jsonSchema.input({ target: "draft-2020-12" });
34
34
  } else if (typeof schema.toJSONSchema === "function") {
35
- json = schema.toJSONSchema();
35
+ json2 = schema.toJSONSchema();
36
36
  } else if (std.vendor === "zod" && schema._def?.typeName) {
37
- json = zod3ToJsonSchema(schema);
37
+ json2 = zod3ToJsonSchema(schema);
38
38
  } else {
39
39
  throw new TypeError(
40
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
41
  );
42
42
  }
43
43
  } else {
44
- json = schema;
44
+ json2 = schema;
45
45
  }
46
- const { $schema: _ignored, ...rest } = json;
46
+ const { $schema: _ignored, ...rest } = json2;
47
47
  return rest;
48
48
  }
49
49
  async function validate(schema, value, what) {
@@ -59,7 +59,7 @@ async function validate(schema, value, what) {
59
59
  }
60
60
  function zod3ToJsonSchema(schema) {
61
61
  const def = schema._def;
62
- const describe = (json) => def.description ? { ...json, description: def.description } : json;
62
+ const describe = (json2) => def.description ? { ...json2, description: def.description } : json2;
63
63
  switch (def.typeName) {
64
64
  case "ZodString":
65
65
  return describe({ type: "string" });
@@ -198,6 +198,305 @@ var init_tool = __esm({
198
198
  }
199
199
  });
200
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
+
201
500
  // src/agents-sdk/errors.ts
202
501
  var AgentsError, MaxTurnsExceededError, GuardrailTripwireTriggered, CencoriRunError;
203
502
  var init_errors = __esm({
@@ -392,6 +691,29 @@ __export(run_exports, {
392
691
  RunState: () => RunState,
393
692
  run: () => run
394
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
+ }
395
717
  function collectAgents(start) {
396
718
  const seen = /* @__PURE__ */ new Map();
397
719
  const visit = (agent) => {
@@ -445,7 +767,7 @@ function completedText(streamed2, data) {
445
767
  }
446
768
  return text;
447
769
  }
448
- async function* consumeTurn(response, agentName, sessionId) {
770
+ async function* consumeTurn(response, agentName, sessionId, items) {
449
771
  let text = "";
450
772
  for await (const { event, data } of readSessionEvents(response)) {
451
773
  switch (event) {
@@ -457,6 +779,14 @@ async function* consumeTurn(response, agentName, sessionId) {
457
779
  }
458
780
  break;
459
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
+ }
460
790
  case "turn.paused": {
461
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)] ?? {}) }];
462
792
  return { kind: "paused", pause: { actionId: String(data.action_id), actions, text } };
@@ -495,7 +825,8 @@ async function* runLoop(startAgent, input, options) {
495
825
  const nextFor = async (agent2, sessionId2) => ({
496
826
  instructions: await agent2.resolveInstructions(contextFor(agent2, sessionId2)) ?? "",
497
827
  model: agent2.model,
498
- tools: wireTools(agent2)
828
+ tools: wireTools(agent2),
829
+ metadata: { sdk: "cencori/agents", agent: agent2.name }
499
830
  });
500
831
  let agent;
501
832
  let sessionId;
@@ -537,6 +868,7 @@ async function* runLoop(startAgent, input, options) {
537
868
  ...agent.modelSettings.reasoningEffort ? { reasoning_effort: agent.modelSettings.reasoningEffort } : {},
538
869
  ...options.memory ? { memory: options.memory } : {},
539
870
  ...options.user ? { user: options.user } : {},
871
+ ...agent.widgets ? { widgets: true } : {},
540
872
  metadata: { sdk: "cencori/agents", agent: agent.name }
541
873
  };
542
874
  if (sessionId) {
@@ -553,7 +885,7 @@ async function* runLoop(startAgent, input, options) {
553
885
  }
554
886
  while (true) {
555
887
  if (response) {
556
- const outcome = yield* consumeTurn(response, agent.name, sessionId);
888
+ const outcome = yield* consumeTurn(response, agent.name, sessionId, items);
557
889
  response = void 0;
558
890
  if (outcome.kind === "completed") {
559
891
  usage = addUsage(usage, outcome.usage);
@@ -626,8 +958,16 @@ async function* runLoop(startAgent, input, options) {
626
958
  if (!t) return { action, output: `Error: there is no tool named ${action.tool}.` };
627
959
  return { action, output: await t.invoke(runContext, action.arguments, action.action_id) };
628
960
  }));
629
- for (const { action, output } of results) {
961
+ for (const result of results) {
962
+ const { action } = result;
630
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;
631
971
  items.push({ type: "tool_output", agentName: agent.name, callId: action.action_id, toolName: action.tool, output });
632
972
  yield { type: "tool_output", callId: action.action_id, toolName: action.tool, output, agentName: agent.name };
633
973
  }
@@ -718,6 +1058,7 @@ var RunState, DEFAULT_MAX_TURNS;
718
1058
  var init_run = __esm({
719
1059
  "src/agents-sdk/run.ts"() {
720
1060
  "use strict";
1061
+ init_spec();
721
1062
  init_agent();
722
1063
  init_errors();
723
1064
  init_schema();
@@ -754,8 +1095,8 @@ var init_run = __esm({
754
1095
  decisions: Object.fromEntries(this.decisions)
755
1096
  };
756
1097
  }
757
- static fromJSON(json) {
758
- const data = typeof json === "string" ? JSON.parse(json) : json;
1098
+ static fromJSON(json2) {
1099
+ const data = typeof json2 === "string" ? JSON.parse(json2) : json2;
759
1100
  if (data?.v !== 1 || !data.sessionId || !data.pending) throw new AgentsError("Not a cencori/agents run state.");
760
1101
  return new _RunState(data);
761
1102
  }
@@ -789,6 +1130,7 @@ var init_agent = __esm({
789
1130
  this.modelSettings = options.modelSettings ?? {};
790
1131
  this.inputGuardrails = options.inputGuardrails ?? [];
791
1132
  this.outputGuardrails = options.outputGuardrails ?? [];
1133
+ this.widgets = options.widgets ?? false;
792
1134
  const names = /* @__PURE__ */ new Set();
793
1135
  for (const t of [...this.tools.map((t2) => t2.name), ...this.handoffs.map((a) => _Agent.handoffToolName(a))]) {
794
1136
  if (names.has(t)) throw new TypeError(`Agent "${this.name}" has two tools named "${t}".`);
@@ -808,6 +1150,7 @@ var init_agent = __esm({
808
1150
  modelSettings: this.modelSettings,
809
1151
  inputGuardrails: this.inputGuardrails,
810
1152
  outputGuardrails: this.outputGuardrails,
1153
+ widgets: this.widgets,
811
1154
  ...overrides
812
1155
  });
813
1156
  }
@@ -872,8 +1215,13 @@ __export(agents_sdk_exports, {
872
1215
  MaxTurnsExceededError: () => MaxTurnsExceededError,
873
1216
  RunState: () => RunState,
874
1217
  SchemaValidationError: () => SchemaValidationError,
1218
+ WIDGET_TYPES: () => WIDGET_TYPES,
1219
+ createAgentChatHandler: () => createAgentChatHandler,
1220
+ isWidgetResult: () => isWidgetResult,
875
1221
  run: () => run,
876
- tool: () => tool
1222
+ toAgentChatStream: () => toAgentChatStream,
1223
+ tool: () => tool,
1224
+ validateWidget: () => validateWidget
877
1225
  });
878
1226
  module.exports = __toCommonJS(agents_sdk_exports);
879
1227
  init_agent();
@@ -881,6 +1229,177 @@ init_tool();
881
1229
  init_run();
882
1230
  init_errors();
883
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();
884
1403
  // Annotate the CommonJS export names for ESM import in node:
885
1404
  0 && (module.exports = {
886
1405
  Agent,
@@ -891,7 +1410,12 @@ init_schema();
891
1410
  MaxTurnsExceededError,
892
1411
  RunState,
893
1412
  SchemaValidationError,
1413
+ WIDGET_TYPES,
1414
+ createAgentChatHandler,
1415
+ isWidgetResult,
894
1416
  run,
895
- tool
1417
+ toAgentChatStream,
1418
+ tool,
1419
+ validateWidget
896
1420
  });
897
1421
  //# sourceMappingURL=index.js.map