@copilotkitnext/runtime 1.51.4 → 1.51.5-next.1

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