@copilotkitnext/runtime 0.0.22-alpha.0 → 0.0.22-alpha.2

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