@copilotkitnext/runtime 0.0.0-0.0.0-max-changeset-10101010101010-20260109191632

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,1120 @@
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.0-0.0.0-max-changeset-10101010101010-20260109191632",
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/shared": "workspace:*",
413
+ "@copilotkitnext/typescript-config": "workspace:*",
414
+ "@types/cors": "^2.8.17",
415
+ "@types/express": "^4.17.21",
416
+ "@types/node": "^22.15.3",
417
+ eslint: "^9.30.0",
418
+ openai: "^5.9.0",
419
+ supertest: "^7.1.1",
420
+ tsup: "^8.5.0",
421
+ typescript: "5.8.2",
422
+ vitest: "^3.0.5"
423
+ },
424
+ dependencies: {
425
+ cors: "^2.8.5",
426
+ express: "^4.21.2",
427
+ hono: "^4.6.13",
428
+ rxjs: "7.8.1"
429
+ },
430
+ peerDependencies: {
431
+ "@ag-ui/client": "0.0.42",
432
+ "@ag-ui/core": "0.0.42",
433
+ "@ag-ui/encoder": "0.0.42",
434
+ "@copilotkitnext/shared": "workspace:*",
435
+ openai: "^5.9.0"
436
+ },
437
+ peerDependenciesMeta: {},
438
+ engines: {
439
+ node: ">=18"
440
+ }
441
+ };
442
+
443
+ // src/runner/in-memory.ts
444
+ var import_rxjs = require("rxjs");
445
+ var import_client4 = require("@ag-ui/client");
446
+ var import_shared = require("@copilotkitnext/shared");
447
+ var InMemoryEventStore = class {
448
+ constructor(threadId) {
449
+ this.threadId = threadId;
450
+ }
451
+ /** The subject that current consumers subscribe to. */
452
+ subject = null;
453
+ /** True while a run is actively producing events. */
454
+ isRunning = false;
455
+ /** Current run ID */
456
+ currentRunId = null;
457
+ /** Historic completed runs */
458
+ historicRuns = [];
459
+ /** Currently running agent instance (if any). */
460
+ agent = null;
461
+ /** Subject returned from run() while the run is active. */
462
+ runSubject = null;
463
+ /** True once stop() has been requested but the run has not yet finalized. */
464
+ stopRequested = false;
465
+ /** Reference to the events emitted in the current run. */
466
+ currentEvents = null;
467
+ };
468
+ var GLOBAL_STORE_KEY = /* @__PURE__ */ Symbol.for("@copilotkitnext/runtime/in-memory-store");
469
+ function getGlobalStore() {
470
+ const globalAny = globalThis;
471
+ if (!globalAny[GLOBAL_STORE_KEY]) {
472
+ globalAny[GLOBAL_STORE_KEY] = {
473
+ stores: /* @__PURE__ */ new Map(),
474
+ historicRunsBackup: /* @__PURE__ */ new Map()
475
+ };
476
+ }
477
+ const data = globalAny[GLOBAL_STORE_KEY];
478
+ if (data.stores.size === 0 && data.historicRunsBackup.size > 0) {
479
+ for (const [threadId, historicRuns] of data.historicRunsBackup) {
480
+ const store = new InMemoryEventStore(threadId);
481
+ store.historicRuns = historicRuns;
482
+ data.stores.set(threadId, store);
483
+ }
484
+ }
485
+ return data.stores;
486
+ }
487
+ var GLOBAL_STORE = getGlobalStore();
488
+
489
+ // src/runtime.ts
490
+ var VERSION = package_default.version;
491
+
492
+ // src/handlers/get-runtime-info.ts
493
+ async function handleGetRuntimeInfo({
494
+ runtime
495
+ }) {
496
+ try {
497
+ const agents = await runtime.agents;
498
+ const agentsDict = Object.entries(agents).reduce(
499
+ (acc, [name, agent]) => {
500
+ acc[name] = {
501
+ name,
502
+ description: agent.description,
503
+ className: agent.constructor.name
504
+ };
505
+ return acc;
506
+ },
507
+ {}
508
+ );
509
+ const runtimeInfo = {
510
+ version: VERSION,
511
+ agents: agentsDict,
512
+ audioFileTranscriptionEnabled: !!runtime.transcriptionService
513
+ };
514
+ return new Response(JSON.stringify(runtimeInfo), {
515
+ status: 200,
516
+ headers: { "Content-Type": "application/json" }
517
+ });
518
+ } catch (error) {
519
+ return new Response(
520
+ JSON.stringify({
521
+ error: "Failed to retrieve runtime information",
522
+ message: error instanceof Error ? error.message : "Unknown error"
523
+ }),
524
+ {
525
+ status: 500,
526
+ headers: { "Content-Type": "application/json" }
527
+ }
528
+ );
529
+ }
530
+ }
531
+
532
+ // src/handlers/handle-transcribe.ts
533
+ async function handleTranscribe({
534
+ runtime,
535
+ request
536
+ }) {
537
+ try {
538
+ if (!runtime.transcriptionService) {
539
+ return new Response(
540
+ JSON.stringify({
541
+ error: "Transcription service not configured",
542
+ message: "No transcription service has been configured in the runtime"
543
+ }),
544
+ {
545
+ status: 503,
546
+ headers: { "Content-Type": "application/json" }
547
+ }
548
+ );
549
+ }
550
+ const contentType = request.headers.get("content-type");
551
+ if (!contentType || !contentType.includes("multipart/form-data")) {
552
+ return new Response(
553
+ JSON.stringify({
554
+ error: "Invalid content type",
555
+ message: "Request must contain multipart/form-data with an audio file"
556
+ }),
557
+ {
558
+ status: 400,
559
+ headers: { "Content-Type": "application/json" }
560
+ }
561
+ );
562
+ }
563
+ const formData = await request.formData();
564
+ const audioFile = formData.get("audio");
565
+ if (!audioFile || !(audioFile instanceof File)) {
566
+ return new Response(
567
+ JSON.stringify({
568
+ error: "Missing audio file",
569
+ message: "No audio file found in form data. Please include an 'audio' field."
570
+ }),
571
+ {
572
+ status: 400,
573
+ headers: { "Content-Type": "application/json" }
574
+ }
575
+ );
576
+ }
577
+ const validAudioTypes = [
578
+ "audio/mpeg",
579
+ "audio/mp3",
580
+ "audio/mp4",
581
+ "audio/wav",
582
+ "audio/webm",
583
+ "audio/ogg",
584
+ "audio/flac",
585
+ "audio/aac"
586
+ ];
587
+ const isValidType = validAudioTypes.includes(audioFile.type) || audioFile.type === "" || audioFile.type === "application/octet-stream";
588
+ if (!isValidType) {
589
+ return new Response(
590
+ JSON.stringify({
591
+ error: "Invalid file type",
592
+ message: `Unsupported audio file type: ${audioFile.type}. Supported types: ${validAudioTypes.join(", ")}, or files with unknown/empty types`
593
+ }),
594
+ {
595
+ status: 400,
596
+ headers: { "Content-Type": "application/json" }
597
+ }
598
+ );
599
+ }
600
+ const transcription = await runtime.transcriptionService.transcribeFile({
601
+ audioFile,
602
+ mimeType: audioFile.type,
603
+ size: audioFile.size
604
+ });
605
+ return new Response(
606
+ JSON.stringify({
607
+ text: transcription,
608
+ size: audioFile.size,
609
+ type: audioFile.type
610
+ }),
611
+ {
612
+ status: 200,
613
+ headers: { "Content-Type": "application/json" }
614
+ }
615
+ );
616
+ } catch (error) {
617
+ return new Response(
618
+ JSON.stringify({
619
+ error: "Transcription failed",
620
+ message: error instanceof Error ? error.message : "Unknown error occurred during transcription"
621
+ }),
622
+ {
623
+ status: 500,
624
+ headers: { "Content-Type": "application/json" }
625
+ }
626
+ );
627
+ }
628
+ }
629
+
630
+ // src/endpoints/express.ts
631
+ var import_shared4 = require("@copilotkitnext/shared");
632
+
633
+ // src/middleware.ts
634
+ var import_shared2 = require("@copilotkitnext/shared");
635
+ async function callBeforeRequestMiddleware({
636
+ runtime,
637
+ request,
638
+ path
639
+ }) {
640
+ const mw = runtime.beforeRequestMiddleware;
641
+ if (!mw) return;
642
+ if (typeof mw === "function") {
643
+ return mw({ runtime, request, path });
644
+ }
645
+ import_shared2.logger.warn({ mw }, "Unsupported beforeRequestMiddleware value \u2013 skipped");
646
+ return;
647
+ }
648
+ async function callAfterRequestMiddleware({
649
+ runtime,
650
+ response,
651
+ path
652
+ }) {
653
+ const mw = runtime.afterRequestMiddleware;
654
+ if (!mw) return;
655
+ if (typeof mw === "function") {
656
+ return mw({ runtime, response, path });
657
+ }
658
+ import_shared2.logger.warn({ mw }, "Unsupported afterRequestMiddleware value \u2013 skipped");
659
+ }
660
+
661
+ // src/endpoints/express-utils.ts
662
+ var import_node_stream = require("stream");
663
+ var import_node_stream2 = require("stream");
664
+ var import_node_util = require("util");
665
+ var import_shared3 = require("@copilotkitnext/shared");
666
+ var streamPipeline = (0, import_node_util.promisify)(import_node_stream2.pipeline);
667
+ var METHODS_WITHOUT_BODY = /* @__PURE__ */ new Set(["GET", "HEAD"]);
668
+ function createFetchRequestFromExpress(req) {
669
+ const method = req.method?.toUpperCase() ?? "GET";
670
+ const origin = buildOrigin(req);
671
+ const url = `${origin}${req.originalUrl ?? req.url ?? ""}`;
672
+ const headers = new Headers();
673
+ for (const [key, value] of Object.entries(req.headers)) {
674
+ if (value === void 0) continue;
675
+ if (Array.isArray(value)) {
676
+ value.forEach((v) => headers.append(key, v));
677
+ } else {
678
+ headers.set(key, value);
679
+ }
680
+ }
681
+ const init = {
682
+ method,
683
+ headers
684
+ };
685
+ const hasParsedBody = req.body !== void 0 && req.body !== null;
686
+ const streamConsumed = isStreamConsumed(req, hasParsedBody);
687
+ if (!METHODS_WITHOUT_BODY.has(method)) {
688
+ const canStreamBody = req.readable !== false && !streamConsumed;
689
+ if (canStreamBody) {
690
+ init.body = import_node_stream.Readable.toWeb(req);
691
+ init.duplex = "half";
692
+ } else if (hasParsedBody) {
693
+ const { body, contentType } = synthesizeBody(req.body);
694
+ if (contentType) {
695
+ headers.set("content-type", contentType);
696
+ }
697
+ headers.delete("content-length");
698
+ if (body !== void 0) {
699
+ init.body = body;
700
+ }
701
+ import_shared3.logger.info(
702
+ {
703
+ url,
704
+ method,
705
+ readable: req.readable,
706
+ readableEnded: req.readableEnded,
707
+ complete: req.complete
708
+ },
709
+ "Express request stream already consumed; synthesized body from parsed content"
710
+ );
711
+ } else {
712
+ headers.delete("content-length");
713
+ import_shared3.logger.warn(
714
+ { url, method },
715
+ "Request stream already consumed but no body was available; sending empty body"
716
+ );
717
+ }
718
+ }
719
+ const controller = new AbortController();
720
+ req.on("close", () => controller.abort());
721
+ init.signal = controller.signal;
722
+ try {
723
+ return new Request(url, init);
724
+ } catch (error) {
725
+ if (error instanceof TypeError && /disturbed|locked/i.test(error.message)) {
726
+ headers.delete("content-length");
727
+ delete init.duplex;
728
+ if (hasParsedBody) {
729
+ const { body, contentType } = synthesizeBody(req.body);
730
+ if (contentType) {
731
+ headers.set("content-type", contentType);
732
+ }
733
+ init.body = body;
734
+ import_shared3.logger.info(
735
+ { url, method },
736
+ "Request stream disturbed while constructing Request; reused parsed body"
737
+ );
738
+ } else {
739
+ init.body = void 0;
740
+ import_shared3.logger.warn(
741
+ { url, method },
742
+ "Request stream was disturbed; falling back to empty body"
743
+ );
744
+ }
745
+ return new Request(url, init);
746
+ }
747
+ throw error;
748
+ }
749
+ }
750
+ async function sendFetchResponse(res, response) {
751
+ res.status(response.status);
752
+ response.headers.forEach((value, key) => {
753
+ if (key.toLowerCase() === "content-length" && response.body !== null) {
754
+ return;
755
+ }
756
+ res.setHeader(key, value);
757
+ });
758
+ if (!response.body) {
759
+ res.end();
760
+ return;
761
+ }
762
+ const nodeStream = import_node_stream.Readable.fromWeb(response.body);
763
+ try {
764
+ await streamPipeline(nodeStream, res);
765
+ } catch (error) {
766
+ res.destroy(error);
767
+ throw error;
768
+ }
769
+ }
770
+ function buildOrigin(req) {
771
+ const protocol = req.protocol || (req.secure ? "https" : "http");
772
+ const host = req.get("host") ?? "localhost";
773
+ return `${protocol}://${host}`;
774
+ }
775
+ function isStreamConsumed(req, hasParsedBody) {
776
+ const state = req._readableState;
777
+ return Boolean(
778
+ hasParsedBody || req.readableEnded || req.complete || state?.ended || state?.endEmitted
779
+ );
780
+ }
781
+ function synthesizeBody(body) {
782
+ if (Buffer.isBuffer(body) || body instanceof Uint8Array) {
783
+ return { body };
784
+ }
785
+ if (typeof body === "string") {
786
+ return { body };
787
+ }
788
+ if (typeof body === "object" && body !== void 0) {
789
+ return { body: JSON.stringify(body), contentType: "application/json" };
790
+ }
791
+ return {};
792
+ }
793
+
794
+ // src/endpoints/express.ts
795
+ function createCopilotEndpointExpress({ runtime, basePath }) {
796
+ const router = import_express.default.Router();
797
+ const normalizedBase = normalizeBasePath(basePath);
798
+ router.use((0, import_cors.default)({
799
+ origin: "*",
800
+ methods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH", "OPTIONS"],
801
+ allowedHeaders: ["*"]
802
+ }));
803
+ router.post(joinPath(normalizedBase, "/agent/:agentId/run"), createRouteHandler(runtime, async ({ request, req }) => {
804
+ const agentId = req.params.agentId;
805
+ return handleRunAgent({ runtime, request, agentId });
806
+ }));
807
+ router.post(joinPath(normalizedBase, "/agent/:agentId/connect"), createRouteHandler(runtime, async ({ request, req }) => {
808
+ const agentId = req.params.agentId;
809
+ return handleConnectAgent({ runtime, request, agentId });
810
+ }));
811
+ router.post(joinPath(normalizedBase, "/agent/:agentId/stop/:threadId"), createRouteHandler(runtime, async ({ request, req }) => {
812
+ const agentId = req.params.agentId;
813
+ const threadId = req.params.threadId;
814
+ return handleStopAgent({ runtime, request, agentId, threadId });
815
+ }));
816
+ router.get(joinPath(normalizedBase, "/info"), createRouteHandler(runtime, async ({ request }) => {
817
+ return handleGetRuntimeInfo({ runtime, request });
818
+ }));
819
+ router.post(joinPath(normalizedBase, "/transcribe"), createRouteHandler(runtime, async ({ request }) => {
820
+ return handleTranscribe({ runtime, request });
821
+ }));
822
+ router.use(joinPath(normalizedBase, "*"), (req, res) => {
823
+ res.status(404).json({ error: "Not found" });
824
+ });
825
+ return router;
826
+ }
827
+ function createRouteHandler(runtime, factory) {
828
+ return async (req, res, next) => {
829
+ const path = req.originalUrl ?? req.path;
830
+ let request = createFetchRequestFromExpress(req);
831
+ try {
832
+ const maybeModifiedRequest = await callBeforeRequestMiddleware({ runtime, request, path });
833
+ if (maybeModifiedRequest) {
834
+ request = maybeModifiedRequest;
835
+ }
836
+ } catch (error) {
837
+ import_shared4.logger.error({ err: error, url: request.url, path }, "Error running before request middleware");
838
+ if (error instanceof Response) {
839
+ try {
840
+ await sendFetchResponse(res, error);
841
+ } catch (streamError) {
842
+ next(streamError);
843
+ }
844
+ return;
845
+ }
846
+ next(error);
847
+ return;
848
+ }
849
+ try {
850
+ const response = await factory({ request, req });
851
+ await sendFetchResponse(res, response);
852
+ callAfterRequestMiddleware({ runtime, response, path }).catch((error) => {
853
+ import_shared4.logger.error({ err: error, url: req.originalUrl ?? req.url, path }, "Error running after request middleware");
854
+ });
855
+ } catch (error) {
856
+ if (error instanceof Response) {
857
+ try {
858
+ await sendFetchResponse(res, error);
859
+ } catch (streamError) {
860
+ next(streamError);
861
+ return;
862
+ }
863
+ callAfterRequestMiddleware({ runtime, response: error, path }).catch((mwError) => {
864
+ import_shared4.logger.error({ err: mwError, url: req.originalUrl ?? req.url, path }, "Error running after request middleware");
865
+ });
866
+ return;
867
+ }
868
+ import_shared4.logger.error({ err: error, url: request.url, path }, "Error running request handler");
869
+ next(error);
870
+ }
871
+ };
872
+ }
873
+ function normalizeBasePath(path) {
874
+ if (!path) {
875
+ throw new Error("basePath must be provided for Express endpoint");
876
+ }
877
+ if (!path.startsWith("/")) {
878
+ return `/${path}`;
879
+ }
880
+ if (path.length > 1 && path.endsWith("/")) {
881
+ return path.slice(0, -1);
882
+ }
883
+ return path;
884
+ }
885
+ function joinPath(basePath, suffix) {
886
+ if (basePath === "/") {
887
+ return suffix.startsWith("/") ? suffix : `/${suffix}`;
888
+ }
889
+ if (!suffix) {
890
+ return basePath;
891
+ }
892
+ if (suffix === "*") {
893
+ return `${basePath}/*`;
894
+ }
895
+ return `${basePath}${suffix.startsWith("/") ? suffix : `/${suffix}`}`;
896
+ }
897
+
898
+ // src/endpoints/express-single.ts
899
+ var import_express2 = __toESM(require("express"));
900
+ var import_cors2 = __toESM(require("cors"));
901
+ var import_shared5 = require("@copilotkitnext/shared");
902
+
903
+ // src/endpoints/single-route-helpers.ts
904
+ var METHOD_NAMES = [
905
+ "agent/run",
906
+ "agent/connect",
907
+ "agent/stop",
908
+ "info",
909
+ "transcribe"
910
+ ];
911
+ async function parseMethodCall(request) {
912
+ const contentType = request.headers.get("content-type") || "";
913
+ if (!contentType.includes("application/json")) {
914
+ throw createResponseError("Single-route endpoint expects JSON payloads", 415);
915
+ }
916
+ let jsonEnvelope;
917
+ try {
918
+ jsonEnvelope = await request.clone().json();
919
+ } catch (error) {
920
+ throw createResponseError("Invalid JSON payload", 400);
921
+ }
922
+ const method = validateMethod(jsonEnvelope.method);
923
+ return {
924
+ method,
925
+ params: jsonEnvelope.params,
926
+ body: jsonEnvelope.body
927
+ };
928
+ }
929
+ function expectString(params, key) {
930
+ const value = params?.[key];
931
+ if (typeof value === "string" && value.trim().length > 0) {
932
+ return value;
933
+ }
934
+ throw createResponseError(`Missing or invalid parameter '${key}'`, 400);
935
+ }
936
+ function createJsonRequest(base, body) {
937
+ if (body === void 0 || body === null) {
938
+ throw createResponseError("Missing request body for JSON handler", 400);
939
+ }
940
+ const headers = new Headers(base.headers);
941
+ headers.set("content-type", "application/json");
942
+ headers.delete("content-length");
943
+ const serializedBody = serializeJsonBody(body);
944
+ return new Request(base.url, {
945
+ method: "POST",
946
+ headers,
947
+ body: serializedBody,
948
+ signal: base.signal
949
+ });
950
+ }
951
+ function createResponseError(message, status) {
952
+ return new Response(
953
+ JSON.stringify({
954
+ error: "invalid_request",
955
+ message
956
+ }),
957
+ {
958
+ status,
959
+ headers: {
960
+ "Content-Type": "application/json"
961
+ }
962
+ }
963
+ );
964
+ }
965
+ function validateMethod(method) {
966
+ if (!method) {
967
+ throw createResponseError("Missing method field", 400);
968
+ }
969
+ if (METHOD_NAMES.includes(method)) {
970
+ return method;
971
+ }
972
+ throw createResponseError(`Unsupported method '${method}'`, 400);
973
+ }
974
+ function serializeJsonBody(body) {
975
+ if (typeof body === "string") {
976
+ return body;
977
+ }
978
+ if (body instanceof Blob || body instanceof ArrayBuffer || body instanceof Uint8Array) {
979
+ return body;
980
+ }
981
+ if (body instanceof FormData || body instanceof URLSearchParams) {
982
+ return body;
983
+ }
984
+ return JSON.stringify(body);
985
+ }
986
+
987
+ // src/endpoints/express-single.ts
988
+ function createCopilotEndpointSingleRouteExpress({
989
+ runtime,
990
+ basePath
991
+ }) {
992
+ const router = import_express2.default.Router();
993
+ const routePath = normalizeSingleRoutePath(basePath);
994
+ router.use((0, import_cors2.default)({
995
+ origin: "*",
996
+ methods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH", "OPTIONS"],
997
+ allowedHeaders: ["*"]
998
+ }));
999
+ router.post(routePath, createSingleRouteHandler(runtime));
1000
+ router.use((req, res) => {
1001
+ res.status(404).json({ error: "Not found" });
1002
+ });
1003
+ return router;
1004
+ }
1005
+ function createSingleRouteHandler(runtime) {
1006
+ return async (req, res, next) => {
1007
+ const path = req.originalUrl ?? req.path;
1008
+ let request = createFetchRequestFromExpress(req);
1009
+ try {
1010
+ const maybeModifiedRequest = await callBeforeRequestMiddleware({ runtime, request, path });
1011
+ if (maybeModifiedRequest) {
1012
+ request = maybeModifiedRequest;
1013
+ }
1014
+ } catch (error) {
1015
+ import_shared5.logger.error({ err: error, url: request.url, path }, "Error running before request middleware");
1016
+ if (error instanceof Response) {
1017
+ try {
1018
+ await sendFetchResponse(res, error);
1019
+ } catch (streamError) {
1020
+ next(streamError);
1021
+ }
1022
+ return;
1023
+ }
1024
+ next(error);
1025
+ return;
1026
+ }
1027
+ let methodCall;
1028
+ try {
1029
+ methodCall = await parseMethodCall(request);
1030
+ } catch (error) {
1031
+ if (error instanceof Response) {
1032
+ import_shared5.logger.warn({ url: request.url }, "Invalid single-route payload");
1033
+ try {
1034
+ await sendFetchResponse(res, error);
1035
+ } catch (streamError) {
1036
+ next(streamError);
1037
+ }
1038
+ return;
1039
+ }
1040
+ import_shared5.logger.warn({ err: error, url: request.url }, "Invalid single-route payload");
1041
+ res.status(400).json({
1042
+ error: "invalid_request",
1043
+ message: error instanceof Error ? error.message : "Invalid request payload"
1044
+ });
1045
+ return;
1046
+ }
1047
+ try {
1048
+ let response;
1049
+ switch (methodCall.method) {
1050
+ case "agent/run": {
1051
+ const agentId = expectString(methodCall.params, "agentId");
1052
+ const handlerRequest = createJsonRequest(request, methodCall.body);
1053
+ response = await handleRunAgent({ runtime, request: handlerRequest, agentId });
1054
+ break;
1055
+ }
1056
+ case "agent/connect": {
1057
+ const agentId = expectString(methodCall.params, "agentId");
1058
+ const handlerRequest = createJsonRequest(request, methodCall.body);
1059
+ response = await handleConnectAgent({ runtime, request: handlerRequest, agentId });
1060
+ break;
1061
+ }
1062
+ case "agent/stop": {
1063
+ const agentId = expectString(methodCall.params, "agentId");
1064
+ const threadId = expectString(methodCall.params, "threadId");
1065
+ response = await handleStopAgent({ runtime, request, agentId, threadId });
1066
+ break;
1067
+ }
1068
+ case "info": {
1069
+ response = await handleGetRuntimeInfo({ runtime, request });
1070
+ break;
1071
+ }
1072
+ case "transcribe": {
1073
+ response = await handleTranscribe({ runtime, request });
1074
+ break;
1075
+ }
1076
+ default: {
1077
+ const exhaustive = methodCall.method;
1078
+ return exhaustive;
1079
+ }
1080
+ }
1081
+ await sendFetchResponse(res, response);
1082
+ callAfterRequestMiddleware({ runtime, response, path }).catch((error) => {
1083
+ import_shared5.logger.error({ err: error, url: req.originalUrl ?? req.url, path }, "Error running after request middleware");
1084
+ });
1085
+ } catch (error) {
1086
+ if (error instanceof Response) {
1087
+ try {
1088
+ await sendFetchResponse(res, error);
1089
+ } catch (streamError) {
1090
+ next(streamError);
1091
+ return;
1092
+ }
1093
+ callAfterRequestMiddleware({ runtime, response: error, path }).catch((mwError) => {
1094
+ import_shared5.logger.error({ err: mwError, url: req.originalUrl ?? req.url, path }, "Error running after request middleware");
1095
+ });
1096
+ return;
1097
+ }
1098
+ import_shared5.logger.error({ err: error, url: request.url, path }, "Error running single-route handler");
1099
+ next(error);
1100
+ }
1101
+ };
1102
+ }
1103
+ function normalizeSingleRoutePath(path) {
1104
+ if (!path) {
1105
+ throw new Error("basePath must be provided for Express single-route endpoint");
1106
+ }
1107
+ if (!path.startsWith("/")) {
1108
+ return `/${path}`;
1109
+ }
1110
+ if (path.length > 1 && path.endsWith("/")) {
1111
+ return path.slice(0, -1);
1112
+ }
1113
+ return path;
1114
+ }
1115
+ // Annotate the CommonJS export names for ESM import in node:
1116
+ 0 && (module.exports = {
1117
+ createCopilotEndpointExpress,
1118
+ createCopilotEndpointSingleRouteExpress
1119
+ });
1120
+ //# sourceMappingURL=express.js.map