cencori 1.11.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- import { W as WidgetNode } from '../protocol-T2jhccPz.mjs';
2
- export { b as AgentChatApprovalItem, c as AgentChatDecision, A as AgentChatEvent, a as AgentChatRequest, B as BadgeNode, r as ButtonNode, C as CardNode, o as ChartNode, n as ChartSeries, w as CheckboxNode, k as ColNode, D as DividerNode, F as FormNode, I as ImageNode, s as InputNode, L as ListViewItem, j as ListViewNode, M as MarkdownNode, y as RenderedWidget, R as RowNode, u as SelectNode, t as SelectOption, S as SpacerNode, m as StatNode, p as TableColumn, q as TableNode, T as TextNode, l as TitleNode, z as WIDGET_LIMITS, d as WIDGET_TYPES, h as WidgetAction, e as WidgetColor, f as WidgetFormat, g as WidgetGap, x as WidgetType, E as WidgetValidation, G as describeWidgetSpec, i as isWidgetResult, v as validateWidget } from '../protocol-T2jhccPz.mjs';
1
+ import { W as WidgetNode } from '../protocol-Dq7rZbRX.mjs';
2
+ export { b as AgentChatApprovalItem, c as AgentChatDecision, A as AgentChatEvent, a as AgentChatRequest, B as BadgeNode, r as ButtonNode, C as CardNode, o as ChartNode, n as ChartSeries, w as CheckboxNode, k as ColNode, D as DividerNode, F as FormNode, I as ImageNode, s as InputNode, L as ListViewItem, j as ListViewNode, M as MarkdownNode, y as RenderedWidget, R as RowNode, u as SelectNode, t as SelectOption, S as SpacerNode, m as StatNode, p as TableColumn, q as TableNode, T as TextNode, l as TitleNode, z as WIDGET_LIMITS, d as WIDGET_TYPES, h as WidgetAction, e as WidgetColor, f as WidgetFormat, g as WidgetGap, x as WidgetType, E as WidgetValidation, G as describeWidgetSpec, i as isWidgetResult, v as validateWidget } from '../protocol-Dq7rZbRX.mjs';
3
3
 
4
4
  /** What tools, guardrails and dynamic instructions receive during a run. */
5
5
  interface RunContext<Ctx = unknown> {
@@ -225,6 +225,13 @@ type RunStreamEvent = {
225
225
  widgetId: string;
226
226
  widget: WidgetNode;
227
227
  agentName: string;
228
+ }
229
+ /** A widget the model is still writing (render_ui): draw it, then replace it with the 'widget' for the same callId. */
230
+ | {
231
+ type: 'widget_partial';
232
+ callId: string;
233
+ widget: WidgetNode;
234
+ agentName: string;
228
235
  } | {
229
236
  type: 'interruption';
230
237
  interruptions: ToolApprovalItem[];
@@ -377,6 +384,12 @@ interface AgentOptions<Ctx = unknown, Out = string> {
377
384
  * `{ widget }` whether or not this is on.
378
385
  */
379
386
  widgets?: boolean;
387
+ /**
388
+ * Run an agent stored in Cencori (POST /v1/agents, or the console) by its
389
+ * id: its model, instructions and stored tools apply, and any `tools` you
390
+ * add here run in your process on top. Usually set with Agent.fromCencori().
391
+ */
392
+ cencoriAgentId?: string;
380
393
  }
381
394
  /** The model an agent uses when none is given: GPT OSS 120B on Cerebras, chosen for speed. */
382
395
  declare const DEFAULT_MODEL = "gpt-oss-120b";
@@ -405,9 +418,23 @@ declare class Agent<Ctx = unknown, Out = string> {
405
418
  readonly inputGuardrails: InputGuardrail<Ctx>[];
406
419
  readonly outputGuardrails: OutputGuardrail<Ctx>[];
407
420
  readonly widgets: boolean;
421
+ readonly cencoriAgentId?: string;
408
422
  constructor(options: AgentOptions<Ctx, Out>);
409
423
  /** A copy with some options changed. */
410
424
  clone(overrides: Partial<AgentOptions<Ctx, Out>>): Agent<Ctx, Out>;
425
+ /**
426
+ * An agent stored in Cencori, run by id. Its model, instructions, stored
427
+ * tools and widgets setting come from Cencori; add local tools, guardrails
428
+ * or handoffs here as for any agent.
429
+ *
430
+ * ```ts
431
+ * const support = Agent.fromCencori('agent_123', { tools: [lookupOrder] });
432
+ * await run(support, 'Where is order 1042?');
433
+ * ```
434
+ */
435
+ static fromCencori<Ctx = unknown>(agentId: string, options?: Omit<AgentOptions<Ctx, string>, 'cencoriAgentId' | 'name'> & {
436
+ name?: string;
437
+ }): Agent<Ctx, string>;
411
438
  /** The tool name a handoff to this agent goes by. */
412
439
  static handoffToolName(agent: Agent<any>): string;
413
440
  /** Instructions for this run, resolving a function if given. */
@@ -1,5 +1,5 @@
1
- import { W as WidgetNode } from '../protocol-T2jhccPz.js';
2
- export { b as AgentChatApprovalItem, c as AgentChatDecision, A as AgentChatEvent, a as AgentChatRequest, B as BadgeNode, r as ButtonNode, C as CardNode, o as ChartNode, n as ChartSeries, w as CheckboxNode, k as ColNode, D as DividerNode, F as FormNode, I as ImageNode, s as InputNode, L as ListViewItem, j as ListViewNode, M as MarkdownNode, y as RenderedWidget, R as RowNode, u as SelectNode, t as SelectOption, S as SpacerNode, m as StatNode, p as TableColumn, q as TableNode, T as TextNode, l as TitleNode, z as WIDGET_LIMITS, d as WIDGET_TYPES, h as WidgetAction, e as WidgetColor, f as WidgetFormat, g as WidgetGap, x as WidgetType, E as WidgetValidation, G as describeWidgetSpec, i as isWidgetResult, v as validateWidget } from '../protocol-T2jhccPz.js';
1
+ import { W as WidgetNode } from '../protocol-Dq7rZbRX.js';
2
+ export { b as AgentChatApprovalItem, c as AgentChatDecision, A as AgentChatEvent, a as AgentChatRequest, B as BadgeNode, r as ButtonNode, C as CardNode, o as ChartNode, n as ChartSeries, w as CheckboxNode, k as ColNode, D as DividerNode, F as FormNode, I as ImageNode, s as InputNode, L as ListViewItem, j as ListViewNode, M as MarkdownNode, y as RenderedWidget, R as RowNode, u as SelectNode, t as SelectOption, S as SpacerNode, m as StatNode, p as TableColumn, q as TableNode, T as TextNode, l as TitleNode, z as WIDGET_LIMITS, d as WIDGET_TYPES, h as WidgetAction, e as WidgetColor, f as WidgetFormat, g as WidgetGap, x as WidgetType, E as WidgetValidation, G as describeWidgetSpec, i as isWidgetResult, v as validateWidget } from '../protocol-Dq7rZbRX.js';
3
3
 
4
4
  /** What tools, guardrails and dynamic instructions receive during a run. */
5
5
  interface RunContext<Ctx = unknown> {
@@ -225,6 +225,13 @@ type RunStreamEvent = {
225
225
  widgetId: string;
226
226
  widget: WidgetNode;
227
227
  agentName: string;
228
+ }
229
+ /** A widget the model is still writing (render_ui): draw it, then replace it with the 'widget' for the same callId. */
230
+ | {
231
+ type: 'widget_partial';
232
+ callId: string;
233
+ widget: WidgetNode;
234
+ agentName: string;
228
235
  } | {
229
236
  type: 'interruption';
230
237
  interruptions: ToolApprovalItem[];
@@ -377,6 +384,12 @@ interface AgentOptions<Ctx = unknown, Out = string> {
377
384
  * `{ widget }` whether or not this is on.
378
385
  */
379
386
  widgets?: boolean;
387
+ /**
388
+ * Run an agent stored in Cencori (POST /v1/agents, or the console) by its
389
+ * id: its model, instructions and stored tools apply, and any `tools` you
390
+ * add here run in your process on top. Usually set with Agent.fromCencori().
391
+ */
392
+ cencoriAgentId?: string;
380
393
  }
381
394
  /** The model an agent uses when none is given: GPT OSS 120B on Cerebras, chosen for speed. */
382
395
  declare const DEFAULT_MODEL = "gpt-oss-120b";
@@ -405,9 +418,23 @@ declare class Agent<Ctx = unknown, Out = string> {
405
418
  readonly inputGuardrails: InputGuardrail<Ctx>[];
406
419
  readonly outputGuardrails: OutputGuardrail<Ctx>[];
407
420
  readonly widgets: boolean;
421
+ readonly cencoriAgentId?: string;
408
422
  constructor(options: AgentOptions<Ctx, Out>);
409
423
  /** A copy with some options changed. */
410
424
  clone(overrides: Partial<AgentOptions<Ctx, Out>>): Agent<Ctx, Out>;
425
+ /**
426
+ * An agent stored in Cencori, run by id. Its model, instructions, stored
427
+ * tools and widgets setting come from Cencori; add local tools, guardrails
428
+ * or handoffs here as for any agent.
429
+ *
430
+ * ```ts
431
+ * const support = Agent.fromCencori('agent_123', { tools: [lookupOrder] });
432
+ * await run(support, 'Where is order 1042?');
433
+ * ```
434
+ */
435
+ static fromCencori<Ctx = unknown>(agentId: string, options?: Omit<AgentOptions<Ctx, string>, 'cencoriAgentId' | 'name'> & {
436
+ name?: string;
437
+ }): Agent<Ctx, string>;
411
438
  /** The tool name a handoff to this agent goes by. */
412
439
  static handoffToolName(agent: Agent<any>): string;
413
440
  /** Instructions for this run, resolving a function if given. */
@@ -497,6 +497,185 @@ var init_spec = __esm({
497
497
  }
498
498
  });
499
499
 
500
+ // src/widgets/partial.ts
501
+ function parsePartialJson(text) {
502
+ const stack = [];
503
+ let safe = 0;
504
+ let safeStack = "";
505
+ let inString = false;
506
+ let stringIsKey = false;
507
+ let escaped = false;
508
+ let tokenStart = -1;
509
+ const frames = () => stack.map((f) => f.t).join("");
510
+ const markSafe = (end) => {
511
+ safe = end;
512
+ safeStack = frames();
513
+ };
514
+ const valueDone = (end) => {
515
+ const top = stack[stack.length - 1];
516
+ if (top) top.expect = "comma";
517
+ markSafe(end);
518
+ };
519
+ let i = 0;
520
+ for (; i < text.length; i++) {
521
+ const c = text[i];
522
+ if (inString) {
523
+ if (escaped) escaped = false;
524
+ else if (c === "\\") escaped = true;
525
+ else if (c === '"') {
526
+ inString = false;
527
+ if (stringIsKey) stack[stack.length - 1].expect = "colon";
528
+ else valueDone(i + 1);
529
+ }
530
+ continue;
531
+ }
532
+ if (tokenStart !== -1 && !/[-+0-9.eEtruefalsn]/.test(c)) {
533
+ if (isCompleteLiteral(text.slice(tokenStart, i))) valueDone(i);
534
+ tokenStart = -1;
535
+ }
536
+ switch (c) {
537
+ case "{":
538
+ stack.push({ t: "o", expect: "key" });
539
+ markSafe(i + 1);
540
+ break;
541
+ case "[":
542
+ stack.push({ t: "a", expect: "value" });
543
+ markSafe(i + 1);
544
+ break;
545
+ case "}":
546
+ case "]":
547
+ stack.pop();
548
+ valueDone(i + 1);
549
+ break;
550
+ case '"': {
551
+ const top = stack[stack.length - 1];
552
+ inString = true;
553
+ stringIsKey = Boolean(top && top.t === "o" && top.expect === "key");
554
+ break;
555
+ }
556
+ case ":":
557
+ if (stack.length) stack[stack.length - 1].expect = "value";
558
+ break;
559
+ case ",":
560
+ if (stack.length) stack[stack.length - 1].expect = stack[stack.length - 1].t === "o" ? "key" : "value";
561
+ break;
562
+ default:
563
+ if (tokenStart === -1 && /[-0-9tfn]/.test(c)) tokenStart = i;
564
+ }
565
+ }
566
+ let candidate;
567
+ if (inString && !stringIsKey) {
568
+ const body = text.replace(/\\u[0-9a-fA-F]{0,3}$|\\$/, "");
569
+ candidate = `${body}"${close(frames())}`;
570
+ } else if (tokenStart !== -1 && isCompleteLiteral(text.slice(tokenStart)) && !/[.eE+-]$/.test(text)) {
571
+ const top = stack[stack.length - 1];
572
+ if (top) top.expect = "comma";
573
+ candidate = `${text}${close(frames())}`;
574
+ } else {
575
+ candidate = `${text.slice(0, safe)}${close(safeStack)}`;
576
+ }
577
+ if (!candidate.trim()) return void 0;
578
+ try {
579
+ return JSON.parse(candidate);
580
+ } catch {
581
+ try {
582
+ return JSON.parse(`${text.slice(0, safe)}${close(safeStack)}`);
583
+ } catch {
584
+ return void 0;
585
+ }
586
+ }
587
+ }
588
+ function isCompleteLiteral(token) {
589
+ return token === "true" || token === "false" || token === "null" || /^-?\d+(\.\d+)?([eE][-+]?\d+)?$/.test(token);
590
+ }
591
+ function close(frames) {
592
+ let out = "";
593
+ for (let i = frames.length - 1; i >= 0; i--) out += frames[i] === "o" ? "}" : "]";
594
+ return out;
595
+ }
596
+ function partialWidget(raw, depth = 0) {
597
+ if (depth > 12 || !raw || typeof raw !== "object" || Array.isArray(raw)) return null;
598
+ const node = { ...raw };
599
+ const type = node.type;
600
+ if (typeof type !== "string" || !KNOWN.has(type)) return null;
601
+ if (type === "Image") return null;
602
+ for (const key of ARRAY_PROPS) {
603
+ if (key in node || requiresArray(type, key)) {
604
+ node[key] = Array.isArray(node[key]) ? node[key] : [];
605
+ }
606
+ }
607
+ for (const key of STRING_PROPS[type] ?? []) {
608
+ if (typeof node[key] !== "string") node[key] = "";
609
+ }
610
+ if (type === "Stat" && typeof node.value !== "number" && typeof node.value !== "string") node.value = "";
611
+ for (const key of ["children", "actions"]) {
612
+ if (Array.isArray(node[key])) node[key] = node[key].map((c) => partialWidget(c, depth + 1)).filter(Boolean);
613
+ }
614
+ for (const key of ["items", "options", "series", "columns", "rows", "data"]) {
615
+ if (Array.isArray(node[key])) node[key] = node[key].filter((v) => v && typeof v === "object" && !Array.isArray(v));
616
+ }
617
+ if (type === "ListView") {
618
+ node.items = node.items.map(({ action: _a, image, ...it }) => ({
619
+ ...it,
620
+ title: typeof it.title === "string" ? it.title : "",
621
+ ...typeof image === "string" && /^https:\/\/\S+\.\S+/.test(image) ? { image } : {}
622
+ }));
623
+ }
624
+ if (type === "Chart" || type === "Table") {
625
+ const keyed = type === "Chart" ? "series" : "columns";
626
+ node[keyed] = node[keyed].filter((s) => typeof s.key === "string");
627
+ }
628
+ delete node.action;
629
+ delete node.href;
630
+ return node;
631
+ }
632
+ function requiresArray(type, key) {
633
+ switch (type) {
634
+ case "Card":
635
+ case "Row":
636
+ case "Col":
637
+ case "Form":
638
+ return key === "children";
639
+ case "ListView":
640
+ return key === "items";
641
+ case "Select":
642
+ return key === "options";
643
+ case "Chart":
644
+ return key === "series" || key === "data";
645
+ case "Table":
646
+ return key === "columns" || key === "rows";
647
+ default:
648
+ return false;
649
+ }
650
+ }
651
+ function partialRenderUiWidget(argumentsSoFar) {
652
+ const parsed = parsePartialJson(argumentsSoFar);
653
+ if (!parsed || typeof parsed !== "object") return null;
654
+ const raw = "widget" in parsed ? parsed.widget : parsed;
655
+ return partialWidget(raw);
656
+ }
657
+ var KNOWN, ARRAY_PROPS, STRING_PROPS;
658
+ var init_partial = __esm({
659
+ "src/widgets/partial.ts"() {
660
+ "use strict";
661
+ init_spec();
662
+ KNOWN = new Set(WIDGET_TYPES);
663
+ ARRAY_PROPS = ["children", "actions", "items", "options", "series", "columns", "rows", "data"];
664
+ STRING_PROPS = {
665
+ Text: ["value"],
666
+ Title: ["value"],
667
+ Markdown: ["value"],
668
+ Badge: ["label"],
669
+ Stat: ["label"],
670
+ Button: ["label"],
671
+ Input: ["name"],
672
+ Select: ["name"],
673
+ Checkbox: ["name", "label"],
674
+ Chart: ["x"]
675
+ };
676
+ }
677
+ });
678
+
500
679
  // src/agents-sdk/errors.ts
501
680
  var AgentsError, MaxTurnsExceededError, GuardrailTripwireTriggered, CencoriRunError;
502
681
  var init_errors = __esm({
@@ -648,7 +827,7 @@ var init_transport = __esm({
648
827
  * predate this answer with the plain session JSON; the turn then goes in a
649
828
  * second request, as before.
650
829
  */
651
- async createSessionWithTurn(metadata, body) {
830
+ async createSessionWithTurn(metadata, body, agentId) {
652
831
  const turn = { ...body, stream: true, pause_on_tool_calls: true };
653
832
  const response = await this.fetchImpl(`${this.baseUrl}/v1/sessions`, {
654
833
  method: "POST",
@@ -657,7 +836,7 @@ var init_transport = __esm({
657
836
  "Content-Type": "application/json",
658
837
  "Accept": "text/event-stream, application/json"
659
838
  },
660
- body: JSON.stringify({ metadata, turn }),
839
+ body: JSON.stringify({ metadata, turn, ...agentId ? { agent_id: agentId } : {} }),
661
840
  signal: this.signal
662
841
  });
663
842
  const headerId = response.headers.get("X-Cencori-Session-Id") ?? void 0;
@@ -769,8 +948,25 @@ function completedText(streamed2, data) {
769
948
  }
770
949
  async function* consumeTurn(response, agentName, sessionId, items) {
771
950
  let text = "";
951
+ const writing = /* @__PURE__ */ new Map();
772
952
  for await (const { event, data } of readSessionEvents(response)) {
773
953
  switch (event) {
954
+ case "tool_call.delta": {
955
+ if (data.tool !== "render_ui" || typeof data.delta !== "string") break;
956
+ const callId = String(data.action_id ?? "");
957
+ const w = writing.get(callId) ?? { args: "", drawnAt: 0, drawn: "" };
958
+ w.args += data.delta;
959
+ writing.set(callId, w);
960
+ const now = Date.now();
961
+ if (now - w.drawnAt < 50) break;
962
+ const partial = partialRenderUiWidget(w.args);
963
+ const key = partial ? JSON.stringify(partial) : "";
964
+ if (!partial || key === w.drawn) break;
965
+ w.drawnAt = now;
966
+ w.drawn = key;
967
+ yield { type: "widget_partial", callId, widget: partial, agentName };
968
+ break;
969
+ }
774
970
  case "output_text.delta": {
775
971
  const delta = typeof data.delta === "string" ? data.delta : "";
776
972
  if (delta) {
@@ -822,7 +1018,13 @@ async function* runLoop(startAgent, input, options) {
822
1018
  Object.defineProperty(ctx, "__runOptions", { value: options, enumerable: false });
823
1019
  return ctx;
824
1020
  };
825
- const nextFor = async (agent2, sessionId2) => ({
1021
+ const nextFor = async (agent2, sessionId2) => {
1022
+ if (agent2.cencoriAgentId) {
1023
+ throw new AgentsError(`"${agent2.name}" is stored in Cencori and can't be a handoff target yet. Use ${agent2.name}.asTool() instead.`);
1024
+ }
1025
+ return nextForLocal(agent2, sessionId2);
1026
+ };
1027
+ const nextForLocal = async (agent2, sessionId2) => ({
826
1028
  instructions: await agent2.resolveInstructions(contextFor(agent2, sessionId2)) ?? "",
827
1029
  model: agent2.model,
828
1030
  tools: wireTools(agent2),
@@ -878,7 +1080,7 @@ async function* runLoop(startAgent, input, options) {
878
1080
  ...options.metadata ?? {},
879
1081
  sdk: "cencori/agents",
880
1082
  agent: startAgent.name
881
- }, firstTurn);
1083
+ }, firstTurn, agent.cencoriAgentId);
882
1084
  sessionId = created.sessionId;
883
1085
  response = created.response;
884
1086
  }
@@ -1059,6 +1261,7 @@ var init_run = __esm({
1059
1261
  "src/agents-sdk/run.ts"() {
1060
1262
  "use strict";
1061
1263
  init_spec();
1264
+ init_partial();
1062
1265
  init_agent();
1063
1266
  init_errors();
1064
1267
  init_schema();
@@ -1131,6 +1334,7 @@ var init_agent = __esm({
1131
1334
  this.inputGuardrails = options.inputGuardrails ?? [];
1132
1335
  this.outputGuardrails = options.outputGuardrails ?? [];
1133
1336
  this.widgets = options.widgets ?? false;
1337
+ this.cencoriAgentId = options.cencoriAgentId;
1134
1338
  const names = /* @__PURE__ */ new Set();
1135
1339
  for (const t of [...this.tools.map((t2) => t2.name), ...this.handoffs.map((a) => _Agent.handoffToolName(a))]) {
1136
1340
  if (names.has(t)) throw new TypeError(`Agent "${this.name}" has two tools named "${t}".`);
@@ -1151,9 +1355,24 @@ var init_agent = __esm({
1151
1355
  inputGuardrails: this.inputGuardrails,
1152
1356
  outputGuardrails: this.outputGuardrails,
1153
1357
  widgets: this.widgets,
1358
+ cencoriAgentId: this.cencoriAgentId,
1154
1359
  ...overrides
1155
1360
  });
1156
1361
  }
1362
+ /**
1363
+ * An agent stored in Cencori, run by id. Its model, instructions, stored
1364
+ * tools and widgets setting come from Cencori; add local tools, guardrails
1365
+ * or handoffs here as for any agent.
1366
+ *
1367
+ * ```ts
1368
+ * const support = Agent.fromCencori('agent_123', { tools: [lookupOrder] });
1369
+ * await run(support, 'Where is order 1042?');
1370
+ * ```
1371
+ */
1372
+ static fromCencori(agentId, options = {}) {
1373
+ if (!agentId || typeof agentId !== "string") throw new TypeError("Agent.fromCencori needs the stored agent's id.");
1374
+ return new _Agent({ ...options, name: options.name ?? "Agent", cencoriAgentId: agentId });
1375
+ }
1157
1376
  /** The tool name a handoff to this agent goes by. */
1158
1377
  static handoffToolName(agent) {
1159
1378
  const name = `transfer_to_${toolSafe(agent.name)}`.slice(0, 64);
@@ -1319,6 +1538,9 @@ function toAgentChatStream(streamed2, options) {
1319
1538
  case "widget":
1320
1539
  send({ event: "widget", data: { id: e2.widgetId, callId: e2.callId, widget: e2.widget, agent: e2.agentName } });
1321
1540
  break;
1541
+ case "widget_partial":
1542
+ send({ event: "widget_partial", data: { callId: e2.callId, widget: e2.widget, agent: e2.agentName } });
1543
+ break;
1322
1544
  case "handoff":
1323
1545
  send({ event: "handoff", data: { from: e2.from, to: e2.to } });
1324
1546
  break;