cencori 1.13.0 → 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.
- package/dist/agents/index.d.mts +117 -5
- package/dist/agents/index.d.ts +117 -5
- package/dist/agents/index.js +299 -157
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/index.mjs +291 -157
- package/dist/agents/index.mjs.map +1 -1
- package/dist/{protocol-Dq7rZbRX.d.mts → protocol-CQy4ZF8f.d.mts} +25 -2
- package/dist/{protocol-Dq7rZbRX.d.ts → protocol-CQy4ZF8f.d.ts} +25 -2
- package/dist/react/index.d.mts +24 -5
- package/dist/react/index.d.ts +24 -5
- package/dist/react/index.js +295 -94
- package/dist/react/index.js.map +1 -1
- package/dist/react/index.mjs +295 -94
- package/dist/react/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/agents/index.js
CHANGED
|
@@ -805,6 +805,236 @@ var init_spec = __esm({
|
|
|
805
805
|
}
|
|
806
806
|
});
|
|
807
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
|
+
|
|
808
1038
|
// src/widgets/partial.ts
|
|
809
1039
|
function parsePartialJson(text) {
|
|
810
1040
|
const stack = [];
|
|
@@ -923,10 +1153,10 @@ function partialWidget(raw, depth = 0) {
|
|
|
923
1153
|
if (Array.isArray(node[key])) node[key] = node[key].filter((v) => v && typeof v === "object" && !Array.isArray(v));
|
|
924
1154
|
}
|
|
925
1155
|
if (type === "ListView") {
|
|
926
|
-
node.items = node.items.map(({ action: _a, image, ...it }) => ({
|
|
1156
|
+
node.items = node.items.map(({ action: _a, image: image2, ...it }) => ({
|
|
927
1157
|
...it,
|
|
928
1158
|
title: typeof it.title === "string" ? it.title : "",
|
|
929
|
-
...typeof
|
|
1159
|
+
...typeof image2 === "string" && /^https:\/\/\S+\.\S+/.test(image2) ? { image: image2 } : {}
|
|
930
1160
|
}));
|
|
931
1161
|
}
|
|
932
1162
|
if (type === "Chart" || type === "Table") {
|
|
@@ -984,155 +1214,6 @@ var init_partial = __esm({
|
|
|
984
1214
|
}
|
|
985
1215
|
});
|
|
986
1216
|
|
|
987
|
-
// src/agents-sdk/transport.ts
|
|
988
|
-
function env(name) {
|
|
989
|
-
try {
|
|
990
|
-
return typeof process !== "undefined" ? process.env?.[name] : void 0;
|
|
991
|
-
} catch {
|
|
992
|
-
return void 0;
|
|
993
|
-
}
|
|
994
|
-
}
|
|
995
|
-
async function errorFrom(response, sessionId) {
|
|
996
|
-
let message = `Cencori returned ${response.status}`;
|
|
997
|
-
let code;
|
|
998
|
-
try {
|
|
999
|
-
const body = await response.json();
|
|
1000
|
-
if (typeof body.error === "string") message = body.error;
|
|
1001
|
-
else if (body.error?.message) {
|
|
1002
|
-
message = body.error.message;
|
|
1003
|
-
code = body.error.code;
|
|
1004
|
-
}
|
|
1005
|
-
} catch {
|
|
1006
|
-
}
|
|
1007
|
-
return new CencoriRunError(message, { status: response.status, code, sessionId });
|
|
1008
|
-
}
|
|
1009
|
-
async function* readSessionEvents(response) {
|
|
1010
|
-
if (!response.body) return;
|
|
1011
|
-
const reader = response.body.getReader();
|
|
1012
|
-
const decoder = new TextDecoder();
|
|
1013
|
-
let buffer = "";
|
|
1014
|
-
let event = "message";
|
|
1015
|
-
let data = [];
|
|
1016
|
-
const flush = () => {
|
|
1017
|
-
if (data.length === 0) {
|
|
1018
|
-
event = "message";
|
|
1019
|
-
return null;
|
|
1020
|
-
}
|
|
1021
|
-
const raw = data.join("\n");
|
|
1022
|
-
data = [];
|
|
1023
|
-
const name = event;
|
|
1024
|
-
event = "message";
|
|
1025
|
-
try {
|
|
1026
|
-
return { event: name, data: JSON.parse(raw) };
|
|
1027
|
-
} catch {
|
|
1028
|
-
return { event: name, data: { raw } };
|
|
1029
|
-
}
|
|
1030
|
-
};
|
|
1031
|
-
try {
|
|
1032
|
-
while (true) {
|
|
1033
|
-
const { done, value } = await reader.read();
|
|
1034
|
-
if (done) break;
|
|
1035
|
-
buffer += decoder.decode(value, { stream: true });
|
|
1036
|
-
let newline;
|
|
1037
|
-
while ((newline = buffer.indexOf("\n")) >= 0) {
|
|
1038
|
-
const line = buffer.slice(0, newline).replace(/\r$/, "");
|
|
1039
|
-
buffer = buffer.slice(newline + 1);
|
|
1040
|
-
if (line === "") {
|
|
1041
|
-
const parsed = flush();
|
|
1042
|
-
if (parsed) yield parsed;
|
|
1043
|
-
} else if (line.startsWith("event:")) {
|
|
1044
|
-
event = line.slice(6).trim();
|
|
1045
|
-
} else if (line.startsWith("data:")) {
|
|
1046
|
-
data.push(line.slice(5).replace(/^ /, ""));
|
|
1047
|
-
}
|
|
1048
|
-
}
|
|
1049
|
-
}
|
|
1050
|
-
buffer += decoder.decode();
|
|
1051
|
-
if (buffer.trim()) {
|
|
1052
|
-
for (const line of buffer.split("\n")) {
|
|
1053
|
-
if (line.startsWith("event:")) event = line.slice(6).trim();
|
|
1054
|
-
else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
|
|
1055
|
-
}
|
|
1056
|
-
}
|
|
1057
|
-
const last = flush();
|
|
1058
|
-
if (last) yield last;
|
|
1059
|
-
} finally {
|
|
1060
|
-
reader.releaseLock();
|
|
1061
|
-
}
|
|
1062
|
-
}
|
|
1063
|
-
var DEFAULT_BASE_URL, Transport;
|
|
1064
|
-
var init_transport = __esm({
|
|
1065
|
-
"src/agents-sdk/transport.ts"() {
|
|
1066
|
-
"use strict";
|
|
1067
|
-
init_errors();
|
|
1068
|
-
DEFAULT_BASE_URL = "https://cencori.com";
|
|
1069
|
-
Transport = class {
|
|
1070
|
-
constructor(options = {}) {
|
|
1071
|
-
const apiKey = options.apiKey ?? env("CENCORI_API_KEY");
|
|
1072
|
-
if (!apiKey) {
|
|
1073
|
-
throw new CencoriRunError("No Cencori API key. Pass apiKey or set CENCORI_API_KEY (a secret project key, csk_...).", { code: "missing_api_key" });
|
|
1074
|
-
}
|
|
1075
|
-
this.apiKey = apiKey;
|
|
1076
|
-
this.baseUrl = (options.baseUrl ?? env("CENCORI_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
1077
|
-
this.fetchImpl = options.fetch ?? fetch;
|
|
1078
|
-
this.signal = options.signal;
|
|
1079
|
-
}
|
|
1080
|
-
async post(path, body, sessionId) {
|
|
1081
|
-
const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
1082
|
-
method: "POST",
|
|
1083
|
-
headers: {
|
|
1084
|
-
"CENCORI_API_KEY": this.apiKey,
|
|
1085
|
-
"Content-Type": "application/json",
|
|
1086
|
-
"Accept": "text/event-stream, application/json"
|
|
1087
|
-
},
|
|
1088
|
-
body: JSON.stringify(body),
|
|
1089
|
-
signal: this.signal
|
|
1090
|
-
});
|
|
1091
|
-
if (!response.ok) throw await errorFrom(response, sessionId);
|
|
1092
|
-
return response;
|
|
1093
|
-
}
|
|
1094
|
-
/**
|
|
1095
|
-
* Create a session and run its first turn in one request. Servers that
|
|
1096
|
-
* predate this answer with the plain session JSON; the turn then goes in a
|
|
1097
|
-
* second request, as before.
|
|
1098
|
-
*/
|
|
1099
|
-
async createSessionWithTurn(metadata, body, agentId) {
|
|
1100
|
-
const turn = { ...body, stream: true, pause_on_tool_calls: true };
|
|
1101
|
-
const response = await this.fetchImpl(`${this.baseUrl}/v1/sessions`, {
|
|
1102
|
-
method: "POST",
|
|
1103
|
-
headers: {
|
|
1104
|
-
"CENCORI_API_KEY": this.apiKey,
|
|
1105
|
-
"Content-Type": "application/json",
|
|
1106
|
-
"Accept": "text/event-stream, application/json"
|
|
1107
|
-
},
|
|
1108
|
-
body: JSON.stringify({ metadata, turn, ...agentId ? { agent_id: agentId } : {} }),
|
|
1109
|
-
signal: this.signal
|
|
1110
|
-
});
|
|
1111
|
-
const headerId = response.headers.get("X-Cencori-Session-Id") ?? void 0;
|
|
1112
|
-
if (!response.ok) throw await errorFrom(response, headerId);
|
|
1113
|
-
if (headerId) return { sessionId: headerId, response };
|
|
1114
|
-
const created = await response.json();
|
|
1115
|
-
if (!created.id) throw new CencoriRunError("Cencori did not return a session id.");
|
|
1116
|
-
return { sessionId: created.id, response: await this.turn(created.id, body) };
|
|
1117
|
-
}
|
|
1118
|
-
turn(sessionId, body) {
|
|
1119
|
-
return this.post(`/v1/sessions/${encodeURIComponent(sessionId)}/turns`, {
|
|
1120
|
-
...body,
|
|
1121
|
-
stream: true,
|
|
1122
|
-
pause_on_tool_calls: true
|
|
1123
|
-
}, sessionId);
|
|
1124
|
-
}
|
|
1125
|
-
resume(sessionId, actionId, toolResults, next) {
|
|
1126
|
-
return this.post(`/v1/sessions/${encodeURIComponent(sessionId)}/approve`, {
|
|
1127
|
-
action_id: actionId,
|
|
1128
|
-
tool_results: toolResults,
|
|
1129
|
-
...next ? { next } : {}
|
|
1130
|
-
}, sessionId);
|
|
1131
|
-
}
|
|
1132
|
-
};
|
|
1133
|
-
}
|
|
1134
|
-
});
|
|
1135
|
-
|
|
1136
1217
|
// src/agents-sdk/run.ts
|
|
1137
1218
|
var run_exports = {};
|
|
1138
1219
|
__export(run_exports, {
|
|
@@ -1258,6 +1339,8 @@ async function* consumeTurn(response, agentName, sessionId, items) {
|
|
|
1258
1339
|
}
|
|
1259
1340
|
case "turn.completed":
|
|
1260
1341
|
return { kind: "completed", text: completedText(text, data), usage: data.usage };
|
|
1342
|
+
case "owner.handling":
|
|
1343
|
+
return { kind: "with_human" };
|
|
1261
1344
|
case "turn.failed": {
|
|
1262
1345
|
const output = data.output;
|
|
1263
1346
|
throw new CencoriRunError(output?.error ?? "The turn failed.", { code: "turn_failed", sessionId });
|
|
@@ -1331,7 +1414,7 @@ async function* runLoop(startAgent, input, options) {
|
|
|
1331
1414
|
sessionId = options.sessionId ?? "";
|
|
1332
1415
|
const runContext = contextFor(agent, sessionId);
|
|
1333
1416
|
for (const guardrail of agent.inputGuardrails) {
|
|
1334
|
-
const verdict = await guardrail.execute({ input, agent, runContext });
|
|
1417
|
+
const verdict = await guardrail.execute({ input: inputText(input), agent, runContext });
|
|
1335
1418
|
if (verdict.tripwireTriggered) throw new GuardrailTripwireTriggered("input", guardrail.name, verdict.outputInfo);
|
|
1336
1419
|
}
|
|
1337
1420
|
yield { type: "agent_updated", agent };
|
|
@@ -1367,6 +1450,10 @@ async function* runLoop(startAgent, input, options) {
|
|
|
1367
1450
|
if (response) {
|
|
1368
1451
|
const outcome = yield* consumeTurn(response, agent.name, sessionId, items);
|
|
1369
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
|
+
}
|
|
1370
1457
|
if (outcome.kind === "completed") {
|
|
1371
1458
|
usage = addUsage(usage, outcome.usage);
|
|
1372
1459
|
let finalOutput = outcome.text;
|
|
@@ -1385,7 +1472,7 @@ async function* runLoop(startAgent, input, options) {
|
|
|
1385
1472
|
const verdict = await guardrail.execute({ output: finalOutput, agent, runContext: runContext2 });
|
|
1386
1473
|
if (verdict.tripwireTriggered) throw new GuardrailTripwireTriggered("output", guardrail.name, verdict.outputInfo);
|
|
1387
1474
|
}
|
|
1388
|
-
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 };
|
|
1389
1476
|
}
|
|
1390
1477
|
pending = outcome.pause;
|
|
1391
1478
|
if (outcome.pause.text) items.push({ type: "message", agentName: agent.name, text: outcome.pause.text });
|
|
@@ -1417,7 +1504,7 @@ async function* runLoop(startAgent, input, options) {
|
|
|
1417
1504
|
if (interruptions.length > 0) {
|
|
1418
1505
|
const state = new RunState({ sessionId, agentName: agent.name, turnsUsed, usage, pending });
|
|
1419
1506
|
yield { type: "interruption", interruptions };
|
|
1420
|
-
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 };
|
|
1421
1508
|
}
|
|
1422
1509
|
if (turnsUsed >= maxTurns) throw new MaxTurnsExceededError(maxTurns, sessionId);
|
|
1423
1510
|
let handoffTo;
|
|
@@ -1450,6 +1537,14 @@ async function* runLoop(startAgent, input, options) {
|
|
|
1450
1537
|
const output = result.output;
|
|
1451
1538
|
items.push({ type: "tool_output", agentName: agent.name, callId: action.action_id, toolName: action.tool, output });
|
|
1452
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
|
+
}
|
|
1453
1548
|
}
|
|
1454
1549
|
let next;
|
|
1455
1550
|
if (handoffTo) {
|
|
@@ -1539,6 +1634,8 @@ var init_run = __esm({
|
|
|
1539
1634
|
"src/agents-sdk/run.ts"() {
|
|
1540
1635
|
"use strict";
|
|
1541
1636
|
init_spec();
|
|
1637
|
+
init_input();
|
|
1638
|
+
init_human();
|
|
1542
1639
|
init_partial();
|
|
1543
1640
|
init_agent();
|
|
1544
1641
|
init_errors();
|
|
@@ -1747,6 +1844,7 @@ __export(agents_sdk_exports, {
|
|
|
1747
1844
|
CencoriRunError: () => CencoriRunError,
|
|
1748
1845
|
DEFAULT_MODEL: () => DEFAULT_MODEL,
|
|
1749
1846
|
GuardrailTripwireTriggered: () => GuardrailTripwireTriggered,
|
|
1847
|
+
HUMAN_HANDOFF_TOOL: () => HUMAN_HANDOFF_TOOL,
|
|
1750
1848
|
MCPServerStdio: () => MCPServerStdio,
|
|
1751
1849
|
MCPServerStreamableHttp: () => MCPServerStreamableHttp,
|
|
1752
1850
|
MaxTurnsExceededError: () => MaxTurnsExceededError,
|
|
@@ -1754,7 +1852,14 @@ __export(agents_sdk_exports, {
|
|
|
1754
1852
|
SchemaValidationError: () => SchemaValidationError,
|
|
1755
1853
|
WIDGET_TYPES: () => WIDGET_TYPES,
|
|
1756
1854
|
createAgentChatHandler: () => createAgentChatHandler,
|
|
1855
|
+
file: () => file,
|
|
1856
|
+
humanHandoff: () => humanHandoff,
|
|
1857
|
+
humanReply: () => humanReply,
|
|
1858
|
+
humanStatus: () => humanStatus,
|
|
1859
|
+
image: () => image,
|
|
1860
|
+
inputText: () => inputText,
|
|
1757
1861
|
isWidgetResult: () => isWidgetResult,
|
|
1862
|
+
releaseToAgent: () => releaseToAgent,
|
|
1758
1863
|
run: () => run,
|
|
1759
1864
|
toAgentChatStream: () => toAgentChatStream,
|
|
1760
1865
|
tool: () => tool,
|
|
@@ -1770,6 +1875,7 @@ init_schema();
|
|
|
1770
1875
|
// src/agents-sdk/chat.ts
|
|
1771
1876
|
init_errors();
|
|
1772
1877
|
init_run();
|
|
1878
|
+
init_human();
|
|
1773
1879
|
|
|
1774
1880
|
// src/agent-chat/protocol.ts
|
|
1775
1881
|
init_transport();
|
|
@@ -1787,6 +1893,8 @@ data: ${JSON.stringify(e2.data)}
|
|
|
1787
1893
|
|
|
1788
1894
|
// src/agents-sdk/chat.ts
|
|
1789
1895
|
var MAX_MESSAGE = 32e3;
|
|
1896
|
+
var MAX_ATTACHMENTS = 5;
|
|
1897
|
+
var MAX_ATTACHMENT_CHARS = 14e6;
|
|
1790
1898
|
function createAgentChatHandler(agent, options = {}) {
|
|
1791
1899
|
const { context, user, authorizeSession, secret, ...runOptions } = options;
|
|
1792
1900
|
return async (req2) => {
|
|
@@ -1798,6 +1906,13 @@ function createAgentChatHandler(agent, options = {}) {
|
|
|
1798
1906
|
}
|
|
1799
1907
|
const signingKey = secret ?? env2("CENCORI_AGENT_CHAT_SECRET") ?? runOptions.apiKey ?? env2("CENCORI_API_KEY");
|
|
1800
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
|
+
}
|
|
1801
1916
|
let input;
|
|
1802
1917
|
let sessionId;
|
|
1803
1918
|
if (body.approval) {
|
|
@@ -1812,9 +1927,20 @@ function createAgentChatHandler(agent, options = {}) {
|
|
|
1812
1927
|
sessionId = state.sessionId;
|
|
1813
1928
|
} else {
|
|
1814
1929
|
const text = typeof body.message === "string" && body.message.trim() ? body.message : body.action && typeof body.action.type === "string" ? formatWidgetAction(body.action) : "";
|
|
1815
|
-
|
|
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.");
|
|
1816
1932
|
if (text.length > MAX_MESSAGE) return json(413, "The message is too long.");
|
|
1817
|
-
|
|
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
|
+
}];
|
|
1818
1944
|
sessionId = typeof body.sessionId === "string" && body.sessionId ? body.sessionId : void 0;
|
|
1819
1945
|
}
|
|
1820
1946
|
if (sessionId && authorizeSession && !await authorizeSession(sessionId, req2)) {
|
|
@@ -1823,7 +1949,7 @@ function createAgentChatHandler(agent, options = {}) {
|
|
|
1823
1949
|
const streamed2 = run(agent, input, {
|
|
1824
1950
|
...runOptions,
|
|
1825
1951
|
stream: true,
|
|
1826
|
-
...sessionId &&
|
|
1952
|
+
...sessionId && !(input instanceof RunState) ? { sessionId } : {},
|
|
1827
1953
|
context: context ? await context(req2) : void 0,
|
|
1828
1954
|
user: user ? await user(req2) : void 0,
|
|
1829
1955
|
signal: req2.signal
|
|
@@ -1862,6 +1988,12 @@ function toAgentChatStream(streamed2, options) {
|
|
|
1862
1988
|
case "handoff":
|
|
1863
1989
|
send({ event: "handoff", data: { from: e2.from, to: e2.to } });
|
|
1864
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;
|
|
1865
1997
|
case "interruption":
|
|
1866
1998
|
break;
|
|
1867
1999
|
}
|
|
@@ -1941,6 +2073,8 @@ function env2(name) {
|
|
|
1941
2073
|
// src/agents-sdk/index.ts
|
|
1942
2074
|
init_spec();
|
|
1943
2075
|
init_mcp();
|
|
2076
|
+
init_human();
|
|
2077
|
+
init_input();
|
|
1944
2078
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1945
2079
|
0 && (module.exports = {
|
|
1946
2080
|
Agent,
|
|
@@ -1948,6 +2082,7 @@ init_mcp();
|
|
|
1948
2082
|
CencoriRunError,
|
|
1949
2083
|
DEFAULT_MODEL,
|
|
1950
2084
|
GuardrailTripwireTriggered,
|
|
2085
|
+
HUMAN_HANDOFF_TOOL,
|
|
1951
2086
|
MCPServerStdio,
|
|
1952
2087
|
MCPServerStreamableHttp,
|
|
1953
2088
|
MaxTurnsExceededError,
|
|
@@ -1955,7 +2090,14 @@ init_mcp();
|
|
|
1955
2090
|
SchemaValidationError,
|
|
1956
2091
|
WIDGET_TYPES,
|
|
1957
2092
|
createAgentChatHandler,
|
|
2093
|
+
file,
|
|
2094
|
+
humanHandoff,
|
|
2095
|
+
humanReply,
|
|
2096
|
+
humanStatus,
|
|
2097
|
+
image,
|
|
2098
|
+
inputText,
|
|
1958
2099
|
isWidgetResult,
|
|
2100
|
+
releaseToAgent,
|
|
1959
2101
|
run,
|
|
1960
2102
|
toAgentChatStream,
|
|
1961
2103
|
tool,
|