cencori 1.12.1 → 1.14.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,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __esm = (fn, res) => function __init() {
7
9
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
@@ -18,6 +20,14 @@ var __copyProps = (to, from, except, desc) => {
18
20
  }
19
21
  return to;
20
22
  };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
21
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
22
32
 
23
33
  // src/agents-sdk/schema.ts
@@ -198,6 +208,304 @@ var init_tool = __esm({
198
208
  }
199
209
  });
200
210
 
211
+ // src/agents-sdk/errors.ts
212
+ var AgentsError, MaxTurnsExceededError, GuardrailTripwireTriggered, CencoriRunError;
213
+ var init_errors = __esm({
214
+ "src/agents-sdk/errors.ts"() {
215
+ "use strict";
216
+ AgentsError = class extends Error {
217
+ constructor(message) {
218
+ super(message);
219
+ this.name = "AgentsError";
220
+ }
221
+ };
222
+ MaxTurnsExceededError = class extends AgentsError {
223
+ constructor(maxTurns, sessionId) {
224
+ super(`The run exceeded maxTurns (${maxTurns}) without a final answer. Raise maxTurns or check for a tool loop.`);
225
+ this.name = "MaxTurnsExceededError";
226
+ this.sessionId = sessionId;
227
+ }
228
+ };
229
+ GuardrailTripwireTriggered = class extends AgentsError {
230
+ constructor(kind, guardrail, outputInfo) {
231
+ super(`${kind === "input" ? "Input" : "Output"} guardrail "${guardrail}" tripped.`);
232
+ this.name = kind === "input" ? "InputGuardrailTripwireTriggered" : "OutputGuardrailTripwireTriggered";
233
+ this.guardrail = guardrail;
234
+ this.kind = kind;
235
+ this.outputInfo = outputInfo;
236
+ }
237
+ };
238
+ CencoriRunError = class extends AgentsError {
239
+ constructor(message, details = {}) {
240
+ super(message);
241
+ this.name = "CencoriRunError";
242
+ this.status = details.status;
243
+ this.code = details.code;
244
+ this.sessionId = details.sessionId;
245
+ }
246
+ };
247
+ }
248
+ });
249
+
250
+ // src/agents-sdk/mcp.ts
251
+ function fromEventStream(text, id) {
252
+ let fallback = null;
253
+ for (const block of text.split(/\r?\n\r?\n/)) {
254
+ const data = block.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trim()).join("\n");
255
+ if (!data) continue;
256
+ try {
257
+ const message = JSON.parse(data);
258
+ if (message.id === id) return message;
259
+ if ("result" in message || "error" in message) fallback ?? (fallback = message);
260
+ } catch {
261
+ }
262
+ }
263
+ if (fallback) return fallback;
264
+ throw new RpcError("MCP response stream carried no result");
265
+ }
266
+ function legacyOnly(error) {
267
+ if (!(error instanceof RpcError)) return false;
268
+ if (error.httpStatus && [400, 404, 405, 501].includes(error.httpStatus)) return true;
269
+ return error.code === -32601 || error.code === -32600 || error.code === -32022;
270
+ }
271
+ function safeHost(url) {
272
+ try {
273
+ return new URL(url).hostname.split(".").slice(-2, -1)[0] || "mcp";
274
+ } catch {
275
+ return "mcp";
276
+ }
277
+ }
278
+ function mcpResultText(result) {
279
+ if (result?.structuredContent !== void 0 && !(result.content ?? []).some((c) => c.type === "text")) {
280
+ return JSON.stringify(result.structuredContent);
281
+ }
282
+ const parts = (result?.content ?? []).map((c) => {
283
+ if (c.type === "text" && typeof c.text === "string") return c.text;
284
+ if (c.type === "resource" && c.resource && typeof c.resource.text === "string") return c.resource.text;
285
+ return `[${c.type} content]`;
286
+ });
287
+ const text = parts.join("\n") || (result?.structuredContent !== void 0 ? JSON.stringify(result.structuredContent) : "");
288
+ return result?.isError ? `Error: ${text || "the tool failed."}` : text;
289
+ }
290
+ function mcpNeedsApproval(server, tool2) {
291
+ const rule = server.options.requireApproval;
292
+ if (rule === false) return false;
293
+ if (rule === true) return true;
294
+ if (Array.isArray(rule)) return rule.includes(tool2.name);
295
+ if (typeof rule === "function") return rule(tool2);
296
+ return tool2.annotations?.destructiveHint === true;
297
+ }
298
+ var MODERN_PROTOCOL, LEGACY_PROTOCOL, CLIENT_INFO, RpcError, nextId, MCPServerStreamableHttp, MCPServerStdio;
299
+ var init_mcp = __esm({
300
+ "src/agents-sdk/mcp.ts"() {
301
+ "use strict";
302
+ init_errors();
303
+ MODERN_PROTOCOL = "2026-07-28";
304
+ LEGACY_PROTOCOL = "2025-11-25";
305
+ CLIENT_INFO = { name: "cencori-agents", version: "1" };
306
+ RpcError = class extends Error {
307
+ constructor(message, code, httpStatus) {
308
+ super(message);
309
+ this.code = code;
310
+ this.httpStatus = httpStatus;
311
+ }
312
+ };
313
+ nextId = 1;
314
+ MCPServerStreamableHttp = class {
315
+ constructor(options) {
316
+ this.mode = null;
317
+ this.sessionHeaders = null;
318
+ this.tools = null;
319
+ if (!options?.url) throw new TypeError("MCPServerStreamableHttp needs a url.");
320
+ this.options = options;
321
+ this.name = options.name ?? safeHost(options.url);
322
+ }
323
+ async connect() {
324
+ await this.listTools();
325
+ }
326
+ async listTools() {
327
+ if (this.tools && this.options.cacheToolsList !== false) return this.tools;
328
+ const result = await this.request("tools/list", {});
329
+ this.tools = Array.isArray(result?.tools) ? result.tools : [];
330
+ return this.tools;
331
+ }
332
+ async callTool(name, args) {
333
+ return await this.request("tools/call", { name, arguments: args }, name);
334
+ }
335
+ async close() {
336
+ const session = this.sessionHeaders?.["mcp-session-id"];
337
+ this.mode = null;
338
+ this.sessionHeaders = null;
339
+ if (session) {
340
+ await (this.options.fetch ?? fetch)(this.options.url, { method: "DELETE", headers: { ...this.options.headers, "mcp-session-id": session } }).catch(() => {
341
+ });
342
+ }
343
+ }
344
+ async request(method, params, toolName) {
345
+ if (this.mode !== "legacy") {
346
+ try {
347
+ const result = await this.post(
348
+ { ...this.options.headers, "MCP-Protocol-Version": MODERN_PROTOCOL, "Mcp-Method": method, ...toolName ? { "Mcp-Name": toolName } : {} },
349
+ method,
350
+ { ...params, _meta: { "io.modelcontextprotocol/clientInfo": CLIENT_INFO } }
351
+ );
352
+ this.mode = "modern";
353
+ return result.result;
354
+ } catch (error) {
355
+ if (this.mode === "modern" || !legacyOnly(error)) throw error;
356
+ }
357
+ }
358
+ if (!this.sessionHeaders) await this.handshake();
359
+ try {
360
+ return (await this.post(this.sessionHeaders, method, params)).result;
361
+ } catch (error) {
362
+ if (error instanceof RpcError && error.httpStatus === 404) {
363
+ await this.handshake();
364
+ return (await this.post(this.sessionHeaders, method, params)).result;
365
+ }
366
+ throw error;
367
+ }
368
+ }
369
+ async handshake() {
370
+ const base = { ...this.options.headers };
371
+ const { result, headers } = await this.post(base, "initialize", { protocolVersion: LEGACY_PROTOCOL, capabilities: {}, clientInfo: CLIENT_INFO });
372
+ const info = result ?? {};
373
+ const session = headers.get("mcp-session-id") ?? info.sessionId;
374
+ this.sessionHeaders = { ...base, "MCP-Protocol-Version": info.protocolVersion ?? LEGACY_PROTOCOL, ...session ? { "mcp-session-id": session } : {} };
375
+ this.mode = "legacy";
376
+ await this.post(this.sessionHeaders, "notifications/initialized", {}, true).catch(() => {
377
+ });
378
+ }
379
+ async post(headers, method, params, notification = false) {
380
+ const id = nextId++;
381
+ const res = await (this.options.fetch ?? fetch)(this.options.url, {
382
+ method: "POST",
383
+ headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream", ...headers },
384
+ body: JSON.stringify(notification ? { jsonrpc: "2.0", method, params } : { jsonrpc: "2.0", id, method, params }),
385
+ signal: AbortSignal.timeout(this.options.timeoutMs ?? 3e4)
386
+ });
387
+ if (!res.ok) {
388
+ const text2 = await res.text().catch(() => "");
389
+ throw new RpcError(`MCP ${method} failed (${res.status}): ${text2.slice(0, 300)}`, void 0, res.status);
390
+ }
391
+ if (notification || res.status === 202) return { result: void 0, headers: res.headers };
392
+ const text = await res.text();
393
+ const message = (res.headers.get("content-type") ?? "").includes("text/event-stream") ? fromEventStream(text, id) : JSON.parse(text);
394
+ if (message.error) throw new RpcError(`MCP ${method}: ${message.error.message ?? "error"}`, message.error.code);
395
+ return { result: message.result, headers: res.headers };
396
+ }
397
+ };
398
+ MCPServerStdio = class {
399
+ constructor(options) {
400
+ this.child = null;
401
+ this.starting = null;
402
+ this.pending = /* @__PURE__ */ new Map();
403
+ this.tools = null;
404
+ this.stderr = "";
405
+ if (!options?.command) throw new TypeError("MCPServerStdio needs a command.");
406
+ this.options = options;
407
+ this.name = options.name ?? (options.args?.find((a) => !a.startsWith("-")) ?? options.command).split("/").pop().replace(/^@[^/]*\//, "");
408
+ }
409
+ connect() {
410
+ this.starting ?? (this.starting = this.start());
411
+ return this.starting;
412
+ }
413
+ async listTools() {
414
+ if (this.tools && this.options.cacheToolsList !== false) return this.tools;
415
+ await this.connect();
416
+ const result = await this.request("tools/list", {});
417
+ this.tools = Array.isArray(result?.tools) ? result.tools : [];
418
+ return this.tools;
419
+ }
420
+ async callTool(name, args) {
421
+ await this.connect();
422
+ return await this.request("tools/call", { name, arguments: args });
423
+ }
424
+ async close() {
425
+ for (const p of this.pending.values()) {
426
+ clearTimeout(p.timer);
427
+ p.reject(new AgentsError(`MCP server ${this.name} closed.`));
428
+ }
429
+ this.pending.clear();
430
+ try {
431
+ this.child?.stdin.end();
432
+ this.child?.kill();
433
+ } catch {
434
+ }
435
+ this.child = null;
436
+ this.starting = null;
437
+ }
438
+ async start() {
439
+ let spawn;
440
+ try {
441
+ ({ spawn } = await import("child_process"));
442
+ } catch {
443
+ throw new AgentsError("MCPServerStdio needs Node.js. In other runtimes use MCPServerStreamableHttp.");
444
+ }
445
+ const child = spawn(this.options.command, this.options.args ?? [], {
446
+ cwd: this.options.cwd,
447
+ env: { ...process.env, ...this.options.env },
448
+ stdio: ["pipe", "pipe", "pipe"]
449
+ });
450
+ this.child = child;
451
+ let buffer = "";
452
+ child.stdout.setEncoding("utf8");
453
+ child.stdout.on("data", (chunk) => {
454
+ buffer += chunk;
455
+ let nl;
456
+ while ((nl = buffer.indexOf("\n")) !== -1) {
457
+ const line = buffer.slice(0, nl).trim();
458
+ buffer = buffer.slice(nl + 1);
459
+ if (!line) continue;
460
+ try {
461
+ const message = JSON.parse(line);
462
+ const waiter = typeof message.id === "number" ? this.pending.get(message.id) : void 0;
463
+ if (!waiter) continue;
464
+ clearTimeout(waiter.timer);
465
+ this.pending.delete(message.id);
466
+ if (message.error) waiter.reject(new AgentsError(`MCP ${this.name}: ${message.error.message ?? "error"}`));
467
+ else waiter.resolve(message.result);
468
+ } catch {
469
+ }
470
+ }
471
+ });
472
+ child.stderr.setEncoding("utf8");
473
+ child.stderr.on("data", (chunk) => {
474
+ this.stderr = (this.stderr + chunk).slice(-2e3);
475
+ });
476
+ const failAll = (why) => {
477
+ for (const p of this.pending.values()) {
478
+ clearTimeout(p.timer);
479
+ p.reject(new AgentsError(why));
480
+ }
481
+ this.pending.clear();
482
+ this.child = null;
483
+ this.starting = null;
484
+ };
485
+ child.on("error", (e2) => failAll(`MCP server ${this.name} didn't start: ${e2.message}`));
486
+ child.on("exit", (code) => failAll(`MCP server ${this.name} exited (${code ?? "signal"})${this.stderr ? `: ${this.stderr.trim().slice(-300)}` : ""}`));
487
+ await this.request("initialize", { protocolVersion: LEGACY_PROTOCOL, capabilities: {}, clientInfo: CLIENT_INFO });
488
+ this.child?.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized", params: {} })}
489
+ `);
490
+ }
491
+ request(method, params) {
492
+ const child = this.child;
493
+ if (!child) return Promise.reject(new AgentsError(`MCP server ${this.name} isn't running.`));
494
+ const id = nextId++;
495
+ return new Promise((resolve, reject) => {
496
+ const timer = setTimeout(() => {
497
+ this.pending.delete(id);
498
+ reject(new AgentsError(`MCP ${this.name} ${method} timed out.`));
499
+ }, this.options.timeoutMs ?? 3e4);
500
+ this.pending.set(id, { resolve, reject, timer });
501
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}
502
+ `);
503
+ });
504
+ }
505
+ };
506
+ }
507
+ });
508
+
201
509
  // src/widgets/spec.ts
202
510
  function safeUrl(v, images) {
203
511
  if (images && /^data:image\/(png|jpe?g|gif|webp|svg\+xml);base64,/i.test(v)) return v.length <= 2e5;
@@ -497,6 +805,236 @@ var init_spec = __esm({
497
805
  }
498
806
  });
499
807
 
808
+ // src/agents-sdk/input.ts
809
+ function inputText(input) {
810
+ if (typeof input === "string") return input;
811
+ return input.flatMap((item) => typeof item.content === "string" ? [item.content] : item.content.filter((p) => p.type === "input_text").map((p) => p.text)).join("\n");
812
+ }
813
+ function image(url, detail) {
814
+ return { type: "input_image", image_url: url, ...detail ? { detail } : {} };
815
+ }
816
+ function file(filename, data, mimeType = guessType(filename)) {
817
+ if (typeof data === "string") return { type: "input_file", filename, file_data: data };
818
+ let binary = "";
819
+ for (const b of data) binary += String.fromCharCode(b);
820
+ return { type: "input_file", filename, file_data: `data:${mimeType};base64,${btoa(binary)}` };
821
+ }
822
+ function guessType(filename) {
823
+ const ext = filename.toLowerCase().split(".").pop() ?? "";
824
+ return { pdf: "application/pdf", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp", gif: "image/gif", csv: "text/csv", json: "application/json", md: "text/markdown", txt: "text/plain" }[ext] ?? "application/octet-stream";
825
+ }
826
+ var init_input = __esm({
827
+ "src/agents-sdk/input.ts"() {
828
+ "use strict";
829
+ }
830
+ });
831
+
832
+ // src/agents-sdk/transport.ts
833
+ function env(name) {
834
+ try {
835
+ return typeof process !== "undefined" ? process.env?.[name] : void 0;
836
+ } catch {
837
+ return void 0;
838
+ }
839
+ }
840
+ async function errorFrom(response, sessionId) {
841
+ let message = `Cencori returned ${response.status}`;
842
+ let code;
843
+ try {
844
+ const body = await response.json();
845
+ if (typeof body.error === "string") message = body.error;
846
+ else if (body.error?.message) {
847
+ message = body.error.message;
848
+ code = body.error.code;
849
+ }
850
+ } catch {
851
+ }
852
+ return new CencoriRunError(message, { status: response.status, code, sessionId });
853
+ }
854
+ async function* readSessionEvents(response) {
855
+ if (!response.body) return;
856
+ const reader = response.body.getReader();
857
+ const decoder = new TextDecoder();
858
+ let buffer = "";
859
+ let event = "message";
860
+ let data = [];
861
+ const flush = () => {
862
+ if (data.length === 0) {
863
+ event = "message";
864
+ return null;
865
+ }
866
+ const raw = data.join("\n");
867
+ data = [];
868
+ const name = event;
869
+ event = "message";
870
+ try {
871
+ return { event: name, data: JSON.parse(raw) };
872
+ } catch {
873
+ return { event: name, data: { raw } };
874
+ }
875
+ };
876
+ try {
877
+ while (true) {
878
+ const { done, value } = await reader.read();
879
+ if (done) break;
880
+ buffer += decoder.decode(value, { stream: true });
881
+ let newline;
882
+ while ((newline = buffer.indexOf("\n")) >= 0) {
883
+ const line = buffer.slice(0, newline).replace(/\r$/, "");
884
+ buffer = buffer.slice(newline + 1);
885
+ if (line === "") {
886
+ const parsed = flush();
887
+ if (parsed) yield parsed;
888
+ } else if (line.startsWith("event:")) {
889
+ event = line.slice(6).trim();
890
+ } else if (line.startsWith("data:")) {
891
+ data.push(line.slice(5).replace(/^ /, ""));
892
+ }
893
+ }
894
+ }
895
+ buffer += decoder.decode();
896
+ if (buffer.trim()) {
897
+ for (const line of buffer.split("\n")) {
898
+ if (line.startsWith("event:")) event = line.slice(6).trim();
899
+ else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
900
+ }
901
+ }
902
+ const last = flush();
903
+ if (last) yield last;
904
+ } finally {
905
+ reader.releaseLock();
906
+ }
907
+ }
908
+ var DEFAULT_BASE_URL, Transport;
909
+ var init_transport = __esm({
910
+ "src/agents-sdk/transport.ts"() {
911
+ "use strict";
912
+ init_errors();
913
+ DEFAULT_BASE_URL = "https://cencori.com";
914
+ Transport = class {
915
+ constructor(options = {}) {
916
+ const apiKey = options.apiKey ?? env("CENCORI_API_KEY");
917
+ if (!apiKey) {
918
+ throw new CencoriRunError("No Cencori API key. Pass apiKey or set CENCORI_API_KEY (a secret project key, csk_...).", { code: "missing_api_key" });
919
+ }
920
+ this.apiKey = apiKey;
921
+ this.baseUrl = (options.baseUrl ?? env("CENCORI_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
922
+ this.fetchImpl = options.fetch ?? fetch;
923
+ this.signal = options.signal;
924
+ }
925
+ async post(path, body, sessionId) {
926
+ const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
927
+ method: "POST",
928
+ headers: {
929
+ "CENCORI_API_KEY": this.apiKey,
930
+ "Content-Type": "application/json",
931
+ "Accept": "text/event-stream, application/json"
932
+ },
933
+ body: JSON.stringify(body),
934
+ signal: this.signal
935
+ });
936
+ if (!response.ok) throw await errorFrom(response, sessionId);
937
+ return response;
938
+ }
939
+ /**
940
+ * Create a session and run its first turn in one request. Servers that
941
+ * predate this answer with the plain session JSON; the turn then goes in a
942
+ * second request, as before.
943
+ */
944
+ async createSessionWithTurn(metadata, body, agentId) {
945
+ const turn = { ...body, stream: true, pause_on_tool_calls: true };
946
+ const response = await this.fetchImpl(`${this.baseUrl}/v1/sessions`, {
947
+ method: "POST",
948
+ headers: {
949
+ "CENCORI_API_KEY": this.apiKey,
950
+ "Content-Type": "application/json",
951
+ "Accept": "text/event-stream, application/json"
952
+ },
953
+ body: JSON.stringify({ metadata, turn, ...agentId ? { agent_id: agentId } : {} }),
954
+ signal: this.signal
955
+ });
956
+ const headerId = response.headers.get("X-Cencori-Session-Id") ?? void 0;
957
+ if (!response.ok) throw await errorFrom(response, headerId);
958
+ if (headerId) return { sessionId: headerId, response };
959
+ const created = await response.json();
960
+ if (!created.id) throw new CencoriRunError("Cencori did not return a session id.");
961
+ return { sessionId: created.id, response: await this.turn(created.id, body) };
962
+ }
963
+ turn(sessionId, body) {
964
+ return this.post(`/v1/sessions/${encodeURIComponent(sessionId)}/turns`, {
965
+ ...body,
966
+ stream: true,
967
+ pause_on_tool_calls: true
968
+ }, sessionId);
969
+ }
970
+ /** Human handoff: hand over, reply as a person, or release (POST /v1/sessions/:id/human). */
971
+ async human(sessionId, body) {
972
+ const response = await this.post(`/v1/sessions/${encodeURIComponent(sessionId)}/human`, body, sessionId);
973
+ return response.json();
974
+ }
975
+ async humanStatus(sessionId, after) {
976
+ const query = after ? `?after=${encodeURIComponent(after)}` : "";
977
+ const response = await this.fetchImpl(`${this.baseUrl}/v1/sessions/${encodeURIComponent(sessionId)}/human${query}`, {
978
+ headers: { "CENCORI_API_KEY": this.apiKey, "Accept": "application/json" },
979
+ signal: this.signal
980
+ });
981
+ if (!response.ok) throw await errorFrom(response, sessionId);
982
+ return response.json();
983
+ }
984
+ resume(sessionId, actionId, toolResults, next) {
985
+ return this.post(`/v1/sessions/${encodeURIComponent(sessionId)}/approve`, {
986
+ action_id: actionId,
987
+ tool_results: toolResults,
988
+ ...next ? { next } : {}
989
+ }, sessionId);
990
+ }
991
+ };
992
+ }
993
+ });
994
+
995
+ // src/agents-sdk/human.ts
996
+ function humanHandoff(options = {}) {
997
+ return tool({
998
+ name: HUMAN_HANDOFF_TOOL,
999
+ description: options.description ?? "Hand this conversation to a person on the team. Use it when the user asks for a human, when they are upset, or when you can't help. Tell the user a person will reply here.",
1000
+ parameters: {
1001
+ type: "object",
1002
+ properties: { reason: { type: "string", description: "Why, in one sentence, for the person picking it up." } },
1003
+ required: ["reason"],
1004
+ additionalProperties: false
1005
+ },
1006
+ async execute(args, runContext) {
1007
+ const { reason } = args;
1008
+ const runOptions = runContext.__runOptions;
1009
+ await new Transport(runOptions ?? {}).human(runContext.sessionId, { action: "handoff", reason });
1010
+ await options.onHandoff?.({ sessionId: runContext.sessionId, reason, runContext });
1011
+ return "Handed to a person on the team. Tell the user, in one short sentence, that a person will reply here soon. Don't try to solve it yourself now.";
1012
+ }
1013
+ });
1014
+ }
1015
+ async function humanReply(sessionId, text, options = {}) {
1016
+ const body = await new Transport(options).human(sessionId, { action: "reply", text });
1017
+ if (!body.message) throw new AgentsError("The reply was not saved.");
1018
+ return body.message;
1019
+ }
1020
+ async function releaseToAgent(sessionId, options = {}) {
1021
+ await new Transport(options).human(sessionId, { action: "release" });
1022
+ }
1023
+ async function humanStatus(sessionId, options = {}) {
1024
+ const body = await new Transport(options).humanStatus(sessionId, options.after);
1025
+ return { handledBy: body.handled_by, handoff: body.handoff, messages: body.messages ?? [] };
1026
+ }
1027
+ var HUMAN_HANDOFF_TOOL;
1028
+ var init_human = __esm({
1029
+ "src/agents-sdk/human.ts"() {
1030
+ "use strict";
1031
+ init_errors();
1032
+ init_tool();
1033
+ init_transport();
1034
+ HUMAN_HANDOFF_TOOL = "handoff_to_human";
1035
+ }
1036
+ });
1037
+
500
1038
  // src/widgets/partial.ts
501
1039
  function parsePartialJson(text) {
502
1040
  const stack = [];
@@ -615,10 +1153,10 @@ function partialWidget(raw, depth = 0) {
615
1153
  if (Array.isArray(node[key])) node[key] = node[key].filter((v) => v && typeof v === "object" && !Array.isArray(v));
616
1154
  }
617
1155
  if (type === "ListView") {
618
- node.items = node.items.map(({ action: _a, image, ...it }) => ({
1156
+ node.items = node.items.map(({ action: _a, image: image2, ...it }) => ({
619
1157
  ...it,
620
1158
  title: typeof it.title === "string" ? it.title : "",
621
- ...typeof image === "string" && /^https:\/\/\S+\.\S+/.test(image) ? { image } : {}
1159
+ ...typeof image2 === "string" && /^https:\/\/\S+\.\S+/.test(image2) ? { image: image2 } : {}
622
1160
  }));
623
1161
  }
624
1162
  if (type === "Chart" || type === "Table") {
@@ -676,194 +1214,6 @@ var init_partial = __esm({
676
1214
  }
677
1215
  });
678
1216
 
679
- // src/agents-sdk/errors.ts
680
- var AgentsError, MaxTurnsExceededError, GuardrailTripwireTriggered, CencoriRunError;
681
- var init_errors = __esm({
682
- "src/agents-sdk/errors.ts"() {
683
- "use strict";
684
- AgentsError = class extends Error {
685
- constructor(message) {
686
- super(message);
687
- this.name = "AgentsError";
688
- }
689
- };
690
- MaxTurnsExceededError = class extends AgentsError {
691
- constructor(maxTurns, sessionId) {
692
- super(`The run exceeded maxTurns (${maxTurns}) without a final answer. Raise maxTurns or check for a tool loop.`);
693
- this.name = "MaxTurnsExceededError";
694
- this.sessionId = sessionId;
695
- }
696
- };
697
- GuardrailTripwireTriggered = class extends AgentsError {
698
- constructor(kind, guardrail, outputInfo) {
699
- super(`${kind === "input" ? "Input" : "Output"} guardrail "${guardrail}" tripped.`);
700
- this.name = kind === "input" ? "InputGuardrailTripwireTriggered" : "OutputGuardrailTripwireTriggered";
701
- this.guardrail = guardrail;
702
- this.kind = kind;
703
- this.outputInfo = outputInfo;
704
- }
705
- };
706
- CencoriRunError = class extends AgentsError {
707
- constructor(message, details = {}) {
708
- super(message);
709
- this.name = "CencoriRunError";
710
- this.status = details.status;
711
- this.code = details.code;
712
- this.sessionId = details.sessionId;
713
- }
714
- };
715
- }
716
- });
717
-
718
- // src/agents-sdk/transport.ts
719
- function env(name) {
720
- try {
721
- return typeof process !== "undefined" ? process.env?.[name] : void 0;
722
- } catch {
723
- return void 0;
724
- }
725
- }
726
- async function errorFrom(response, sessionId) {
727
- let message = `Cencori returned ${response.status}`;
728
- let code;
729
- try {
730
- const body = await response.json();
731
- if (typeof body.error === "string") message = body.error;
732
- else if (body.error?.message) {
733
- message = body.error.message;
734
- code = body.error.code;
735
- }
736
- } catch {
737
- }
738
- return new CencoriRunError(message, { status: response.status, code, sessionId });
739
- }
740
- async function* readSessionEvents(response) {
741
- if (!response.body) return;
742
- const reader = response.body.getReader();
743
- const decoder = new TextDecoder();
744
- let buffer = "";
745
- let event = "message";
746
- let data = [];
747
- const flush = () => {
748
- if (data.length === 0) {
749
- event = "message";
750
- return null;
751
- }
752
- const raw = data.join("\n");
753
- data = [];
754
- const name = event;
755
- event = "message";
756
- try {
757
- return { event: name, data: JSON.parse(raw) };
758
- } catch {
759
- return { event: name, data: { raw } };
760
- }
761
- };
762
- try {
763
- while (true) {
764
- const { done, value } = await reader.read();
765
- if (done) break;
766
- buffer += decoder.decode(value, { stream: true });
767
- let newline;
768
- while ((newline = buffer.indexOf("\n")) >= 0) {
769
- const line = buffer.slice(0, newline).replace(/\r$/, "");
770
- buffer = buffer.slice(newline + 1);
771
- if (line === "") {
772
- const parsed = flush();
773
- if (parsed) yield parsed;
774
- } else if (line.startsWith("event:")) {
775
- event = line.slice(6).trim();
776
- } else if (line.startsWith("data:")) {
777
- data.push(line.slice(5).replace(/^ /, ""));
778
- }
779
- }
780
- }
781
- buffer += decoder.decode();
782
- if (buffer.trim()) {
783
- for (const line of buffer.split("\n")) {
784
- if (line.startsWith("event:")) event = line.slice(6).trim();
785
- else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
786
- }
787
- }
788
- const last = flush();
789
- if (last) yield last;
790
- } finally {
791
- reader.releaseLock();
792
- }
793
- }
794
- var DEFAULT_BASE_URL, Transport;
795
- var init_transport = __esm({
796
- "src/agents-sdk/transport.ts"() {
797
- "use strict";
798
- init_errors();
799
- DEFAULT_BASE_URL = "https://cencori.com";
800
- Transport = class {
801
- constructor(options = {}) {
802
- const apiKey = options.apiKey ?? env("CENCORI_API_KEY");
803
- if (!apiKey) {
804
- throw new CencoriRunError("No Cencori API key. Pass apiKey or set CENCORI_API_KEY (a secret project key, csk_...).", { code: "missing_api_key" });
805
- }
806
- this.apiKey = apiKey;
807
- this.baseUrl = (options.baseUrl ?? env("CENCORI_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
808
- this.fetchImpl = options.fetch ?? fetch;
809
- this.signal = options.signal;
810
- }
811
- async post(path, body, sessionId) {
812
- const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
813
- method: "POST",
814
- headers: {
815
- "CENCORI_API_KEY": this.apiKey,
816
- "Content-Type": "application/json",
817
- "Accept": "text/event-stream, application/json"
818
- },
819
- body: JSON.stringify(body),
820
- signal: this.signal
821
- });
822
- if (!response.ok) throw await errorFrom(response, sessionId);
823
- return response;
824
- }
825
- /**
826
- * Create a session and run its first turn in one request. Servers that
827
- * predate this answer with the plain session JSON; the turn then goes in a
828
- * second request, as before.
829
- */
830
- async createSessionWithTurn(metadata, body, agentId) {
831
- const turn = { ...body, stream: true, pause_on_tool_calls: true };
832
- const response = await this.fetchImpl(`${this.baseUrl}/v1/sessions`, {
833
- method: "POST",
834
- headers: {
835
- "CENCORI_API_KEY": this.apiKey,
836
- "Content-Type": "application/json",
837
- "Accept": "text/event-stream, application/json"
838
- },
839
- body: JSON.stringify({ metadata, turn, ...agentId ? { agent_id: agentId } : {} }),
840
- signal: this.signal
841
- });
842
- const headerId = response.headers.get("X-Cencori-Session-Id") ?? void 0;
843
- if (!response.ok) throw await errorFrom(response, headerId);
844
- if (headerId) return { sessionId: headerId, response };
845
- const created = await response.json();
846
- if (!created.id) throw new CencoriRunError("Cencori did not return a session id.");
847
- return { sessionId: created.id, response: await this.turn(created.id, body) };
848
- }
849
- turn(sessionId, body) {
850
- return this.post(`/v1/sessions/${encodeURIComponent(sessionId)}/turns`, {
851
- ...body,
852
- stream: true,
853
- pause_on_tool_calls: true
854
- }, sessionId);
855
- }
856
- resume(sessionId, actionId, toolResults, next) {
857
- return this.post(`/v1/sessions/${encodeURIComponent(sessionId)}/approve`, {
858
- action_id: actionId,
859
- tool_results: toolResults,
860
- ...next ? { next } : {}
861
- }, sessionId);
862
- }
863
- };
864
- }
865
- });
866
-
867
1217
  // src/agents-sdk/run.ts
868
1218
  var run_exports = {};
869
1219
  __export(run_exports, {
@@ -903,8 +1253,8 @@ function collectAgents(start) {
903
1253
  visit(start);
904
1254
  return seen;
905
1255
  }
906
- function wireTools(agent) {
907
- const tools = agent.tools.map((t) => ({
1256
+ function wireTools(agent, resolved = agent.tools) {
1257
+ const tools = resolved.map((t) => ({
908
1258
  type: "function",
909
1259
  function: { name: t.name, description: t.description, parameters: t.parameters },
910
1260
  // Only an unconditional approval is the server's to hold and record; a
@@ -989,6 +1339,8 @@ async function* consumeTurn(response, agentName, sessionId, items) {
989
1339
  }
990
1340
  case "turn.completed":
991
1341
  return { kind: "completed", text: completedText(text, data), usage: data.usage };
1342
+ case "owner.handling":
1343
+ return { kind: "with_human" };
992
1344
  case "turn.failed": {
993
1345
  const output = data.output;
994
1346
  throw new CencoriRunError(output?.error ?? "The turn failed.", { code: "turn_failed", sessionId });
@@ -1024,10 +1376,19 @@ async function* runLoop(startAgent, input, options) {
1024
1376
  }
1025
1377
  return nextForLocal(agent2, sessionId2);
1026
1378
  };
1379
+ const resolvedTools = /* @__PURE__ */ new Map();
1380
+ const toolsOf = (agent2) => {
1381
+ let tools = resolvedTools.get(agent2);
1382
+ if (!tools) {
1383
+ tools = agent2.resolveTools();
1384
+ resolvedTools.set(agent2, tools);
1385
+ }
1386
+ return tools;
1387
+ };
1027
1388
  const nextForLocal = async (agent2, sessionId2) => ({
1028
1389
  instructions: await agent2.resolveInstructions(contextFor(agent2, sessionId2)) ?? "",
1029
1390
  model: agent2.model,
1030
- tools: wireTools(agent2),
1391
+ tools: wireTools(agent2, await toolsOf(agent2)),
1031
1392
  metadata: { sdk: "cencori/agents", agent: agent2.name }
1032
1393
  });
1033
1394
  let agent;
@@ -1053,12 +1414,12 @@ async function* runLoop(startAgent, input, options) {
1053
1414
  sessionId = options.sessionId ?? "";
1054
1415
  const runContext = contextFor(agent, sessionId);
1055
1416
  for (const guardrail of agent.inputGuardrails) {
1056
- const verdict = await guardrail.execute({ input, agent, runContext });
1417
+ const verdict = await guardrail.execute({ input: inputText(input), agent, runContext });
1057
1418
  if (verdict.tripwireTriggered) throw new GuardrailTripwireTriggered("input", guardrail.name, verdict.outputInfo);
1058
1419
  }
1059
1420
  yield { type: "agent_updated", agent };
1060
1421
  turnsUsed++;
1061
- const firstTools = wireTools(agent);
1422
+ const firstTools = wireTools(agent, await toolsOf(agent));
1062
1423
  const firstTurn = {
1063
1424
  input,
1064
1425
  model: agent.model,
@@ -1089,6 +1450,10 @@ async function* runLoop(startAgent, input, options) {
1089
1450
  if (response) {
1090
1451
  const outcome = yield* consumeTurn(response, agent.name, sessionId, items);
1091
1452
  response = void 0;
1453
+ if (outcome.kind === "with_human") {
1454
+ yield { type: "with_human" };
1455
+ return { finalOutput: void 0, sessionId, lastAgent: agent, interruptions: [], state: void 0, newItems: items, usage, withHuman: true };
1456
+ }
1092
1457
  if (outcome.kind === "completed") {
1093
1458
  usage = addUsage(usage, outcome.usage);
1094
1459
  let finalOutput = outcome.text;
@@ -1107,7 +1472,7 @@ async function* runLoop(startAgent, input, options) {
1107
1472
  const verdict = await guardrail.execute({ output: finalOutput, agent, runContext: runContext2 });
1108
1473
  if (verdict.tripwireTriggered) throw new GuardrailTripwireTriggered("output", guardrail.name, verdict.outputInfo);
1109
1474
  }
1110
- return { finalOutput, sessionId, lastAgent: agent, interruptions: [], state: void 0, newItems: items, usage };
1475
+ return { finalOutput, sessionId, lastAgent: agent, interruptions: [], state: void 0, newItems: items, usage, withHuman: false };
1111
1476
  }
1112
1477
  pending = outcome.pause;
1113
1478
  if (outcome.pause.text) items.push({ type: "message", agentName: agent.name, text: outcome.pause.text });
@@ -1118,7 +1483,7 @@ async function* runLoop(startAgent, input, options) {
1118
1483
  }
1119
1484
  if (!pending) throw new AgentsError("Nothing to continue.");
1120
1485
  const runContext = contextFor(agent, sessionId);
1121
- const toolsByName = new Map(agent.tools.map((t) => [t.name, t]));
1486
+ const toolsByName = new Map((await toolsOf(agent)).map((t) => [t.name, t]));
1122
1487
  const handoffsByName = new Map(agent.handoffs.map((a) => [Agent.handoffToolName(a), a]));
1123
1488
  const interruptions = [];
1124
1489
  for (const action of pending.actions) {
@@ -1139,7 +1504,7 @@ async function* runLoop(startAgent, input, options) {
1139
1504
  if (interruptions.length > 0) {
1140
1505
  const state = new RunState({ sessionId, agentName: agent.name, turnsUsed, usage, pending });
1141
1506
  yield { type: "interruption", interruptions };
1142
- return { finalOutput: void 0, sessionId, lastAgent: agent, interruptions, state, newItems: items, usage };
1507
+ return { finalOutput: void 0, sessionId, lastAgent: agent, interruptions, state, newItems: items, usage, withHuman: false };
1143
1508
  }
1144
1509
  if (turnsUsed >= maxTurns) throw new MaxTurnsExceededError(maxTurns, sessionId);
1145
1510
  let handoffTo;
@@ -1172,6 +1537,14 @@ async function* runLoop(startAgent, input, options) {
1172
1537
  const output = result.output;
1173
1538
  items.push({ type: "tool_output", agentName: agent.name, callId: action.action_id, toolName: action.tool, output });
1174
1539
  yield { type: "tool_output", callId: action.action_id, toolName: action.tool, output, agentName: agent.name };
1540
+ if (action.tool === HUMAN_HANDOFF_TOOL && !output.startsWith("Error")) {
1541
+ let reason = "";
1542
+ try {
1543
+ reason = String(JSON.parse(action.arguments || "{}").reason ?? "");
1544
+ } catch {
1545
+ }
1546
+ yield { type: "human_handoff", reason, agentName: agent.name };
1547
+ }
1175
1548
  }
1176
1549
  let next;
1177
1550
  if (handoffTo) {
@@ -1261,6 +1634,8 @@ var init_run = __esm({
1261
1634
  "src/agents-sdk/run.ts"() {
1262
1635
  "use strict";
1263
1636
  init_spec();
1637
+ init_input();
1638
+ init_human();
1264
1639
  init_partial();
1265
1640
  init_agent();
1266
1641
  init_errors();
@@ -1318,6 +1693,8 @@ var init_agent = __esm({
1318
1693
  "src/agents-sdk/agent.ts"() {
1319
1694
  "use strict";
1320
1695
  init_tool();
1696
+ init_errors();
1697
+ init_mcp();
1321
1698
  DEFAULT_MODEL = "gpt-oss-120b";
1322
1699
  Agent = class _Agent {
1323
1700
  constructor(options) {
@@ -1335,6 +1712,7 @@ var init_agent = __esm({
1335
1712
  this.outputGuardrails = options.outputGuardrails ?? [];
1336
1713
  this.widgets = options.widgets ?? false;
1337
1714
  this.cencoriAgentId = options.cencoriAgentId;
1715
+ this.mcpServers = options.mcpServers ?? [];
1338
1716
  const names = /* @__PURE__ */ new Set();
1339
1717
  for (const t of [...this.tools.map((t2) => t2.name), ...this.handoffs.map((a) => _Agent.handoffToolName(a))]) {
1340
1718
  if (names.has(t)) throw new TypeError(`Agent "${this.name}" has two tools named "${t}".`);
@@ -1356,6 +1734,7 @@ var init_agent = __esm({
1356
1734
  outputGuardrails: this.outputGuardrails,
1357
1735
  widgets: this.widgets,
1358
1736
  cencoriAgentId: this.cencoriAgentId,
1737
+ mcpServers: this.mcpServers,
1359
1738
  ...overrides
1360
1739
  });
1361
1740
  }
@@ -1373,6 +1752,40 @@ var init_agent = __esm({
1373
1752
  if (!agentId || typeof agentId !== "string") throw new TypeError("Agent.fromCencori needs the stored agent's id.");
1374
1753
  return new _Agent({ ...options, name: options.name ?? "Agent", cencoriAgentId: agentId });
1375
1754
  }
1755
+ /**
1756
+ * Every tool this agent can call: its own, then its MCP servers' (fetched
1757
+ * from each server, once per server unless it says otherwise). An MCP tool
1758
+ * whose name is taken gets its server's name in front.
1759
+ */
1760
+ async resolveTools() {
1761
+ if (this.mcpServers.length === 0) return this.tools;
1762
+ const taken = /* @__PURE__ */ new Set([...this.tools.map((t) => t.name), ...this.handoffs.map((a) => _Agent.handoffToolName(a))]);
1763
+ const out = [...this.tools];
1764
+ for (const server of this.mcpServers) {
1765
+ let listed;
1766
+ try {
1767
+ listed = await server.listTools();
1768
+ } catch (error) {
1769
+ throw new AgentsError(`Couldn't list the tools of MCP server "${server.name}": ${error instanceof Error ? error.message : String(error)}`);
1770
+ }
1771
+ const allowed = server.options.allowedTools;
1772
+ for (const t of listed) {
1773
+ if (allowed && !allowed.includes(t.name)) continue;
1774
+ let name = toolSafe(t.name).slice(0, 64);
1775
+ if (taken.has(name)) name = `${toolSafe(server.name)}_${toolSafe(t.name)}`.slice(0, 64);
1776
+ if (taken.has(name) || !TOOL_NAME_PATTERN.test(name)) continue;
1777
+ taken.add(name);
1778
+ out.push(tool({
1779
+ name,
1780
+ description: (t.description ?? `${t.name} (from ${server.name})`).slice(0, 1024),
1781
+ parameters: t.inputSchema && typeof t.inputSchema === "object" ? t.inputSchema : { type: "object", properties: {} },
1782
+ needsApproval: mcpNeedsApproval(server, t),
1783
+ execute: async (args) => mcpResultText(await server.callTool(t.name, args ?? {}))
1784
+ }));
1785
+ }
1786
+ }
1787
+ return out;
1788
+ }
1376
1789
  /** The tool name a handoff to this agent goes by. */
1377
1790
  static handoffToolName(agent) {
1378
1791
  const name = `transfer_to_${toolSafe(agent.name)}`.slice(0, 64);
@@ -1431,12 +1844,22 @@ __export(agents_sdk_exports, {
1431
1844
  CencoriRunError: () => CencoriRunError,
1432
1845
  DEFAULT_MODEL: () => DEFAULT_MODEL,
1433
1846
  GuardrailTripwireTriggered: () => GuardrailTripwireTriggered,
1847
+ HUMAN_HANDOFF_TOOL: () => HUMAN_HANDOFF_TOOL,
1848
+ MCPServerStdio: () => MCPServerStdio,
1849
+ MCPServerStreamableHttp: () => MCPServerStreamableHttp,
1434
1850
  MaxTurnsExceededError: () => MaxTurnsExceededError,
1435
1851
  RunState: () => RunState,
1436
1852
  SchemaValidationError: () => SchemaValidationError,
1437
1853
  WIDGET_TYPES: () => WIDGET_TYPES,
1438
1854
  createAgentChatHandler: () => createAgentChatHandler,
1855
+ file: () => file,
1856
+ humanHandoff: () => humanHandoff,
1857
+ humanReply: () => humanReply,
1858
+ humanStatus: () => humanStatus,
1859
+ image: () => image,
1860
+ inputText: () => inputText,
1439
1861
  isWidgetResult: () => isWidgetResult,
1862
+ releaseToAgent: () => releaseToAgent,
1440
1863
  run: () => run,
1441
1864
  toAgentChatStream: () => toAgentChatStream,
1442
1865
  tool: () => tool,
@@ -1452,6 +1875,7 @@ init_schema();
1452
1875
  // src/agents-sdk/chat.ts
1453
1876
  init_errors();
1454
1877
  init_run();
1878
+ init_human();
1455
1879
 
1456
1880
  // src/agent-chat/protocol.ts
1457
1881
  init_transport();
@@ -1469,6 +1893,8 @@ data: ${JSON.stringify(e2.data)}
1469
1893
 
1470
1894
  // src/agents-sdk/chat.ts
1471
1895
  var MAX_MESSAGE = 32e3;
1896
+ var MAX_ATTACHMENTS = 5;
1897
+ var MAX_ATTACHMENT_CHARS = 14e6;
1472
1898
  function createAgentChatHandler(agent, options = {}) {
1473
1899
  const { context, user, authorizeSession, secret, ...runOptions } = options;
1474
1900
  return async (req2) => {
@@ -1480,6 +1906,13 @@ function createAgentChatHandler(agent, options = {}) {
1480
1906
  }
1481
1907
  const signingKey = secret ?? env2("CENCORI_AGENT_CHAT_SECRET") ?? runOptions.apiKey ?? env2("CENCORI_API_KEY");
1482
1908
  if (!signingKey) return json(500, "Set CENCORI_API_KEY (or pass secret) to serve an agent chat.");
1909
+ if (body.poll) {
1910
+ const sid = typeof body.sessionId === "string" ? body.sessionId : "";
1911
+ if (!sid) return json(400, "sessionId is required to poll.");
1912
+ if (authorizeSession && !await authorizeSession(sid, req2)) return json(403, "This conversation belongs to someone else.");
1913
+ const status = await humanStatus(sid, { ...runOptions, after: body.poll.after });
1914
+ return new Response(JSON.stringify({ handled_by: status.handledBy, messages: status.messages }), { headers: { "Content-Type": "application/json" } });
1915
+ }
1483
1916
  let input;
1484
1917
  let sessionId;
1485
1918
  if (body.approval) {
@@ -1494,9 +1927,20 @@ function createAgentChatHandler(agent, options = {}) {
1494
1927
  sessionId = state.sessionId;
1495
1928
  } else {
1496
1929
  const text = typeof body.message === "string" && body.message.trim() ? body.message : body.action && typeof body.action.type === "string" ? formatWidgetAction(body.action) : "";
1497
- if (!text) return json(400, "Send a message, an action or an approval.");
1930
+ const attachments = Array.isArray(body.attachments) ? body.attachments.slice(0, MAX_ATTACHMENTS) : [];
1931
+ if (!text && attachments.length === 0) return json(400, "Send a message, an action or an approval.");
1498
1932
  if (text.length > MAX_MESSAGE) return json(413, "The message is too long.");
1499
- input = text;
1933
+ if (attachments.some((a) => typeof a?.data_url !== "string" || !a.data_url.startsWith("data:") || a.data_url.length > MAX_ATTACHMENT_CHARS)) {
1934
+ return json(413, "Each attachment must be a data URL under 10 MB.");
1935
+ }
1936
+ input = attachments.length === 0 ? text : [{
1937
+ type: "message",
1938
+ role: "user",
1939
+ content: [
1940
+ ...text ? [{ type: "input_text", text }] : [],
1941
+ ...attachments.map((a) => a.kind === "image" ? { type: "input_image", image_url: a.data_url } : { type: "input_file", filename: String(a.name || "file").slice(0, 200), file_data: a.data_url })
1942
+ ]
1943
+ }];
1500
1944
  sessionId = typeof body.sessionId === "string" && body.sessionId ? body.sessionId : void 0;
1501
1945
  }
1502
1946
  if (sessionId && authorizeSession && !await authorizeSession(sessionId, req2)) {
@@ -1505,7 +1949,7 @@ function createAgentChatHandler(agent, options = {}) {
1505
1949
  const streamed2 = run(agent, input, {
1506
1950
  ...runOptions,
1507
1951
  stream: true,
1508
- ...sessionId && typeof input === "string" ? { sessionId } : {},
1952
+ ...sessionId && !(input instanceof RunState) ? { sessionId } : {},
1509
1953
  context: context ? await context(req2) : void 0,
1510
1954
  user: user ? await user(req2) : void 0,
1511
1955
  signal: req2.signal
@@ -1544,6 +1988,12 @@ function toAgentChatStream(streamed2, options) {
1544
1988
  case "handoff":
1545
1989
  send({ event: "handoff", data: { from: e2.from, to: e2.to } });
1546
1990
  break;
1991
+ case "human_handoff":
1992
+ send({ event: "human_handoff", data: { reason: e2.reason } });
1993
+ break;
1994
+ case "with_human":
1995
+ send({ event: "with_human", data: {} });
1996
+ break;
1547
1997
  case "interruption":
1548
1998
  break;
1549
1999
  }
@@ -1622,6 +2072,9 @@ function env2(name) {
1622
2072
 
1623
2073
  // src/agents-sdk/index.ts
1624
2074
  init_spec();
2075
+ init_mcp();
2076
+ init_human();
2077
+ init_input();
1625
2078
  // Annotate the CommonJS export names for ESM import in node:
1626
2079
  0 && (module.exports = {
1627
2080
  Agent,
@@ -1629,12 +2082,22 @@ init_spec();
1629
2082
  CencoriRunError,
1630
2083
  DEFAULT_MODEL,
1631
2084
  GuardrailTripwireTriggered,
2085
+ HUMAN_HANDOFF_TOOL,
2086
+ MCPServerStdio,
2087
+ MCPServerStreamableHttp,
1632
2088
  MaxTurnsExceededError,
1633
2089
  RunState,
1634
2090
  SchemaValidationError,
1635
2091
  WIDGET_TYPES,
1636
2092
  createAgentChatHandler,
2093
+ file,
2094
+ humanHandoff,
2095
+ humanReply,
2096
+ humanStatus,
2097
+ image,
2098
+ inputText,
1637
2099
  isWidgetResult,
2100
+ releaseToAgent,
1638
2101
  run,
1639
2102
  toAgentChatStream,
1640
2103
  tool,