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