@copilotkitnext/runtime 0.0.20 → 0.0.21-alpha.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.
@@ -0,0 +1,1003 @@
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
+ async function handleRunAgent({
46
+ runtime,
47
+ request,
48
+ agentId
49
+ }) {
50
+ try {
51
+ const agents = await runtime.agents;
52
+ if (!agents[agentId]) {
53
+ return new Response(
54
+ JSON.stringify({
55
+ error: "Agent not found",
56
+ message: `Agent '${agentId}' does not exist`
57
+ }),
58
+ {
59
+ status: 404,
60
+ headers: { "Content-Type": "application/json" }
61
+ }
62
+ );
63
+ }
64
+ const registeredAgent = agents[agentId];
65
+ const agent = registeredAgent.clone();
66
+ if (agent && "headers" in agent) {
67
+ const shouldForward = (headerName) => {
68
+ const lower = headerName.toLowerCase();
69
+ return lower === "authorization" || lower.startsWith("x-");
70
+ };
71
+ const forwardableHeaders = {};
72
+ request.headers.forEach((value, key) => {
73
+ if (shouldForward(key)) {
74
+ forwardableHeaders[key] = value;
75
+ }
76
+ });
77
+ agent.headers = {
78
+ ...agent.headers,
79
+ ...forwardableHeaders
80
+ };
81
+ }
82
+ const stream = new TransformStream();
83
+ const writer = stream.writable.getWriter();
84
+ const encoder = new import_encoder.EventEncoder();
85
+ let streamClosed = false;
86
+ (async () => {
87
+ let input;
88
+ try {
89
+ const requestBody = await request.json();
90
+ input = import_client.RunAgentInputSchema.parse(requestBody);
91
+ } catch {
92
+ return new Response(
93
+ JSON.stringify({
94
+ error: "Invalid request body"
95
+ }),
96
+ { status: 400 }
97
+ );
98
+ }
99
+ agent.setMessages(input.messages);
100
+ agent.setState(input.state);
101
+ agent.threadId = input.threadId;
102
+ runtime.runner.run({
103
+ threadId: input.threadId,
104
+ agent,
105
+ input
106
+ }).subscribe({
107
+ next: async (event) => {
108
+ if (!request.signal.aborted && !streamClosed) {
109
+ try {
110
+ await writer.write(encoder.encode(event));
111
+ } catch (error) {
112
+ if (error instanceof Error && error.name === "AbortError") {
113
+ streamClosed = true;
114
+ }
115
+ }
116
+ }
117
+ },
118
+ error: async (error) => {
119
+ console.error("Error running agent:", error);
120
+ if (!streamClosed) {
121
+ try {
122
+ await writer.close();
123
+ streamClosed = true;
124
+ } catch {
125
+ }
126
+ }
127
+ },
128
+ complete: async () => {
129
+ if (!streamClosed) {
130
+ try {
131
+ await writer.close();
132
+ streamClosed = true;
133
+ } catch {
134
+ }
135
+ }
136
+ }
137
+ });
138
+ })().catch((error) => {
139
+ console.error("Error running agent:", error);
140
+ console.error(
141
+ "Error stack:",
142
+ error instanceof Error ? error.stack : "No stack trace"
143
+ );
144
+ console.error("Error details:", {
145
+ name: error instanceof Error ? error.name : "Unknown",
146
+ message: error instanceof Error ? error.message : String(error),
147
+ cause: error instanceof Error ? error.cause : void 0
148
+ });
149
+ if (!streamClosed) {
150
+ try {
151
+ writer.close();
152
+ streamClosed = true;
153
+ } catch {
154
+ }
155
+ }
156
+ });
157
+ return new Response(stream.readable, {
158
+ status: 200,
159
+ headers: {
160
+ "Content-Type": "text/event-stream",
161
+ "Cache-Control": "no-cache",
162
+ Connection: "keep-alive"
163
+ }
164
+ });
165
+ } catch (error) {
166
+ console.error("Error running agent:", error);
167
+ console.error(
168
+ "Error stack:",
169
+ error instanceof Error ? error.stack : "No stack trace"
170
+ );
171
+ console.error("Error details:", {
172
+ name: error instanceof Error ? error.name : "Unknown",
173
+ message: error instanceof Error ? error.message : String(error),
174
+ cause: error instanceof Error ? error.cause : void 0
175
+ });
176
+ return new Response(
177
+ JSON.stringify({
178
+ error: "Failed to run agent",
179
+ message: error instanceof Error ? error.message : "Unknown error"
180
+ }),
181
+ {
182
+ status: 500,
183
+ headers: { "Content-Type": "application/json" }
184
+ }
185
+ );
186
+ }
187
+ }
188
+
189
+ // src/handlers/handle-connect.ts
190
+ var import_client2 = require("@ag-ui/client");
191
+ var import_encoder2 = require("@ag-ui/encoder");
192
+ async function handleConnectAgent({
193
+ runtime,
194
+ request,
195
+ agentId
196
+ }) {
197
+ try {
198
+ const agents = await runtime.agents;
199
+ if (!agents[agentId]) {
200
+ return new Response(
201
+ JSON.stringify({
202
+ error: "Agent not found",
203
+ message: `Agent '${agentId}' does not exist`
204
+ }),
205
+ {
206
+ status: 404,
207
+ headers: { "Content-Type": "application/json" }
208
+ }
209
+ );
210
+ }
211
+ const stream = new TransformStream();
212
+ const writer = stream.writable.getWriter();
213
+ const encoder = new import_encoder2.EventEncoder();
214
+ let streamClosed = false;
215
+ (async () => {
216
+ let input;
217
+ try {
218
+ const requestBody = await request.json();
219
+ input = import_client2.RunAgentInputSchema.parse(requestBody);
220
+ } catch {
221
+ return new Response(
222
+ JSON.stringify({
223
+ error: "Invalid request body"
224
+ }),
225
+ { status: 400 }
226
+ );
227
+ }
228
+ runtime.runner.connect({
229
+ threadId: input.threadId
230
+ }).subscribe({
231
+ next: async (event) => {
232
+ if (!request.signal.aborted && !streamClosed) {
233
+ try {
234
+ await writer.write(encoder.encode(event));
235
+ } catch (error) {
236
+ if (error instanceof Error && error.name === "AbortError") {
237
+ streamClosed = true;
238
+ }
239
+ }
240
+ }
241
+ },
242
+ error: async (error) => {
243
+ console.error("Error running agent:", error);
244
+ if (!streamClosed) {
245
+ try {
246
+ await writer.close();
247
+ streamClosed = true;
248
+ } catch {
249
+ }
250
+ }
251
+ },
252
+ complete: async () => {
253
+ if (!streamClosed) {
254
+ try {
255
+ await writer.close();
256
+ streamClosed = true;
257
+ } catch {
258
+ }
259
+ }
260
+ }
261
+ });
262
+ })().catch((error) => {
263
+ console.error("Error running agent:", error);
264
+ console.error(
265
+ "Error stack:",
266
+ error instanceof Error ? error.stack : "No stack trace"
267
+ );
268
+ console.error("Error details:", {
269
+ name: error instanceof Error ? error.name : "Unknown",
270
+ message: error instanceof Error ? error.message : String(error),
271
+ cause: error instanceof Error ? error.cause : void 0
272
+ });
273
+ if (!streamClosed) {
274
+ try {
275
+ writer.close();
276
+ streamClosed = true;
277
+ } catch {
278
+ }
279
+ }
280
+ });
281
+ return new Response(stream.readable, {
282
+ status: 200,
283
+ headers: {
284
+ "Content-Type": "text/event-stream",
285
+ "Cache-Control": "no-cache",
286
+ Connection: "keep-alive"
287
+ }
288
+ });
289
+ } catch (error) {
290
+ console.error("Error running agent:", error);
291
+ console.error(
292
+ "Error stack:",
293
+ error instanceof Error ? error.stack : "No stack trace"
294
+ );
295
+ console.error("Error details:", {
296
+ name: error instanceof Error ? error.name : "Unknown",
297
+ message: error instanceof Error ? error.message : String(error),
298
+ cause: error instanceof Error ? error.cause : void 0
299
+ });
300
+ return new Response(
301
+ JSON.stringify({
302
+ error: "Failed to run agent",
303
+ message: error instanceof Error ? error.message : "Unknown error"
304
+ }),
305
+ {
306
+ status: 500,
307
+ headers: { "Content-Type": "application/json" }
308
+ }
309
+ );
310
+ }
311
+ }
312
+
313
+ // src/handlers/handle-stop.ts
314
+ var import_client3 = require("@ag-ui/client");
315
+ async function handleStopAgent({
316
+ runtime,
317
+ request,
318
+ agentId,
319
+ threadId
320
+ }) {
321
+ try {
322
+ const agents = await runtime.agents;
323
+ if (!agents[agentId]) {
324
+ return new Response(
325
+ JSON.stringify({
326
+ error: "Agent not found",
327
+ message: `Agent '${agentId}' does not exist`
328
+ }),
329
+ {
330
+ status: 404,
331
+ headers: { "Content-Type": "application/json" }
332
+ }
333
+ );
334
+ }
335
+ const stopped = await runtime.runner.stop({ threadId });
336
+ if (!stopped) {
337
+ return new Response(
338
+ JSON.stringify({
339
+ stopped: false,
340
+ message: `No active run for thread '${threadId}'.`
341
+ }),
342
+ {
343
+ status: 200,
344
+ headers: { "Content-Type": "application/json" }
345
+ }
346
+ );
347
+ }
348
+ return new Response(
349
+ JSON.stringify({
350
+ stopped: true,
351
+ interrupt: {
352
+ type: import_client3.EventType.RUN_ERROR,
353
+ message: "Run stopped by user",
354
+ code: "STOPPED"
355
+ }
356
+ }),
357
+ {
358
+ status: 200,
359
+ headers: { "Content-Type": "application/json" }
360
+ }
361
+ );
362
+ } catch (error) {
363
+ console.error("Error stopping agent run:", error);
364
+ return new Response(
365
+ JSON.stringify({
366
+ error: "Failed to stop agent",
367
+ message: error instanceof Error ? error.message : "Unknown error"
368
+ }),
369
+ {
370
+ status: 500,
371
+ headers: { "Content-Type": "application/json" }
372
+ }
373
+ );
374
+ }
375
+ }
376
+
377
+ // package.json
378
+ var package_default = {
379
+ name: "@copilotkitnext/runtime",
380
+ version: "0.0.21-alpha.0",
381
+ description: "Server-side runtime package for CopilotKit2",
382
+ main: "dist/index.js",
383
+ types: "dist/index.d.ts",
384
+ exports: {
385
+ ".": {
386
+ types: "./dist/index.d.ts",
387
+ import: "./dist/index.mjs",
388
+ require: "./dist/index.js"
389
+ },
390
+ "./express": {
391
+ types: "./dist/express.d.ts",
392
+ import: "./dist/express.mjs",
393
+ require: "./dist/express.js"
394
+ }
395
+ },
396
+ publishConfig: {
397
+ access: "public"
398
+ },
399
+ scripts: {
400
+ build: "tsup",
401
+ prepublishOnly: "pnpm run build",
402
+ dev: "tsup --watch",
403
+ lint: "eslint . --max-warnings 0",
404
+ "check-types": "tsc --noEmit",
405
+ clean: "rm -rf dist",
406
+ test: "vitest run",
407
+ "test:watch": "vitest",
408
+ "test:coverage": "vitest run --coverage"
409
+ },
410
+ devDependencies: {
411
+ "@copilotkitnext/eslint-config": "workspace:*",
412
+ "@copilotkitnext/typescript-config": "workspace:*",
413
+ "@types/cors": "^2.8.17",
414
+ "@types/express": "^4.17.21",
415
+ "@types/node": "^22.15.3",
416
+ eslint: "^9.30.0",
417
+ openai: "^5.9.0",
418
+ supertest: "^7.1.1",
419
+ tsup: "^8.5.0",
420
+ typescript: "5.8.2",
421
+ vitest: "^3.0.5"
422
+ },
423
+ dependencies: {
424
+ "@ag-ui/client": "0.0.40-alpha.11",
425
+ "@ag-ui/core": "0.0.40-alpha.11",
426
+ "@ag-ui/encoder": "0.0.40-alpha.11",
427
+ "@copilotkitnext/shared": "workspace:*",
428
+ cors: "^2.8.5",
429
+ express: "^4.21.2",
430
+ hono: "^4.6.13",
431
+ rxjs: "7.8.1"
432
+ },
433
+ peerDependencies: {
434
+ openai: "^5.9.0"
435
+ },
436
+ peerDependenciesMeta: {},
437
+ engines: {
438
+ node: ">=18"
439
+ }
440
+ };
441
+
442
+ // src/runner/in-memory.ts
443
+ var import_rxjs = require("rxjs");
444
+ var import_client4 = require("@ag-ui/client");
445
+ var import_shared = require("@copilotkitnext/shared");
446
+
447
+ // src/runtime.ts
448
+ var VERSION = package_default.version;
449
+
450
+ // src/handlers/get-runtime-info.ts
451
+ async function handleGetRuntimeInfo({
452
+ runtime
453
+ }) {
454
+ try {
455
+ const agents = await runtime.agents;
456
+ const agentsDict = Object.entries(agents).reduce(
457
+ (acc, [name, agent]) => {
458
+ acc[name] = {
459
+ name,
460
+ description: agent.description,
461
+ className: agent.constructor.name
462
+ };
463
+ return acc;
464
+ },
465
+ {}
466
+ );
467
+ const runtimeInfo = {
468
+ version: VERSION,
469
+ agents: agentsDict,
470
+ audioFileTranscriptionEnabled: !!runtime.transcriptionService
471
+ };
472
+ return new Response(JSON.stringify(runtimeInfo), {
473
+ status: 200,
474
+ headers: { "Content-Type": "application/json" }
475
+ });
476
+ } catch (error) {
477
+ return new Response(
478
+ JSON.stringify({
479
+ error: "Failed to retrieve runtime information",
480
+ message: error instanceof Error ? error.message : "Unknown error"
481
+ }),
482
+ {
483
+ status: 500,
484
+ headers: { "Content-Type": "application/json" }
485
+ }
486
+ );
487
+ }
488
+ }
489
+
490
+ // src/handlers/handle-transcribe.ts
491
+ async function handleTranscribe({
492
+ runtime,
493
+ request
494
+ }) {
495
+ try {
496
+ if (!runtime.transcriptionService) {
497
+ return new Response(
498
+ JSON.stringify({
499
+ error: "Transcription service not configured",
500
+ message: "No transcription service has been configured in the runtime"
501
+ }),
502
+ {
503
+ status: 503,
504
+ headers: { "Content-Type": "application/json" }
505
+ }
506
+ );
507
+ }
508
+ const contentType = request.headers.get("content-type");
509
+ if (!contentType || !contentType.includes("multipart/form-data")) {
510
+ return new Response(
511
+ JSON.stringify({
512
+ error: "Invalid content type",
513
+ message: "Request must contain multipart/form-data with an audio file"
514
+ }),
515
+ {
516
+ status: 400,
517
+ headers: { "Content-Type": "application/json" }
518
+ }
519
+ );
520
+ }
521
+ const formData = await request.formData();
522
+ const audioFile = formData.get("audio");
523
+ if (!audioFile || !(audioFile instanceof File)) {
524
+ return new Response(
525
+ JSON.stringify({
526
+ error: "Missing audio file",
527
+ message: "No audio file found in form data. Please include an 'audio' field."
528
+ }),
529
+ {
530
+ status: 400,
531
+ headers: { "Content-Type": "application/json" }
532
+ }
533
+ );
534
+ }
535
+ const validAudioTypes = [
536
+ "audio/mpeg",
537
+ "audio/mp3",
538
+ "audio/mp4",
539
+ "audio/wav",
540
+ "audio/webm",
541
+ "audio/ogg",
542
+ "audio/flac",
543
+ "audio/aac"
544
+ ];
545
+ const isValidType = validAudioTypes.includes(audioFile.type) || audioFile.type === "" || audioFile.type === "application/octet-stream";
546
+ if (!isValidType) {
547
+ return new Response(
548
+ JSON.stringify({
549
+ error: "Invalid file type",
550
+ message: `Unsupported audio file type: ${audioFile.type}. Supported types: ${validAudioTypes.join(", ")}, or files with unknown/empty types`
551
+ }),
552
+ {
553
+ status: 400,
554
+ headers: { "Content-Type": "application/json" }
555
+ }
556
+ );
557
+ }
558
+ const transcription = await runtime.transcriptionService.transcribeFile({
559
+ audioFile,
560
+ mimeType: audioFile.type,
561
+ size: audioFile.size
562
+ });
563
+ return new Response(
564
+ JSON.stringify({
565
+ text: transcription,
566
+ size: audioFile.size,
567
+ type: audioFile.type
568
+ }),
569
+ {
570
+ status: 200,
571
+ headers: { "Content-Type": "application/json" }
572
+ }
573
+ );
574
+ } catch (error) {
575
+ return new Response(
576
+ JSON.stringify({
577
+ error: "Transcription failed",
578
+ message: error instanceof Error ? error.message : "Unknown error occurred during transcription"
579
+ }),
580
+ {
581
+ status: 500,
582
+ headers: { "Content-Type": "application/json" }
583
+ }
584
+ );
585
+ }
586
+ }
587
+
588
+ // src/endpoints/express.ts
589
+ var import_shared3 = require("@copilotkitnext/shared");
590
+
591
+ // src/middleware.ts
592
+ var import_shared2 = require("@copilotkitnext/shared");
593
+ async function callBeforeRequestMiddleware({
594
+ runtime,
595
+ request,
596
+ path
597
+ }) {
598
+ const mw = runtime.beforeRequestMiddleware;
599
+ if (!mw) return;
600
+ if (typeof mw === "function") {
601
+ return mw({ runtime, request, path });
602
+ }
603
+ import_shared2.logger.warn({ mw }, "Unsupported beforeRequestMiddleware value \u2013 skipped");
604
+ return;
605
+ }
606
+ async function callAfterRequestMiddleware({
607
+ runtime,
608
+ response,
609
+ path
610
+ }) {
611
+ const mw = runtime.afterRequestMiddleware;
612
+ if (!mw) return;
613
+ if (typeof mw === "function") {
614
+ return mw({ runtime, response, path });
615
+ }
616
+ import_shared2.logger.warn({ mw }, "Unsupported afterRequestMiddleware value \u2013 skipped");
617
+ }
618
+
619
+ // src/endpoints/express-utils.ts
620
+ var import_node_stream = require("stream");
621
+ var import_node_stream2 = require("stream");
622
+ var import_node_util = require("util");
623
+ var streamPipeline = (0, import_node_util.promisify)(import_node_stream2.pipeline);
624
+ var METHODS_WITHOUT_BODY = /* @__PURE__ */ new Set(["GET", "HEAD"]);
625
+ function createFetchRequestFromExpress(req) {
626
+ const method = req.method?.toUpperCase() ?? "GET";
627
+ const origin = buildOrigin(req);
628
+ const url = `${origin}${req.originalUrl ?? req.url ?? ""}`;
629
+ const headers = new Headers();
630
+ for (const [key, value] of Object.entries(req.headers)) {
631
+ if (value === void 0) continue;
632
+ if (Array.isArray(value)) {
633
+ value.forEach((v) => headers.append(key, v));
634
+ } else {
635
+ headers.set(key, value);
636
+ }
637
+ }
638
+ const init = {
639
+ method,
640
+ headers
641
+ };
642
+ if (!METHODS_WITHOUT_BODY.has(method)) {
643
+ init.body = import_node_stream.Readable.toWeb(req);
644
+ init.duplex = "half";
645
+ }
646
+ const controller = new AbortController();
647
+ req.on("close", () => controller.abort());
648
+ init.signal = controller.signal;
649
+ return new Request(url, init);
650
+ }
651
+ async function sendFetchResponse(res, response) {
652
+ res.status(response.status);
653
+ response.headers.forEach((value, key) => {
654
+ if (key.toLowerCase() === "content-length" && response.body !== null) {
655
+ return;
656
+ }
657
+ res.setHeader(key, value);
658
+ });
659
+ if (!response.body) {
660
+ res.end();
661
+ return;
662
+ }
663
+ const nodeStream = import_node_stream.Readable.fromWeb(response.body);
664
+ try {
665
+ await streamPipeline(nodeStream, res);
666
+ } catch (error) {
667
+ res.destroy(error);
668
+ throw error;
669
+ }
670
+ }
671
+ function buildOrigin(req) {
672
+ const protocol = req.protocol || (req.secure ? "https" : "http");
673
+ const host = req.get("host") ?? "localhost";
674
+ return `${protocol}://${host}`;
675
+ }
676
+
677
+ // src/endpoints/express.ts
678
+ function createCopilotEndpointExpress({ runtime, basePath }) {
679
+ const router = import_express.default.Router();
680
+ const normalizedBase = normalizeBasePath(basePath);
681
+ router.use((0, import_cors.default)({
682
+ origin: "*",
683
+ methods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH", "OPTIONS"],
684
+ allowedHeaders: ["*"]
685
+ }));
686
+ router.post(joinPath(normalizedBase, "/agent/:agentId/run"), createRouteHandler(runtime, async ({ request, req }) => {
687
+ const agentId = req.params.agentId;
688
+ return handleRunAgent({ runtime, request, agentId });
689
+ }));
690
+ router.post(joinPath(normalizedBase, "/agent/:agentId/connect"), createRouteHandler(runtime, async ({ request, req }) => {
691
+ const agentId = req.params.agentId;
692
+ return handleConnectAgent({ runtime, request, agentId });
693
+ }));
694
+ router.post(joinPath(normalizedBase, "/agent/:agentId/stop/:threadId"), createRouteHandler(runtime, async ({ request, req }) => {
695
+ const agentId = req.params.agentId;
696
+ const threadId = req.params.threadId;
697
+ return handleStopAgent({ runtime, request, agentId, threadId });
698
+ }));
699
+ router.get(joinPath(normalizedBase, "/info"), createRouteHandler(runtime, async ({ request }) => {
700
+ return handleGetRuntimeInfo({ runtime, request });
701
+ }));
702
+ router.post(joinPath(normalizedBase, "/transcribe"), createRouteHandler(runtime, async ({ request }) => {
703
+ return handleTranscribe({ runtime, request });
704
+ }));
705
+ router.use(joinPath(normalizedBase, "*"), (req, res) => {
706
+ res.status(404).json({ error: "Not found" });
707
+ });
708
+ return router;
709
+ }
710
+ function createRouteHandler(runtime, factory) {
711
+ return async (req, res, next) => {
712
+ const path = req.originalUrl ?? req.path;
713
+ let request = createFetchRequestFromExpress(req);
714
+ try {
715
+ const maybeModifiedRequest = await callBeforeRequestMiddleware({ runtime, request, path });
716
+ if (maybeModifiedRequest) {
717
+ request = maybeModifiedRequest;
718
+ }
719
+ } catch (error) {
720
+ import_shared3.logger.error({ err: error, url: request.url, path }, "Error running before request middleware");
721
+ if (error instanceof Response) {
722
+ try {
723
+ await sendFetchResponse(res, error);
724
+ } catch (streamError) {
725
+ next(streamError);
726
+ }
727
+ return;
728
+ }
729
+ next(error);
730
+ return;
731
+ }
732
+ try {
733
+ const response = await factory({ request, req });
734
+ await sendFetchResponse(res, response);
735
+ callAfterRequestMiddleware({ runtime, response, path }).catch((error) => {
736
+ import_shared3.logger.error({ err: error, url: req.originalUrl ?? req.url, path }, "Error running after request middleware");
737
+ });
738
+ } catch (error) {
739
+ if (error instanceof Response) {
740
+ try {
741
+ await sendFetchResponse(res, error);
742
+ } catch (streamError) {
743
+ next(streamError);
744
+ return;
745
+ }
746
+ callAfterRequestMiddleware({ runtime, response: error, path }).catch((mwError) => {
747
+ import_shared3.logger.error({ err: mwError, url: req.originalUrl ?? req.url, path }, "Error running after request middleware");
748
+ });
749
+ return;
750
+ }
751
+ import_shared3.logger.error({ err: error, url: request.url, path }, "Error running request handler");
752
+ next(error);
753
+ }
754
+ };
755
+ }
756
+ function normalizeBasePath(path) {
757
+ if (!path) {
758
+ throw new Error("basePath must be provided for Express endpoint");
759
+ }
760
+ if (!path.startsWith("/")) {
761
+ return `/${path}`;
762
+ }
763
+ if (path.length > 1 && path.endsWith("/")) {
764
+ return path.slice(0, -1);
765
+ }
766
+ return path;
767
+ }
768
+ function joinPath(basePath, suffix) {
769
+ if (basePath === "/") {
770
+ return suffix.startsWith("/") ? suffix : `/${suffix}`;
771
+ }
772
+ if (!suffix) {
773
+ return basePath;
774
+ }
775
+ if (suffix === "*") {
776
+ return `${basePath}/*`;
777
+ }
778
+ return `${basePath}${suffix.startsWith("/") ? suffix : `/${suffix}`}`;
779
+ }
780
+
781
+ // src/endpoints/express-single.ts
782
+ var import_express2 = __toESM(require("express"));
783
+ var import_cors2 = __toESM(require("cors"));
784
+ var import_shared4 = require("@copilotkitnext/shared");
785
+
786
+ // src/endpoints/single-route-helpers.ts
787
+ var METHOD_NAMES = [
788
+ "agent/run",
789
+ "agent/connect",
790
+ "agent/stop",
791
+ "info",
792
+ "transcribe"
793
+ ];
794
+ async function parseMethodCall(request) {
795
+ const contentType = request.headers.get("content-type") || "";
796
+ if (!contentType.includes("application/json")) {
797
+ throw createResponseError("Single-route endpoint expects JSON payloads", 415);
798
+ }
799
+ let jsonEnvelope;
800
+ try {
801
+ jsonEnvelope = await request.clone().json();
802
+ } catch (error) {
803
+ throw createResponseError("Invalid JSON payload", 400);
804
+ }
805
+ const method = validateMethod(jsonEnvelope.method);
806
+ return {
807
+ method,
808
+ params: jsonEnvelope.params,
809
+ body: jsonEnvelope.body
810
+ };
811
+ }
812
+ function expectString(params, key) {
813
+ const value = params?.[key];
814
+ if (typeof value === "string" && value.trim().length > 0) {
815
+ return value;
816
+ }
817
+ throw createResponseError(`Missing or invalid parameter '${key}'`, 400);
818
+ }
819
+ function createJsonRequest(base, body) {
820
+ if (body === void 0 || body === null) {
821
+ throw createResponseError("Missing request body for JSON handler", 400);
822
+ }
823
+ const headers = new Headers(base.headers);
824
+ headers.set("content-type", "application/json");
825
+ headers.delete("content-length");
826
+ const serializedBody = serializeJsonBody(body);
827
+ return new Request(base.url, {
828
+ method: "POST",
829
+ headers,
830
+ body: serializedBody,
831
+ signal: base.signal
832
+ });
833
+ }
834
+ function createResponseError(message, status) {
835
+ return new Response(
836
+ JSON.stringify({
837
+ error: "invalid_request",
838
+ message
839
+ }),
840
+ {
841
+ status,
842
+ headers: {
843
+ "Content-Type": "application/json"
844
+ }
845
+ }
846
+ );
847
+ }
848
+ function validateMethod(method) {
849
+ if (!method) {
850
+ throw createResponseError("Missing method field", 400);
851
+ }
852
+ if (METHOD_NAMES.includes(method)) {
853
+ return method;
854
+ }
855
+ throw createResponseError(`Unsupported method '${method}'`, 400);
856
+ }
857
+ function serializeJsonBody(body) {
858
+ if (typeof body === "string") {
859
+ return body;
860
+ }
861
+ if (body instanceof Blob || body instanceof ArrayBuffer || body instanceof Uint8Array) {
862
+ return body;
863
+ }
864
+ if (body instanceof FormData || body instanceof URLSearchParams) {
865
+ return body;
866
+ }
867
+ return JSON.stringify(body);
868
+ }
869
+
870
+ // src/endpoints/express-single.ts
871
+ function createCopilotEndpointSingleRouteExpress({
872
+ runtime,
873
+ basePath
874
+ }) {
875
+ const router = import_express2.default.Router();
876
+ const routePath = normalizeSingleRoutePath(basePath);
877
+ router.use((0, import_cors2.default)({
878
+ origin: "*",
879
+ methods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH", "OPTIONS"],
880
+ allowedHeaders: ["*"]
881
+ }));
882
+ router.post(routePath, createSingleRouteHandler(runtime));
883
+ router.use((req, res) => {
884
+ res.status(404).json({ error: "Not found" });
885
+ });
886
+ return router;
887
+ }
888
+ function createSingleRouteHandler(runtime) {
889
+ return async (req, res, next) => {
890
+ const path = req.originalUrl ?? req.path;
891
+ let request = createFetchRequestFromExpress(req);
892
+ try {
893
+ const maybeModifiedRequest = await callBeforeRequestMiddleware({ runtime, request, path });
894
+ if (maybeModifiedRequest) {
895
+ request = maybeModifiedRequest;
896
+ }
897
+ } catch (error) {
898
+ import_shared4.logger.error({ err: error, url: request.url, path }, "Error running before request middleware");
899
+ if (error instanceof Response) {
900
+ try {
901
+ await sendFetchResponse(res, error);
902
+ } catch (streamError) {
903
+ next(streamError);
904
+ }
905
+ return;
906
+ }
907
+ next(error);
908
+ return;
909
+ }
910
+ let methodCall;
911
+ try {
912
+ methodCall = await parseMethodCall(request);
913
+ } catch (error) {
914
+ if (error instanceof Response) {
915
+ import_shared4.logger.warn({ url: request.url }, "Invalid single-route payload");
916
+ try {
917
+ await sendFetchResponse(res, error);
918
+ } catch (streamError) {
919
+ next(streamError);
920
+ }
921
+ return;
922
+ }
923
+ import_shared4.logger.warn({ err: error, url: request.url }, "Invalid single-route payload");
924
+ res.status(400).json({
925
+ error: "invalid_request",
926
+ message: error instanceof Error ? error.message : "Invalid request payload"
927
+ });
928
+ return;
929
+ }
930
+ try {
931
+ let response;
932
+ switch (methodCall.method) {
933
+ case "agent/run": {
934
+ const agentId = expectString(methodCall.params, "agentId");
935
+ const handlerRequest = createJsonRequest(request, methodCall.body);
936
+ response = await handleRunAgent({ runtime, request: handlerRequest, agentId });
937
+ break;
938
+ }
939
+ case "agent/connect": {
940
+ const agentId = expectString(methodCall.params, "agentId");
941
+ const handlerRequest = createJsonRequest(request, methodCall.body);
942
+ response = await handleConnectAgent({ runtime, request: handlerRequest, agentId });
943
+ break;
944
+ }
945
+ case "agent/stop": {
946
+ const agentId = expectString(methodCall.params, "agentId");
947
+ const threadId = expectString(methodCall.params, "threadId");
948
+ response = await handleStopAgent({ runtime, request, agentId, threadId });
949
+ break;
950
+ }
951
+ case "info": {
952
+ response = await handleGetRuntimeInfo({ runtime, request });
953
+ break;
954
+ }
955
+ case "transcribe": {
956
+ response = await handleTranscribe({ runtime, request });
957
+ break;
958
+ }
959
+ default: {
960
+ const exhaustive = methodCall.method;
961
+ return exhaustive;
962
+ }
963
+ }
964
+ await sendFetchResponse(res, response);
965
+ callAfterRequestMiddleware({ runtime, response, path }).catch((error) => {
966
+ import_shared4.logger.error({ err: error, url: req.originalUrl ?? req.url, path }, "Error running after request middleware");
967
+ });
968
+ } catch (error) {
969
+ if (error instanceof Response) {
970
+ try {
971
+ await sendFetchResponse(res, error);
972
+ } catch (streamError) {
973
+ next(streamError);
974
+ return;
975
+ }
976
+ callAfterRequestMiddleware({ runtime, response: error, path }).catch((mwError) => {
977
+ import_shared4.logger.error({ err: mwError, url: req.originalUrl ?? req.url, path }, "Error running after request middleware");
978
+ });
979
+ return;
980
+ }
981
+ import_shared4.logger.error({ err: error, url: request.url, path }, "Error running single-route handler");
982
+ next(error);
983
+ }
984
+ };
985
+ }
986
+ function normalizeSingleRoutePath(path) {
987
+ if (!path) {
988
+ throw new Error("basePath must be provided for Express single-route endpoint");
989
+ }
990
+ if (!path.startsWith("/")) {
991
+ return `/${path}`;
992
+ }
993
+ if (path.length > 1 && path.endsWith("/")) {
994
+ return path.slice(0, -1);
995
+ }
996
+ return path;
997
+ }
998
+ // Annotate the CommonJS export names for ESM import in node:
999
+ 0 && (module.exports = {
1000
+ createCopilotEndpointExpress,
1001
+ createCopilotEndpointSingleRouteExpress
1002
+ });
1003
+ //# sourceMappingURL=express.js.map