@copilotkitnext/runtime 1.51.4 → 1.51.5-next.1
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/_virtual/_rolldown/runtime.cjs +29 -0
- package/dist/endpoints/express-single.cjs +187 -0
- package/dist/endpoints/express-single.cjs.map +1 -0
- package/dist/endpoints/express-single.d.cts +15 -0
- package/dist/endpoints/express-single.d.cts.map +1 -0
- package/dist/endpoints/express-single.d.mts +15 -0
- package/dist/endpoints/express-single.d.mts.map +1 -0
- package/dist/endpoints/express-single.mjs +184 -0
- package/dist/endpoints/express-single.mjs.map +1 -0
- package/dist/endpoints/express-utils.cjs +118 -0
- package/dist/endpoints/express-utils.cjs.map +1 -0
- package/dist/endpoints/express-utils.mjs +116 -0
- package/dist/endpoints/express-utils.mjs.map +1 -0
- package/dist/endpoints/express.cjs +165 -0
- package/dist/endpoints/express.cjs.map +1 -0
- package/dist/endpoints/express.d.cts +15 -0
- package/dist/endpoints/express.d.cts.map +1 -0
- package/dist/endpoints/express.d.mts +15 -0
- package/dist/endpoints/express.d.mts.map +1 -0
- package/dist/endpoints/express.mjs +162 -0
- package/dist/endpoints/express.mjs.map +1 -0
- package/dist/endpoints/hono-single.cjs +140 -0
- package/dist/endpoints/hono-single.cjs.map +1 -0
- package/dist/endpoints/hono-single.d.cts +31 -0
- package/dist/endpoints/hono-single.d.cts.map +1 -0
- package/dist/endpoints/hono-single.d.mts +31 -0
- package/dist/endpoints/hono-single.d.mts.map +1 -0
- package/dist/endpoints/hono-single.mjs +139 -0
- package/dist/endpoints/hono-single.mjs.map +1 -0
- package/dist/endpoints/hono.cjs +152 -0
- package/dist/endpoints/hono.cjs.map +1 -0
- package/dist/endpoints/hono.d.cts +47 -0
- package/dist/endpoints/hono.d.cts.map +1 -0
- package/dist/endpoints/hono.d.mts +47 -0
- package/dist/endpoints/hono.d.mts.map +1 -0
- package/dist/endpoints/hono.mjs +151 -0
- package/dist/endpoints/hono.mjs.map +1 -0
- package/dist/endpoints/index.cjs +2 -0
- package/dist/endpoints/index.d.mts +2 -0
- package/dist/endpoints/index.mjs +4 -0
- package/dist/endpoints/single-route-helpers.cjs +67 -0
- package/dist/endpoints/single-route-helpers.cjs.map +1 -0
- package/dist/endpoints/single-route-helpers.mjs +64 -0
- package/dist/endpoints/single-route-helpers.mjs.map +1 -0
- package/dist/express.cjs +6 -0
- package/dist/express.d.cts +3 -0
- package/dist/express.d.mts +3 -19
- package/dist/express.mjs +3 -477
- package/dist/handlers/get-runtime-info.cjs +36 -0
- package/dist/handlers/get-runtime-info.cjs.map +1 -0
- package/dist/handlers/get-runtime-info.mjs +36 -0
- package/dist/handlers/get-runtime-info.mjs.map +1 -0
- package/dist/handlers/handle-connect.cjs +102 -0
- package/dist/handlers/handle-connect.cjs.map +1 -0
- package/dist/handlers/handle-connect.mjs +101 -0
- package/dist/handlers/handle-connect.mjs.map +1 -0
- package/dist/handlers/handle-run.cjs +114 -0
- package/dist/handlers/handle-run.cjs.map +1 -0
- package/dist/handlers/handle-run.mjs +113 -0
- package/dist/handlers/handle-run.mjs.map +1 -0
- package/dist/handlers/handle-stop.cjs +46 -0
- package/dist/handlers/handle-stop.cjs.map +1 -0
- package/dist/handlers/handle-stop.mjs +45 -0
- package/dist/handlers/handle-stop.mjs.map +1 -0
- package/dist/handlers/handle-transcribe.cjs +111 -0
- package/dist/handlers/handle-transcribe.cjs.map +1 -0
- package/dist/handlers/handle-transcribe.mjs +110 -0
- package/dist/handlers/handle-transcribe.mjs.map +1 -0
- package/dist/handlers/header-utils.cjs +25 -0
- package/dist/handlers/header-utils.cjs.map +1 -0
- package/dist/handlers/header-utils.mjs +24 -0
- package/dist/handlers/header-utils.mjs.map +1 -0
- package/dist/index.cjs +25 -0
- package/dist/index.d.cts +8 -0
- package/dist/index.d.mts +9 -139
- package/dist/index.mjs +10 -335
- package/dist/middleware.cjs +29 -0
- package/dist/middleware.cjs.map +1 -0
- package/dist/middleware.d.cts +24 -0
- package/dist/middleware.d.cts.map +1 -0
- package/dist/middleware.d.mts +24 -0
- package/dist/middleware.d.mts.map +1 -0
- package/dist/middleware.mjs +27 -0
- package/dist/middleware.mjs.map +1 -0
- package/dist/package.cjs +12 -0
- package/dist/package.cjs.map +1 -0
- package/dist/package.mjs +6 -0
- package/dist/package.mjs.map +1 -0
- package/dist/runner/agent-runner.cjs +7 -0
- package/dist/runner/agent-runner.cjs.map +1 -0
- package/dist/runner/agent-runner.d.cts +28 -0
- package/dist/runner/agent-runner.d.cts.map +1 -0
- package/dist/runner/agent-runner.d.mts +28 -0
- package/dist/runner/agent-runner.d.mts.map +1 -0
- package/dist/runner/agent-runner.mjs +6 -0
- package/dist/runner/agent-runner.mjs.map +1 -0
- package/dist/runner/in-memory.cjs +230 -0
- package/dist/runner/in-memory.cjs.map +1 -0
- package/dist/runner/in-memory.d.cts +14 -0
- package/dist/runner/in-memory.d.cts.map +1 -0
- package/dist/runner/in-memory.d.mts +14 -0
- package/dist/runner/in-memory.d.mts.map +1 -0
- package/dist/runner/in-memory.mjs +229 -0
- package/dist/runner/in-memory.mjs.map +1 -0
- package/dist/runner/index.cjs +4 -0
- package/dist/runner/index.d.cts +4 -0
- package/dist/runner/index.d.mts +4 -0
- package/dist/runner/index.mjs +5 -0
- package/dist/runtime.cjs +27 -0
- package/dist/runtime.cjs.map +1 -0
- package/dist/runtime.d.cts +43 -0
- package/dist/runtime.d.cts.map +1 -0
- package/dist/runtime.d.mts +43 -0
- package/dist/runtime.d.mts.map +1 -0
- package/dist/runtime.mjs +26 -0
- package/dist/runtime.mjs.map +1 -0
- package/dist/transcription-service/transcription-service.cjs +7 -0
- package/dist/transcription-service/transcription-service.cjs.map +1 -0
- package/dist/transcription-service/transcription-service.d.cts +14 -0
- package/dist/transcription-service/transcription-service.d.cts.map +1 -0
- package/dist/transcription-service/transcription-service.d.mts +14 -0
- package/dist/transcription-service/transcription-service.d.mts.map +1 -0
- package/dist/transcription-service/transcription-service.mjs +6 -0
- package/dist/transcription-service/transcription-service.mjs.map +1 -0
- package/package.json +25 -22
- package/tsdown.config.ts +16 -0
- package/dist/chunk-5GKH3W25.mjs +0 -1054
- package/dist/chunk-5GKH3W25.mjs.map +0 -1
- package/dist/express.d.ts +0 -19
- package/dist/express.js +0 -1292
- package/dist/express.js.map +0 -1
- package/dist/express.mjs.map +0 -1
- package/dist/index.d.ts +0 -139
- package/dist/index.js +0 -1387
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/runtime-BsuyYT2l.d.mts +0 -98
- package/dist/runtime-BsuyYT2l.d.ts +0 -98
package/dist/express.js
DELETED
|
@@ -1,1292 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __create = Object.create;
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __export = (target, all) => {
|
|
9
|
-
for (var name in all)
|
|
10
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
-
};
|
|
12
|
-
var __copyProps = (to, from, except, desc) => {
|
|
13
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
-
for (let key of __getOwnPropNames(from))
|
|
15
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
-
}
|
|
18
|
-
return to;
|
|
19
|
-
};
|
|
20
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
-
mod
|
|
27
|
-
));
|
|
28
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
-
|
|
30
|
-
// src/express.ts
|
|
31
|
-
var express_exports = {};
|
|
32
|
-
__export(express_exports, {
|
|
33
|
-
createCopilotEndpointExpress: () => createCopilotEndpointExpress,
|
|
34
|
-
createCopilotEndpointSingleRouteExpress: () => createCopilotEndpointSingleRouteExpress
|
|
35
|
-
});
|
|
36
|
-
module.exports = __toCommonJS(express_exports);
|
|
37
|
-
|
|
38
|
-
// src/endpoints/express.ts
|
|
39
|
-
var import_express = __toESM(require("express"));
|
|
40
|
-
var import_cors = __toESM(require("cors"));
|
|
41
|
-
|
|
42
|
-
// src/handlers/handle-run.ts
|
|
43
|
-
var import_client = require("@ag-ui/client");
|
|
44
|
-
var import_encoder = require("@ag-ui/encoder");
|
|
45
|
-
|
|
46
|
-
// src/handlers/header-utils.ts
|
|
47
|
-
function shouldForwardHeader(headerName) {
|
|
48
|
-
const lower = headerName.toLowerCase();
|
|
49
|
-
return lower === "authorization" || lower.startsWith("x-");
|
|
50
|
-
}
|
|
51
|
-
function extractForwardableHeaders(request) {
|
|
52
|
-
const forwardableHeaders = {};
|
|
53
|
-
request.headers.forEach((value, key) => {
|
|
54
|
-
if (shouldForwardHeader(key)) {
|
|
55
|
-
forwardableHeaders[key] = value;
|
|
56
|
-
}
|
|
57
|
-
});
|
|
58
|
-
return forwardableHeaders;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
// src/handlers/handle-run.ts
|
|
62
|
-
async function handleRunAgent({
|
|
63
|
-
runtime,
|
|
64
|
-
request,
|
|
65
|
-
agentId
|
|
66
|
-
}) {
|
|
67
|
-
try {
|
|
68
|
-
const agents = await runtime.agents;
|
|
69
|
-
if (!agents[agentId]) {
|
|
70
|
-
return new Response(
|
|
71
|
-
JSON.stringify({
|
|
72
|
-
error: "Agent not found",
|
|
73
|
-
message: `Agent '${agentId}' does not exist`
|
|
74
|
-
}),
|
|
75
|
-
{
|
|
76
|
-
status: 404,
|
|
77
|
-
headers: { "Content-Type": "application/json" }
|
|
78
|
-
}
|
|
79
|
-
);
|
|
80
|
-
}
|
|
81
|
-
const registeredAgent = agents[agentId];
|
|
82
|
-
const agent = registeredAgent.clone();
|
|
83
|
-
if (agent && "headers" in agent) {
|
|
84
|
-
const forwardableHeaders = extractForwardableHeaders(request);
|
|
85
|
-
agent.headers = {
|
|
86
|
-
...agent.headers,
|
|
87
|
-
...forwardableHeaders
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
let input;
|
|
91
|
-
try {
|
|
92
|
-
const requestBody = await request.json();
|
|
93
|
-
input = import_client.RunAgentInputSchema.parse(requestBody);
|
|
94
|
-
} catch (error) {
|
|
95
|
-
console.error("Invalid run request body:", error);
|
|
96
|
-
return new Response(
|
|
97
|
-
JSON.stringify({
|
|
98
|
-
error: "Invalid request body",
|
|
99
|
-
details: error instanceof Error ? error.message : String(error)
|
|
100
|
-
}),
|
|
101
|
-
{
|
|
102
|
-
status: 400,
|
|
103
|
-
headers: { "Content-Type": "application/json" }
|
|
104
|
-
}
|
|
105
|
-
);
|
|
106
|
-
}
|
|
107
|
-
const stream = new TransformStream();
|
|
108
|
-
const writer = stream.writable.getWriter();
|
|
109
|
-
const encoder = new import_encoder.EventEncoder();
|
|
110
|
-
let streamClosed = false;
|
|
111
|
-
agent.setMessages(input.messages);
|
|
112
|
-
agent.setState(input.state);
|
|
113
|
-
agent.threadId = input.threadId;
|
|
114
|
-
(async () => {
|
|
115
|
-
runtime.runner.run({
|
|
116
|
-
threadId: input.threadId,
|
|
117
|
-
agent,
|
|
118
|
-
input
|
|
119
|
-
}).subscribe({
|
|
120
|
-
next: async (event) => {
|
|
121
|
-
if (!request.signal.aborted && !streamClosed) {
|
|
122
|
-
try {
|
|
123
|
-
await writer.write(encoder.encode(event));
|
|
124
|
-
} catch (error) {
|
|
125
|
-
if (error instanceof Error && error.name === "AbortError") {
|
|
126
|
-
streamClosed = true;
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
},
|
|
131
|
-
error: async (error) => {
|
|
132
|
-
console.error("Error running agent:", error);
|
|
133
|
-
if (!streamClosed) {
|
|
134
|
-
try {
|
|
135
|
-
await writer.close();
|
|
136
|
-
streamClosed = true;
|
|
137
|
-
} catch {
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
},
|
|
141
|
-
complete: async () => {
|
|
142
|
-
if (!streamClosed) {
|
|
143
|
-
try {
|
|
144
|
-
await writer.close();
|
|
145
|
-
streamClosed = true;
|
|
146
|
-
} catch {
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
});
|
|
151
|
-
})().catch((error) => {
|
|
152
|
-
console.error("Error running agent:", error);
|
|
153
|
-
console.error(
|
|
154
|
-
"Error stack:",
|
|
155
|
-
error instanceof Error ? error.stack : "No stack trace"
|
|
156
|
-
);
|
|
157
|
-
console.error("Error details:", {
|
|
158
|
-
name: error instanceof Error ? error.name : "Unknown",
|
|
159
|
-
message: error instanceof Error ? error.message : String(error),
|
|
160
|
-
cause: error instanceof Error ? error.cause : void 0
|
|
161
|
-
});
|
|
162
|
-
if (!streamClosed) {
|
|
163
|
-
try {
|
|
164
|
-
writer.close();
|
|
165
|
-
streamClosed = true;
|
|
166
|
-
} catch {
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
});
|
|
170
|
-
return new Response(stream.readable, {
|
|
171
|
-
status: 200,
|
|
172
|
-
headers: {
|
|
173
|
-
"Content-Type": "text/event-stream",
|
|
174
|
-
"Cache-Control": "no-cache",
|
|
175
|
-
Connection: "keep-alive"
|
|
176
|
-
}
|
|
177
|
-
});
|
|
178
|
-
} catch (error) {
|
|
179
|
-
console.error("Error running agent:", error);
|
|
180
|
-
console.error(
|
|
181
|
-
"Error stack:",
|
|
182
|
-
error instanceof Error ? error.stack : "No stack trace"
|
|
183
|
-
);
|
|
184
|
-
console.error("Error details:", {
|
|
185
|
-
name: error instanceof Error ? error.name : "Unknown",
|
|
186
|
-
message: error instanceof Error ? error.message : String(error),
|
|
187
|
-
cause: error instanceof Error ? error.cause : void 0
|
|
188
|
-
});
|
|
189
|
-
return new Response(
|
|
190
|
-
JSON.stringify({
|
|
191
|
-
error: "Failed to run agent",
|
|
192
|
-
message: error instanceof Error ? error.message : "Unknown error"
|
|
193
|
-
}),
|
|
194
|
-
{
|
|
195
|
-
status: 500,
|
|
196
|
-
headers: { "Content-Type": "application/json" }
|
|
197
|
-
}
|
|
198
|
-
);
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
// src/handlers/handle-connect.ts
|
|
203
|
-
var import_client2 = require("@ag-ui/client");
|
|
204
|
-
var import_encoder2 = require("@ag-ui/encoder");
|
|
205
|
-
async function handleConnectAgent({
|
|
206
|
-
runtime,
|
|
207
|
-
request,
|
|
208
|
-
agentId
|
|
209
|
-
}) {
|
|
210
|
-
try {
|
|
211
|
-
const agents = await runtime.agents;
|
|
212
|
-
if (!agents[agentId]) {
|
|
213
|
-
return new Response(
|
|
214
|
-
JSON.stringify({
|
|
215
|
-
error: "Agent not found",
|
|
216
|
-
message: `Agent '${agentId}' does not exist`
|
|
217
|
-
}),
|
|
218
|
-
{
|
|
219
|
-
status: 404,
|
|
220
|
-
headers: { "Content-Type": "application/json" }
|
|
221
|
-
}
|
|
222
|
-
);
|
|
223
|
-
}
|
|
224
|
-
let input;
|
|
225
|
-
try {
|
|
226
|
-
const requestBody = await request.json();
|
|
227
|
-
input = import_client2.RunAgentInputSchema.parse(requestBody);
|
|
228
|
-
} catch (error) {
|
|
229
|
-
console.error("Invalid connect request body:", error);
|
|
230
|
-
return new Response(
|
|
231
|
-
JSON.stringify({
|
|
232
|
-
error: "Invalid request body",
|
|
233
|
-
details: error instanceof Error ? error.message : String(error)
|
|
234
|
-
}),
|
|
235
|
-
{
|
|
236
|
-
status: 400,
|
|
237
|
-
headers: { "Content-Type": "application/json" }
|
|
238
|
-
}
|
|
239
|
-
);
|
|
240
|
-
}
|
|
241
|
-
const stream = new TransformStream();
|
|
242
|
-
const writer = stream.writable.getWriter();
|
|
243
|
-
const encoder = new import_encoder2.EventEncoder();
|
|
244
|
-
let streamClosed = false;
|
|
245
|
-
(async () => {
|
|
246
|
-
const forwardableHeaders = extractForwardableHeaders(request);
|
|
247
|
-
runtime.runner.connect({
|
|
248
|
-
threadId: input.threadId,
|
|
249
|
-
headers: forwardableHeaders
|
|
250
|
-
}).subscribe({
|
|
251
|
-
next: async (event) => {
|
|
252
|
-
if (!request.signal.aborted && !streamClosed) {
|
|
253
|
-
try {
|
|
254
|
-
await writer.write(encoder.encode(event));
|
|
255
|
-
} catch (error) {
|
|
256
|
-
if (error instanceof Error && error.name === "AbortError") {
|
|
257
|
-
streamClosed = true;
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
},
|
|
262
|
-
error: async (error) => {
|
|
263
|
-
console.error("Error running agent:", error);
|
|
264
|
-
if (!streamClosed) {
|
|
265
|
-
try {
|
|
266
|
-
await writer.close();
|
|
267
|
-
streamClosed = true;
|
|
268
|
-
} catch {
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
},
|
|
272
|
-
complete: async () => {
|
|
273
|
-
if (!streamClosed) {
|
|
274
|
-
try {
|
|
275
|
-
await writer.close();
|
|
276
|
-
streamClosed = true;
|
|
277
|
-
} catch {
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
});
|
|
282
|
-
})().catch((error) => {
|
|
283
|
-
console.error("Error running agent:", error);
|
|
284
|
-
console.error(
|
|
285
|
-
"Error stack:",
|
|
286
|
-
error instanceof Error ? error.stack : "No stack trace"
|
|
287
|
-
);
|
|
288
|
-
console.error("Error details:", {
|
|
289
|
-
name: error instanceof Error ? error.name : "Unknown",
|
|
290
|
-
message: error instanceof Error ? error.message : String(error),
|
|
291
|
-
cause: error instanceof Error ? error.cause : void 0
|
|
292
|
-
});
|
|
293
|
-
if (!streamClosed) {
|
|
294
|
-
try {
|
|
295
|
-
writer.close();
|
|
296
|
-
streamClosed = true;
|
|
297
|
-
} catch {
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
});
|
|
301
|
-
return new Response(stream.readable, {
|
|
302
|
-
status: 200,
|
|
303
|
-
headers: {
|
|
304
|
-
"Content-Type": "text/event-stream",
|
|
305
|
-
"Cache-Control": "no-cache",
|
|
306
|
-
Connection: "keep-alive"
|
|
307
|
-
}
|
|
308
|
-
});
|
|
309
|
-
} catch (error) {
|
|
310
|
-
console.error("Error running agent:", error);
|
|
311
|
-
console.error(
|
|
312
|
-
"Error stack:",
|
|
313
|
-
error instanceof Error ? error.stack : "No stack trace"
|
|
314
|
-
);
|
|
315
|
-
console.error("Error details:", {
|
|
316
|
-
name: error instanceof Error ? error.name : "Unknown",
|
|
317
|
-
message: error instanceof Error ? error.message : String(error),
|
|
318
|
-
cause: error instanceof Error ? error.cause : void 0
|
|
319
|
-
});
|
|
320
|
-
return new Response(
|
|
321
|
-
JSON.stringify({
|
|
322
|
-
error: "Failed to run agent",
|
|
323
|
-
message: error instanceof Error ? error.message : "Unknown error"
|
|
324
|
-
}),
|
|
325
|
-
{
|
|
326
|
-
status: 500,
|
|
327
|
-
headers: { "Content-Type": "application/json" }
|
|
328
|
-
}
|
|
329
|
-
);
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
// src/handlers/handle-stop.ts
|
|
334
|
-
var import_client3 = require("@ag-ui/client");
|
|
335
|
-
async function handleStopAgent({
|
|
336
|
-
runtime,
|
|
337
|
-
request,
|
|
338
|
-
agentId,
|
|
339
|
-
threadId
|
|
340
|
-
}) {
|
|
341
|
-
try {
|
|
342
|
-
const agents = await runtime.agents;
|
|
343
|
-
if (!agents[agentId]) {
|
|
344
|
-
return new Response(
|
|
345
|
-
JSON.stringify({
|
|
346
|
-
error: "Agent not found",
|
|
347
|
-
message: `Agent '${agentId}' does not exist`
|
|
348
|
-
}),
|
|
349
|
-
{
|
|
350
|
-
status: 404,
|
|
351
|
-
headers: { "Content-Type": "application/json" }
|
|
352
|
-
}
|
|
353
|
-
);
|
|
354
|
-
}
|
|
355
|
-
const stopped = await runtime.runner.stop({ threadId });
|
|
356
|
-
if (!stopped) {
|
|
357
|
-
return new Response(
|
|
358
|
-
JSON.stringify({
|
|
359
|
-
stopped: false,
|
|
360
|
-
message: `No active run for thread '${threadId}'.`
|
|
361
|
-
}),
|
|
362
|
-
{
|
|
363
|
-
status: 200,
|
|
364
|
-
headers: { "Content-Type": "application/json" }
|
|
365
|
-
}
|
|
366
|
-
);
|
|
367
|
-
}
|
|
368
|
-
return new Response(
|
|
369
|
-
JSON.stringify({
|
|
370
|
-
stopped: true,
|
|
371
|
-
interrupt: {
|
|
372
|
-
type: import_client3.EventType.RUN_ERROR,
|
|
373
|
-
message: "Run stopped by user",
|
|
374
|
-
code: "STOPPED"
|
|
375
|
-
}
|
|
376
|
-
}),
|
|
377
|
-
{
|
|
378
|
-
status: 200,
|
|
379
|
-
headers: { "Content-Type": "application/json" }
|
|
380
|
-
}
|
|
381
|
-
);
|
|
382
|
-
} catch (error) {
|
|
383
|
-
console.error("Error stopping agent run:", error);
|
|
384
|
-
return new Response(
|
|
385
|
-
JSON.stringify({
|
|
386
|
-
error: "Failed to stop agent",
|
|
387
|
-
message: error instanceof Error ? error.message : "Unknown error"
|
|
388
|
-
}),
|
|
389
|
-
{
|
|
390
|
-
status: 500,
|
|
391
|
-
headers: { "Content-Type": "application/json" }
|
|
392
|
-
}
|
|
393
|
-
);
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
// package.json
|
|
398
|
-
var package_default = {
|
|
399
|
-
name: "@copilotkitnext/runtime",
|
|
400
|
-
version: "1.51.4",
|
|
401
|
-
description: "Server-side runtime package for CopilotKit2",
|
|
402
|
-
main: "dist/index.js",
|
|
403
|
-
types: "dist/index.d.ts",
|
|
404
|
-
exports: {
|
|
405
|
-
".": {
|
|
406
|
-
types: "./dist/index.d.ts",
|
|
407
|
-
import: "./dist/index.mjs",
|
|
408
|
-
require: "./dist/index.js"
|
|
409
|
-
},
|
|
410
|
-
"./express": {
|
|
411
|
-
types: "./dist/express.d.ts",
|
|
412
|
-
import: "./dist/express.mjs",
|
|
413
|
-
require: "./dist/express.js"
|
|
414
|
-
}
|
|
415
|
-
},
|
|
416
|
-
publishConfig: {
|
|
417
|
-
access: "public"
|
|
418
|
-
},
|
|
419
|
-
scripts: {
|
|
420
|
-
build: "tsup",
|
|
421
|
-
dev: "tsup --watch",
|
|
422
|
-
lint: "eslint .",
|
|
423
|
-
"check-types": "tsc --noEmit",
|
|
424
|
-
test: "vitest run",
|
|
425
|
-
"test:watch": "vitest",
|
|
426
|
-
"test:coverage": "vitest run --coverage"
|
|
427
|
-
},
|
|
428
|
-
devDependencies: {
|
|
429
|
-
"@copilotkitnext/eslint-config": "workspace:*",
|
|
430
|
-
"@copilotkitnext/typescript-config": "workspace:*",
|
|
431
|
-
"@types/cors": "^2.8.17",
|
|
432
|
-
"@types/express": "^4.17.21",
|
|
433
|
-
"@types/node": "^22.15.3",
|
|
434
|
-
eslint: "^9.30.0",
|
|
435
|
-
supertest: "^7.1.1",
|
|
436
|
-
tsup: "^8.5.0",
|
|
437
|
-
typescript: "5.8.2",
|
|
438
|
-
vitest: "^3.0.5"
|
|
439
|
-
},
|
|
440
|
-
dependencies: {
|
|
441
|
-
"@ag-ui/client": "0.0.42",
|
|
442
|
-
"@ag-ui/core": "0.0.42",
|
|
443
|
-
"@ag-ui/encoder": "0.0.42",
|
|
444
|
-
"@copilotkitnext/shared": "workspace:*",
|
|
445
|
-
cors: "^2.8.5",
|
|
446
|
-
express: "^4.21.2",
|
|
447
|
-
hono: "^4.11.4",
|
|
448
|
-
rxjs: "7.8.1"
|
|
449
|
-
},
|
|
450
|
-
peerDependencies: {
|
|
451
|
-
"@ag-ui/client": "0.0.42",
|
|
452
|
-
"@ag-ui/core": "0.0.42",
|
|
453
|
-
"@ag-ui/encoder": "0.0.42",
|
|
454
|
-
"@copilotkitnext/shared": "workspace:*"
|
|
455
|
-
},
|
|
456
|
-
peerDependenciesMeta: {},
|
|
457
|
-
engines: {
|
|
458
|
-
node: ">=18"
|
|
459
|
-
}
|
|
460
|
-
};
|
|
461
|
-
|
|
462
|
-
// src/runner/in-memory.ts
|
|
463
|
-
var import_rxjs = require("rxjs");
|
|
464
|
-
var import_client4 = require("@ag-ui/client");
|
|
465
|
-
var import_shared = require("@copilotkitnext/shared");
|
|
466
|
-
var InMemoryEventStore = class {
|
|
467
|
-
constructor(threadId) {
|
|
468
|
-
this.threadId = threadId;
|
|
469
|
-
}
|
|
470
|
-
/** The subject that current consumers subscribe to. */
|
|
471
|
-
subject = null;
|
|
472
|
-
/** True while a run is actively producing events. */
|
|
473
|
-
isRunning = false;
|
|
474
|
-
/** Current run ID */
|
|
475
|
-
currentRunId = null;
|
|
476
|
-
/** Historic completed runs */
|
|
477
|
-
historicRuns = [];
|
|
478
|
-
/** Currently running agent instance (if any). */
|
|
479
|
-
agent = null;
|
|
480
|
-
/** Subject returned from run() while the run is active. */
|
|
481
|
-
runSubject = null;
|
|
482
|
-
/** True once stop() has been requested but the run has not yet finalized. */
|
|
483
|
-
stopRequested = false;
|
|
484
|
-
/** Reference to the events emitted in the current run. */
|
|
485
|
-
currentEvents = null;
|
|
486
|
-
};
|
|
487
|
-
var GLOBAL_STORE_KEY = /* @__PURE__ */ Symbol.for("@copilotkitnext/runtime/in-memory-store");
|
|
488
|
-
function getGlobalStore() {
|
|
489
|
-
const globalAny = globalThis;
|
|
490
|
-
if (!globalAny[GLOBAL_STORE_KEY]) {
|
|
491
|
-
globalAny[GLOBAL_STORE_KEY] = {
|
|
492
|
-
stores: /* @__PURE__ */ new Map(),
|
|
493
|
-
historicRunsBackup: /* @__PURE__ */ new Map()
|
|
494
|
-
};
|
|
495
|
-
}
|
|
496
|
-
const data = globalAny[GLOBAL_STORE_KEY];
|
|
497
|
-
if (data.stores.size === 0 && data.historicRunsBackup.size > 0) {
|
|
498
|
-
for (const [threadId, historicRuns] of data.historicRunsBackup) {
|
|
499
|
-
const store = new InMemoryEventStore(threadId);
|
|
500
|
-
store.historicRuns = historicRuns;
|
|
501
|
-
data.stores.set(threadId, store);
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
|
-
return data.stores;
|
|
505
|
-
}
|
|
506
|
-
var GLOBAL_STORE = getGlobalStore();
|
|
507
|
-
|
|
508
|
-
// src/runtime.ts
|
|
509
|
-
var VERSION = package_default.version;
|
|
510
|
-
|
|
511
|
-
// src/handlers/get-runtime-info.ts
|
|
512
|
-
async function handleGetRuntimeInfo({
|
|
513
|
-
runtime
|
|
514
|
-
}) {
|
|
515
|
-
try {
|
|
516
|
-
const agents = await runtime.agents;
|
|
517
|
-
const agentsDict = Object.entries(agents).reduce(
|
|
518
|
-
(acc, [name, agent]) => {
|
|
519
|
-
acc[name] = {
|
|
520
|
-
name,
|
|
521
|
-
description: agent.description,
|
|
522
|
-
className: agent.constructor.name
|
|
523
|
-
};
|
|
524
|
-
return acc;
|
|
525
|
-
},
|
|
526
|
-
{}
|
|
527
|
-
);
|
|
528
|
-
const runtimeInfo = {
|
|
529
|
-
version: VERSION,
|
|
530
|
-
agents: agentsDict,
|
|
531
|
-
audioFileTranscriptionEnabled: !!runtime.transcriptionService
|
|
532
|
-
};
|
|
533
|
-
return new Response(JSON.stringify(runtimeInfo), {
|
|
534
|
-
status: 200,
|
|
535
|
-
headers: { "Content-Type": "application/json" }
|
|
536
|
-
});
|
|
537
|
-
} catch (error) {
|
|
538
|
-
return new Response(
|
|
539
|
-
JSON.stringify({
|
|
540
|
-
error: "Failed to retrieve runtime information",
|
|
541
|
-
message: error instanceof Error ? error.message : "Unknown error"
|
|
542
|
-
}),
|
|
543
|
-
{
|
|
544
|
-
status: 500,
|
|
545
|
-
headers: { "Content-Type": "application/json" }
|
|
546
|
-
}
|
|
547
|
-
);
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
// src/handlers/handle-transcribe.ts
|
|
552
|
-
var import_shared2 = require("@copilotkitnext/shared");
|
|
553
|
-
var ERROR_STATUS_CODES = {
|
|
554
|
-
[import_shared2.TranscriptionErrorCode.SERVICE_NOT_CONFIGURED]: 503,
|
|
555
|
-
[import_shared2.TranscriptionErrorCode.INVALID_AUDIO_FORMAT]: 400,
|
|
556
|
-
[import_shared2.TranscriptionErrorCode.AUDIO_TOO_LONG]: 400,
|
|
557
|
-
[import_shared2.TranscriptionErrorCode.AUDIO_TOO_SHORT]: 400,
|
|
558
|
-
[import_shared2.TranscriptionErrorCode.RATE_LIMITED]: 429,
|
|
559
|
-
[import_shared2.TranscriptionErrorCode.AUTH_FAILED]: 401,
|
|
560
|
-
[import_shared2.TranscriptionErrorCode.PROVIDER_ERROR]: 500,
|
|
561
|
-
[import_shared2.TranscriptionErrorCode.NETWORK_ERROR]: 502,
|
|
562
|
-
[import_shared2.TranscriptionErrorCode.INVALID_REQUEST]: 400
|
|
563
|
-
};
|
|
564
|
-
var VALID_AUDIO_TYPES = [
|
|
565
|
-
"audio/mpeg",
|
|
566
|
-
"audio/mp3",
|
|
567
|
-
"audio/mp4",
|
|
568
|
-
"audio/wav",
|
|
569
|
-
"audio/webm",
|
|
570
|
-
"audio/ogg",
|
|
571
|
-
"audio/flac",
|
|
572
|
-
"audio/aac"
|
|
573
|
-
];
|
|
574
|
-
function isValidAudioType(type) {
|
|
575
|
-
const baseType = type.split(";")[0]?.trim() ?? "";
|
|
576
|
-
return VALID_AUDIO_TYPES.includes(baseType) || baseType === "" || baseType === "application/octet-stream";
|
|
577
|
-
}
|
|
578
|
-
function createErrorResponse(errorResponse) {
|
|
579
|
-
const status = ERROR_STATUS_CODES[errorResponse.error] ?? 500;
|
|
580
|
-
return new Response(JSON.stringify(errorResponse), {
|
|
581
|
-
status,
|
|
582
|
-
headers: { "Content-Type": "application/json" }
|
|
583
|
-
});
|
|
584
|
-
}
|
|
585
|
-
function base64ToFile(base64, mimeType, filename) {
|
|
586
|
-
const base64Data = base64.includes(",") ? base64.split(",")[1] ?? base64 : base64;
|
|
587
|
-
const binaryString = atob(base64Data);
|
|
588
|
-
const bytes = new Uint8Array(binaryString.length);
|
|
589
|
-
for (let i = 0; i < binaryString.length; i++) {
|
|
590
|
-
bytes[i] = binaryString.charCodeAt(i);
|
|
591
|
-
}
|
|
592
|
-
return new File([bytes], filename, { type: mimeType });
|
|
593
|
-
}
|
|
594
|
-
async function extractAudioFromFormData(request) {
|
|
595
|
-
const formData = await request.formData();
|
|
596
|
-
const audioFile = formData.get("audio");
|
|
597
|
-
if (!audioFile || !(audioFile instanceof File)) {
|
|
598
|
-
const err = import_shared2.TranscriptionErrors.invalidRequest(
|
|
599
|
-
"No audio file found in form data. Please include an 'audio' field."
|
|
600
|
-
);
|
|
601
|
-
return { error: createErrorResponse(err) };
|
|
602
|
-
}
|
|
603
|
-
if (!isValidAudioType(audioFile.type)) {
|
|
604
|
-
const err = import_shared2.TranscriptionErrors.invalidAudioFormat(
|
|
605
|
-
audioFile.type,
|
|
606
|
-
VALID_AUDIO_TYPES
|
|
607
|
-
);
|
|
608
|
-
return { error: createErrorResponse(err) };
|
|
609
|
-
}
|
|
610
|
-
return { file: audioFile };
|
|
611
|
-
}
|
|
612
|
-
async function extractAudioFromJson(request) {
|
|
613
|
-
let body;
|
|
614
|
-
try {
|
|
615
|
-
body = await request.json();
|
|
616
|
-
} catch {
|
|
617
|
-
const err = import_shared2.TranscriptionErrors.invalidRequest(
|
|
618
|
-
"Request body must be valid JSON"
|
|
619
|
-
);
|
|
620
|
-
return { error: createErrorResponse(err) };
|
|
621
|
-
}
|
|
622
|
-
if (!body.audio || typeof body.audio !== "string") {
|
|
623
|
-
const err = import_shared2.TranscriptionErrors.invalidRequest(
|
|
624
|
-
"Request must include 'audio' field with base64-encoded audio data"
|
|
625
|
-
);
|
|
626
|
-
return { error: createErrorResponse(err) };
|
|
627
|
-
}
|
|
628
|
-
if (!body.mimeType || typeof body.mimeType !== "string") {
|
|
629
|
-
const err = import_shared2.TranscriptionErrors.invalidRequest(
|
|
630
|
-
"Request must include 'mimeType' field (e.g., 'audio/webm')"
|
|
631
|
-
);
|
|
632
|
-
return { error: createErrorResponse(err) };
|
|
633
|
-
}
|
|
634
|
-
if (!isValidAudioType(body.mimeType)) {
|
|
635
|
-
const err = import_shared2.TranscriptionErrors.invalidAudioFormat(
|
|
636
|
-
body.mimeType,
|
|
637
|
-
VALID_AUDIO_TYPES
|
|
638
|
-
);
|
|
639
|
-
return { error: createErrorResponse(err) };
|
|
640
|
-
}
|
|
641
|
-
try {
|
|
642
|
-
const filename = body.filename || "recording.webm";
|
|
643
|
-
const file = base64ToFile(body.audio, body.mimeType, filename);
|
|
644
|
-
return { file };
|
|
645
|
-
} catch {
|
|
646
|
-
const err = import_shared2.TranscriptionErrors.invalidRequest(
|
|
647
|
-
"Failed to decode base64 audio data"
|
|
648
|
-
);
|
|
649
|
-
return { error: createErrorResponse(err) };
|
|
650
|
-
}
|
|
651
|
-
}
|
|
652
|
-
function categorizeProviderError(error) {
|
|
653
|
-
const message = error instanceof Error ? error.message : "Unknown error occurred";
|
|
654
|
-
const errorStr = String(error).toLowerCase();
|
|
655
|
-
if (errorStr.includes("rate") || errorStr.includes("429") || errorStr.includes("too many")) {
|
|
656
|
-
return import_shared2.TranscriptionErrors.rateLimited();
|
|
657
|
-
}
|
|
658
|
-
if (errorStr.includes("auth") || errorStr.includes("401") || errorStr.includes("api key") || errorStr.includes("unauthorized")) {
|
|
659
|
-
return import_shared2.TranscriptionErrors.authFailed();
|
|
660
|
-
}
|
|
661
|
-
if (errorStr.includes("too long") || errorStr.includes("duration") || errorStr.includes("length")) {
|
|
662
|
-
return import_shared2.TranscriptionErrors.audioTooLong();
|
|
663
|
-
}
|
|
664
|
-
return import_shared2.TranscriptionErrors.providerError(message);
|
|
665
|
-
}
|
|
666
|
-
async function handleTranscribe({
|
|
667
|
-
runtime,
|
|
668
|
-
request
|
|
669
|
-
}) {
|
|
670
|
-
try {
|
|
671
|
-
if (!runtime.transcriptionService) {
|
|
672
|
-
const err = import_shared2.TranscriptionErrors.serviceNotConfigured();
|
|
673
|
-
return createErrorResponse(err);
|
|
674
|
-
}
|
|
675
|
-
const contentType = request.headers.get("content-type") || "";
|
|
676
|
-
let extractResult;
|
|
677
|
-
if (contentType.includes("multipart/form-data")) {
|
|
678
|
-
extractResult = await extractAudioFromFormData(request);
|
|
679
|
-
} else if (contentType.includes("application/json")) {
|
|
680
|
-
extractResult = await extractAudioFromJson(request);
|
|
681
|
-
} else {
|
|
682
|
-
const err = import_shared2.TranscriptionErrors.invalidRequest(
|
|
683
|
-
"Request must be multipart/form-data or application/json with base64 audio"
|
|
684
|
-
);
|
|
685
|
-
return createErrorResponse(err);
|
|
686
|
-
}
|
|
687
|
-
if ("error" in extractResult) {
|
|
688
|
-
return extractResult.error;
|
|
689
|
-
}
|
|
690
|
-
const audioFile = extractResult.file;
|
|
691
|
-
const transcription = await runtime.transcriptionService.transcribeFile({
|
|
692
|
-
audioFile,
|
|
693
|
-
mimeType: audioFile.type,
|
|
694
|
-
size: audioFile.size
|
|
695
|
-
});
|
|
696
|
-
return new Response(
|
|
697
|
-
JSON.stringify({
|
|
698
|
-
text: transcription,
|
|
699
|
-
size: audioFile.size,
|
|
700
|
-
type: audioFile.type
|
|
701
|
-
}),
|
|
702
|
-
{
|
|
703
|
-
status: 200,
|
|
704
|
-
headers: { "Content-Type": "application/json" }
|
|
705
|
-
}
|
|
706
|
-
);
|
|
707
|
-
} catch (error) {
|
|
708
|
-
return createErrorResponse(categorizeProviderError(error));
|
|
709
|
-
}
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
// src/endpoints/express.ts
|
|
713
|
-
var import_shared5 = require("@copilotkitnext/shared");
|
|
714
|
-
|
|
715
|
-
// src/middleware.ts
|
|
716
|
-
var import_shared3 = require("@copilotkitnext/shared");
|
|
717
|
-
async function callBeforeRequestMiddleware({
|
|
718
|
-
runtime,
|
|
719
|
-
request,
|
|
720
|
-
path
|
|
721
|
-
}) {
|
|
722
|
-
const mw = runtime.beforeRequestMiddleware;
|
|
723
|
-
if (!mw) return;
|
|
724
|
-
if (typeof mw === "function") {
|
|
725
|
-
return mw({ runtime, request, path });
|
|
726
|
-
}
|
|
727
|
-
import_shared3.logger.warn({ mw }, "Unsupported beforeRequestMiddleware value \u2013 skipped");
|
|
728
|
-
return;
|
|
729
|
-
}
|
|
730
|
-
async function callAfterRequestMiddleware({
|
|
731
|
-
runtime,
|
|
732
|
-
response,
|
|
733
|
-
path
|
|
734
|
-
}) {
|
|
735
|
-
const mw = runtime.afterRequestMiddleware;
|
|
736
|
-
if (!mw) return;
|
|
737
|
-
if (typeof mw === "function") {
|
|
738
|
-
return mw({ runtime, response, path });
|
|
739
|
-
}
|
|
740
|
-
import_shared3.logger.warn({ mw }, "Unsupported afterRequestMiddleware value \u2013 skipped");
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
// src/endpoints/express-utils.ts
|
|
744
|
-
var import_node_stream = require("stream");
|
|
745
|
-
var import_node_stream2 = require("stream");
|
|
746
|
-
var import_node_util = require("util");
|
|
747
|
-
var import_shared4 = require("@copilotkitnext/shared");
|
|
748
|
-
var streamPipeline = (0, import_node_util.promisify)(import_node_stream2.pipeline);
|
|
749
|
-
var METHODS_WITHOUT_BODY = /* @__PURE__ */ new Set(["GET", "HEAD"]);
|
|
750
|
-
function createFetchRequestFromExpress(req) {
|
|
751
|
-
const method = req.method?.toUpperCase() ?? "GET";
|
|
752
|
-
const origin = buildOrigin(req);
|
|
753
|
-
const url = `${origin}${req.originalUrl ?? req.url ?? ""}`;
|
|
754
|
-
const headers = new Headers();
|
|
755
|
-
for (const [key, value] of Object.entries(req.headers)) {
|
|
756
|
-
if (value === void 0) continue;
|
|
757
|
-
if (Array.isArray(value)) {
|
|
758
|
-
value.forEach((v) => headers.append(key, v));
|
|
759
|
-
} else {
|
|
760
|
-
headers.set(key, value);
|
|
761
|
-
}
|
|
762
|
-
}
|
|
763
|
-
const init = {
|
|
764
|
-
method,
|
|
765
|
-
headers
|
|
766
|
-
};
|
|
767
|
-
const hasParsedBody = req.body !== void 0 && req.body !== null;
|
|
768
|
-
const streamConsumed = isStreamConsumed(req, hasParsedBody);
|
|
769
|
-
if (!METHODS_WITHOUT_BODY.has(method)) {
|
|
770
|
-
const canStreamBody = req.readable !== false && !streamConsumed;
|
|
771
|
-
if (canStreamBody) {
|
|
772
|
-
init.body = import_node_stream.Readable.toWeb(req);
|
|
773
|
-
init.duplex = "half";
|
|
774
|
-
} else if (hasParsedBody) {
|
|
775
|
-
const { body, contentType } = synthesizeBody(req.body);
|
|
776
|
-
if (contentType) {
|
|
777
|
-
headers.set("content-type", contentType);
|
|
778
|
-
}
|
|
779
|
-
headers.delete("content-length");
|
|
780
|
-
if (body !== void 0) {
|
|
781
|
-
init.body = body;
|
|
782
|
-
}
|
|
783
|
-
import_shared4.logger.info(
|
|
784
|
-
{
|
|
785
|
-
url,
|
|
786
|
-
method,
|
|
787
|
-
readable: req.readable,
|
|
788
|
-
readableEnded: req.readableEnded,
|
|
789
|
-
complete: req.complete
|
|
790
|
-
},
|
|
791
|
-
"Express request stream already consumed; synthesized body from parsed content"
|
|
792
|
-
);
|
|
793
|
-
} else {
|
|
794
|
-
headers.delete("content-length");
|
|
795
|
-
import_shared4.logger.warn(
|
|
796
|
-
{ url, method },
|
|
797
|
-
"Request stream already consumed but no body was available; sending empty body"
|
|
798
|
-
);
|
|
799
|
-
}
|
|
800
|
-
}
|
|
801
|
-
const controller = new AbortController();
|
|
802
|
-
const abort = () => controller.abort();
|
|
803
|
-
req.on("aborted", abort);
|
|
804
|
-
req.on("error", abort);
|
|
805
|
-
req.on("close", () => {
|
|
806
|
-
if (req.aborted) {
|
|
807
|
-
abort();
|
|
808
|
-
}
|
|
809
|
-
});
|
|
810
|
-
init.signal = controller.signal;
|
|
811
|
-
try {
|
|
812
|
-
return new Request(url, init);
|
|
813
|
-
} catch (error) {
|
|
814
|
-
if (error instanceof TypeError && /disturbed|locked/i.test(error.message)) {
|
|
815
|
-
headers.delete("content-length");
|
|
816
|
-
delete init.duplex;
|
|
817
|
-
if (hasParsedBody) {
|
|
818
|
-
const { body, contentType } = synthesizeBody(req.body);
|
|
819
|
-
if (contentType) {
|
|
820
|
-
headers.set("content-type", contentType);
|
|
821
|
-
}
|
|
822
|
-
init.body = body;
|
|
823
|
-
import_shared4.logger.info(
|
|
824
|
-
{ url, method },
|
|
825
|
-
"Request stream disturbed while constructing Request; reused parsed body"
|
|
826
|
-
);
|
|
827
|
-
} else {
|
|
828
|
-
init.body = void 0;
|
|
829
|
-
import_shared4.logger.warn(
|
|
830
|
-
{ url, method },
|
|
831
|
-
"Request stream was disturbed; falling back to empty body"
|
|
832
|
-
);
|
|
833
|
-
}
|
|
834
|
-
return new Request(url, init);
|
|
835
|
-
}
|
|
836
|
-
throw error;
|
|
837
|
-
}
|
|
838
|
-
}
|
|
839
|
-
async function sendFetchResponse(res, response) {
|
|
840
|
-
res.status(response.status);
|
|
841
|
-
response.headers.forEach((value, key) => {
|
|
842
|
-
if (key.toLowerCase() === "content-length" && response.body !== null) {
|
|
843
|
-
return;
|
|
844
|
-
}
|
|
845
|
-
res.setHeader(key, value);
|
|
846
|
-
});
|
|
847
|
-
if (!response.body) {
|
|
848
|
-
res.end();
|
|
849
|
-
return;
|
|
850
|
-
}
|
|
851
|
-
const nodeStream = import_node_stream.Readable.fromWeb(response.body);
|
|
852
|
-
try {
|
|
853
|
-
await streamPipeline(nodeStream, res);
|
|
854
|
-
} catch (error) {
|
|
855
|
-
res.destroy(error);
|
|
856
|
-
throw error;
|
|
857
|
-
}
|
|
858
|
-
}
|
|
859
|
-
function buildOrigin(req) {
|
|
860
|
-
const protocol = req.protocol || (req.secure ? "https" : "http");
|
|
861
|
-
const host = req.get("host") ?? "localhost";
|
|
862
|
-
return `${protocol}://${host}`;
|
|
863
|
-
}
|
|
864
|
-
function isStreamConsumed(req, hasParsedBody) {
|
|
865
|
-
const state = req._readableState;
|
|
866
|
-
return Boolean(
|
|
867
|
-
hasParsedBody || req.readableEnded || req.complete || state?.ended || state?.endEmitted
|
|
868
|
-
);
|
|
869
|
-
}
|
|
870
|
-
function synthesizeBody(body) {
|
|
871
|
-
if (Buffer.isBuffer(body) || body instanceof Uint8Array) {
|
|
872
|
-
return { body };
|
|
873
|
-
}
|
|
874
|
-
if (typeof body === "string") {
|
|
875
|
-
return { body };
|
|
876
|
-
}
|
|
877
|
-
if (typeof body === "object" && body !== void 0) {
|
|
878
|
-
return { body: JSON.stringify(body), contentType: "application/json" };
|
|
879
|
-
}
|
|
880
|
-
return {};
|
|
881
|
-
}
|
|
882
|
-
|
|
883
|
-
// src/endpoints/express.ts
|
|
884
|
-
function createCopilotEndpointExpress({
|
|
885
|
-
runtime,
|
|
886
|
-
basePath
|
|
887
|
-
}) {
|
|
888
|
-
const router = import_express.default.Router();
|
|
889
|
-
const normalizedBase = normalizeBasePath(basePath);
|
|
890
|
-
router.use(
|
|
891
|
-
(0, import_cors.default)({
|
|
892
|
-
origin: "*",
|
|
893
|
-
methods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH", "OPTIONS"],
|
|
894
|
-
allowedHeaders: ["*"]
|
|
895
|
-
})
|
|
896
|
-
);
|
|
897
|
-
router.post(
|
|
898
|
-
joinPath(normalizedBase, "/agent/:agentId/run"),
|
|
899
|
-
createRouteHandler(runtime, async ({ request, req }) => {
|
|
900
|
-
const agentId = req.params.agentId;
|
|
901
|
-
return handleRunAgent({ runtime, request, agentId });
|
|
902
|
-
})
|
|
903
|
-
);
|
|
904
|
-
router.post(
|
|
905
|
-
joinPath(normalizedBase, "/agent/:agentId/connect"),
|
|
906
|
-
createRouteHandler(runtime, async ({ request, req }) => {
|
|
907
|
-
const agentId = req.params.agentId;
|
|
908
|
-
return handleConnectAgent({ runtime, request, agentId });
|
|
909
|
-
})
|
|
910
|
-
);
|
|
911
|
-
router.post(
|
|
912
|
-
joinPath(normalizedBase, "/agent/:agentId/stop/:threadId"),
|
|
913
|
-
createRouteHandler(runtime, async ({ request, req }) => {
|
|
914
|
-
const agentId = req.params.agentId;
|
|
915
|
-
const threadId = req.params.threadId;
|
|
916
|
-
return handleStopAgent({ runtime, request, agentId, threadId });
|
|
917
|
-
})
|
|
918
|
-
);
|
|
919
|
-
router.get(
|
|
920
|
-
joinPath(normalizedBase, "/info"),
|
|
921
|
-
createRouteHandler(runtime, async ({ request }) => {
|
|
922
|
-
return handleGetRuntimeInfo({ runtime, request });
|
|
923
|
-
})
|
|
924
|
-
);
|
|
925
|
-
router.post(
|
|
926
|
-
joinPath(normalizedBase, "/transcribe"),
|
|
927
|
-
createRouteHandler(runtime, async ({ request }) => {
|
|
928
|
-
return handleTranscribe({ runtime, request });
|
|
929
|
-
})
|
|
930
|
-
);
|
|
931
|
-
router.use(joinPath(normalizedBase, "*"), (req, res) => {
|
|
932
|
-
res.status(404).json({ error: "Not found" });
|
|
933
|
-
});
|
|
934
|
-
return router;
|
|
935
|
-
}
|
|
936
|
-
function createRouteHandler(runtime, factory) {
|
|
937
|
-
return async (req, res, next) => {
|
|
938
|
-
const path = req.originalUrl ?? req.path;
|
|
939
|
-
let request = createFetchRequestFromExpress(req);
|
|
940
|
-
try {
|
|
941
|
-
const maybeModifiedRequest = await callBeforeRequestMiddleware({
|
|
942
|
-
runtime,
|
|
943
|
-
request,
|
|
944
|
-
path
|
|
945
|
-
});
|
|
946
|
-
if (maybeModifiedRequest) {
|
|
947
|
-
request = maybeModifiedRequest;
|
|
948
|
-
}
|
|
949
|
-
} catch (error) {
|
|
950
|
-
import_shared5.logger.error(
|
|
951
|
-
{ err: error, url: request.url, path },
|
|
952
|
-
"Error running before request middleware"
|
|
953
|
-
);
|
|
954
|
-
if (error instanceof Response) {
|
|
955
|
-
try {
|
|
956
|
-
await sendFetchResponse(res, error);
|
|
957
|
-
} catch (streamError) {
|
|
958
|
-
next(streamError);
|
|
959
|
-
}
|
|
960
|
-
return;
|
|
961
|
-
}
|
|
962
|
-
next(error);
|
|
963
|
-
return;
|
|
964
|
-
}
|
|
965
|
-
try {
|
|
966
|
-
const response = await factory({ request, req });
|
|
967
|
-
await sendFetchResponse(res, response);
|
|
968
|
-
callAfterRequestMiddleware({ runtime, response, path }).catch((error) => {
|
|
969
|
-
import_shared5.logger.error(
|
|
970
|
-
{ err: error, url: req.originalUrl ?? req.url, path },
|
|
971
|
-
"Error running after request middleware"
|
|
972
|
-
);
|
|
973
|
-
});
|
|
974
|
-
} catch (error) {
|
|
975
|
-
if (error instanceof Response) {
|
|
976
|
-
try {
|
|
977
|
-
await sendFetchResponse(res, error);
|
|
978
|
-
} catch (streamError) {
|
|
979
|
-
next(streamError);
|
|
980
|
-
return;
|
|
981
|
-
}
|
|
982
|
-
callAfterRequestMiddleware({ runtime, response: error, path }).catch(
|
|
983
|
-
(mwError) => {
|
|
984
|
-
import_shared5.logger.error(
|
|
985
|
-
{ err: mwError, url: req.originalUrl ?? req.url, path },
|
|
986
|
-
"Error running after request middleware"
|
|
987
|
-
);
|
|
988
|
-
}
|
|
989
|
-
);
|
|
990
|
-
return;
|
|
991
|
-
}
|
|
992
|
-
import_shared5.logger.error(
|
|
993
|
-
{ err: error, url: request.url, path },
|
|
994
|
-
"Error running request handler"
|
|
995
|
-
);
|
|
996
|
-
next(error);
|
|
997
|
-
}
|
|
998
|
-
};
|
|
999
|
-
}
|
|
1000
|
-
function normalizeBasePath(path) {
|
|
1001
|
-
if (!path) {
|
|
1002
|
-
throw new Error("basePath must be provided for Express endpoint");
|
|
1003
|
-
}
|
|
1004
|
-
if (!path.startsWith("/")) {
|
|
1005
|
-
return `/${path}`;
|
|
1006
|
-
}
|
|
1007
|
-
if (path.length > 1 && path.endsWith("/")) {
|
|
1008
|
-
return path.slice(0, -1);
|
|
1009
|
-
}
|
|
1010
|
-
return path;
|
|
1011
|
-
}
|
|
1012
|
-
function joinPath(basePath, suffix) {
|
|
1013
|
-
if (basePath === "/") {
|
|
1014
|
-
return suffix.startsWith("/") ? suffix : `/${suffix}`;
|
|
1015
|
-
}
|
|
1016
|
-
if (!suffix) {
|
|
1017
|
-
return basePath;
|
|
1018
|
-
}
|
|
1019
|
-
if (suffix === "*") {
|
|
1020
|
-
return `${basePath}/*`;
|
|
1021
|
-
}
|
|
1022
|
-
return `${basePath}${suffix.startsWith("/") ? suffix : `/${suffix}`}`;
|
|
1023
|
-
}
|
|
1024
|
-
|
|
1025
|
-
// src/endpoints/express-single.ts
|
|
1026
|
-
var import_express2 = __toESM(require("express"));
|
|
1027
|
-
var import_cors2 = __toESM(require("cors"));
|
|
1028
|
-
var import_shared6 = require("@copilotkitnext/shared");
|
|
1029
|
-
|
|
1030
|
-
// src/endpoints/single-route-helpers.ts
|
|
1031
|
-
var METHOD_NAMES = [
|
|
1032
|
-
"agent/run",
|
|
1033
|
-
"agent/connect",
|
|
1034
|
-
"agent/stop",
|
|
1035
|
-
"info",
|
|
1036
|
-
"transcribe"
|
|
1037
|
-
];
|
|
1038
|
-
async function parseMethodCall(request) {
|
|
1039
|
-
const contentType = request.headers.get("content-type") || "";
|
|
1040
|
-
if (!contentType.includes("application/json")) {
|
|
1041
|
-
throw createResponseError(
|
|
1042
|
-
"Single-route endpoint expects JSON payloads",
|
|
1043
|
-
415
|
|
1044
|
-
);
|
|
1045
|
-
}
|
|
1046
|
-
let jsonEnvelope;
|
|
1047
|
-
try {
|
|
1048
|
-
jsonEnvelope = await request.clone().json();
|
|
1049
|
-
} catch (error) {
|
|
1050
|
-
throw createResponseError("Invalid JSON payload", 400);
|
|
1051
|
-
}
|
|
1052
|
-
const method = validateMethod(jsonEnvelope.method);
|
|
1053
|
-
return {
|
|
1054
|
-
method,
|
|
1055
|
-
params: jsonEnvelope.params,
|
|
1056
|
-
body: jsonEnvelope.body
|
|
1057
|
-
};
|
|
1058
|
-
}
|
|
1059
|
-
function expectString(params, key) {
|
|
1060
|
-
const value = params?.[key];
|
|
1061
|
-
if (typeof value === "string" && value.trim().length > 0) {
|
|
1062
|
-
return value;
|
|
1063
|
-
}
|
|
1064
|
-
throw createResponseError(`Missing or invalid parameter '${key}'`, 400);
|
|
1065
|
-
}
|
|
1066
|
-
function createJsonRequest(base, body) {
|
|
1067
|
-
if (body === void 0 || body === null) {
|
|
1068
|
-
throw createResponseError("Missing request body for JSON handler", 400);
|
|
1069
|
-
}
|
|
1070
|
-
const headers = new Headers(base.headers);
|
|
1071
|
-
headers.set("content-type", "application/json");
|
|
1072
|
-
headers.delete("content-length");
|
|
1073
|
-
const serializedBody = serializeJsonBody(body);
|
|
1074
|
-
return new Request(base.url, {
|
|
1075
|
-
method: "POST",
|
|
1076
|
-
headers,
|
|
1077
|
-
body: serializedBody,
|
|
1078
|
-
signal: base.signal
|
|
1079
|
-
});
|
|
1080
|
-
}
|
|
1081
|
-
function createResponseError(message, status) {
|
|
1082
|
-
return new Response(
|
|
1083
|
-
JSON.stringify({
|
|
1084
|
-
error: "invalid_request",
|
|
1085
|
-
message
|
|
1086
|
-
}),
|
|
1087
|
-
{
|
|
1088
|
-
status,
|
|
1089
|
-
headers: {
|
|
1090
|
-
"Content-Type": "application/json"
|
|
1091
|
-
}
|
|
1092
|
-
}
|
|
1093
|
-
);
|
|
1094
|
-
}
|
|
1095
|
-
function validateMethod(method) {
|
|
1096
|
-
if (!method) {
|
|
1097
|
-
throw createResponseError("Missing method field", 400);
|
|
1098
|
-
}
|
|
1099
|
-
if (METHOD_NAMES.includes(method)) {
|
|
1100
|
-
return method;
|
|
1101
|
-
}
|
|
1102
|
-
throw createResponseError(`Unsupported method '${method}'`, 400);
|
|
1103
|
-
}
|
|
1104
|
-
function serializeJsonBody(body) {
|
|
1105
|
-
if (typeof body === "string") {
|
|
1106
|
-
return body;
|
|
1107
|
-
}
|
|
1108
|
-
if (body instanceof Blob || body instanceof ArrayBuffer || body instanceof Uint8Array) {
|
|
1109
|
-
return body;
|
|
1110
|
-
}
|
|
1111
|
-
if (body instanceof FormData || body instanceof URLSearchParams) {
|
|
1112
|
-
return body;
|
|
1113
|
-
}
|
|
1114
|
-
return JSON.stringify(body);
|
|
1115
|
-
}
|
|
1116
|
-
|
|
1117
|
-
// src/endpoints/express-single.ts
|
|
1118
|
-
function createCopilotEndpointSingleRouteExpress({
|
|
1119
|
-
runtime,
|
|
1120
|
-
basePath
|
|
1121
|
-
}) {
|
|
1122
|
-
const router = import_express2.default.Router();
|
|
1123
|
-
const routePath = normalizeSingleRoutePath(basePath);
|
|
1124
|
-
router.use(
|
|
1125
|
-
(0, import_cors2.default)({
|
|
1126
|
-
origin: "*",
|
|
1127
|
-
methods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH", "OPTIONS"],
|
|
1128
|
-
allowedHeaders: ["*"]
|
|
1129
|
-
})
|
|
1130
|
-
);
|
|
1131
|
-
router.post(routePath, createSingleRouteHandler(runtime));
|
|
1132
|
-
router.use((req, res) => {
|
|
1133
|
-
res.status(404).json({ error: "Not found" });
|
|
1134
|
-
});
|
|
1135
|
-
return router;
|
|
1136
|
-
}
|
|
1137
|
-
function createSingleRouteHandler(runtime) {
|
|
1138
|
-
return async (req, res, next) => {
|
|
1139
|
-
const path = req.originalUrl ?? req.path;
|
|
1140
|
-
let request = createFetchRequestFromExpress(req);
|
|
1141
|
-
try {
|
|
1142
|
-
const maybeModifiedRequest = await callBeforeRequestMiddleware({
|
|
1143
|
-
runtime,
|
|
1144
|
-
request,
|
|
1145
|
-
path
|
|
1146
|
-
});
|
|
1147
|
-
if (maybeModifiedRequest) {
|
|
1148
|
-
request = maybeModifiedRequest;
|
|
1149
|
-
}
|
|
1150
|
-
} catch (error) {
|
|
1151
|
-
import_shared6.logger.error(
|
|
1152
|
-
{ err: error, url: request.url, path },
|
|
1153
|
-
"Error running before request middleware"
|
|
1154
|
-
);
|
|
1155
|
-
if (error instanceof Response) {
|
|
1156
|
-
try {
|
|
1157
|
-
await sendFetchResponse(res, error);
|
|
1158
|
-
} catch (streamError) {
|
|
1159
|
-
next(streamError);
|
|
1160
|
-
}
|
|
1161
|
-
return;
|
|
1162
|
-
}
|
|
1163
|
-
next(error);
|
|
1164
|
-
return;
|
|
1165
|
-
}
|
|
1166
|
-
let methodCall;
|
|
1167
|
-
try {
|
|
1168
|
-
methodCall = await parseMethodCall(request);
|
|
1169
|
-
} catch (error) {
|
|
1170
|
-
if (error instanceof Response) {
|
|
1171
|
-
import_shared6.logger.warn({ url: request.url }, "Invalid single-route payload");
|
|
1172
|
-
try {
|
|
1173
|
-
await sendFetchResponse(res, error);
|
|
1174
|
-
} catch (streamError) {
|
|
1175
|
-
next(streamError);
|
|
1176
|
-
}
|
|
1177
|
-
return;
|
|
1178
|
-
}
|
|
1179
|
-
import_shared6.logger.warn(
|
|
1180
|
-
{ err: error, url: request.url },
|
|
1181
|
-
"Invalid single-route payload"
|
|
1182
|
-
);
|
|
1183
|
-
res.status(400).json({
|
|
1184
|
-
error: "invalid_request",
|
|
1185
|
-
message: error instanceof Error ? error.message : "Invalid request payload"
|
|
1186
|
-
});
|
|
1187
|
-
return;
|
|
1188
|
-
}
|
|
1189
|
-
try {
|
|
1190
|
-
let response;
|
|
1191
|
-
switch (methodCall.method) {
|
|
1192
|
-
case "agent/run": {
|
|
1193
|
-
const agentId = expectString(methodCall.params, "agentId");
|
|
1194
|
-
const handlerRequest = createJsonRequest(request, methodCall.body);
|
|
1195
|
-
response = await handleRunAgent({
|
|
1196
|
-
runtime,
|
|
1197
|
-
request: handlerRequest,
|
|
1198
|
-
agentId
|
|
1199
|
-
});
|
|
1200
|
-
break;
|
|
1201
|
-
}
|
|
1202
|
-
case "agent/connect": {
|
|
1203
|
-
const agentId = expectString(methodCall.params, "agentId");
|
|
1204
|
-
const handlerRequest = createJsonRequest(request, methodCall.body);
|
|
1205
|
-
response = await handleConnectAgent({
|
|
1206
|
-
runtime,
|
|
1207
|
-
request: handlerRequest,
|
|
1208
|
-
agentId
|
|
1209
|
-
});
|
|
1210
|
-
break;
|
|
1211
|
-
}
|
|
1212
|
-
case "agent/stop": {
|
|
1213
|
-
const agentId = expectString(methodCall.params, "agentId");
|
|
1214
|
-
const threadId = expectString(methodCall.params, "threadId");
|
|
1215
|
-
response = await handleStopAgent({
|
|
1216
|
-
runtime,
|
|
1217
|
-
request,
|
|
1218
|
-
agentId,
|
|
1219
|
-
threadId
|
|
1220
|
-
});
|
|
1221
|
-
break;
|
|
1222
|
-
}
|
|
1223
|
-
case "info": {
|
|
1224
|
-
response = await handleGetRuntimeInfo({ runtime, request });
|
|
1225
|
-
break;
|
|
1226
|
-
}
|
|
1227
|
-
case "transcribe": {
|
|
1228
|
-
const handlerRequest = createJsonRequest(request, methodCall.body);
|
|
1229
|
-
response = await handleTranscribe({
|
|
1230
|
-
runtime,
|
|
1231
|
-
request: handlerRequest
|
|
1232
|
-
});
|
|
1233
|
-
break;
|
|
1234
|
-
}
|
|
1235
|
-
default: {
|
|
1236
|
-
const exhaustive = methodCall.method;
|
|
1237
|
-
return exhaustive;
|
|
1238
|
-
}
|
|
1239
|
-
}
|
|
1240
|
-
await sendFetchResponse(res, response);
|
|
1241
|
-
callAfterRequestMiddleware({ runtime, response, path }).catch((error) => {
|
|
1242
|
-
import_shared6.logger.error(
|
|
1243
|
-
{ err: error, url: req.originalUrl ?? req.url, path },
|
|
1244
|
-
"Error running after request middleware"
|
|
1245
|
-
);
|
|
1246
|
-
});
|
|
1247
|
-
} catch (error) {
|
|
1248
|
-
if (error instanceof Response) {
|
|
1249
|
-
try {
|
|
1250
|
-
await sendFetchResponse(res, error);
|
|
1251
|
-
} catch (streamError) {
|
|
1252
|
-
next(streamError);
|
|
1253
|
-
return;
|
|
1254
|
-
}
|
|
1255
|
-
callAfterRequestMiddleware({ runtime, response: error, path }).catch(
|
|
1256
|
-
(mwError) => {
|
|
1257
|
-
import_shared6.logger.error(
|
|
1258
|
-
{ err: mwError, url: req.originalUrl ?? req.url, path },
|
|
1259
|
-
"Error running after request middleware"
|
|
1260
|
-
);
|
|
1261
|
-
}
|
|
1262
|
-
);
|
|
1263
|
-
return;
|
|
1264
|
-
}
|
|
1265
|
-
import_shared6.logger.error(
|
|
1266
|
-
{ err: error, url: request.url, path },
|
|
1267
|
-
"Error running single-route handler"
|
|
1268
|
-
);
|
|
1269
|
-
next(error);
|
|
1270
|
-
}
|
|
1271
|
-
};
|
|
1272
|
-
}
|
|
1273
|
-
function normalizeSingleRoutePath(path) {
|
|
1274
|
-
if (!path) {
|
|
1275
|
-
throw new Error(
|
|
1276
|
-
"basePath must be provided for Express single-route endpoint"
|
|
1277
|
-
);
|
|
1278
|
-
}
|
|
1279
|
-
if (!path.startsWith("/")) {
|
|
1280
|
-
return `/${path}`;
|
|
1281
|
-
}
|
|
1282
|
-
if (path.length > 1 && path.endsWith("/")) {
|
|
1283
|
-
return path.slice(0, -1);
|
|
1284
|
-
}
|
|
1285
|
-
return path;
|
|
1286
|
-
}
|
|
1287
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
1288
|
-
0 && (module.exports = {
|
|
1289
|
-
createCopilotEndpointExpress,
|
|
1290
|
-
createCopilotEndpointSingleRouteExpress
|
|
1291
|
-
});
|
|
1292
|
-
//# sourceMappingURL=express.js.map
|