@copilotkitnext/runtime 1.52.1 → 1.52.2-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.
- package/dist/endpoints/express-single.cjs +4 -2
- package/dist/endpoints/express-single.cjs.map +1 -1
- package/dist/endpoints/express-single.mjs +4 -2
- package/dist/endpoints/express-single.mjs.map +1 -1
- package/dist/endpoints/express.cjs +4 -2
- package/dist/endpoints/express.cjs.map +1 -1
- package/dist/endpoints/express.mjs +4 -2
- package/dist/endpoints/express.mjs.map +1 -1
- package/dist/endpoints/hono-single.cjs +1 -1
- package/dist/endpoints/hono-single.cjs.map +1 -1
- package/dist/endpoints/hono-single.mjs +1 -1
- package/dist/endpoints/hono-single.mjs.map +1 -1
- package/dist/endpoints/hono.cjs +1 -1
- package/dist/endpoints/hono.cjs.map +1 -1
- package/dist/endpoints/hono.mjs +1 -1
- package/dist/endpoints/hono.mjs.map +1 -1
- package/dist/middleware-sse-parser.cjs +137 -0
- package/dist/middleware-sse-parser.cjs.map +1 -0
- package/dist/middleware-sse-parser.d.cts +21 -0
- package/dist/middleware-sse-parser.d.cts.map +1 -0
- package/dist/middleware-sse-parser.d.mts +21 -0
- package/dist/middleware-sse-parser.d.mts.map +1 -0
- package/dist/middleware-sse-parser.mjs +136 -0
- package/dist/middleware-sse-parser.mjs.map +1 -0
- package/dist/middleware.cjs +6 -1
- package/dist/middleware.cjs.map +1 -1
- package/dist/middleware.d.cts +7 -0
- package/dist/middleware.d.cts.map +1 -1
- package/dist/middleware.d.mts +7 -0
- package/dist/middleware.d.mts.map +1 -1
- package/dist/middleware.mjs +6 -1
- package/dist/middleware.mjs.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.mjs +1 -1
- package/package.json +5 -5
|
@@ -133,10 +133,11 @@ function createSingleRouteHandler(runtime) {
|
|
|
133
133
|
break;
|
|
134
134
|
default: return methodCall.method;
|
|
135
135
|
}
|
|
136
|
+
const responseForMiddleware = response.clone();
|
|
136
137
|
await require_express_utils.sendFetchResponse(res, response);
|
|
137
138
|
require_middleware.callAfterRequestMiddleware({
|
|
138
139
|
runtime,
|
|
139
|
-
response,
|
|
140
|
+
response: responseForMiddleware,
|
|
140
141
|
path
|
|
141
142
|
}).catch((error) => {
|
|
142
143
|
_copilotkitnext_shared.logger.error({
|
|
@@ -147,6 +148,7 @@ function createSingleRouteHandler(runtime) {
|
|
|
147
148
|
});
|
|
148
149
|
} catch (error) {
|
|
149
150
|
if (error instanceof Response) {
|
|
151
|
+
const errorResponseForMiddleware = error.clone();
|
|
150
152
|
try {
|
|
151
153
|
await require_express_utils.sendFetchResponse(res, error);
|
|
152
154
|
} catch (streamError) {
|
|
@@ -155,7 +157,7 @@ function createSingleRouteHandler(runtime) {
|
|
|
155
157
|
}
|
|
156
158
|
require_middleware.callAfterRequestMiddleware({
|
|
157
159
|
runtime,
|
|
158
|
-
response:
|
|
160
|
+
response: errorResponseForMiddleware,
|
|
159
161
|
path
|
|
160
162
|
}).catch((mwError) => {
|
|
161
163
|
_copilotkitnext_shared.logger.error({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express-single.cjs","names":["createFetchRequestFromExpress","callBeforeRequestMiddleware","sendFetchResponse","parseMethodCall","expectString","handleRunAgent","createJsonRequest","handleConnectAgent","handleStopAgent","handleGetRuntimeInfo","handleTranscribe"],"sources":["../../src/endpoints/express-single.ts"],"sourcesContent":["import express from \"express\";\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n NextFunction,\n Router,\n} from \"express\";\nimport cors from \"cors\";\n\nimport { CopilotRuntime } from \"../runtime\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"../middleware\";\nimport {\n createFetchRequestFromExpress,\n sendFetchResponse,\n} from \"./express-utils\";\nimport {\n createJsonRequest,\n expectString,\n MethodCall,\n parseMethodCall,\n} from \"./single-route-helpers\";\n\ninterface CopilotSingleRouteExpressParams {\n runtime: CopilotRuntime;\n basePath: string;\n}\n\nexport function createCopilotEndpointSingleRouteExpress({\n runtime,\n basePath,\n}: CopilotSingleRouteExpressParams): Router {\n const router = express.Router();\n const routePath = normalizeSingleRoutePath(basePath);\n\n router.use(\n cors({\n origin: \"*\",\n methods: [\"GET\", \"HEAD\", \"PUT\", \"POST\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\"*\"],\n }),\n );\n\n router.post(routePath, createSingleRouteHandler(runtime));\n\n router.use((req, res) => {\n res.status(404).json({ error: \"Not found\" });\n });\n\n return router;\n}\n\nfunction createSingleRouteHandler(runtime: CopilotRuntime) {\n return async (\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ) => {\n const path = req.originalUrl ?? req.path;\n let request = createFetchRequestFromExpress(req);\n\n try {\n const maybeModifiedRequest = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModifiedRequest) {\n request = maybeModifiedRequest;\n }\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (error instanceof Response) {\n try {\n await sendFetchResponse(res, error);\n } catch (streamError) {\n next(streamError);\n }\n return;\n }\n next(error);\n return;\n }\n\n let methodCall: MethodCall;\n try {\n methodCall = await parseMethodCall(request);\n } catch (error) {\n if (error instanceof Response) {\n logger.warn({ url: request.url }, \"Invalid single-route payload\");\n try {\n await sendFetchResponse(res, error);\n } catch (streamError) {\n next(streamError);\n }\n return;\n }\n logger.warn(\n { err: error, url: request.url },\n \"Invalid single-route payload\",\n );\n res.status(400).json({\n error: \"invalid_request\",\n message:\n error instanceof Error ? error.message : \"Invalid request payload\",\n });\n return;\n }\n\n try {\n let response: Response;\n switch (methodCall.method) {\n case \"agent/run\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const handlerRequest = createJsonRequest(request, methodCall.body);\n response = await handleRunAgent({\n runtime,\n request: handlerRequest,\n agentId,\n });\n break;\n }\n case \"agent/connect\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const handlerRequest = createJsonRequest(request, methodCall.body);\n response = await handleConnectAgent({\n runtime,\n request: handlerRequest,\n agentId,\n });\n break;\n }\n case \"agent/stop\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const threadId = expectString(methodCall.params, \"threadId\");\n response = await handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n });\n break;\n }\n case \"info\": {\n response = await handleGetRuntimeInfo({ runtime, request });\n break;\n }\n case \"transcribe\": {\n const handlerRequest = createJsonRequest(request, methodCall.body);\n response = await handleTranscribe({\n runtime,\n request: handlerRequest,\n });\n break;\n }\n default: {\n const exhaustive: never = methodCall.method;\n return exhaustive;\n }\n }\n\n await sendFetchResponse(res, response);\n callAfterRequestMiddleware({
|
|
1
|
+
{"version":3,"file":"express-single.cjs","names":["createFetchRequestFromExpress","callBeforeRequestMiddleware","sendFetchResponse","parseMethodCall","expectString","handleRunAgent","createJsonRequest","handleConnectAgent","handleStopAgent","handleGetRuntimeInfo","handleTranscribe"],"sources":["../../src/endpoints/express-single.ts"],"sourcesContent":["import express from \"express\";\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n NextFunction,\n Router,\n} from \"express\";\nimport cors from \"cors\";\n\nimport { CopilotRuntime } from \"../runtime\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"../middleware\";\nimport {\n createFetchRequestFromExpress,\n sendFetchResponse,\n} from \"./express-utils\";\nimport {\n createJsonRequest,\n expectString,\n MethodCall,\n parseMethodCall,\n} from \"./single-route-helpers\";\n\ninterface CopilotSingleRouteExpressParams {\n runtime: CopilotRuntime;\n basePath: string;\n}\n\nexport function createCopilotEndpointSingleRouteExpress({\n runtime,\n basePath,\n}: CopilotSingleRouteExpressParams): Router {\n const router = express.Router();\n const routePath = normalizeSingleRoutePath(basePath);\n\n router.use(\n cors({\n origin: \"*\",\n methods: [\"GET\", \"HEAD\", \"PUT\", \"POST\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\"*\"],\n }),\n );\n\n router.post(routePath, createSingleRouteHandler(runtime));\n\n router.use((req, res) => {\n res.status(404).json({ error: \"Not found\" });\n });\n\n return router;\n}\n\nfunction createSingleRouteHandler(runtime: CopilotRuntime) {\n return async (\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ) => {\n const path = req.originalUrl ?? req.path;\n let request = createFetchRequestFromExpress(req);\n\n try {\n const maybeModifiedRequest = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModifiedRequest) {\n request = maybeModifiedRequest;\n }\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (error instanceof Response) {\n try {\n await sendFetchResponse(res, error);\n } catch (streamError) {\n next(streamError);\n }\n return;\n }\n next(error);\n return;\n }\n\n let methodCall: MethodCall;\n try {\n methodCall = await parseMethodCall(request);\n } catch (error) {\n if (error instanceof Response) {\n logger.warn({ url: request.url }, \"Invalid single-route payload\");\n try {\n await sendFetchResponse(res, error);\n } catch (streamError) {\n next(streamError);\n }\n return;\n }\n logger.warn(\n { err: error, url: request.url },\n \"Invalid single-route payload\",\n );\n res.status(400).json({\n error: \"invalid_request\",\n message:\n error instanceof Error ? error.message : \"Invalid request payload\",\n });\n return;\n }\n\n try {\n let response: Response;\n switch (methodCall.method) {\n case \"agent/run\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const handlerRequest = createJsonRequest(request, methodCall.body);\n response = await handleRunAgent({\n runtime,\n request: handlerRequest,\n agentId,\n });\n break;\n }\n case \"agent/connect\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const handlerRequest = createJsonRequest(request, methodCall.body);\n response = await handleConnectAgent({\n runtime,\n request: handlerRequest,\n agentId,\n });\n break;\n }\n case \"agent/stop\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const threadId = expectString(methodCall.params, \"threadId\");\n response = await handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n });\n break;\n }\n case \"info\": {\n response = await handleGetRuntimeInfo({ runtime, request });\n break;\n }\n case \"transcribe\": {\n const handlerRequest = createJsonRequest(request, methodCall.body);\n response = await handleTranscribe({\n runtime,\n request: handlerRequest,\n });\n break;\n }\n default: {\n const exhaustive: never = methodCall.method;\n return exhaustive;\n }\n }\n\n const responseForMiddleware = response.clone();\n await sendFetchResponse(res, response);\n callAfterRequestMiddleware({\n runtime,\n response: responseForMiddleware,\n path,\n }).catch((error) => {\n logger.error(\n { err: error, url: req.originalUrl ?? req.url, path },\n \"Error running after request middleware\",\n );\n });\n } catch (error) {\n if (error instanceof Response) {\n const errorResponseForMiddleware = error.clone();\n try {\n await sendFetchResponse(res, error);\n } catch (streamError) {\n next(streamError);\n return;\n }\n callAfterRequestMiddleware({\n runtime,\n response: errorResponseForMiddleware,\n path,\n }).catch((mwError) => {\n logger.error(\n { err: mwError, url: req.originalUrl ?? req.url, path },\n \"Error running after request middleware\",\n );\n });\n return;\n }\n logger.error(\n { err: error, url: request.url, path },\n \"Error running single-route handler\",\n );\n next(error);\n }\n };\n}\n\nfunction normalizeSingleRoutePath(path: string): string {\n if (!path) {\n throw new Error(\n \"basePath must be provided for Express single-route endpoint\",\n );\n }\n\n if (!path.startsWith(\"/\")) {\n return `/${path}`;\n }\n\n if (path.length > 1 && path.endsWith(\"/\")) {\n return path.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A2B;KACzB;KACA,UAAU;KACV;KACD,CAAC,CAAC,OAAO,YAAY;AACpB,mCAAO,MACL;MAAE,KAAK;MAAS,KAAK,IAAI,eAAe,IAAI;MAAK;MAAM,EACvD,yCACD;MACD;AACF;;AAEF,iCAAO,MACL;IAAE,KAAK;IAAO,KAAK,QAAQ;IAAK;IAAM,EACtC,qCACD;AACD,QAAK,MAAM;;;;AAKjB,SAAS,yBAAyB,MAAsB;AACtD,KAAI,CAAC,KACH,OAAM,IAAI,MACR,8DACD;AAGH,KAAI,CAAC,KAAK,WAAW,IAAI,CACvB,QAAO,IAAI;AAGb,KAAI,KAAK,SAAS,KAAK,KAAK,SAAS,IAAI,CACvC,QAAO,KAAK,MAAM,GAAG,GAAG;AAG1B,QAAO"}
|
|
@@ -130,10 +130,11 @@ function createSingleRouteHandler(runtime) {
|
|
|
130
130
|
break;
|
|
131
131
|
default: return methodCall.method;
|
|
132
132
|
}
|
|
133
|
+
const responseForMiddleware = response.clone();
|
|
133
134
|
await sendFetchResponse(res, response);
|
|
134
135
|
callAfterRequestMiddleware({
|
|
135
136
|
runtime,
|
|
136
|
-
response,
|
|
137
|
+
response: responseForMiddleware,
|
|
137
138
|
path
|
|
138
139
|
}).catch((error) => {
|
|
139
140
|
logger.error({
|
|
@@ -144,6 +145,7 @@ function createSingleRouteHandler(runtime) {
|
|
|
144
145
|
});
|
|
145
146
|
} catch (error) {
|
|
146
147
|
if (error instanceof Response) {
|
|
148
|
+
const errorResponseForMiddleware = error.clone();
|
|
147
149
|
try {
|
|
148
150
|
await sendFetchResponse(res, error);
|
|
149
151
|
} catch (streamError) {
|
|
@@ -152,7 +154,7 @@ function createSingleRouteHandler(runtime) {
|
|
|
152
154
|
}
|
|
153
155
|
callAfterRequestMiddleware({
|
|
154
156
|
runtime,
|
|
155
|
-
response:
|
|
157
|
+
response: errorResponseForMiddleware,
|
|
156
158
|
path
|
|
157
159
|
}).catch((mwError) => {
|
|
158
160
|
logger.error({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express-single.mjs","names":[],"sources":["../../src/endpoints/express-single.ts"],"sourcesContent":["import express from \"express\";\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n NextFunction,\n Router,\n} from \"express\";\nimport cors from \"cors\";\n\nimport { CopilotRuntime } from \"../runtime\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"../middleware\";\nimport {\n createFetchRequestFromExpress,\n sendFetchResponse,\n} from \"./express-utils\";\nimport {\n createJsonRequest,\n expectString,\n MethodCall,\n parseMethodCall,\n} from \"./single-route-helpers\";\n\ninterface CopilotSingleRouteExpressParams {\n runtime: CopilotRuntime;\n basePath: string;\n}\n\nexport function createCopilotEndpointSingleRouteExpress({\n runtime,\n basePath,\n}: CopilotSingleRouteExpressParams): Router {\n const router = express.Router();\n const routePath = normalizeSingleRoutePath(basePath);\n\n router.use(\n cors({\n origin: \"*\",\n methods: [\"GET\", \"HEAD\", \"PUT\", \"POST\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\"*\"],\n }),\n );\n\n router.post(routePath, createSingleRouteHandler(runtime));\n\n router.use((req, res) => {\n res.status(404).json({ error: \"Not found\" });\n });\n\n return router;\n}\n\nfunction createSingleRouteHandler(runtime: CopilotRuntime) {\n return async (\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ) => {\n const path = req.originalUrl ?? req.path;\n let request = createFetchRequestFromExpress(req);\n\n try {\n const maybeModifiedRequest = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModifiedRequest) {\n request = maybeModifiedRequest;\n }\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (error instanceof Response) {\n try {\n await sendFetchResponse(res, error);\n } catch (streamError) {\n next(streamError);\n }\n return;\n }\n next(error);\n return;\n }\n\n let methodCall: MethodCall;\n try {\n methodCall = await parseMethodCall(request);\n } catch (error) {\n if (error instanceof Response) {\n logger.warn({ url: request.url }, \"Invalid single-route payload\");\n try {\n await sendFetchResponse(res, error);\n } catch (streamError) {\n next(streamError);\n }\n return;\n }\n logger.warn(\n { err: error, url: request.url },\n \"Invalid single-route payload\",\n );\n res.status(400).json({\n error: \"invalid_request\",\n message:\n error instanceof Error ? error.message : \"Invalid request payload\",\n });\n return;\n }\n\n try {\n let response: Response;\n switch (methodCall.method) {\n case \"agent/run\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const handlerRequest = createJsonRequest(request, methodCall.body);\n response = await handleRunAgent({\n runtime,\n request: handlerRequest,\n agentId,\n });\n break;\n }\n case \"agent/connect\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const handlerRequest = createJsonRequest(request, methodCall.body);\n response = await handleConnectAgent({\n runtime,\n request: handlerRequest,\n agentId,\n });\n break;\n }\n case \"agent/stop\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const threadId = expectString(methodCall.params, \"threadId\");\n response = await handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n });\n break;\n }\n case \"info\": {\n response = await handleGetRuntimeInfo({ runtime, request });\n break;\n }\n case \"transcribe\": {\n const handlerRequest = createJsonRequest(request, methodCall.body);\n response = await handleTranscribe({\n runtime,\n request: handlerRequest,\n });\n break;\n }\n default: {\n const exhaustive: never = methodCall.method;\n return exhaustive;\n }\n }\n\n await sendFetchResponse(res, response);\n callAfterRequestMiddleware({
|
|
1
|
+
{"version":3,"file":"express-single.mjs","names":[],"sources":["../../src/endpoints/express-single.ts"],"sourcesContent":["import express from \"express\";\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n NextFunction,\n Router,\n} from \"express\";\nimport cors from \"cors\";\n\nimport { CopilotRuntime } from \"../runtime\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"../middleware\";\nimport {\n createFetchRequestFromExpress,\n sendFetchResponse,\n} from \"./express-utils\";\nimport {\n createJsonRequest,\n expectString,\n MethodCall,\n parseMethodCall,\n} from \"./single-route-helpers\";\n\ninterface CopilotSingleRouteExpressParams {\n runtime: CopilotRuntime;\n basePath: string;\n}\n\nexport function createCopilotEndpointSingleRouteExpress({\n runtime,\n basePath,\n}: CopilotSingleRouteExpressParams): Router {\n const router = express.Router();\n const routePath = normalizeSingleRoutePath(basePath);\n\n router.use(\n cors({\n origin: \"*\",\n methods: [\"GET\", \"HEAD\", \"PUT\", \"POST\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\"*\"],\n }),\n );\n\n router.post(routePath, createSingleRouteHandler(runtime));\n\n router.use((req, res) => {\n res.status(404).json({ error: \"Not found\" });\n });\n\n return router;\n}\n\nfunction createSingleRouteHandler(runtime: CopilotRuntime) {\n return async (\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ) => {\n const path = req.originalUrl ?? req.path;\n let request = createFetchRequestFromExpress(req);\n\n try {\n const maybeModifiedRequest = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModifiedRequest) {\n request = maybeModifiedRequest;\n }\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (error instanceof Response) {\n try {\n await sendFetchResponse(res, error);\n } catch (streamError) {\n next(streamError);\n }\n return;\n }\n next(error);\n return;\n }\n\n let methodCall: MethodCall;\n try {\n methodCall = await parseMethodCall(request);\n } catch (error) {\n if (error instanceof Response) {\n logger.warn({ url: request.url }, \"Invalid single-route payload\");\n try {\n await sendFetchResponse(res, error);\n } catch (streamError) {\n next(streamError);\n }\n return;\n }\n logger.warn(\n { err: error, url: request.url },\n \"Invalid single-route payload\",\n );\n res.status(400).json({\n error: \"invalid_request\",\n message:\n error instanceof Error ? error.message : \"Invalid request payload\",\n });\n return;\n }\n\n try {\n let response: Response;\n switch (methodCall.method) {\n case \"agent/run\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const handlerRequest = createJsonRequest(request, methodCall.body);\n response = await handleRunAgent({\n runtime,\n request: handlerRequest,\n agentId,\n });\n break;\n }\n case \"agent/connect\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const handlerRequest = createJsonRequest(request, methodCall.body);\n response = await handleConnectAgent({\n runtime,\n request: handlerRequest,\n agentId,\n });\n break;\n }\n case \"agent/stop\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const threadId = expectString(methodCall.params, \"threadId\");\n response = await handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n });\n break;\n }\n case \"info\": {\n response = await handleGetRuntimeInfo({ runtime, request });\n break;\n }\n case \"transcribe\": {\n const handlerRequest = createJsonRequest(request, methodCall.body);\n response = await handleTranscribe({\n runtime,\n request: handlerRequest,\n });\n break;\n }\n default: {\n const exhaustive: never = methodCall.method;\n return exhaustive;\n }\n }\n\n const responseForMiddleware = response.clone();\n await sendFetchResponse(res, response);\n callAfterRequestMiddleware({\n runtime,\n response: responseForMiddleware,\n path,\n }).catch((error) => {\n logger.error(\n { err: error, url: req.originalUrl ?? req.url, path },\n \"Error running after request middleware\",\n );\n });\n } catch (error) {\n if (error instanceof Response) {\n const errorResponseForMiddleware = error.clone();\n try {\n await sendFetchResponse(res, error);\n } catch (streamError) {\n next(streamError);\n return;\n }\n callAfterRequestMiddleware({\n runtime,\n response: errorResponseForMiddleware,\n path,\n }).catch((mwError) => {\n logger.error(\n { err: mwError, url: req.originalUrl ?? req.url, path },\n \"Error running after request middleware\",\n );\n });\n return;\n }\n logger.error(\n { err: error, url: request.url, path },\n \"Error running single-route handler\",\n );\n next(error);\n }\n };\n}\n\nfunction normalizeSingleRoutePath(path: string): string {\n if (!path) {\n throw new Error(\n \"basePath must be provided for Express single-route endpoint\",\n );\n }\n\n if (!path.startsWith(\"/\")) {\n return `/${path}`;\n }\n\n if (path.length > 1 && path.endsWith(\"/\")) {\n return path.slice(0, -1);\n }\n\n return path;\n}\n"],"mappings":";;;;;;;;;;;;;AAoCA,SAAgB,wCAAwC,EACtD,SACA,YAC0C;CAC1C,MAAM,SAAS,QAAQ,QAAQ;CAC/B,MAAM,YAAY,yBAAyB,SAAS;AAEpD,QAAO,IACL,KAAK;EACH,QAAQ;EACR,SAAS;GAAC;GAAO;GAAQ;GAAO;GAAQ;GAAU;GAAS;GAAU;EACrE,gBAAgB,CAAC,IAAI;EACtB,CAAC,CACH;AAED,QAAO,KAAK,WAAW,yBAAyB,QAAQ,CAAC;AAEzD,QAAO,KAAK,KAAK,QAAQ;AACvB,MAAI,OAAO,IAAI,CAAC,KAAK,EAAE,OAAO,aAAa,CAAC;GAC5C;AAEF,QAAO;;AAGT,SAAS,yBAAyB,SAAyB;AACzD,QAAO,OACL,KACA,KACA,SACG;EACH,MAAM,OAAO,IAAI,eAAe,IAAI;EACpC,IAAI,UAAU,8BAA8B,IAAI;AAEhD,MAAI;GACF,MAAM,uBAAuB,MAAM,4BAA4B;IAC7D;IACA;IACA;IACD,CAAC;AACF,OAAI,qBACF,WAAU;WAEL,OAAO;AACd,UAAO,MACL;IAAE,KAAK;IAAO,KAAK,QAAQ;IAAK;IAAM,EACtC,0CACD;AACD,OAAI,iBAAiB,UAAU;AAC7B,QAAI;AACF,WAAM,kBAAkB,KAAK,MAAM;aAC5B,aAAa;AACpB,UAAK,YAAY;;AAEnB;;AAEF,QAAK,MAAM;AACX;;EAGF,IAAI;AACJ,MAAI;AACF,g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AAC,OAAO,UAAU;AAClB,WAAO,MACL;KAAE,KAAK;KAAO,KAAK,IAAI,eAAe,IAAI;KAAK;KAAM,EACrD,yCACD;KACD;WACK,OAAO;AACd,OAAI,iBAAiB,UAAU;IAC7B,MAAM,6BAA6B,MAAM,OAAO;AAChD,QAAI;AACF,WAAM,kBAAkB,KAAK,MAAM;aAC5B,aAAa;AACpB,UAAK,YAAY;AACjB;;AAEF,+BAA2B;KACzB;KACA,UAAU;KACV;KACD,CAAC,CAAC,OAAO,YAAY;AACpB,YAAO,MACL;MAAE,KAAK;MAAS,KAAK,IAAI,eAAe,IAAI;MAAK;MAAM,EACvD,yCACD;MACD;AACF;;AAEF,UAAO,MACL;IAAE,KAAK;IAAO,KAAK,QAAQ;IAAK;IAAM,EACtC,qCACD;AACD,QAAK,MAAM;;;;AAKjB,SAAS,yBAAyB,MAAsB;AACtD,KAAI,CAAC,KACH,OAAM,IAAI,MACR,8DACD;AAGH,KAAI,CAAC,KAAK,WAAW,IAAI,CACvB,QAAO,IAAI;AAGb,KAAI,KAAK,SAAS,KAAK,KAAK,SAAS,IAAI,CACvC,QAAO,KAAK,MAAM,GAAG,GAAG;AAG1B,QAAO"}
|
|
@@ -105,10 +105,11 @@ function createRouteHandler(runtime, factory) {
|
|
|
105
105
|
request,
|
|
106
106
|
req
|
|
107
107
|
});
|
|
108
|
+
const responseForMiddleware = response.clone();
|
|
108
109
|
await require_express_utils.sendFetchResponse(res, response);
|
|
109
110
|
require_middleware.callAfterRequestMiddleware({
|
|
110
111
|
runtime,
|
|
111
|
-
response,
|
|
112
|
+
response: responseForMiddleware,
|
|
112
113
|
path
|
|
113
114
|
}).catch((error) => {
|
|
114
115
|
_copilotkitnext_shared.logger.error({
|
|
@@ -119,6 +120,7 @@ function createRouteHandler(runtime, factory) {
|
|
|
119
120
|
});
|
|
120
121
|
} catch (error) {
|
|
121
122
|
if (error instanceof Response) {
|
|
123
|
+
const errorResponseForMiddleware = error.clone();
|
|
122
124
|
try {
|
|
123
125
|
await require_express_utils.sendFetchResponse(res, error);
|
|
124
126
|
} catch (streamError) {
|
|
@@ -127,7 +129,7 @@ function createRouteHandler(runtime, factory) {
|
|
|
127
129
|
}
|
|
128
130
|
require_middleware.callAfterRequestMiddleware({
|
|
129
131
|
runtime,
|
|
130
|
-
response:
|
|
132
|
+
response: errorResponseForMiddleware,
|
|
131
133
|
path
|
|
132
134
|
}).catch((mwError) => {
|
|
133
135
|
_copilotkitnext_shared.logger.error({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express.cjs","names":["handleRunAgent","handleConnectAgent","handleStopAgent","handleGetRuntimeInfo","handleTranscribe","createFetchRequestFromExpress","callBeforeRequestMiddleware","sendFetchResponse"],"sources":["../../src/endpoints/express.ts"],"sourcesContent":["import express from \"express\";\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n NextFunction,\n Router,\n} from \"express\";\nimport cors from \"cors\";\n\nimport { CopilotRuntime } from \"../runtime\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"../middleware\";\nimport {\n createFetchRequestFromExpress,\n sendFetchResponse,\n} from \"./express-utils\";\n\ninterface CopilotExpressEndpointParams {\n runtime: CopilotRuntime;\n basePath: string;\n}\n\nexport function createCopilotEndpointExpress({\n runtime,\n basePath,\n}: CopilotExpressEndpointParams): Router {\n const router = express.Router();\n const normalizedBase = normalizeBasePath(basePath);\n\n router.use(\n cors({\n origin: \"*\",\n methods: [\"GET\", \"HEAD\", \"PUT\", \"POST\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\"*\"],\n }),\n );\n\n router.post(\n joinPath(normalizedBase, \"/agent/:agentId/run\"),\n createRouteHandler(runtime, async ({ request, req }) => {\n const agentId = req.params.agentId as string;\n return handleRunAgent({ runtime, request, agentId });\n }),\n );\n\n router.post(\n joinPath(normalizedBase, \"/agent/:agentId/connect\"),\n createRouteHandler(runtime, async ({ request, req }) => {\n const agentId = req.params.agentId as string;\n return handleConnectAgent({ runtime, request, agentId });\n }),\n );\n\n router.post(\n joinPath(normalizedBase, \"/agent/:agentId/stop/:threadId\"),\n createRouteHandler(runtime, async ({ request, req }) => {\n const agentId = req.params.agentId as string;\n const threadId = req.params.threadId as string;\n return handleStopAgent({ runtime, request, agentId, threadId });\n }),\n );\n\n router.get(\n joinPath(normalizedBase, \"/info\"),\n createRouteHandler(runtime, async ({ request }) => {\n return handleGetRuntimeInfo({ runtime, request });\n }),\n );\n\n router.post(\n joinPath(normalizedBase, \"/transcribe\"),\n createRouteHandler(runtime, async ({ request }) => {\n return handleTranscribe({ runtime, request });\n }),\n );\n\n router.use(joinPath(normalizedBase, \"*\"), (req, res) => {\n res.status(404).json({ error: \"Not found\" });\n });\n\n return router;\n}\n\ntype RouteHandlerContext = {\n request: Request;\n req: ExpressRequest;\n};\n\ntype RouteHandlerFactory = (ctx: RouteHandlerContext) => Promise<Response>;\n\nfunction createRouteHandler(\n runtime: CopilotRuntime,\n factory: RouteHandlerFactory,\n) {\n return async (\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ) => {\n const path = req.originalUrl ?? req.path;\n let request = createFetchRequestFromExpress(req);\n try {\n const maybeModifiedRequest = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModifiedRequest) {\n request = maybeModifiedRequest;\n }\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (error instanceof Response) {\n try {\n await sendFetchResponse(res, error);\n } catch (streamError) {\n next(streamError);\n }\n return;\n }\n next(error);\n return;\n }\n\n try {\n const response = await factory({ request, req });\n await sendFetchResponse(res, response);\n callAfterRequestMiddleware({
|
|
1
|
+
{"version":3,"file":"express.cjs","names":["handleRunAgent","handleConnectAgent","handleStopAgent","handleGetRuntimeInfo","handleTranscribe","createFetchRequestFromExpress","callBeforeRequestMiddleware","sendFetchResponse"],"sources":["../../src/endpoints/express.ts"],"sourcesContent":["import express from \"express\";\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n NextFunction,\n Router,\n} from \"express\";\nimport cors from \"cors\";\n\nimport { CopilotRuntime } from \"../runtime\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"../middleware\";\nimport {\n createFetchRequestFromExpress,\n sendFetchResponse,\n} from \"./express-utils\";\n\ninterface CopilotExpressEndpointParams {\n runtime: CopilotRuntime;\n basePath: string;\n}\n\nexport function createCopilotEndpointExpress({\n runtime,\n basePath,\n}: CopilotExpressEndpointParams): Router {\n const router = express.Router();\n const normalizedBase = normalizeBasePath(basePath);\n\n router.use(\n cors({\n origin: \"*\",\n methods: [\"GET\", \"HEAD\", \"PUT\", \"POST\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\"*\"],\n }),\n );\n\n router.post(\n joinPath(normalizedBase, \"/agent/:agentId/run\"),\n createRouteHandler(runtime, async ({ request, req }) => {\n const agentId = req.params.agentId as string;\n return handleRunAgent({ runtime, request, agentId });\n }),\n );\n\n router.post(\n joinPath(normalizedBase, \"/agent/:agentId/connect\"),\n createRouteHandler(runtime, async ({ request, req }) => {\n const agentId = req.params.agentId as string;\n return handleConnectAgent({ runtime, request, agentId });\n }),\n );\n\n router.post(\n joinPath(normalizedBase, \"/agent/:agentId/stop/:threadId\"),\n createRouteHandler(runtime, async ({ request, req }) => {\n const agentId = req.params.agentId as string;\n const threadId = req.params.threadId as string;\n return handleStopAgent({ runtime, request, agentId, threadId });\n }),\n );\n\n router.get(\n joinPath(normalizedBase, \"/info\"),\n createRouteHandler(runtime, async ({ request }) => {\n return handleGetRuntimeInfo({ runtime, request });\n }),\n );\n\n router.post(\n joinPath(normalizedBase, \"/transcribe\"),\n createRouteHandler(runtime, async ({ request }) => {\n return handleTranscribe({ runtime, request });\n }),\n );\n\n router.use(joinPath(normalizedBase, \"*\"), (req, res) => {\n res.status(404).json({ error: \"Not found\" });\n });\n\n return router;\n}\n\ntype RouteHandlerContext = {\n request: Request;\n req: ExpressRequest;\n};\n\ntype RouteHandlerFactory = (ctx: RouteHandlerContext) => Promise<Response>;\n\nfunction createRouteHandler(\n runtime: CopilotRuntime,\n factory: RouteHandlerFactory,\n) {\n return async (\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ) => {\n const path = req.originalUrl ?? req.path;\n let request = createFetchRequestFromExpress(req);\n try {\n const maybeModifiedRequest = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModifiedRequest) {\n request = maybeModifiedRequest;\n }\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (error instanceof Response) {\n try {\n await sendFetchResponse(res, error);\n } catch (streamError) {\n next(streamError);\n }\n return;\n }\n next(error);\n return;\n }\n\n try {\n const response = await factory({ request, req });\n const responseForMiddleware = response.clone();\n await sendFetchResponse(res, response);\n callAfterRequestMiddleware({\n runtime,\n response: responseForMiddleware,\n path,\n }).catch((error) => {\n logger.error(\n { err: error, url: req.originalUrl ?? req.url, path },\n \"Error running after request middleware\",\n );\n });\n } catch (error) {\n if (error instanceof Response) {\n const errorResponseForMiddleware = error.clone();\n try {\n await sendFetchResponse(res, error);\n } catch (streamError) {\n next(streamError);\n return;\n }\n callAfterRequestMiddleware({\n runtime,\n response: errorResponseForMiddleware,\n path,\n }).catch((mwError) => {\n logger.error(\n { err: mwError, url: req.originalUrl ?? req.url, path },\n \"Error running after request middleware\",\n );\n });\n return;\n }\n logger.error(\n { err: error, url: request.url, path },\n \"Error running request handler\",\n );\n next(error);\n }\n };\n}\n\nfunction normalizeBasePath(path: string): string {\n if (!path) {\n throw new Error(\"basePath must be provided for Express endpoint\");\n }\n\n if (!path.startsWith(\"/\")) {\n return `/${path}`;\n }\n\n if (path.length > 1 && path.endsWith(\"/\")) {\n return path.slice(0, -1);\n }\n\n return path;\n}\n\nfunction joinPath(basePath: string, suffix: string): string {\n if (basePath === \"/\") {\n return suffix.startsWith(\"/\") ? suffix : `/${suffix}`;\n }\n\n if (!suffix) {\n return basePath;\n }\n\n if (suffix === \"*\") {\n return `${basePath}/*`;\n }\n\n return `${basePath}${suffix.startsWith(\"/\") ? suffix : `/${suffix}`}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,SAAgB,6BAA6B,EAC3C,SACA,YACuC;CACvC,MAAM,SAAS,gBAAQ,QAAQ;CAC/B,MAAM,iBAAiB,kBAAkB,SAAS;AAElD,QAAO,sBACA;EACH,QAAQ;EACR,SAAS;GAAC;GAAO;GAAQ;GAAO;GAAQ;GAAU;GAAS;GAAU;EACrE,gBAAgB,CAAC,IAAI;EACtB,CAAC,CACH;AAED,QAAO,KACL,SAAS,gBAAgB,sBAAsB,EAC/C,mBAAmB,SAAS,OAAO,EAAE,SAAS,UAAU;EACtD,MAAM,UAAU,IAAI,OAAO;AAC3B,SAAOA,kCAAe;GAAE;GAAS;GAAS;GAAS,CAAC;GACpD,CACH;AAED,QAAO,KACL,SAAS,gBAAgB,0BAA0B,EACnD,mBAAmB,SAAS,OAAO,EAAE,SAAS,UAAU;EACtD,MAAM,UAAU,IAAI,OAAO;AAC3B,SAAOC,0CAAmB;GAAE;GAAS;GAAS;GAAS,CAAC;GACxD,CACH;AAED,QAAO,KACL,SAAS,gBAAgB,iCAAiC,EAC1D,mBAAmB,SAAS,OAA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,KAAK,IAAI,eAAe,IAAI;KAAK;KAAM,EACrD,yCACD;KACD;WACK,OAAO;AACd,OAAI,iBAAiB,UAAU;IAC7B,MAAM,6BAA6B,MAAM,OAAO;AAChD,QAAI;AACF,WAAMA,wCAAkB,KAAK,MAAM;aAC5B,aAAa;AACpB,UAAK,YAAY;AACjB;;AAEF,kDAA2B;KACzB;KACA,UAAU;KACV;KACD,CAAC,CAAC,OAAO,YAAY;AACpB,mCAAO,MACL;MAAE,KAAK;MAAS,KAAK,IAAI,eAAe,IAAI;MAAK;MAAM,EACvD,yCACD;MACD;AACF;;AAEF,iCAAO,MACL;IAAE,KAAK;IAAO,KAAK,QAAQ;IAAK;IAAM,EACtC,gCACD;AACD,QAAK,MAAM;;;;AAKjB,SAAS,kBAAkB,MAAsB;AAC/C,KAAI,CAAC,KACH,OAAM,IAAI,MAAM,iDAAiD;AAGnE,KAAI,CAAC,KAAK,WAAW,IAAI,CACvB,QAAO,IAAI;AAGb,KAAI,KAAK,SAAS,KAAK,KAAK,SAAS,IAAI,CACvC,QAAO,KAAK,MAAM,GAAG,GAAG;AAG1B,QAAO;;AAGT,SAAS,SAAS,UAAkB,QAAwB;AAC1D,KAAI,aAAa,IACf,QAAO,OAAO,WAAW,IAAI,GAAG,SAAS,IAAI;AAG/C,KAAI,CAAC,OACH,QAAO;AAGT,KAAI,WAAW,IACb,QAAO,GAAG,SAAS;AAGrB,QAAO,GAAG,WAAW,OAAO,WAAW,IAAI,GAAG,SAAS,IAAI"}
|
|
@@ -102,10 +102,11 @@ function createRouteHandler(runtime, factory) {
|
|
|
102
102
|
request,
|
|
103
103
|
req
|
|
104
104
|
});
|
|
105
|
+
const responseForMiddleware = response.clone();
|
|
105
106
|
await sendFetchResponse(res, response);
|
|
106
107
|
callAfterRequestMiddleware({
|
|
107
108
|
runtime,
|
|
108
|
-
response,
|
|
109
|
+
response: responseForMiddleware,
|
|
109
110
|
path
|
|
110
111
|
}).catch((error) => {
|
|
111
112
|
logger.error({
|
|
@@ -116,6 +117,7 @@ function createRouteHandler(runtime, factory) {
|
|
|
116
117
|
});
|
|
117
118
|
} catch (error) {
|
|
118
119
|
if (error instanceof Response) {
|
|
120
|
+
const errorResponseForMiddleware = error.clone();
|
|
119
121
|
try {
|
|
120
122
|
await sendFetchResponse(res, error);
|
|
121
123
|
} catch (streamError) {
|
|
@@ -124,7 +126,7 @@ function createRouteHandler(runtime, factory) {
|
|
|
124
126
|
}
|
|
125
127
|
callAfterRequestMiddleware({
|
|
126
128
|
runtime,
|
|
127
|
-
response:
|
|
129
|
+
response: errorResponseForMiddleware,
|
|
128
130
|
path
|
|
129
131
|
}).catch((mwError) => {
|
|
130
132
|
logger.error({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express.mjs","names":[],"sources":["../../src/endpoints/express.ts"],"sourcesContent":["import express from \"express\";\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n NextFunction,\n Router,\n} from \"express\";\nimport cors from \"cors\";\n\nimport { CopilotRuntime } from \"../runtime\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"../middleware\";\nimport {\n createFetchRequestFromExpress,\n sendFetchResponse,\n} from \"./express-utils\";\n\ninterface CopilotExpressEndpointParams {\n runtime: CopilotRuntime;\n basePath: string;\n}\n\nexport function createCopilotEndpointExpress({\n runtime,\n basePath,\n}: CopilotExpressEndpointParams): Router {\n const router = express.Router();\n const normalizedBase = normalizeBasePath(basePath);\n\n router.use(\n cors({\n origin: \"*\",\n methods: [\"GET\", \"HEAD\", \"PUT\", \"POST\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\"*\"],\n }),\n );\n\n router.post(\n joinPath(normalizedBase, \"/agent/:agentId/run\"),\n createRouteHandler(runtime, async ({ request, req }) => {\n const agentId = req.params.agentId as string;\n return handleRunAgent({ runtime, request, agentId });\n }),\n );\n\n router.post(\n joinPath(normalizedBase, \"/agent/:agentId/connect\"),\n createRouteHandler(runtime, async ({ request, req }) => {\n const agentId = req.params.agentId as string;\n return handleConnectAgent({ runtime, request, agentId });\n }),\n );\n\n router.post(\n joinPath(normalizedBase, \"/agent/:agentId/stop/:threadId\"),\n createRouteHandler(runtime, async ({ request, req }) => {\n const agentId = req.params.agentId as string;\n const threadId = req.params.threadId as string;\n return handleStopAgent({ runtime, request, agentId, threadId });\n }),\n );\n\n router.get(\n joinPath(normalizedBase, \"/info\"),\n createRouteHandler(runtime, async ({ request }) => {\n return handleGetRuntimeInfo({ runtime, request });\n }),\n );\n\n router.post(\n joinPath(normalizedBase, \"/transcribe\"),\n createRouteHandler(runtime, async ({ request }) => {\n return handleTranscribe({ runtime, request });\n }),\n );\n\n router.use(joinPath(normalizedBase, \"*\"), (req, res) => {\n res.status(404).json({ error: \"Not found\" });\n });\n\n return router;\n}\n\ntype RouteHandlerContext = {\n request: Request;\n req: ExpressRequest;\n};\n\ntype RouteHandlerFactory = (ctx: RouteHandlerContext) => Promise<Response>;\n\nfunction createRouteHandler(\n runtime: CopilotRuntime,\n factory: RouteHandlerFactory,\n) {\n return async (\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ) => {\n const path = req.originalUrl ?? req.path;\n let request = createFetchRequestFromExpress(req);\n try {\n const maybeModifiedRequest = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModifiedRequest) {\n request = maybeModifiedRequest;\n }\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (error instanceof Response) {\n try {\n await sendFetchResponse(res, error);\n } catch (streamError) {\n next(streamError);\n }\n return;\n }\n next(error);\n return;\n }\n\n try {\n const response = await factory({ request, req });\n await sendFetchResponse(res, response);\n callAfterRequestMiddleware({
|
|
1
|
+
{"version":3,"file":"express.mjs","names":[],"sources":["../../src/endpoints/express.ts"],"sourcesContent":["import express from \"express\";\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n NextFunction,\n Router,\n} from \"express\";\nimport cors from \"cors\";\n\nimport { CopilotRuntime } from \"../runtime\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"../middleware\";\nimport {\n createFetchRequestFromExpress,\n sendFetchResponse,\n} from \"./express-utils\";\n\ninterface CopilotExpressEndpointParams {\n runtime: CopilotRuntime;\n basePath: string;\n}\n\nexport function createCopilotEndpointExpress({\n runtime,\n basePath,\n}: CopilotExpressEndpointParams): Router {\n const router = express.Router();\n const normalizedBase = normalizeBasePath(basePath);\n\n router.use(\n cors({\n origin: \"*\",\n methods: [\"GET\", \"HEAD\", \"PUT\", \"POST\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\"*\"],\n }),\n );\n\n router.post(\n joinPath(normalizedBase, \"/agent/:agentId/run\"),\n createRouteHandler(runtime, async ({ request, req }) => {\n const agentId = req.params.agentId as string;\n return handleRunAgent({ runtime, request, agentId });\n }),\n );\n\n router.post(\n joinPath(normalizedBase, \"/agent/:agentId/connect\"),\n createRouteHandler(runtime, async ({ request, req }) => {\n const agentId = req.params.agentId as string;\n return handleConnectAgent({ runtime, request, agentId });\n }),\n );\n\n router.post(\n joinPath(normalizedBase, \"/agent/:agentId/stop/:threadId\"),\n createRouteHandler(runtime, async ({ request, req }) => {\n const agentId = req.params.agentId as string;\n const threadId = req.params.threadId as string;\n return handleStopAgent({ runtime, request, agentId, threadId });\n }),\n );\n\n router.get(\n joinPath(normalizedBase, \"/info\"),\n createRouteHandler(runtime, async ({ request }) => {\n return handleGetRuntimeInfo({ runtime, request });\n }),\n );\n\n router.post(\n joinPath(normalizedBase, \"/transcribe\"),\n createRouteHandler(runtime, async ({ request }) => {\n return handleTranscribe({ runtime, request });\n }),\n );\n\n router.use(joinPath(normalizedBase, \"*\"), (req, res) => {\n res.status(404).json({ error: \"Not found\" });\n });\n\n return router;\n}\n\ntype RouteHandlerContext = {\n request: Request;\n req: ExpressRequest;\n};\n\ntype RouteHandlerFactory = (ctx: RouteHandlerContext) => Promise<Response>;\n\nfunction createRouteHandler(\n runtime: CopilotRuntime,\n factory: RouteHandlerFactory,\n) {\n return async (\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ) => {\n const path = req.originalUrl ?? req.path;\n let request = createFetchRequestFromExpress(req);\n try {\n const maybeModifiedRequest = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModifiedRequest) {\n request = maybeModifiedRequest;\n }\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (error instanceof Response) {\n try {\n await sendFetchResponse(res, error);\n } catch (streamError) {\n next(streamError);\n }\n return;\n }\n next(error);\n return;\n }\n\n try {\n const response = await factory({ request, req });\n const responseForMiddleware = response.clone();\n await sendFetchResponse(res, response);\n callAfterRequestMiddleware({\n runtime,\n response: responseForMiddleware,\n path,\n }).catch((error) => {\n logger.error(\n { err: error, url: req.originalUrl ?? req.url, path },\n \"Error running after request middleware\",\n );\n });\n } catch (error) {\n if (error instanceof Response) {\n const errorResponseForMiddleware = error.clone();\n try {\n await sendFetchResponse(res, error);\n } catch (streamError) {\n next(streamError);\n return;\n }\n callAfterRequestMiddleware({\n runtime,\n response: errorResponseForMiddleware,\n path,\n }).catch((mwError) => {\n logger.error(\n { err: mwError, url: req.originalUrl ?? req.url, path },\n \"Error running after request middleware\",\n );\n });\n return;\n }\n logger.error(\n { err: error, url: request.url, path },\n \"Error running request handler\",\n );\n next(error);\n }\n };\n}\n\nfunction normalizeBasePath(path: string): string {\n if (!path) {\n throw new Error(\"basePath must be provided for Express endpoint\");\n }\n\n if (!path.startsWith(\"/\")) {\n return `/${path}`;\n }\n\n if (path.length > 1 && path.endsWith(\"/\")) {\n return path.slice(0, -1);\n }\n\n return path;\n}\n\nfunction joinPath(basePath: string, suffix: string): string {\n if (basePath === \"/\") {\n return suffix.startsWith(\"/\") ? suffix : `/${suffix}`;\n }\n\n if (!suffix) {\n return basePath;\n }\n\n if (suffix === \"*\") {\n return `${basePath}/*`;\n }\n\n return `${basePath}${suffix.startsWith(\"/\") ? suffix : `/${suffix}`}`;\n}\n"],"mappings":";;;;;;;;;;;;AA8BA,SAAgB,6BAA6B,EAC3C,SACA,YACuC;CACvC,MAAM,SAAS,QAAQ,QAAQ;CAC/B,MAAM,iBAAiB,kBAAkB,SAAS;AAElD,QAAO,IACL,KAAK;EACH,QAAQ;EACR,SAAS;GAAC;GAAO;GAAQ;GAAO;GAAQ;GAAU;GAAS;GAAU;EACrE,gBAAgB,CAAC,IAAI;EACtB,CAAC,CACH;AAED,QAAO,KACL,SAAS,gBAAgB,sBAAsB,EAC/C,mBAAmB,SAAS,OAAO,EAAE,SAAS,UAAU;EACtD,MAAM,UAAU,IAAI,OAAO;AAC3B,SAAO,eAAe;GAAE;GAAS;GAAS;GAAS,CAAC;GACpD,CACH;AAED,QAAO,KACL,SAAS,gBAAgB,0BAA0B,EACnD,mBAAmB,SAAS,OAAO,EAAE,SAAS,UAAU;EACtD,MAAM,UAAU,IAAI,OAAO;AAC3B,SAAO,mBAAmB;GAAE;GAAS;GAAS;GAAS,CAAC;GACxD,CACH;AAED,QAAO,KACL,SAAS,gBAAgB,iCAAiC,EAC1D,mBAAmB,SAAS,OAAO,EAAE,SAAS,UAAU;EACtD,MAAM,UAAU,IAAI,OAAO;EAC3B,MAAM,WAAW,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iB,UAAU;IAC7B,MAAM,6BAA6B,MAAM,OAAO;AAChD,QAAI;AACF,WAAM,kBAAkB,KAAK,MAAM;aAC5B,aAAa;AACpB,UAAK,YAAY;AACjB;;AAEF,+BAA2B;KACzB;KACA,UAAU;KACV;KACD,CAAC,CAAC,OAAO,YAAY;AACpB,YAAO,MACL;MAAE,KAAK;MAAS,KAAK,IAAI,eAAe,IAAI;MAAK;MAAM,EACvD,yCACD;MACD;AACF;;AAEF,UAAO,MACL;IAAE,KAAK;IAAO,KAAK,QAAQ;IAAK;IAAM,EACtC,gCACD;AACD,QAAK,MAAM;;;;AAKjB,SAAS,kBAAkB,MAAsB;AAC/C,KAAI,CAAC,KACH,OAAM,IAAI,MAAM,iDAAiD;AAGnE,KAAI,CAAC,KAAK,WAAW,IAAI,CACvB,QAAO,IAAI;AAGb,KAAI,KAAK,SAAS,KAAK,KAAK,SAAS,IAAI,CACvC,QAAO,KAAK,MAAM,GAAG,GAAG;AAG1B,QAAO;;AAGT,SAAS,SAAS,UAAkB,QAAwB;AAC1D,KAAI,aAAa,IACf,QAAO,OAAO,WAAW,IAAI,GAAG,SAAS,IAAI;AAG/C,KAAI,CAAC,OACH,QAAO;AAGT,KAAI,WAAW,IACb,QAAO,GAAG,SAAS;AAGrB,QAAO,GAAG,WAAW,OAAO,WAAW,IAAI,GAAG,SAAS,IAAI"}
|
|
@@ -49,7 +49,7 @@ function createCopilotEndpointSingleRoute({ runtime, basePath, cors: corsConfig
|
|
|
49
49
|
await next();
|
|
50
50
|
}).use("*", async (c, next) => {
|
|
51
51
|
await next();
|
|
52
|
-
const response = c.res;
|
|
52
|
+
const response = c.res.clone();
|
|
53
53
|
const path = c.req.path;
|
|
54
54
|
require_middleware.callAfterRequestMiddleware({
|
|
55
55
|
runtime,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hono-single.cjs","names":["Hono","callBeforeRequestMiddleware","parseMethodCall","expectString","handleRunAgent","createJsonRequest","handleConnectAgent","handleStopAgent","handleGetRuntimeInfo","handleTranscribe"],"sources":["../../src/endpoints/hono-single.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\n\nimport { CopilotRuntime } from \"../runtime\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"../middleware\";\nimport {\n createJsonRequest,\n expectString,\n MethodCall,\n parseMethodCall,\n} from \"./single-route-helpers\";\n\nimport { CopilotEndpointCorsConfig } from \"./hono\";\n\ninterface CopilotSingleEndpointParams {\n runtime: CopilotRuntime;\n /**\n * Absolute path at which to mount the single-route endpoint (e.g. \"/api/copilotkit\").\n */\n basePath: string;\n /**\n * Optional CORS configuration. When not provided, defaults to allowing all origins without credentials.\n * To support HTTP-only cookies, provide cors config with credentials: true and explicit origin.\n */\n cors?: CopilotEndpointCorsConfig;\n}\n\ntype CopilotEndpointContext = {\n Variables: {\n modifiedRequest?: Request;\n };\n};\n\nexport function createCopilotEndpointSingleRoute({\n runtime,\n basePath,\n cors: corsConfig,\n}: CopilotSingleEndpointParams) {\n const app = new Hono<CopilotEndpointContext>();\n const routePath = normalizePath(basePath);\n\n return app\n .basePath(routePath)\n .use(\n \"*\",\n cors({\n origin: corsConfig?.origin ?? \"*\",\n allowMethods: [\n \"GET\",\n \"HEAD\",\n \"PUT\",\n \"POST\",\n \"DELETE\",\n \"PATCH\",\n \"OPTIONS\",\n ],\n allowHeaders: [\"*\"],\n credentials: corsConfig?.credentials ?? false,\n }),\n )\n .use(\"*\", async (c, next) => {\n const request = c.req.raw;\n const path = c.req.path;\n\n try {\n const maybeModifiedRequest = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModifiedRequest) {\n c.set(\"modifiedRequest\", maybeModifiedRequest);\n }\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (error instanceof Response) {\n return error;\n }\n throw error;\n }\n\n await next();\n })\n .use(\"*\", async (c, next) => {\n await next();\n\n const response = c.res;\n const path = c.req.path;\n\n callAfterRequestMiddleware({\n runtime,\n response,\n path,\n }).catch((error) => {\n logger.error(\n { err: error, url: c.req.url, path },\n \"Error running after request middleware\",\n );\n });\n })\n .post(\"/\", async (c) => {\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n let methodCall: MethodCall;\n try {\n methodCall = await parseMethodCall(request);\n } catch (error) {\n if (error instanceof Response) {\n logger.warn({ url: request.url }, \"Invalid single-route payload\");\n return error;\n }\n logger.warn(\n { err: error, url: request.url },\n \"Invalid single-route payload\",\n );\n return c.json(\n {\n error: \"invalid_request\",\n message:\n error instanceof Error\n ? error.message\n : \"Invalid request payload\",\n },\n 400,\n );\n }\n\n try {\n switch (methodCall.method) {\n case \"agent/run\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const handlerRequest = createJsonRequest(request, methodCall.body);\n return await handleRunAgent({\n runtime,\n request: handlerRequest,\n agentId,\n });\n }\n case \"agent/connect\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const handlerRequest = createJsonRequest(request, methodCall.body);\n return await handleConnectAgent({\n runtime,\n request: handlerRequest,\n agentId,\n });\n }\n case \"agent/stop\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const threadId = expectString(methodCall.params, \"threadId\");\n return await handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n });\n }\n case \"info\": {\n return await handleGetRuntimeInfo({ runtime, request });\n }\n case \"transcribe\": {\n const handlerRequest = createJsonRequest(request, methodCall.body);\n return await handleTranscribe({ runtime, request: handlerRequest });\n }\n default: {\n const exhaustiveCheck: never = methodCall.method;\n return exhaustiveCheck;\n }\n }\n } catch (error) {\n if (error instanceof Response) {\n return error;\n }\n logger.error(\n { err: error, url: request.url, method: methodCall.method },\n \"Error running single-route handler\",\n );\n throw error;\n }\n })\n .notFound((c) => {\n return c.json({ error: \"Not found\" }, 404);\n });\n}\n\nfunction normalizePath(path: string): string {\n if (!path) {\n throw new Error(\"basePath must be provided for single-route endpoint\");\n }\n\n if (!path.startsWith(\"/\")) {\n return `/${path}`;\n }\n\n if (path.length > 1 && path.endsWith(\"/\")) {\n return path.slice(0, -1);\n }\n\n return path;\n}\n"],"mappings":";;;;;;;;;;;;;AA0CA,SAAgB,iCAAiC,EAC/C,SACA,UACA,MAAM,cACwB;CAC9B,MAAM,MAAM,IAAIA,WAA8B;CAC9C,MAAM,YAAY,cAAc,SAAS;AAEzC,QAAO,IACJ,SAAS,UAAU,CACnB,IACC,yBACK;EACH,QAAQ,YAAY,UAAU;EAC9B,cAAc;GACZ;GACA;GACA;GACA;GACA;GACA;GACA;GACD;EACD,cAAc,CAAC,IAAI;EACnB,aAAa,YAAY,eAAe;EACzC,CAAC,CACH,CACA,IAAI,KAAK,OAAO,GAAG,SAAS;EAC3B,MAAM,UAAU,EAAE,IAAI;EACtB,MAAM,OAAO,EAAE,IAAI;AAEnB,MAAI;GACF,MAAM,uBAAuB,MAAMC,+CAA4B;IAC7D;IACA;IACA;IACD,CAAC;AACF,OAAI,qBACF,GAAE,IAAI,mBAAmB,qBAAqB;WAEzC,OAAO;AACd,iCAAO,MACL;IAAE,KAAK;IAAO,KAAK,QAAQ;IAAK;IAAM,EACtC,0CACD;AACD,OAAI,iBAAiB,SACnB,QAAO;AAET,SAAM;;AAGR,QAAM,MAAM;GACZ,CACD,IAAI,KAAK,OAAO,GAAG,SAAS;AAC3B,QAAM,MAAM;EAEZ,MAAM,WAAW,EAAE;
|
|
1
|
+
{"version":3,"file":"hono-single.cjs","names":["Hono","callBeforeRequestMiddleware","parseMethodCall","expectString","handleRunAgent","createJsonRequest","handleConnectAgent","handleStopAgent","handleGetRuntimeInfo","handleTranscribe"],"sources":["../../src/endpoints/hono-single.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\n\nimport { CopilotRuntime } from \"../runtime\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"../middleware\";\nimport {\n createJsonRequest,\n expectString,\n MethodCall,\n parseMethodCall,\n} from \"./single-route-helpers\";\n\nimport { CopilotEndpointCorsConfig } from \"./hono\";\n\ninterface CopilotSingleEndpointParams {\n runtime: CopilotRuntime;\n /**\n * Absolute path at which to mount the single-route endpoint (e.g. \"/api/copilotkit\").\n */\n basePath: string;\n /**\n * Optional CORS configuration. When not provided, defaults to allowing all origins without credentials.\n * To support HTTP-only cookies, provide cors config with credentials: true and explicit origin.\n */\n cors?: CopilotEndpointCorsConfig;\n}\n\ntype CopilotEndpointContext = {\n Variables: {\n modifiedRequest?: Request;\n };\n};\n\nexport function createCopilotEndpointSingleRoute({\n runtime,\n basePath,\n cors: corsConfig,\n}: CopilotSingleEndpointParams) {\n const app = new Hono<CopilotEndpointContext>();\n const routePath = normalizePath(basePath);\n\n return app\n .basePath(routePath)\n .use(\n \"*\",\n cors({\n origin: corsConfig?.origin ?? \"*\",\n allowMethods: [\n \"GET\",\n \"HEAD\",\n \"PUT\",\n \"POST\",\n \"DELETE\",\n \"PATCH\",\n \"OPTIONS\",\n ],\n allowHeaders: [\"*\"],\n credentials: corsConfig?.credentials ?? false,\n }),\n )\n .use(\"*\", async (c, next) => {\n const request = c.req.raw;\n const path = c.req.path;\n\n try {\n const maybeModifiedRequest = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModifiedRequest) {\n c.set(\"modifiedRequest\", maybeModifiedRequest);\n }\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (error instanceof Response) {\n return error;\n }\n throw error;\n }\n\n await next();\n })\n .use(\"*\", async (c, next) => {\n await next();\n\n const response = c.res.clone();\n const path = c.req.path;\n\n callAfterRequestMiddleware({\n runtime,\n response,\n path,\n }).catch((error) => {\n logger.error(\n { err: error, url: c.req.url, path },\n \"Error running after request middleware\",\n );\n });\n })\n .post(\"/\", async (c) => {\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n let methodCall: MethodCall;\n try {\n methodCall = await parseMethodCall(request);\n } catch (error) {\n if (error instanceof Response) {\n logger.warn({ url: request.url }, \"Invalid single-route payload\");\n return error;\n }\n logger.warn(\n { err: error, url: request.url },\n \"Invalid single-route payload\",\n );\n return c.json(\n {\n error: \"invalid_request\",\n message:\n error instanceof Error\n ? error.message\n : \"Invalid request payload\",\n },\n 400,\n );\n }\n\n try {\n switch (methodCall.method) {\n case \"agent/run\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const handlerRequest = createJsonRequest(request, methodCall.body);\n return await handleRunAgent({\n runtime,\n request: handlerRequest,\n agentId,\n });\n }\n case \"agent/connect\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const handlerRequest = createJsonRequest(request, methodCall.body);\n return await handleConnectAgent({\n runtime,\n request: handlerRequest,\n agentId,\n });\n }\n case \"agent/stop\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const threadId = expectString(methodCall.params, \"threadId\");\n return await handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n });\n }\n case \"info\": {\n return await handleGetRuntimeInfo({ runtime, request });\n }\n case \"transcribe\": {\n const handlerRequest = createJsonRequest(request, methodCall.body);\n return await handleTranscribe({ runtime, request: handlerRequest });\n }\n default: {\n const exhaustiveCheck: never = methodCall.method;\n return exhaustiveCheck;\n }\n }\n } catch (error) {\n if (error instanceof Response) {\n return error;\n }\n logger.error(\n { err: error, url: request.url, method: methodCall.method },\n \"Error running single-route handler\",\n );\n throw error;\n }\n })\n .notFound((c) => {\n return c.json({ error: \"Not found\" }, 404);\n });\n}\n\nfunction normalizePath(path: string): string {\n if (!path) {\n throw new Error(\"basePath must be provided for single-route endpoint\");\n }\n\n if (!path.startsWith(\"/\")) {\n return `/${path}`;\n }\n\n if (path.length > 1 && path.endsWith(\"/\")) {\n return path.slice(0, -1);\n }\n\n return path;\n}\n"],"mappings":";;;;;;;;;;;;;AA0CA,SAAgB,iCAAiC,EAC/C,SACA,UACA,MAAM,cACwB;CAC9B,MAAM,MAAM,IAAIA,WAA8B;CAC9C,MAAM,YAAY,cAAc,SAAS;AAEzC,QAAO,IACJ,SAAS,UAAU,CACnB,IACC,yBACK;EACH,QAAQ,YAAY,UAAU;EAC9B,cAAc;GACZ;GACA;GACA;GACA;GACA;GACA;GACA;GACD;EACD,cAAc,CAAC,IAAI;EACnB,aAAa,YAAY,eAAe;EACzC,CAAC,CACH,CACA,IAAI,KAAK,OAAO,GAAG,SAAS;EAC3B,MAAM,UAAU,EAAE,IAAI;EACtB,MAAM,OAAO,EAAE,IAAI;AAEnB,MAAI;GACF,MAAM,uBAAuB,MAAMC,+CAA4B;IAC7D;IACA;IACA;IACD,CAAC;AACF,OAAI,qBACF,GAAE,IAAI,mBAAmB,qBAAqB;WAEzC,OAAO;AACd,iCAAO,MACL;IAAE,KAAK;IAAO,KAAK,QAAQ;IAAK;IAAM,EACtC,0CACD;AACD,OAAI,iBAAiB,SACnB,QAAO;AAET,SAAM;;AAGR,QAAM,MAAM;GACZ,CACD,IAAI,KAAK,OAAO,GAAG,SAAS;AAC3B,QAAM,MAAM;EAEZ,MAAM,WAAW,EAAE,IAAI,OAAO;EAC9B,MAAM,OAAO,EAAE,IAAI;AAEnB,gDAA2B;GACzB;GACA;GACA;GACD,CAAC,CAAC,OAAO,UAAU;AAClB,iCAAO,MACL;IAAE,KAAK;IAAO,KAAK,EAAE,IAAI;IAAK;IAAM,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EAC3D,qCACD;AACD,SAAM;;GAER,CACD,UAAU,MAAM;AACf,SAAO,EAAE,KAAK,EAAE,OAAO,aAAa,EAAE,IAAI;GAC1C;;AAGN,SAAS,cAAc,MAAsB;AAC3C,KAAI,CAAC,KACH,OAAM,IAAI,MAAM,sDAAsD;AAGxE,KAAI,CAAC,KAAK,WAAW,IAAI,CACvB,QAAO,IAAI;AAGb,KAAI,KAAK,SAAS,KAAK,KAAK,SAAS,IAAI,CACvC,QAAO,KAAK,MAAM,GAAG,GAAG;AAG1B,QAAO"}
|
|
@@ -48,7 +48,7 @@ function createCopilotEndpointSingleRoute({ runtime, basePath, cors: corsConfig
|
|
|
48
48
|
await next();
|
|
49
49
|
}).use("*", async (c, next) => {
|
|
50
50
|
await next();
|
|
51
|
-
const response = c.res;
|
|
51
|
+
const response = c.res.clone();
|
|
52
52
|
const path = c.req.path;
|
|
53
53
|
callAfterRequestMiddleware({
|
|
54
54
|
runtime,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hono-single.mjs","names":[],"sources":["../../src/endpoints/hono-single.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\n\nimport { CopilotRuntime } from \"../runtime\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"../middleware\";\nimport {\n createJsonRequest,\n expectString,\n MethodCall,\n parseMethodCall,\n} from \"./single-route-helpers\";\n\nimport { CopilotEndpointCorsConfig } from \"./hono\";\n\ninterface CopilotSingleEndpointParams {\n runtime: CopilotRuntime;\n /**\n * Absolute path at which to mount the single-route endpoint (e.g. \"/api/copilotkit\").\n */\n basePath: string;\n /**\n * Optional CORS configuration. When not provided, defaults to allowing all origins without credentials.\n * To support HTTP-only cookies, provide cors config with credentials: true and explicit origin.\n */\n cors?: CopilotEndpointCorsConfig;\n}\n\ntype CopilotEndpointContext = {\n Variables: {\n modifiedRequest?: Request;\n };\n};\n\nexport function createCopilotEndpointSingleRoute({\n runtime,\n basePath,\n cors: corsConfig,\n}: CopilotSingleEndpointParams) {\n const app = new Hono<CopilotEndpointContext>();\n const routePath = normalizePath(basePath);\n\n return app\n .basePath(routePath)\n .use(\n \"*\",\n cors({\n origin: corsConfig?.origin ?? \"*\",\n allowMethods: [\n \"GET\",\n \"HEAD\",\n \"PUT\",\n \"POST\",\n \"DELETE\",\n \"PATCH\",\n \"OPTIONS\",\n ],\n allowHeaders: [\"*\"],\n credentials: corsConfig?.credentials ?? false,\n }),\n )\n .use(\"*\", async (c, next) => {\n const request = c.req.raw;\n const path = c.req.path;\n\n try {\n const maybeModifiedRequest = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModifiedRequest) {\n c.set(\"modifiedRequest\", maybeModifiedRequest);\n }\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (error instanceof Response) {\n return error;\n }\n throw error;\n }\n\n await next();\n })\n .use(\"*\", async (c, next) => {\n await next();\n\n const response = c.res;\n const path = c.req.path;\n\n callAfterRequestMiddleware({\n runtime,\n response,\n path,\n }).catch((error) => {\n logger.error(\n { err: error, url: c.req.url, path },\n \"Error running after request middleware\",\n );\n });\n })\n .post(\"/\", async (c) => {\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n let methodCall: MethodCall;\n try {\n methodCall = await parseMethodCall(request);\n } catch (error) {\n if (error instanceof Response) {\n logger.warn({ url: request.url }, \"Invalid single-route payload\");\n return error;\n }\n logger.warn(\n { err: error, url: request.url },\n \"Invalid single-route payload\",\n );\n return c.json(\n {\n error: \"invalid_request\",\n message:\n error instanceof Error\n ? error.message\n : \"Invalid request payload\",\n },\n 400,\n );\n }\n\n try {\n switch (methodCall.method) {\n case \"agent/run\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const handlerRequest = createJsonRequest(request, methodCall.body);\n return await handleRunAgent({\n runtime,\n request: handlerRequest,\n agentId,\n });\n }\n case \"agent/connect\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const handlerRequest = createJsonRequest(request, methodCall.body);\n return await handleConnectAgent({\n runtime,\n request: handlerRequest,\n agentId,\n });\n }\n case \"agent/stop\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const threadId = expectString(methodCall.params, \"threadId\");\n return await handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n });\n }\n case \"info\": {\n return await handleGetRuntimeInfo({ runtime, request });\n }\n case \"transcribe\": {\n const handlerRequest = createJsonRequest(request, methodCall.body);\n return await handleTranscribe({ runtime, request: handlerRequest });\n }\n default: {\n const exhaustiveCheck: never = methodCall.method;\n return exhaustiveCheck;\n }\n }\n } catch (error) {\n if (error instanceof Response) {\n return error;\n }\n logger.error(\n { err: error, url: request.url, method: methodCall.method },\n \"Error running single-route handler\",\n );\n throw error;\n }\n })\n .notFound((c) => {\n return c.json({ error: \"Not found\" }, 404);\n });\n}\n\nfunction normalizePath(path: string): string {\n if (!path) {\n throw new Error(\"basePath must be provided for single-route endpoint\");\n }\n\n if (!path.startsWith(\"/\")) {\n return `/${path}`;\n }\n\n if (path.length > 1 && path.endsWith(\"/\")) {\n return path.slice(0, -1);\n }\n\n return path;\n}\n"],"mappings":";;;;;;;;;;;;AA0CA,SAAgB,iCAAiC,EAC/C,SACA,UACA,MAAM,cACwB;CAC9B,MAAM,MAAM,IAAI,MAA8B;CAC9C,MAAM,YAAY,cAAc,SAAS;AAEzC,QAAO,IACJ,SAAS,UAAU,CACnB,IACC,KACA,KAAK;EACH,QAAQ,YAAY,UAAU;EAC9B,cAAc;GACZ;GACA;GACA;GACA;GACA;GACA;GACA;GACD;EACD,cAAc,CAAC,IAAI;EACnB,aAAa,YAAY,eAAe;EACzC,CAAC,CACH,CACA,IAAI,KAAK,OAAO,GAAG,SAAS;EAC3B,MAAM,UAAU,EAAE,IAAI;EACtB,MAAM,OAAO,EAAE,IAAI;AAEnB,MAAI;GACF,MAAM,uBAAuB,MAAM,4BAA4B;IAC7D;IACA;IACA;IACD,CAAC;AACF,OAAI,qBACF,GAAE,IAAI,mBAAmB,qBAAqB;WAEzC,OAAO;AACd,UAAO,MACL;IAAE,KAAK;IAAO,KAAK,QAAQ;IAAK;IAAM,EACtC,0CACD;AACD,OAAI,iBAAiB,SACnB,QAAO;AAET,SAAM;;AAGR,QAAM,MAAM;GACZ,CACD,IAAI,KAAK,OAAO,GAAG,SAAS;AAC3B,QAAM,MAAM;EAEZ,MAAM,WAAW,EAAE;
|
|
1
|
+
{"version":3,"file":"hono-single.mjs","names":[],"sources":["../../src/endpoints/hono-single.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\n\nimport { CopilotRuntime } from \"../runtime\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"../middleware\";\nimport {\n createJsonRequest,\n expectString,\n MethodCall,\n parseMethodCall,\n} from \"./single-route-helpers\";\n\nimport { CopilotEndpointCorsConfig } from \"./hono\";\n\ninterface CopilotSingleEndpointParams {\n runtime: CopilotRuntime;\n /**\n * Absolute path at which to mount the single-route endpoint (e.g. \"/api/copilotkit\").\n */\n basePath: string;\n /**\n * Optional CORS configuration. When not provided, defaults to allowing all origins without credentials.\n * To support HTTP-only cookies, provide cors config with credentials: true and explicit origin.\n */\n cors?: CopilotEndpointCorsConfig;\n}\n\ntype CopilotEndpointContext = {\n Variables: {\n modifiedRequest?: Request;\n };\n};\n\nexport function createCopilotEndpointSingleRoute({\n runtime,\n basePath,\n cors: corsConfig,\n}: CopilotSingleEndpointParams) {\n const app = new Hono<CopilotEndpointContext>();\n const routePath = normalizePath(basePath);\n\n return app\n .basePath(routePath)\n .use(\n \"*\",\n cors({\n origin: corsConfig?.origin ?? \"*\",\n allowMethods: [\n \"GET\",\n \"HEAD\",\n \"PUT\",\n \"POST\",\n \"DELETE\",\n \"PATCH\",\n \"OPTIONS\",\n ],\n allowHeaders: [\"*\"],\n credentials: corsConfig?.credentials ?? false,\n }),\n )\n .use(\"*\", async (c, next) => {\n const request = c.req.raw;\n const path = c.req.path;\n\n try {\n const maybeModifiedRequest = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModifiedRequest) {\n c.set(\"modifiedRequest\", maybeModifiedRequest);\n }\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (error instanceof Response) {\n return error;\n }\n throw error;\n }\n\n await next();\n })\n .use(\"*\", async (c, next) => {\n await next();\n\n const response = c.res.clone();\n const path = c.req.path;\n\n callAfterRequestMiddleware({\n runtime,\n response,\n path,\n }).catch((error) => {\n logger.error(\n { err: error, url: c.req.url, path },\n \"Error running after request middleware\",\n );\n });\n })\n .post(\"/\", async (c) => {\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n let methodCall: MethodCall;\n try {\n methodCall = await parseMethodCall(request);\n } catch (error) {\n if (error instanceof Response) {\n logger.warn({ url: request.url }, \"Invalid single-route payload\");\n return error;\n }\n logger.warn(\n { err: error, url: request.url },\n \"Invalid single-route payload\",\n );\n return c.json(\n {\n error: \"invalid_request\",\n message:\n error instanceof Error\n ? error.message\n : \"Invalid request payload\",\n },\n 400,\n );\n }\n\n try {\n switch (methodCall.method) {\n case \"agent/run\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const handlerRequest = createJsonRequest(request, methodCall.body);\n return await handleRunAgent({\n runtime,\n request: handlerRequest,\n agentId,\n });\n }\n case \"agent/connect\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const handlerRequest = createJsonRequest(request, methodCall.body);\n return await handleConnectAgent({\n runtime,\n request: handlerRequest,\n agentId,\n });\n }\n case \"agent/stop\": {\n const agentId = expectString(methodCall.params, \"agentId\");\n const threadId = expectString(methodCall.params, \"threadId\");\n return await handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n });\n }\n case \"info\": {\n return await handleGetRuntimeInfo({ runtime, request });\n }\n case \"transcribe\": {\n const handlerRequest = createJsonRequest(request, methodCall.body);\n return await handleTranscribe({ runtime, request: handlerRequest });\n }\n default: {\n const exhaustiveCheck: never = methodCall.method;\n return exhaustiveCheck;\n }\n }\n } catch (error) {\n if (error instanceof Response) {\n return error;\n }\n logger.error(\n { err: error, url: request.url, method: methodCall.method },\n \"Error running single-route handler\",\n );\n throw error;\n }\n })\n .notFound((c) => {\n return c.json({ error: \"Not found\" }, 404);\n });\n}\n\nfunction normalizePath(path: string): string {\n if (!path) {\n throw new Error(\"basePath must be provided for single-route endpoint\");\n }\n\n if (!path.startsWith(\"/\")) {\n return `/${path}`;\n }\n\n if (path.length > 1 && path.endsWith(\"/\")) {\n return path.slice(0, -1);\n }\n\n return path;\n}\n"],"mappings":";;;;;;;;;;;;AA0CA,SAAgB,iCAAiC,EAC/C,SACA,UACA,MAAM,cACwB;CAC9B,MAAM,MAAM,IAAI,MAA8B;CAC9C,MAAM,YAAY,cAAc,SAAS;AAEzC,QAAO,IACJ,SAAS,UAAU,CACnB,IACC,KACA,KAAK;EACH,QAAQ,YAAY,UAAU;EAC9B,cAAc;GACZ;GACA;GACA;GACA;GACA;GACA;GACA;GACD;EACD,cAAc,CAAC,IAAI;EACnB,aAAa,YAAY,eAAe;EACzC,CAAC,CACH,CACA,IAAI,KAAK,OAAO,GAAG,SAAS;EAC3B,MAAM,UAAU,EAAE,IAAI;EACtB,MAAM,OAAO,EAAE,IAAI;AA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AHqB,kBAAkB,SAAS,WAAW,KAAK;MAIhE;MACD,CAAC;;IAEJ,KAAK,aAGH,QAAO,MAAM,gBAAgB;KAC3B;KACA;KACA,SALc,aAAa,WAAW,QAAQ,UAAU;KAMxD,UALe,aAAa,WAAW,QAAQ,WAAW;KAM3D,CAAC;IAEJ,KAAK,OACH,QAAO,MAAM,qBAAqB;KAAE;KAAS;KAAS,CAAC;IAEzD,KAAK,aAEH,QAAO,MAAM,iBAAiB;KAAE;KAAS,SADlB,kBAAkB,SAAS,WAAW,KAAK;KACA,CAAC;IAErE,QAEE,QAD+B,WAAW;;WAIvC,OAAO;AACd,OAAI,iBAAiB,SACnB,QAAO;AAET,UAAO,MACL;IAAE,KAAK;IAAO,KAAK,QAAQ;IAAK,QAAQ,WAAW;IAAQ,EAC3D,qCACD;AACD,SAAM;;GAER,CACD,UAAU,MAAM;AACf,SAAO,EAAE,KAAK,EAAE,OAAO,aAAa,EAAE,IAAI;GAC1C;;AAGN,SAAS,cAAc,MAAsB;AAC3C,KAAI,CAAC,KACH,OAAM,IAAI,MAAM,sDAAsD;AAGxE,KAAI,CAAC,KAAK,WAAW,IAAI,CACvB,QAAO,IAAI;AAGb,KAAI,KAAK,SAAS,KAAK,KAAK,SAAS,IAAI,CACvC,QAAO,KAAK,MAAM,GAAG,GAAG;AAG1B,QAAO"}
|
package/dist/endpoints/hono.cjs
CHANGED
|
@@ -46,7 +46,7 @@ function createCopilotEndpoint({ runtime, basePath, cors: corsConfig }) {
|
|
|
46
46
|
await next();
|
|
47
47
|
}).use("*", async (c, next) => {
|
|
48
48
|
await next();
|
|
49
|
-
const response = c.res;
|
|
49
|
+
const response = c.res.clone();
|
|
50
50
|
const path = c.req.path;
|
|
51
51
|
require_middleware.callAfterRequestMiddleware({
|
|
52
52
|
runtime,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hono.cjs","names":["Hono","callBeforeRequestMiddleware","handleRunAgent","handleConnectAgent","handleStopAgent","handleGetRuntimeInfo","handleTranscribe"],"sources":["../../src/endpoints/hono.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport { CopilotRuntime } from \"../runtime\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"../middleware\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\n\n/**\n * CORS configuration for CopilotKit endpoints.\n * When using credentials (e.g., HTTP-only cookies), you must specify an explicit origin.\n */\nexport interface CopilotEndpointCorsConfig {\n /**\n * Allowed origin(s) for CORS. Can be:\n * - A string: exact origin (e.g., \"https://myapp.com\")\n * - An array: list of allowed origins\n * - A function: dynamic origin resolution\n *\n * Note: When credentials is true, origin cannot be \"*\"\n */\n origin:\n | string\n | string[]\n | ((origin: string, c: any) => string | undefined | null);\n /**\n * Whether to allow credentials (cookies, HTTP authentication).\n * When true, origin must be explicitly specified (not \"*\").\n */\n credentials?: boolean;\n}\n\ninterface CopilotEndpointParams {\n runtime: CopilotRuntime;\n basePath: string;\n /**\n * Optional CORS configuration. When not provided, defaults to allowing all origins without credentials.\n * To support HTTP-only cookies, provide cors config with credentials: true and explicit origin.\n */\n cors?: CopilotEndpointCorsConfig;\n}\n\n// Define the context variables type\ntype CopilotEndpointContext = {\n Variables: {\n modifiedRequest?: Request;\n };\n};\n\nexport function createCopilotEndpoint({\n runtime,\n basePath,\n cors: corsConfig,\n}: CopilotEndpointParams) {\n const app = new Hono<CopilotEndpointContext>();\n\n return app\n .basePath(basePath)\n .use(\n \"*\",\n cors({\n origin: corsConfig?.origin ?? \"*\",\n allowMethods: [\n \"GET\",\n \"HEAD\",\n \"PUT\",\n \"POST\",\n \"DELETE\",\n \"PATCH\",\n \"OPTIONS\",\n ],\n allowHeaders: [\"*\"],\n credentials: corsConfig?.credentials ?? false,\n }),\n )\n .use(\"*\", async (c, next) => {\n const request = c.req.raw;\n const path = c.req.path;\n\n try {\n const maybeModifiedRequest = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModifiedRequest) {\n c.set(\"modifiedRequest\", maybeModifiedRequest);\n }\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (error instanceof Response) {\n return error;\n }\n throw error;\n }\n\n await next();\n })\n .use(\"*\", async (c, next) => {\n await next();\n\n const response = c.res;\n const path = c.req.path;\n\n // Non-blocking after middleware\n callAfterRequestMiddleware({\n runtime,\n response,\n path,\n }).catch((error) => {\n logger.error(\n { err: error, url: c.req.url, path },\n \"Error running after request middleware\",\n );\n });\n })\n .post(\"/agent/:agentId/run\", async (c) => {\n const agentId = c.req.param(\"agentId\");\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleRunAgent({\n runtime,\n request,\n agentId,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n .post(\"/agent/:agentId/connect\", async (c) => {\n const agentId = c.req.param(\"agentId\");\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleConnectAgent({\n runtime,\n request,\n agentId,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n\n .post(\"/agent/:agentId/stop/:threadId\", async (c) => {\n const agentId = c.req.param(\"agentId\");\n const threadId = c.req.param(\"threadId\");\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n .get(\"/info\", async (c) => {\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleGetRuntimeInfo({\n runtime,\n request,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n .post(\"/transcribe\", async (c) => {\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleTranscribe({\n runtime,\n request,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n .notFound((c) => {\n return c.json({ error: \"Not found\" }, 404);\n });\n\n // return app;\n}\n"],"mappings":";;;;;;;;;;;;AAuDA,SAAgB,sBAAsB,EACpC,SACA,UACA,MAAM,cACkB;AAGxB,QAFY,IAAIA,WAA8B,CAG3C,SAAS,SAAS,CAClB,IACC,yBACK;EACH,QAAQ,YAAY,UAAU;EAC9B,cAAc;GACZ;GACA;GACA;GACA;GACA;GACA;GACA;GACD;EACD,cAAc,CAAC,IAAI;EACnB,aAAa,YAAY,eAAe;EACzC,CAAC,CACH,CACA,IAAI,KAAK,OAAO,GAAG,SAAS;EAC3B,MAAM,UAAU,EAAE,IAAI;EACtB,MAAM,OAAO,EAAE,IAAI;AAEnB,MAAI;GACF,MAAM,uBAAuB,MAAMC,+CAA4B;IAC7D;IACA;IACA;IACD,CAAC;AACF,OAAI,qBACF,GAAE,IAAI,mBAAmB,qBAAqB;WAEzC,OAAO;AACd,iCAAO,MACL;IAAE,KAAK;IAAO,KAAK,QAAQ;IAAK;IAAM,EACtC,0CACD;AACD,OAAI,iBAAiB,SACnB,QAAO;AAET,SAAM;;AAGR,QAAM,MAAM;GACZ,CACD,IAAI,KAAK,OAAO,GAAG,SAAS;AAC3B,QAAM,MAAM;EAEZ,MAAM,WAAW,EAAE;
|
|
1
|
+
{"version":3,"file":"hono.cjs","names":["Hono","callBeforeRequestMiddleware","handleRunAgent","handleConnectAgent","handleStopAgent","handleGetRuntimeInfo","handleTranscribe"],"sources":["../../src/endpoints/hono.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport { CopilotRuntime } from \"../runtime\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"../middleware\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\n\n/**\n * CORS configuration for CopilotKit endpoints.\n * When using credentials (e.g., HTTP-only cookies), you must specify an explicit origin.\n */\nexport interface CopilotEndpointCorsConfig {\n /**\n * Allowed origin(s) for CORS. Can be:\n * - A string: exact origin (e.g., \"https://myapp.com\")\n * - An array: list of allowed origins\n * - A function: dynamic origin resolution\n *\n * Note: When credentials is true, origin cannot be \"*\"\n */\n origin:\n | string\n | string[]\n | ((origin: string, c: any) => string | undefined | null);\n /**\n * Whether to allow credentials (cookies, HTTP authentication).\n * When true, origin must be explicitly specified (not \"*\").\n */\n credentials?: boolean;\n}\n\ninterface CopilotEndpointParams {\n runtime: CopilotRuntime;\n basePath: string;\n /**\n * Optional CORS configuration. When not provided, defaults to allowing all origins without credentials.\n * To support HTTP-only cookies, provide cors config with credentials: true and explicit origin.\n */\n cors?: CopilotEndpointCorsConfig;\n}\n\n// Define the context variables type\ntype CopilotEndpointContext = {\n Variables: {\n modifiedRequest?: Request;\n };\n};\n\nexport function createCopilotEndpoint({\n runtime,\n basePath,\n cors: corsConfig,\n}: CopilotEndpointParams) {\n const app = new Hono<CopilotEndpointContext>();\n\n return app\n .basePath(basePath)\n .use(\n \"*\",\n cors({\n origin: corsConfig?.origin ?? \"*\",\n allowMethods: [\n \"GET\",\n \"HEAD\",\n \"PUT\",\n \"POST\",\n \"DELETE\",\n \"PATCH\",\n \"OPTIONS\",\n ],\n allowHeaders: [\"*\"],\n credentials: corsConfig?.credentials ?? false,\n }),\n )\n .use(\"*\", async (c, next) => {\n const request = c.req.raw;\n const path = c.req.path;\n\n try {\n const maybeModifiedRequest = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModifiedRequest) {\n c.set(\"modifiedRequest\", maybeModifiedRequest);\n }\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (error instanceof Response) {\n return error;\n }\n throw error;\n }\n\n await next();\n })\n .use(\"*\", async (c, next) => {\n await next();\n\n const response = c.res.clone();\n const path = c.req.path;\n\n // Non-blocking after middleware\n callAfterRequestMiddleware({\n runtime,\n response,\n path,\n }).catch((error) => {\n logger.error(\n { err: error, url: c.req.url, path },\n \"Error running after request middleware\",\n );\n });\n })\n .post(\"/agent/:agentId/run\", async (c) => {\n const agentId = c.req.param(\"agentId\");\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleRunAgent({\n runtime,\n request,\n agentId,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n .post(\"/agent/:agentId/connect\", async (c) => {\n const agentId = c.req.param(\"agentId\");\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleConnectAgent({\n runtime,\n request,\n agentId,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n\n .post(\"/agent/:agentId/stop/:threadId\", async (c) => {\n const agentId = c.req.param(\"agentId\");\n const threadId = c.req.param(\"threadId\");\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n .get(\"/info\", async (c) => {\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleGetRuntimeInfo({\n runtime,\n request,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n .post(\"/transcribe\", async (c) => {\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleTranscribe({\n runtime,\n request,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n .notFound((c) => {\n return c.json({ error: \"Not found\" }, 404);\n });\n\n // return app;\n}\n"],"mappings":";;;;;;;;;;;;AAuDA,SAAgB,sBAAsB,EACpC,SACA,UACA,MAAM,cACkB;AAGxB,QAFY,IAAIA,WAA8B,CAG3C,SAAS,SAAS,CAClB,IACC,yBACK;EACH,QAAQ,YAAY,UAAU;EAC9B,cAAc;GACZ;GACA;GACA;GACA;GACA;GACA;GACA;GACD;EACD,cAAc,CAAC,IAAI;EACnB,aAAa,YAAY,eAAe;EACzC,CAAC,CACH,CACA,IAAI,KAAK,OAAO,GAAG,SAAS;EAC3B,MAAM,UAAU,EAAE,IAAI;EACtB,MAAM,OAAO,EAAE,IAAI;AAEnB,MAAI;GACF,MAAM,uBAAuB,MAAMC,+CAA4B;IAC7D;IACA;IACA;IACD,CAAC;AACF,OAAI,qBACF,GAAE,IAAI,mBAAmB,qBAAqB;WAEzC,OAAO;AACd,iCAAO,MACL;IAAE,KAAK;IAAO,KAAK,QAAQ;IAAK;IAAM,EACtC,0CACD;AACD,OAAI,iBAAiB,SACnB,QAAO;AAET,SAAM;;AAGR,QAAM,MAAM;GACZ,CACD,IAAI,KAAK,OAAO,GAAG,SAAS;AAC3B,QAAM,MAAM;EAEZ,MAAM,WAAW,EAAE,IAAI,OAAO;EAC9B,MAAM,OAAO,EAAE,IAAI;AAGnB,gDAA2B;GACzB;GACA;GACA;GACD,CAAC,CAAC,OAAO,UAAU;AAClB,iCAAO,MACL;IAAE,KAAK;IAAO,KAAK,EAAE,IAAI;IAAK;IAAM,EACpC,yCACD;IACD;GACF,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ACD;AACD,SAAM;;GAER,CACD,KAAK,eAAe,OAAO,MAAM;EAChC,MAAM,UAAU,EAAE,IAAI,kBAAkB,IAAI,EAAE,IAAI;AAElD,MAAI;AACF,UAAO,MAAMC,2CAAiB;IAC5B;IACA;IACD,CAAC;WACK,OAAO;AACd,iCAAO,MACL;IAAE,KAAK;IAAO,KAAK,QAAQ;IAAK,MAAM,EAAE,IAAI;IAAM,EAClD,gCACD;AACD,SAAM;;GAER,CACD,UAAU,MAAM;AACf,SAAO,EAAE,KAAK,EAAE,OAAO,aAAa,EAAE,IAAI;GAC1C"}
|
package/dist/endpoints/hono.mjs
CHANGED
|
@@ -45,7 +45,7 @@ function createCopilotEndpoint({ runtime, basePath, cors: corsConfig }) {
|
|
|
45
45
|
await next();
|
|
46
46
|
}).use("*", async (c, next) => {
|
|
47
47
|
await next();
|
|
48
|
-
const response = c.res;
|
|
48
|
+
const response = c.res.clone();
|
|
49
49
|
const path = c.req.path;
|
|
50
50
|
callAfterRequestMiddleware({
|
|
51
51
|
runtime,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hono.mjs","names":[],"sources":["../../src/endpoints/hono.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport { CopilotRuntime } from \"../runtime\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"../middleware\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\n\n/**\n * CORS configuration for CopilotKit endpoints.\n * When using credentials (e.g., HTTP-only cookies), you must specify an explicit origin.\n */\nexport interface CopilotEndpointCorsConfig {\n /**\n * Allowed origin(s) for CORS. Can be:\n * - A string: exact origin (e.g., \"https://myapp.com\")\n * - An array: list of allowed origins\n * - A function: dynamic origin resolution\n *\n * Note: When credentials is true, origin cannot be \"*\"\n */\n origin:\n | string\n | string[]\n | ((origin: string, c: any) => string | undefined | null);\n /**\n * Whether to allow credentials (cookies, HTTP authentication).\n * When true, origin must be explicitly specified (not \"*\").\n */\n credentials?: boolean;\n}\n\ninterface CopilotEndpointParams {\n runtime: CopilotRuntime;\n basePath: string;\n /**\n * Optional CORS configuration. When not provided, defaults to allowing all origins without credentials.\n * To support HTTP-only cookies, provide cors config with credentials: true and explicit origin.\n */\n cors?: CopilotEndpointCorsConfig;\n}\n\n// Define the context variables type\ntype CopilotEndpointContext = {\n Variables: {\n modifiedRequest?: Request;\n };\n};\n\nexport function createCopilotEndpoint({\n runtime,\n basePath,\n cors: corsConfig,\n}: CopilotEndpointParams) {\n const app = new Hono<CopilotEndpointContext>();\n\n return app\n .basePath(basePath)\n .use(\n \"*\",\n cors({\n origin: corsConfig?.origin ?? \"*\",\n allowMethods: [\n \"GET\",\n \"HEAD\",\n \"PUT\",\n \"POST\",\n \"DELETE\",\n \"PATCH\",\n \"OPTIONS\",\n ],\n allowHeaders: [\"*\"],\n credentials: corsConfig?.credentials ?? false,\n }),\n )\n .use(\"*\", async (c, next) => {\n const request = c.req.raw;\n const path = c.req.path;\n\n try {\n const maybeModifiedRequest = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModifiedRequest) {\n c.set(\"modifiedRequest\", maybeModifiedRequest);\n }\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (error instanceof Response) {\n return error;\n }\n throw error;\n }\n\n await next();\n })\n .use(\"*\", async (c, next) => {\n await next();\n\n const response = c.res;\n const path = c.req.path;\n\n // Non-blocking after middleware\n callAfterRequestMiddleware({\n runtime,\n response,\n path,\n }).catch((error) => {\n logger.error(\n { err: error, url: c.req.url, path },\n \"Error running after request middleware\",\n );\n });\n })\n .post(\"/agent/:agentId/run\", async (c) => {\n const agentId = c.req.param(\"agentId\");\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleRunAgent({\n runtime,\n request,\n agentId,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n .post(\"/agent/:agentId/connect\", async (c) => {\n const agentId = c.req.param(\"agentId\");\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleConnectAgent({\n runtime,\n request,\n agentId,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n\n .post(\"/agent/:agentId/stop/:threadId\", async (c) => {\n const agentId = c.req.param(\"agentId\");\n const threadId = c.req.param(\"threadId\");\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n .get(\"/info\", async (c) => {\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleGetRuntimeInfo({\n runtime,\n request,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n .post(\"/transcribe\", async (c) => {\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleTranscribe({\n runtime,\n request,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n .notFound((c) => {\n return c.json({ error: \"Not found\" }, 404);\n });\n\n // return app;\n}\n"],"mappings":";;;;;;;;;;;AAuDA,SAAgB,sBAAsB,EACpC,SACA,UACA,MAAM,cACkB;AAGxB,QAFY,IAAI,MAA8B,CAG3C,SAAS,SAAS,CAClB,IACC,KACA,KAAK;EACH,QAAQ,YAAY,UAAU;EAC9B,cAAc;GACZ;GACA;GACA;GACA;GACA;GACA;GACA;GACD;EACD,cAAc,CAAC,IAAI;EACnB,aAAa,YAAY,eAAe;EACzC,CAAC,CACH,CACA,IAAI,KAAK,OAAO,GAAG,SAAS;EAC3B,MAAM,UAAU,EAAE,IAAI;EACtB,MAAM,OAAO,EAAE,IAAI;AAEnB,MAAI;GACF,MAAM,uBAAuB,MAAM,4BAA4B;IAC7D;IACA;IACA;IACD,CAAC;AACF,OAAI,qBACF,GAAE,IAAI,mBAAmB,qBAAqB;WAEzC,OAAO;AACd,UAAO,MACL;IAAE,KAAK;IAAO,KAAK,QAAQ;IAAK;IAAM,EACtC,0CACD;AACD,OAAI,iBAAiB,SACnB,QAAO;AAET,SAAM;;AAGR,QAAM,MAAM;GACZ,CACD,IAAI,KAAK,OAAO,GAAG,SAAS;AAC3B,QAAM,MAAM;EAEZ,MAAM,WAAW,EAAE;
|
|
1
|
+
{"version":3,"file":"hono.mjs","names":[],"sources":["../../src/endpoints/hono.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport { CopilotRuntime } from \"../runtime\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"../middleware\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\n\n/**\n * CORS configuration for CopilotKit endpoints.\n * When using credentials (e.g., HTTP-only cookies), you must specify an explicit origin.\n */\nexport interface CopilotEndpointCorsConfig {\n /**\n * Allowed origin(s) for CORS. Can be:\n * - A string: exact origin (e.g., \"https://myapp.com\")\n * - An array: list of allowed origins\n * - A function: dynamic origin resolution\n *\n * Note: When credentials is true, origin cannot be \"*\"\n */\n origin:\n | string\n | string[]\n | ((origin: string, c: any) => string | undefined | null);\n /**\n * Whether to allow credentials (cookies, HTTP authentication).\n * When true, origin must be explicitly specified (not \"*\").\n */\n credentials?: boolean;\n}\n\ninterface CopilotEndpointParams {\n runtime: CopilotRuntime;\n basePath: string;\n /**\n * Optional CORS configuration. When not provided, defaults to allowing all origins without credentials.\n * To support HTTP-only cookies, provide cors config with credentials: true and explicit origin.\n */\n cors?: CopilotEndpointCorsConfig;\n}\n\n// Define the context variables type\ntype CopilotEndpointContext = {\n Variables: {\n modifiedRequest?: Request;\n };\n};\n\nexport function createCopilotEndpoint({\n runtime,\n basePath,\n cors: corsConfig,\n}: CopilotEndpointParams) {\n const app = new Hono<CopilotEndpointContext>();\n\n return app\n .basePath(basePath)\n .use(\n \"*\",\n cors({\n origin: corsConfig?.origin ?? \"*\",\n allowMethods: [\n \"GET\",\n \"HEAD\",\n \"PUT\",\n \"POST\",\n \"DELETE\",\n \"PATCH\",\n \"OPTIONS\",\n ],\n allowHeaders: [\"*\"],\n credentials: corsConfig?.credentials ?? false,\n }),\n )\n .use(\"*\", async (c, next) => {\n const request = c.req.raw;\n const path = c.req.path;\n\n try {\n const maybeModifiedRequest = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModifiedRequest) {\n c.set(\"modifiedRequest\", maybeModifiedRequest);\n }\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (error instanceof Response) {\n return error;\n }\n throw error;\n }\n\n await next();\n })\n .use(\"*\", async (c, next) => {\n await next();\n\n const response = c.res.clone();\n const path = c.req.path;\n\n // Non-blocking after middleware\n callAfterRequestMiddleware({\n runtime,\n response,\n path,\n }).catch((error) => {\n logger.error(\n { err: error, url: c.req.url, path },\n \"Error running after request middleware\",\n );\n });\n })\n .post(\"/agent/:agentId/run\", async (c) => {\n const agentId = c.req.param(\"agentId\");\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleRunAgent({\n runtime,\n request,\n agentId,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n .post(\"/agent/:agentId/connect\", async (c) => {\n const agentId = c.req.param(\"agentId\");\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleConnectAgent({\n runtime,\n request,\n agentId,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n\n .post(\"/agent/:agentId/stop/:threadId\", async (c) => {\n const agentId = c.req.param(\"agentId\");\n const threadId = c.req.param(\"threadId\");\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n .get(\"/info\", async (c) => {\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleGetRuntimeInfo({\n runtime,\n request,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n .post(\"/transcribe\", async (c) => {\n const request = c.get(\"modifiedRequest\") || c.req.raw;\n\n try {\n return await handleTranscribe({\n runtime,\n request,\n });\n } catch (error) {\n logger.error(\n { err: error, url: request.url, path: c.req.path },\n \"Error running request handler\",\n );\n throw error;\n }\n })\n .notFound((c) => {\n return c.json({ error: \"Not found\" }, 404);\n });\n\n // return app;\n}\n"],"mappings":";;;;;;;;;;;AAuDA,SAAgB,sBAAsB,EACpC,SACA,UACA,MAAM,cACkB;AAGxB,QAFY,IAAI,MAA8B,CAG3C,SAAS,SAAS,CAClB,IACC,KACA,KAAK;EACH,QAAQ,YAAY,UAAU;EAC9B,cAAc;GACZ;GACA;GACA;GACA;GACA;GACA;GACA;GACD;EACD,cAAc,CAAC,IAAI;EACnB,aAAa,YAAY,eAAe;EACzC,CAAC,CACH,CACA,IAAI,KAAK,OAAO,GAAG,SAAS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AAK,kCAAkC,OAAO,MAAM;EACnD,MAAM,UAAU,EAAE,IAAI,MAAM,UAAU;EACtC,MAAM,WAAW,EAAE,IAAI,MAAM,WAAW;EACxC,MAAM,UAAU,EAAE,IAAI,kBAAkB,IAAI,EAAE,IAAI;AAElD,MAAI;AACF,UAAO,MAAM,gBAAgB;IAC3B;IACA;IACA;IACA;IACD,CAAC;WACK,OAAO;AACd,UAAO,MACL;IAAE,KAAK;IAAO,KAAK,QAAQ;IAAK,MAAM,EAAE,IAAI;IAAM,EAClD,gCACD;AACD,SAAM;;GAER,CACD,IAAI,SAAS,OAAO,MAAM;EACzB,MAAM,UAAU,EAAE,IAAI,kBAAkB,IAAI,EAAE,IAAI;AAElD,MAAI;AACF,UAAO,MAAM,qBAAqB;IAChC;IACA;IACD,CAAC;WACK,OAAO;AACd,UAAO,MACL;IAAE,KAAK;IAAO,KAAK,QAAQ;IAAK,MAAM,EAAE,IAAI;IAAM,EAClD,gCACD;AACD,SAAM;;GAER,CACD,KAAK,eAAe,OAAO,MAAM;EAChC,MAAM,UAAU,EAAE,IAAI,kBAAkB,IAAI,EAAE,IAAI;AAElD,MAAI;AACF,UAAO,MAAM,iBAAiB;IAC5B;IACA;IACD,CAAC;WACK,OAAO;AACd,UAAO,MACL;IAAE,KAAK;IAAO,KAAK,QAAQ;IAAK,MAAM,EAAE,IAAI;IAAM,EAClD,gCACD;AACD,SAAM;;GAER,CACD,UAAU,MAAM;AACf,SAAO,EAAE,KAAK,EAAE,OAAO,aAAa,EAAE,IAAI;GAC1C"}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
|
|
2
|
+
let _copilotkitnext_shared = require("@copilotkitnext/shared");
|
|
3
|
+
|
|
4
|
+
//#region src/middleware-sse-parser.ts
|
|
5
|
+
/**
|
|
6
|
+
* Parse a cloned SSE Response body into structured messages.
|
|
7
|
+
* Returns empty results for non-SSE responses.
|
|
8
|
+
*/
|
|
9
|
+
async function parseSSEResponse(response) {
|
|
10
|
+
if (!(response.headers.get("content-type") ?? "").includes("text/event-stream")) return { messages: [] };
|
|
11
|
+
let text;
|
|
12
|
+
try {
|
|
13
|
+
text = await response.text();
|
|
14
|
+
} catch {
|
|
15
|
+
_copilotkitnext_shared.logger.warn("Failed to read SSE response body in afterRequestMiddleware");
|
|
16
|
+
return { messages: [] };
|
|
17
|
+
}
|
|
18
|
+
if (!text.trim()) return { messages: [] };
|
|
19
|
+
let threadId;
|
|
20
|
+
let runId;
|
|
21
|
+
const messagesById = /* @__PURE__ */ new Map();
|
|
22
|
+
const toolCallsById = /* @__PURE__ */ new Map();
|
|
23
|
+
const toolCallParent = /* @__PURE__ */ new Map();
|
|
24
|
+
let snapshotMessages;
|
|
25
|
+
for (const line of text.split("\n")) {
|
|
26
|
+
const trimmed = line.trim();
|
|
27
|
+
if (!trimmed.startsWith("data:")) continue;
|
|
28
|
+
let event;
|
|
29
|
+
try {
|
|
30
|
+
event = JSON.parse(trimmed.slice(5).trim());
|
|
31
|
+
} catch {
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
switch (event.type) {
|
|
35
|
+
case "RUN_STARTED":
|
|
36
|
+
threadId = event.threadId;
|
|
37
|
+
runId = event.runId;
|
|
38
|
+
break;
|
|
39
|
+
case "MESSAGES_SNAPSHOT":
|
|
40
|
+
if (Array.isArray(event.messages)) snapshotMessages = event.messages;
|
|
41
|
+
break;
|
|
42
|
+
case "TEXT_MESSAGE_START":
|
|
43
|
+
messagesById.set(event.messageId, {
|
|
44
|
+
id: event.messageId,
|
|
45
|
+
role: event.role ?? "assistant",
|
|
46
|
+
content: ""
|
|
47
|
+
});
|
|
48
|
+
break;
|
|
49
|
+
case "TEXT_MESSAGE_CONTENT": {
|
|
50
|
+
const msg = messagesById.get(event.messageId);
|
|
51
|
+
if (msg) msg.content = (msg.content ?? "") + (event.delta ?? "");
|
|
52
|
+
break;
|
|
53
|
+
}
|
|
54
|
+
case "TEXT_MESSAGE_CHUNK":
|
|
55
|
+
if (event.messageId) {
|
|
56
|
+
const existing = messagesById.get(event.messageId);
|
|
57
|
+
if (existing) existing.content = (existing.content ?? "") + (event.delta ?? "");
|
|
58
|
+
else messagesById.set(event.messageId, {
|
|
59
|
+
id: event.messageId,
|
|
60
|
+
role: event.role ?? "assistant",
|
|
61
|
+
content: event.delta ?? ""
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
break;
|
|
65
|
+
case "TOOL_CALL_START": {
|
|
66
|
+
const tc = {
|
|
67
|
+
id: event.toolCallId,
|
|
68
|
+
name: event.toolCallName,
|
|
69
|
+
args: ""
|
|
70
|
+
};
|
|
71
|
+
toolCallsById.set(event.toolCallId, tc);
|
|
72
|
+
if (event.parentMessageId) toolCallParent.set(event.toolCallId, event.parentMessageId);
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
case "TOOL_CALL_ARGS": {
|
|
76
|
+
const tc = toolCallsById.get(event.toolCallId);
|
|
77
|
+
if (tc) tc.args += event.delta ?? "";
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
case "TOOL_CALL_CHUNK":
|
|
81
|
+
if (event.toolCallId) {
|
|
82
|
+
let tc = toolCallsById.get(event.toolCallId);
|
|
83
|
+
if (!tc) {
|
|
84
|
+
tc = {
|
|
85
|
+
id: event.toolCallId,
|
|
86
|
+
name: event.toolCallName ?? "",
|
|
87
|
+
args: ""
|
|
88
|
+
};
|
|
89
|
+
toolCallsById.set(event.toolCallId, tc);
|
|
90
|
+
if (event.parentMessageId) toolCallParent.set(event.toolCallId, event.parentMessageId);
|
|
91
|
+
}
|
|
92
|
+
if (event.toolCallName) tc.name = event.toolCallName;
|
|
93
|
+
tc.args += event.delta ?? "";
|
|
94
|
+
}
|
|
95
|
+
break;
|
|
96
|
+
case "TOOL_CALL_END": {
|
|
97
|
+
const tc = toolCallsById.get(event.toolCallId);
|
|
98
|
+
const parentId = toolCallParent.get(event.toolCallId);
|
|
99
|
+
if (tc && parentId) {
|
|
100
|
+
const parent = messagesById.get(parentId);
|
|
101
|
+
if (parent) {
|
|
102
|
+
parent.toolCalls = parent.toolCalls ?? [];
|
|
103
|
+
parent.toolCalls.push(tc);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
case "TOOL_CALL_RESULT":
|
|
109
|
+
messagesById.set(event.messageId, {
|
|
110
|
+
id: event.messageId,
|
|
111
|
+
role: "tool",
|
|
112
|
+
content: event.content,
|
|
113
|
+
toolCallId: event.toolCallId
|
|
114
|
+
});
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
for (const [toolCallId, tc] of toolCallsById) {
|
|
119
|
+
const parentId = toolCallParent.get(toolCallId);
|
|
120
|
+
if (!parentId) continue;
|
|
121
|
+
const parent = messagesById.get(parentId);
|
|
122
|
+
if (!parent) continue;
|
|
123
|
+
if (!parent.toolCalls?.some((t) => t.id === tc.id)) {
|
|
124
|
+
parent.toolCalls = parent.toolCalls ?? [];
|
|
125
|
+
parent.toolCalls.push(tc);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return {
|
|
129
|
+
messages: snapshotMessages ?? [...messagesById.values()],
|
|
130
|
+
threadId,
|
|
131
|
+
runId
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
//#endregion
|
|
136
|
+
exports.parseSSEResponse = parseSSEResponse;
|
|
137
|
+
//# sourceMappingURL=middleware-sse-parser.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware-sse-parser.cjs","names":[],"sources":["../src/middleware-sse-parser.ts"],"sourcesContent":["import { logger } from \"@copilotkitnext/shared\";\n\nexport interface ParsedSSEResult {\n messages: Message[];\n threadId?: string;\n runId?: string;\n}\n\n/** Minimal message shape reconstructed from AG-UI events. */\nexport interface Message {\n id: string;\n role: string;\n content?: string;\n toolCalls?: ToolCall[];\n toolCallId?: string;\n}\n\ninterface ToolCall {\n id: string;\n name: string;\n args: string;\n}\n\n/**\n * Parse a cloned SSE Response body into structured messages.\n * Returns empty results for non-SSE responses.\n */\nexport async function parseSSEResponse(\n response: Response,\n): Promise<ParsedSSEResult> {\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (!contentType.includes(\"text/event-stream\")) {\n return { messages: [] };\n }\n\n let text: string;\n try {\n text = await response.text();\n } catch {\n logger.warn(\"Failed to read SSE response body in afterRequestMiddleware\");\n return { messages: [] };\n }\n\n if (!text.trim()) {\n return { messages: [] };\n }\n\n let threadId: string | undefined;\n let runId: string | undefined;\n const messagesById = new Map<string, Message>();\n const toolCallsById = new Map<string, ToolCall>();\n const toolCallParent = new Map<string, string>(); // toolCallId → messageId\n let snapshotMessages: Message[] | undefined;\n\n for (const line of text.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"data:\")) continue;\n\n let event: Record<string, any>;\n try {\n event = JSON.parse(trimmed.slice(5).trim());\n } catch {\n continue;\n }\n\n switch (event.type) {\n case \"RUN_STARTED\":\n threadId = event.threadId;\n runId = event.runId;\n break;\n\n case \"MESSAGES_SNAPSHOT\":\n if (Array.isArray(event.messages)) {\n snapshotMessages = event.messages;\n }\n break;\n\n case \"TEXT_MESSAGE_START\":\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: event.role ?? \"assistant\",\n content: \"\",\n });\n break;\n\n case \"TEXT_MESSAGE_CONTENT\": {\n const msg = messagesById.get(event.messageId);\n if (msg) {\n msg.content = (msg.content ?? \"\") + (event.delta ?? \"\");\n }\n break;\n }\n\n case \"TEXT_MESSAGE_CHUNK\": {\n // Chunk format: combined start+content. First chunk creates the\n // message, subsequent chunks append delta to content.\n if (event.messageId) {\n const existing = messagesById.get(event.messageId);\n if (existing) {\n existing.content = (existing.content ?? \"\") + (event.delta ?? \"\");\n } else {\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: event.role ?? \"assistant\",\n content: event.delta ?? \"\",\n });\n }\n }\n break;\n }\n\n case \"TOOL_CALL_START\": {\n const tc: ToolCall = {\n id: event.toolCallId,\n name: event.toolCallName,\n args: \"\",\n };\n toolCallsById.set(event.toolCallId, tc);\n if (event.parentMessageId) {\n toolCallParent.set(event.toolCallId, event.parentMessageId);\n }\n break;\n }\n\n case \"TOOL_CALL_ARGS\": {\n const tc = toolCallsById.get(event.toolCallId);\n if (tc) {\n tc.args += event.delta ?? \"\";\n }\n break;\n }\n\n case \"TOOL_CALL_CHUNK\": {\n // Chunk format: combined start+args. First chunk for a given\n // toolCallId creates the tool call, subsequent chunks append delta.\n if (event.toolCallId) {\n let tc = toolCallsById.get(event.toolCallId);\n if (!tc) {\n tc = {\n id: event.toolCallId,\n name: event.toolCallName ?? \"\",\n args: \"\",\n };\n toolCallsById.set(event.toolCallId, tc);\n if (event.parentMessageId) {\n toolCallParent.set(event.toolCallId, event.parentMessageId);\n }\n }\n if (event.toolCallName) {\n tc.name = event.toolCallName;\n }\n tc.args += event.delta ?? \"\";\n }\n break;\n }\n\n case \"TOOL_CALL_END\": {\n const tc = toolCallsById.get(event.toolCallId);\n const parentId = toolCallParent.get(event.toolCallId);\n if (tc && parentId) {\n const parent = messagesById.get(parentId);\n if (parent) {\n parent.toolCalls = parent.toolCalls ?? [];\n parent.toolCalls.push(tc);\n }\n }\n break;\n }\n\n case \"TOOL_CALL_RESULT\":\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: \"tool\",\n content: event.content,\n toolCallId: event.toolCallId,\n });\n break;\n }\n }\n\n // Attach any tool calls not yet linked to their parent message.\n // This handles TOOL_CALL_CHUNK flows which don't emit TOOL_CALL_END.\n for (const [toolCallId, tc] of toolCallsById) {\n const parentId = toolCallParent.get(toolCallId);\n if (!parentId) continue;\n const parent = messagesById.get(parentId);\n if (!parent) continue;\n const alreadyAttached = parent.toolCalls?.some((t) => t.id === tc.id);\n if (!alreadyAttached) {\n parent.toolCalls = parent.toolCalls ?? [];\n parent.toolCalls.push(tc);\n }\n }\n\n // Prefer MESSAGES_SNAPSHOT if present (contains full history).\n // Otherwise reconstruct from individual events.\n const messages = snapshotMessages ?? [...messagesById.values()];\n\n return { messages, threadId, runId };\n}\n"],"mappings":";;;;;;;;AA2BA,eAAsB,iBACpB,UAC0B;AAE1B,KAAI,EADgB,SAAS,QAAQ,IAAI,eAAe,IAAI,IAC3C,SAAS,oBAAoB,CAC5C,QAAO,EAAE,UAAU,EAAE,EAAE;CAGzB,IAAI;AACJ,KAAI;AACF,SAAO,MAAM,SAAS,MAAM;SACtB;AACN,gCAAO,KAAK,6DAA6D;AACzE,SAAO,EAAE,UAAU,EAAE,EAAE;;AAGzB,KAAI,CAAC,KAAK,MAAM,CACd,QAAO,EAAE,UAAU,EAAE,EAAE;CAGzB,IAAI;CACJ,IAAI;CACJ,MAAM,+BAAe,IAAI,KAAsB;CAC/C,MAAM,gCAAgB,IAAI,KAAuB;CACjD,MAAM,iCAAiB,IAAI,KAAqB;CAChD,IAAI;AAEJ,MAAK,MAAM,QAAQ,KAAK,MAAM,KAAK,EAAE;EACnC,MAAM,UAAU,KAAK,MAAM;AAC3B,MAAI,CAAC,QAAQ,WAAW,QAAQ,CAAE;EAElC,IAAI;AACJ,MAAI;AACF,WAAQ,KAAK,MAAM,QAAQ,MAAM,EAAE,CAAC,MAAM,CAAC;UACrC;AACN;;AAGF,UAAQ,MAAM,MAAd;GACE,KAAK;AACH,eAAW,MAAM;AACjB,YAAQ,MAAM;AACd;GAEF,KAAK;AACH,QAAI,MAAM,QAAQ,MAAM,SAAS,CAC/B,oBAAmB,MAAM;AAE3B;GAEF,KAAK;AACH,iBAAa,IAAI,MAAM,WAAW;KAChC,IAAI,MAAM;KACV,MAAM,MAAM,QAAQ;KACpB,SAAS;KACV,CAAC;AACF;GAEF,KAAK,wBAAwB;IAC3B,MAAM,MAAM,aAAa,IAAI,MAAM,UAAU;AAC7C,QAAI,IACF,KAAI,WAAW,IAAI,WAAW,OAAO,MAAM,SAAS;AAEtD;;GAGF,KAAK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M;KACV,MAAM;KACN,SAAS,MAAM;KACf,YAAY,MAAM;KACnB,CAAC;AACF;;;AAMN,MAAK,MAAM,CAAC,YAAY,OAAO,eAAe;EAC5C,MAAM,WAAW,eAAe,IAAI,WAAW;AAC/C,MAAI,CAAC,SAAU;EACf,MAAM,SAAS,aAAa,IAAI,SAAS;AACzC,MAAI,CAAC,OAAQ;AAEb,MAAI,CADoB,OAAO,WAAW,MAAM,MAAM,EAAE,OAAO,GAAG,GAAG,EAC/C;AACpB,UAAO,YAAY,OAAO,aAAa,EAAE;AACzC,UAAO,UAAU,KAAK,GAAG;;;AAQ7B,QAAO;EAAE,UAFQ,oBAAoB,CAAC,GAAG,aAAa,QAAQ,CAAC;EAE5C;EAAU;EAAO"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
//#region src/middleware-sse-parser.d.ts
|
|
2
|
+
/** Minimal message shape reconstructed from AG-UI events. */
|
|
3
|
+
interface Message {
|
|
4
|
+
id: string;
|
|
5
|
+
role: string;
|
|
6
|
+
content?: string;
|
|
7
|
+
toolCalls?: ToolCall[];
|
|
8
|
+
toolCallId?: string;
|
|
9
|
+
}
|
|
10
|
+
interface ToolCall {
|
|
11
|
+
id: string;
|
|
12
|
+
name: string;
|
|
13
|
+
args: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Parse a cloned SSE Response body into structured messages.
|
|
17
|
+
* Returns empty results for non-SSE responses.
|
|
18
|
+
*/
|
|
19
|
+
//#endregion
|
|
20
|
+
export { Message };
|
|
21
|
+
//# sourceMappingURL=middleware-sse-parser.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware-sse-parser.d.cts","names":[],"sources":["../src/middleware-sse-parser.ts"],"mappings":";;UASiB,OAAA;EACf,EAAA;EACA,IAAA;EACA,OAAA;EACA,SAAA,GAAY,QAAA;EACZ,UAAA;AAAA;AAAA,UAGQ,QAAA;EACR,EAAA;EACA,IAAA;EACA,IAAA;AAAA"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
//#region src/middleware-sse-parser.d.ts
|
|
2
|
+
/** Minimal message shape reconstructed from AG-UI events. */
|
|
3
|
+
interface Message {
|
|
4
|
+
id: string;
|
|
5
|
+
role: string;
|
|
6
|
+
content?: string;
|
|
7
|
+
toolCalls?: ToolCall[];
|
|
8
|
+
toolCallId?: string;
|
|
9
|
+
}
|
|
10
|
+
interface ToolCall {
|
|
11
|
+
id: string;
|
|
12
|
+
name: string;
|
|
13
|
+
args: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Parse a cloned SSE Response body into structured messages.
|
|
17
|
+
* Returns empty results for non-SSE responses.
|
|
18
|
+
*/
|
|
19
|
+
//#endregion
|
|
20
|
+
export { Message };
|
|
21
|
+
//# sourceMappingURL=middleware-sse-parser.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware-sse-parser.d.mts","names":[],"sources":["../src/middleware-sse-parser.ts"],"mappings":";;UASiB,OAAA;EACf,EAAA;EACA,IAAA;EACA,OAAA;EACA,SAAA,GAAY,QAAA;EACZ,UAAA;AAAA;AAAA,UAGQ,QAAA;EACR,EAAA;EACA,IAAA;EACA,IAAA;AAAA"}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { logger } from "@copilotkitnext/shared";
|
|
2
|
+
|
|
3
|
+
//#region src/middleware-sse-parser.ts
|
|
4
|
+
/**
|
|
5
|
+
* Parse a cloned SSE Response body into structured messages.
|
|
6
|
+
* Returns empty results for non-SSE responses.
|
|
7
|
+
*/
|
|
8
|
+
async function parseSSEResponse(response) {
|
|
9
|
+
if (!(response.headers.get("content-type") ?? "").includes("text/event-stream")) return { messages: [] };
|
|
10
|
+
let text;
|
|
11
|
+
try {
|
|
12
|
+
text = await response.text();
|
|
13
|
+
} catch {
|
|
14
|
+
logger.warn("Failed to read SSE response body in afterRequestMiddleware");
|
|
15
|
+
return { messages: [] };
|
|
16
|
+
}
|
|
17
|
+
if (!text.trim()) return { messages: [] };
|
|
18
|
+
let threadId;
|
|
19
|
+
let runId;
|
|
20
|
+
const messagesById = /* @__PURE__ */ new Map();
|
|
21
|
+
const toolCallsById = /* @__PURE__ */ new Map();
|
|
22
|
+
const toolCallParent = /* @__PURE__ */ new Map();
|
|
23
|
+
let snapshotMessages;
|
|
24
|
+
for (const line of text.split("\n")) {
|
|
25
|
+
const trimmed = line.trim();
|
|
26
|
+
if (!trimmed.startsWith("data:")) continue;
|
|
27
|
+
let event;
|
|
28
|
+
try {
|
|
29
|
+
event = JSON.parse(trimmed.slice(5).trim());
|
|
30
|
+
} catch {
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
switch (event.type) {
|
|
34
|
+
case "RUN_STARTED":
|
|
35
|
+
threadId = event.threadId;
|
|
36
|
+
runId = event.runId;
|
|
37
|
+
break;
|
|
38
|
+
case "MESSAGES_SNAPSHOT":
|
|
39
|
+
if (Array.isArray(event.messages)) snapshotMessages = event.messages;
|
|
40
|
+
break;
|
|
41
|
+
case "TEXT_MESSAGE_START":
|
|
42
|
+
messagesById.set(event.messageId, {
|
|
43
|
+
id: event.messageId,
|
|
44
|
+
role: event.role ?? "assistant",
|
|
45
|
+
content: ""
|
|
46
|
+
});
|
|
47
|
+
break;
|
|
48
|
+
case "TEXT_MESSAGE_CONTENT": {
|
|
49
|
+
const msg = messagesById.get(event.messageId);
|
|
50
|
+
if (msg) msg.content = (msg.content ?? "") + (event.delta ?? "");
|
|
51
|
+
break;
|
|
52
|
+
}
|
|
53
|
+
case "TEXT_MESSAGE_CHUNK":
|
|
54
|
+
if (event.messageId) {
|
|
55
|
+
const existing = messagesById.get(event.messageId);
|
|
56
|
+
if (existing) existing.content = (existing.content ?? "") + (event.delta ?? "");
|
|
57
|
+
else messagesById.set(event.messageId, {
|
|
58
|
+
id: event.messageId,
|
|
59
|
+
role: event.role ?? "assistant",
|
|
60
|
+
content: event.delta ?? ""
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
break;
|
|
64
|
+
case "TOOL_CALL_START": {
|
|
65
|
+
const tc = {
|
|
66
|
+
id: event.toolCallId,
|
|
67
|
+
name: event.toolCallName,
|
|
68
|
+
args: ""
|
|
69
|
+
};
|
|
70
|
+
toolCallsById.set(event.toolCallId, tc);
|
|
71
|
+
if (event.parentMessageId) toolCallParent.set(event.toolCallId, event.parentMessageId);
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
case "TOOL_CALL_ARGS": {
|
|
75
|
+
const tc = toolCallsById.get(event.toolCallId);
|
|
76
|
+
if (tc) tc.args += event.delta ?? "";
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
case "TOOL_CALL_CHUNK":
|
|
80
|
+
if (event.toolCallId) {
|
|
81
|
+
let tc = toolCallsById.get(event.toolCallId);
|
|
82
|
+
if (!tc) {
|
|
83
|
+
tc = {
|
|
84
|
+
id: event.toolCallId,
|
|
85
|
+
name: event.toolCallName ?? "",
|
|
86
|
+
args: ""
|
|
87
|
+
};
|
|
88
|
+
toolCallsById.set(event.toolCallId, tc);
|
|
89
|
+
if (event.parentMessageId) toolCallParent.set(event.toolCallId, event.parentMessageId);
|
|
90
|
+
}
|
|
91
|
+
if (event.toolCallName) tc.name = event.toolCallName;
|
|
92
|
+
tc.args += event.delta ?? "";
|
|
93
|
+
}
|
|
94
|
+
break;
|
|
95
|
+
case "TOOL_CALL_END": {
|
|
96
|
+
const tc = toolCallsById.get(event.toolCallId);
|
|
97
|
+
const parentId = toolCallParent.get(event.toolCallId);
|
|
98
|
+
if (tc && parentId) {
|
|
99
|
+
const parent = messagesById.get(parentId);
|
|
100
|
+
if (parent) {
|
|
101
|
+
parent.toolCalls = parent.toolCalls ?? [];
|
|
102
|
+
parent.toolCalls.push(tc);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
break;
|
|
106
|
+
}
|
|
107
|
+
case "TOOL_CALL_RESULT":
|
|
108
|
+
messagesById.set(event.messageId, {
|
|
109
|
+
id: event.messageId,
|
|
110
|
+
role: "tool",
|
|
111
|
+
content: event.content,
|
|
112
|
+
toolCallId: event.toolCallId
|
|
113
|
+
});
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
for (const [toolCallId, tc] of toolCallsById) {
|
|
118
|
+
const parentId = toolCallParent.get(toolCallId);
|
|
119
|
+
if (!parentId) continue;
|
|
120
|
+
const parent = messagesById.get(parentId);
|
|
121
|
+
if (!parent) continue;
|
|
122
|
+
if (!parent.toolCalls?.some((t) => t.id === tc.id)) {
|
|
123
|
+
parent.toolCalls = parent.toolCalls ?? [];
|
|
124
|
+
parent.toolCalls.push(tc);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
messages: snapshotMessages ?? [...messagesById.values()],
|
|
129
|
+
threadId,
|
|
130
|
+
runId
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
//#endregion
|
|
135
|
+
export { parseSSEResponse };
|
|
136
|
+
//# sourceMappingURL=middleware-sse-parser.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware-sse-parser.mjs","names":[],"sources":["../src/middleware-sse-parser.ts"],"sourcesContent":["import { logger } from \"@copilotkitnext/shared\";\n\nexport interface ParsedSSEResult {\n messages: Message[];\n threadId?: string;\n runId?: string;\n}\n\n/** Minimal message shape reconstructed from AG-UI events. */\nexport interface Message {\n id: string;\n role: string;\n content?: string;\n toolCalls?: ToolCall[];\n toolCallId?: string;\n}\n\ninterface ToolCall {\n id: string;\n name: string;\n args: string;\n}\n\n/**\n * Parse a cloned SSE Response body into structured messages.\n * Returns empty results for non-SSE responses.\n */\nexport async function parseSSEResponse(\n response: Response,\n): Promise<ParsedSSEResult> {\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (!contentType.includes(\"text/event-stream\")) {\n return { messages: [] };\n }\n\n let text: string;\n try {\n text = await response.text();\n } catch {\n logger.warn(\"Failed to read SSE response body in afterRequestMiddleware\");\n return { messages: [] };\n }\n\n if (!text.trim()) {\n return { messages: [] };\n }\n\n let threadId: string | undefined;\n let runId: string | undefined;\n const messagesById = new Map<string, Message>();\n const toolCallsById = new Map<string, ToolCall>();\n const toolCallParent = new Map<string, string>(); // toolCallId → messageId\n let snapshotMessages: Message[] | undefined;\n\n for (const line of text.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"data:\")) continue;\n\n let event: Record<string, any>;\n try {\n event = JSON.parse(trimmed.slice(5).trim());\n } catch {\n continue;\n }\n\n switch (event.type) {\n case \"RUN_STARTED\":\n threadId = event.threadId;\n runId = event.runId;\n break;\n\n case \"MESSAGES_SNAPSHOT\":\n if (Array.isArray(event.messages)) {\n snapshotMessages = event.messages;\n }\n break;\n\n case \"TEXT_MESSAGE_START\":\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: event.role ?? \"assistant\",\n content: \"\",\n });\n break;\n\n case \"TEXT_MESSAGE_CONTENT\": {\n const msg = messagesById.get(event.messageId);\n if (msg) {\n msg.content = (msg.content ?? \"\") + (event.delta ?? \"\");\n }\n break;\n }\n\n case \"TEXT_MESSAGE_CHUNK\": {\n // Chunk format: combined start+content. First chunk creates the\n // message, subsequent chunks append delta to content.\n if (event.messageId) {\n const existing = messagesById.get(event.messageId);\n if (existing) {\n existing.content = (existing.content ?? \"\") + (event.delta ?? \"\");\n } else {\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: event.role ?? \"assistant\",\n content: event.delta ?? \"\",\n });\n }\n }\n break;\n }\n\n case \"TOOL_CALL_START\": {\n const tc: ToolCall = {\n id: event.toolCallId,\n name: event.toolCallName,\n args: \"\",\n };\n toolCallsById.set(event.toolCallId, tc);\n if (event.parentMessageId) {\n toolCallParent.set(event.toolCallId, event.parentMessageId);\n }\n break;\n }\n\n case \"TOOL_CALL_ARGS\": {\n const tc = toolCallsById.get(event.toolCallId);\n if (tc) {\n tc.args += event.delta ?? \"\";\n }\n break;\n }\n\n case \"TOOL_CALL_CHUNK\": {\n // Chunk format: combined start+args. First chunk for a given\n // toolCallId creates the tool call, subsequent chunks append delta.\n if (event.toolCallId) {\n let tc = toolCallsById.get(event.toolCallId);\n if (!tc) {\n tc = {\n id: event.toolCallId,\n name: event.toolCallName ?? \"\",\n args: \"\",\n };\n toolCallsById.set(event.toolCallId, tc);\n if (event.parentMessageId) {\n toolCallParent.set(event.toolCallId, event.parentMessageId);\n }\n }\n if (event.toolCallName) {\n tc.name = event.toolCallName;\n }\n tc.args += event.delta ?? \"\";\n }\n break;\n }\n\n case \"TOOL_CALL_END\": {\n const tc = toolCallsById.get(event.toolCallId);\n const parentId = toolCallParent.get(event.toolCallId);\n if (tc && parentId) {\n const parent = messagesById.get(parentId);\n if (parent) {\n parent.toolCalls = parent.toolCalls ?? [];\n parent.toolCalls.push(tc);\n }\n }\n break;\n }\n\n case \"TOOL_CALL_RESULT\":\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: \"tool\",\n content: event.content,\n toolCallId: event.toolCallId,\n });\n break;\n }\n }\n\n // Attach any tool calls not yet linked to their parent message.\n // This handles TOOL_CALL_CHUNK flows which don't emit TOOL_CALL_END.\n for (const [toolCallId, tc] of toolCallsById) {\n const parentId = toolCallParent.get(toolCallId);\n if (!parentId) continue;\n const parent = messagesById.get(parentId);\n if (!parent) continue;\n const alreadyAttached = parent.toolCalls?.some((t) => t.id === tc.id);\n if (!alreadyAttached) {\n parent.toolCalls = parent.toolCalls ?? [];\n parent.toolCalls.push(tc);\n }\n }\n\n // Prefer MESSAGES_SNAPSHOT if present (contains full history).\n // Otherwise reconstruct from individual events.\n const messages = snapshotMessages ?? [...messagesById.values()];\n\n return { messages, threadId, runId };\n}\n"],"mappings":";;;;;;;AA2BA,eAAsB,iBACpB,UAC0B;AAE1B,KAAI,EADgB,SAAS,QAAQ,IAAI,eAAe,IAAI,IAC3C,SAAS,oBAAoB,CAC5C,QAAO,EAAE,UAAU,EA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AAM,MAAM,EAAE,OAAO,GAAG,GAAG,EAC/C;AACpB,UAAO,YAAY,OAAO,aAAa,EAAE;AACzC,UAAO,UAAU,KAAK,GAAG;;;AAQ7B,QAAO;EAAE,UAFQ,oBAAoB,CAAC,GAAG,aAAa,QAAQ,CAAC;EAE5C;EAAU;EAAO"}
|
package/dist/middleware.cjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
|
|
2
|
+
const require_middleware_sse_parser = require('./middleware-sse-parser.cjs');
|
|
2
3
|
let _copilotkitnext_shared = require("@copilotkitnext/shared");
|
|
3
4
|
|
|
4
5
|
//#region src/middleware.ts
|
|
@@ -15,10 +16,14 @@ async function callBeforeRequestMiddleware({ runtime, request, path }) {
|
|
|
15
16
|
async function callAfterRequestMiddleware({ runtime, response, path }) {
|
|
16
17
|
const mw = runtime.afterRequestMiddleware;
|
|
17
18
|
if (!mw) return;
|
|
19
|
+
const { messages, threadId, runId } = await require_middleware_sse_parser.parseSSEResponse(response);
|
|
18
20
|
if (typeof mw === "function") return mw({
|
|
19
21
|
runtime,
|
|
20
22
|
response,
|
|
21
|
-
path
|
|
23
|
+
path,
|
|
24
|
+
messages,
|
|
25
|
+
threadId,
|
|
26
|
+
runId
|
|
22
27
|
});
|
|
23
28
|
_copilotkitnext_shared.logger.warn({ mw }, "Unsupported afterRequestMiddleware value – skipped");
|
|
24
29
|
}
|
package/dist/middleware.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.cjs","names":[],"sources":["../src/middleware.ts"],"sourcesContent":["/**\n * Middleware support for CopilotKit Runtime.\n *\n * A middleware hook can be provided as either:\n * 1. A **callback function** executed in-process.\n * 2. A **webhook URL** (http/https). The runtime will `POST` a JSON payload\n * to the URL and, for *before* hooks, accept an optional modified\n * `Request` object in the response body.\n *\n * Two lifecycle hooks are available:\n * • `BEFORE_REQUEST` – runs *before* the request handler.\n * • `AFTER_REQUEST` – runs *after* the handler returns a `Response`.\n */\n\nimport type { CopilotRuntime } from \"./runtime\";\nimport type { MaybePromise } from \"@copilotkitnext/shared\";\nimport { logger } from \"@copilotkitnext/shared\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface BeforeRequestMiddlewareParameters {\n runtime: CopilotRuntime;\n request: Request;\n path: string;\n}\nexport interface AfterRequestMiddlewareParameters {\n runtime: CopilotRuntime;\n response: Response;\n path: string;\n}\n\nexport type BeforeRequestMiddlewareFn = (\n params: BeforeRequestMiddlewareParameters,\n) => MaybePromise<Request | void>;\nexport type AfterRequestMiddlewareFn = (\n params: AfterRequestMiddlewareParameters,\n) => MaybePromise<void>;\n\n/**\n * A middleware value can be either a callback function or a webhook URL.\n */\nexport type BeforeRequestMiddleware = BeforeRequestMiddlewareFn;\nexport type AfterRequestMiddleware = AfterRequestMiddlewareFn;\n\n/** Lifecycle events emitted to webhook middleware. */\nexport enum CopilotKitMiddlewareEvent {\n BeforeRequest = \"BEFORE_REQUEST\",\n AfterRequest = \"AFTER_REQUEST\",\n}\n\n/** Stages used by the Middleware Webhook Protocol */\n/** Stages used by the CopilotKit webhook protocol */\nexport enum WebhookStage {\n BeforeRequest = \"before_request\",\n AfterRequest = \"after_request\",\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal helpers – (de)serialisation\n * --------------------------------------------------------------------------------------------- */\n\nexport async function callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n}: BeforeRequestMiddlewareParameters): Promise<Request | void> {\n const mw = runtime.beforeRequestMiddleware;\n if (!mw) return;\n\n // Function-based middleware (in-process)\n if (typeof mw === \"function\") {\n return (mw as BeforeRequestMiddlewareFn)({ runtime, request, path });\n }\n\n logger.warn({ mw }, \"Unsupported beforeRequestMiddleware value – skipped\");\n return;\n}\n\nexport async function callAfterRequestMiddleware({\n runtime,\n response,\n path,\n}:
|
|
1
|
+
{"version":3,"file":"middleware.cjs","names":["parseSSEResponse"],"sources":["../src/middleware.ts"],"sourcesContent":["/**\n * Middleware support for CopilotKit Runtime.\n *\n * A middleware hook can be provided as either:\n * 1. A **callback function** executed in-process.\n * 2. A **webhook URL** (http/https). The runtime will `POST` a JSON payload\n * to the URL and, for *before* hooks, accept an optional modified\n * `Request` object in the response body.\n *\n * Two lifecycle hooks are available:\n * • `BEFORE_REQUEST` – runs *before* the request handler.\n * • `AFTER_REQUEST` – runs *after* the handler returns a `Response`.\n */\n\nimport type { CopilotRuntime } from \"./runtime\";\nimport type { MaybePromise } from \"@copilotkitnext/shared\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport { parseSSEResponse } from \"./middleware-sse-parser\";\nimport type { Message } from \"./middleware-sse-parser\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface BeforeRequestMiddlewareParameters {\n runtime: CopilotRuntime;\n request: Request;\n path: string;\n}\nexport interface AfterRequestMiddlewareParameters {\n runtime: CopilotRuntime;\n response: Response;\n path: string;\n /** Reconstructed messages from the SSE stream (empty for non-SSE responses). */\n messages?: Message[];\n /** Thread ID extracted from the RUN_STARTED event. */\n threadId?: string;\n /** Run ID extracted from the RUN_STARTED event. */\n runId?: string;\n}\n\nexport type BeforeRequestMiddlewareFn = (\n params: BeforeRequestMiddlewareParameters,\n) => MaybePromise<Request | void>;\nexport type AfterRequestMiddlewareFn = (\n params: AfterRequestMiddlewareParameters,\n) => MaybePromise<void>;\n\n/**\n * A middleware value can be either a callback function or a webhook URL.\n */\nexport type BeforeRequestMiddleware = BeforeRequestMiddlewareFn;\nexport type AfterRequestMiddleware = AfterRequestMiddlewareFn;\n\n/** Lifecycle events emitted to webhook middleware. */\nexport enum CopilotKitMiddlewareEvent {\n BeforeRequest = \"BEFORE_REQUEST\",\n AfterRequest = \"AFTER_REQUEST\",\n}\n\n/** Stages used by the Middleware Webhook Protocol */\n/** Stages used by the CopilotKit webhook protocol */\nexport enum WebhookStage {\n BeforeRequest = \"before_request\",\n AfterRequest = \"after_request\",\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal helpers – (de)serialisation\n * --------------------------------------------------------------------------------------------- */\n\nexport async function callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n}: BeforeRequestMiddlewareParameters): Promise<Request | void> {\n const mw = runtime.beforeRequestMiddleware;\n if (!mw) return;\n\n // Function-based middleware (in-process)\n if (typeof mw === \"function\") {\n return (mw as BeforeRequestMiddlewareFn)({ runtime, request, path });\n }\n\n logger.warn({ mw }, \"Unsupported beforeRequestMiddleware value – skipped\");\n return;\n}\n\nexport async function callAfterRequestMiddleware({\n runtime,\n response,\n path,\n}: {\n runtime: CopilotRuntime;\n response: Response;\n path: string;\n}): Promise<void> {\n const mw = runtime.afterRequestMiddleware;\n if (!mw) return;\n\n const { messages, threadId, runId } = await parseSSEResponse(response);\n\n if (typeof mw === \"function\") {\n return (mw as AfterRequestMiddlewareFn)({\n runtime,\n response,\n path,\n messages,\n threadId,\n runId,\n });\n }\n\n logger.warn({ mw }, \"Unsupported afterRequestMiddleware value – skipped\");\n}\n"],"mappings":";;;;;AAuEA,eAAsB,4BAA4B,EAChD,SACA,SACA,QAC6D;CAC7D,MAAM,KAAK,QAAQ;AACnB,KAAI,CAAC,GAAI;AAGT,KAAI,OAAO,OAAO,WAChB,QAAQ,GAAiC;EAAE;EAAS;EAAS;EAAM,CAAC;AAGtE,+BAAO,KAAK,EAAE,IAAI,EAAE,sDAAsD;;AAI5E,eAAsB,2BAA2B,EAC/C,SACA,UACA,QAKgB;CAChB,MAAM,KAAK,QAAQ;AACnB,KAAI,CAAC,GAAI;CAET,MAAM,EAAE,UAAU,UAAU,UAAU,MAAMA,+CAAiB,SAAS;AAEtE,KAAI,OAAO,OAAO,WAChB,QAAQ,GAAgC;EACtC;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAGJ,+BAAO,KAAK,EAAE,IAAI,EAAE,qDAAqD"}
|
package/dist/middleware.d.cts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Message } from "./middleware-sse-parser.cjs";
|
|
1
2
|
import { CopilotRuntime } from "./runtime.cjs";
|
|
2
3
|
import { MaybePromise } from "@copilotkitnext/shared";
|
|
3
4
|
|
|
@@ -11,6 +12,12 @@ interface AfterRequestMiddlewareParameters {
|
|
|
11
12
|
runtime: CopilotRuntime;
|
|
12
13
|
response: Response;
|
|
13
14
|
path: string;
|
|
15
|
+
/** Reconstructed messages from the SSE stream (empty for non-SSE responses). */
|
|
16
|
+
messages?: Message[];
|
|
17
|
+
/** Thread ID extracted from the RUN_STARTED event. */
|
|
18
|
+
threadId?: string;
|
|
19
|
+
/** Run ID extracted from the RUN_STARTED event. */
|
|
20
|
+
runId?: string;
|
|
14
21
|
}
|
|
15
22
|
type BeforeRequestMiddlewareFn = (params: BeforeRequestMiddlewareParameters) => MaybePromise<Request | void>;
|
|
16
23
|
type AfterRequestMiddlewareFn = (params: AfterRequestMiddlewareParameters) => MaybePromise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.d.cts","names":[],"sources":["../src/middleware.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"middleware.d.cts","names":[],"sources":["../src/middleware.ts"],"mappings":";;;;;UAwBiB,iCAAA;EACf,OAAA,EAAS,cAAA;EACT,OAAA,EAAS,OAAA;EACT,IAAA;AAAA;AAAA,UAEe,gCAAA;EACf,OAAA,EAAS,cAAA;EACT,QAAA,EAAU,QAAA;EACV,IAAA;EAFS;EAIT,QAAA,GAAW,OAAA;EAHD;EAKV,QAAA;EAFA;EAIA,KAAA;AAAA;AAAA,KAGU,yBAAA,IACV,MAAA,EAAQ,iCAAA,KACL,YAAA,CAAa,OAAA;AAAA,KACN,wBAAA,IACV,MAAA,EAAQ,gCAAA,KACL,YAAA;;AALL;;KAUY,uBAAA,GAA0B,yBAAA;AAAA,KAC1B,sBAAA,GAAyB,wBAAA"}
|
package/dist/middleware.d.mts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Message } from "./middleware-sse-parser.mjs";
|
|
1
2
|
import { CopilotRuntime } from "./runtime.mjs";
|
|
2
3
|
import { MaybePromise } from "@copilotkitnext/shared";
|
|
3
4
|
|
|
@@ -11,6 +12,12 @@ interface AfterRequestMiddlewareParameters {
|
|
|
11
12
|
runtime: CopilotRuntime;
|
|
12
13
|
response: Response;
|
|
13
14
|
path: string;
|
|
15
|
+
/** Reconstructed messages from the SSE stream (empty for non-SSE responses). */
|
|
16
|
+
messages?: Message[];
|
|
17
|
+
/** Thread ID extracted from the RUN_STARTED event. */
|
|
18
|
+
threadId?: string;
|
|
19
|
+
/** Run ID extracted from the RUN_STARTED event. */
|
|
20
|
+
runId?: string;
|
|
14
21
|
}
|
|
15
22
|
type BeforeRequestMiddlewareFn = (params: BeforeRequestMiddlewareParameters) => MaybePromise<Request | void>;
|
|
16
23
|
type AfterRequestMiddlewareFn = (params: AfterRequestMiddlewareParameters) => MaybePromise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.d.mts","names":[],"sources":["../src/middleware.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"middleware.d.mts","names":[],"sources":["../src/middleware.ts"],"mappings":";;;;;UAwBiB,iCAAA;EACf,OAAA,EAAS,cAAA;EACT,OAAA,EAAS,OAAA;EACT,IAAA;AAAA;AAAA,UAEe,gCAAA;EACf,OAAA,EAAS,cAAA;EACT,QAAA,EAAU,QAAA;EACV,IAAA;EAFS;EAIT,QAAA,GAAW,OAAA;EAHD;EAKV,QAAA;EAFA;EAIA,KAAA;AAAA;AAAA,KAGU,yBAAA,IACV,MAAA,EAAQ,iCAAA,KACL,YAAA,CAAa,OAAA;AAAA,KACN,wBAAA,IACV,MAAA,EAAQ,gCAAA,KACL,YAAA;;AALL;;KAUY,uBAAA,GAA0B,yBAAA;AAAA,KAC1B,sBAAA,GAAyB,wBAAA"}
|
package/dist/middleware.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { parseSSEResponse } from "./middleware-sse-parser.mjs";
|
|
1
2
|
import { logger } from "@copilotkitnext/shared";
|
|
2
3
|
|
|
3
4
|
//#region src/middleware.ts
|
|
@@ -14,10 +15,14 @@ async function callBeforeRequestMiddleware({ runtime, request, path }) {
|
|
|
14
15
|
async function callAfterRequestMiddleware({ runtime, response, path }) {
|
|
15
16
|
const mw = runtime.afterRequestMiddleware;
|
|
16
17
|
if (!mw) return;
|
|
18
|
+
const { messages, threadId, runId } = await parseSSEResponse(response);
|
|
17
19
|
if (typeof mw === "function") return mw({
|
|
18
20
|
runtime,
|
|
19
21
|
response,
|
|
20
|
-
path
|
|
22
|
+
path,
|
|
23
|
+
messages,
|
|
24
|
+
threadId,
|
|
25
|
+
runId
|
|
21
26
|
});
|
|
22
27
|
logger.warn({ mw }, "Unsupported afterRequestMiddleware value – skipped");
|
|
23
28
|
}
|
package/dist/middleware.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.mjs","names":[],"sources":["../src/middleware.ts"],"sourcesContent":["/**\n * Middleware support for CopilotKit Runtime.\n *\n * A middleware hook can be provided as either:\n * 1. A **callback function** executed in-process.\n * 2. A **webhook URL** (http/https). The runtime will `POST` a JSON payload\n * to the URL and, for *before* hooks, accept an optional modified\n * `Request` object in the response body.\n *\n * Two lifecycle hooks are available:\n * • `BEFORE_REQUEST` – runs *before* the request handler.\n * • `AFTER_REQUEST` – runs *after* the handler returns a `Response`.\n */\n\nimport type { CopilotRuntime } from \"./runtime\";\nimport type { MaybePromise } from \"@copilotkitnext/shared\";\nimport { logger } from \"@copilotkitnext/shared\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface BeforeRequestMiddlewareParameters {\n runtime: CopilotRuntime;\n request: Request;\n path: string;\n}\nexport interface AfterRequestMiddlewareParameters {\n runtime: CopilotRuntime;\n response: Response;\n path: string;\n}\n\nexport type BeforeRequestMiddlewareFn = (\n params: BeforeRequestMiddlewareParameters,\n) => MaybePromise<Request | void>;\nexport type AfterRequestMiddlewareFn = (\n params: AfterRequestMiddlewareParameters,\n) => MaybePromise<void>;\n\n/**\n * A middleware value can be either a callback function or a webhook URL.\n */\nexport type BeforeRequestMiddleware = BeforeRequestMiddlewareFn;\nexport type AfterRequestMiddleware = AfterRequestMiddlewareFn;\n\n/** Lifecycle events emitted to webhook middleware. */\nexport enum CopilotKitMiddlewareEvent {\n BeforeRequest = \"BEFORE_REQUEST\",\n AfterRequest = \"AFTER_REQUEST\",\n}\n\n/** Stages used by the Middleware Webhook Protocol */\n/** Stages used by the CopilotKit webhook protocol */\nexport enum WebhookStage {\n BeforeRequest = \"before_request\",\n AfterRequest = \"after_request\",\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal helpers – (de)serialisation\n * --------------------------------------------------------------------------------------------- */\n\nexport async function callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n}: BeforeRequestMiddlewareParameters): Promise<Request | void> {\n const mw = runtime.beforeRequestMiddleware;\n if (!mw) return;\n\n // Function-based middleware (in-process)\n if (typeof mw === \"function\") {\n return (mw as BeforeRequestMiddlewareFn)({ runtime, request, path });\n }\n\n logger.warn({ mw }, \"Unsupported beforeRequestMiddleware value – skipped\");\n return;\n}\n\nexport async function callAfterRequestMiddleware({\n runtime,\n response,\n path,\n}:
|
|
1
|
+
{"version":3,"file":"middleware.mjs","names":[],"sources":["../src/middleware.ts"],"sourcesContent":["/**\n * Middleware support for CopilotKit Runtime.\n *\n * A middleware hook can be provided as either:\n * 1. A **callback function** executed in-process.\n * 2. A **webhook URL** (http/https). The runtime will `POST` a JSON payload\n * to the URL and, for *before* hooks, accept an optional modified\n * `Request` object in the response body.\n *\n * Two lifecycle hooks are available:\n * • `BEFORE_REQUEST` – runs *before* the request handler.\n * • `AFTER_REQUEST` – runs *after* the handler returns a `Response`.\n */\n\nimport type { CopilotRuntime } from \"./runtime\";\nimport type { MaybePromise } from \"@copilotkitnext/shared\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport { parseSSEResponse } from \"./middleware-sse-parser\";\nimport type { Message } from \"./middleware-sse-parser\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface BeforeRequestMiddlewareParameters {\n runtime: CopilotRuntime;\n request: Request;\n path: string;\n}\nexport interface AfterRequestMiddlewareParameters {\n runtime: CopilotRuntime;\n response: Response;\n path: string;\n /** Reconstructed messages from the SSE stream (empty for non-SSE responses). */\n messages?: Message[];\n /** Thread ID extracted from the RUN_STARTED event. */\n threadId?: string;\n /** Run ID extracted from the RUN_STARTED event. */\n runId?: string;\n}\n\nexport type BeforeRequestMiddlewareFn = (\n params: BeforeRequestMiddlewareParameters,\n) => MaybePromise<Request | void>;\nexport type AfterRequestMiddlewareFn = (\n params: AfterRequestMiddlewareParameters,\n) => MaybePromise<void>;\n\n/**\n * A middleware value can be either a callback function or a webhook URL.\n */\nexport type BeforeRequestMiddleware = BeforeRequestMiddlewareFn;\nexport type AfterRequestMiddleware = AfterRequestMiddlewareFn;\n\n/** Lifecycle events emitted to webhook middleware. */\nexport enum CopilotKitMiddlewareEvent {\n BeforeRequest = \"BEFORE_REQUEST\",\n AfterRequest = \"AFTER_REQUEST\",\n}\n\n/** Stages used by the Middleware Webhook Protocol */\n/** Stages used by the CopilotKit webhook protocol */\nexport enum WebhookStage {\n BeforeRequest = \"before_request\",\n AfterRequest = \"after_request\",\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal helpers – (de)serialisation\n * --------------------------------------------------------------------------------------------- */\n\nexport async function callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n}: BeforeRequestMiddlewareParameters): Promise<Request | void> {\n const mw = runtime.beforeRequestMiddleware;\n if (!mw) return;\n\n // Function-based middleware (in-process)\n if (typeof mw === \"function\") {\n return (mw as BeforeRequestMiddlewareFn)({ runtime, request, path });\n }\n\n logger.warn({ mw }, \"Unsupported beforeRequestMiddleware value – skipped\");\n return;\n}\n\nexport async function callAfterRequestMiddleware({\n runtime,\n response,\n path,\n}: {\n runtime: CopilotRuntime;\n response: Response;\n path: string;\n}): Promise<void> {\n const mw = runtime.afterRequestMiddleware;\n if (!mw) return;\n\n const { messages, threadId, runId } = await parseSSEResponse(response);\n\n if (typeof mw === \"function\") {\n return (mw as AfterRequestMiddlewareFn)({\n runtime,\n response,\n path,\n messages,\n threadId,\n runId,\n });\n }\n\n logger.warn({ mw }, \"Unsupported afterRequestMiddleware value – skipped\");\n}\n"],"mappings":";;;;AAuEA,eAAsB,4BAA4B,EAChD,SACA,SACA,QAC6D;CAC7D,MAAM,KAAK,QAAQ;AACnB,KAAI,CAAC,GAAI;AAGT,KAAI,OAAO,OAAO,WAChB,QAAQ,GAAiC;EAAE;EAAS;EAAS;EAAM,CAAC;AAGtE,QAAO,KAAK,EAAE,IAAI,EAAE,sDAAsD;;AAI5E,eAAsB,2BAA2B,EAC/C,SACA,UACA,QAKgB;CAChB,MAAM,KAAK,QAAQ;AACnB,KAAI,CAAC,GAAI;CAET,MAAM,EAAE,UAAU,UAAU,UAAU,MAAM,iBAAiB,SAAS;AAEtE,KAAI,OAAO,OAAO,WAChB,QAAQ,GAAgC;EACtC;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAGJ,QAAO,KAAK,EAAE,IAAI,EAAE,qDAAqD"}
|
package/dist/package.cjs
CHANGED
package/dist/package.mjs
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@copilotkitnext/runtime",
|
|
3
|
-
"version": "1.52.1",
|
|
3
|
+
"version": "1.52.2-next.1",
|
|
4
4
|
"description": "Server-side runtime package for CopilotKit2",
|
|
5
5
|
"main": "./dist/index.cjs",
|
|
6
6
|
"types": "./dist/index.d.cts",
|
|
@@ -28,8 +28,8 @@
|
|
|
28
28
|
"tsdown": "^0.20.3",
|
|
29
29
|
"typescript": "5.8.2",
|
|
30
30
|
"vitest": "^3.0.5",
|
|
31
|
-
"@copilotkitnext/eslint-config": "1.52.1",
|
|
32
|
-
"@copilotkitnext/typescript-config": "1.52.1"
|
|
31
|
+
"@copilotkitnext/eslint-config": "1.52.2-next.1",
|
|
32
|
+
"@copilotkitnext/typescript-config": "1.52.2-next.1"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
35
|
"@ag-ui/client": "0.0.46",
|
|
@@ -39,13 +39,13 @@
|
|
|
39
39
|
"express": "^4.21.2",
|
|
40
40
|
"hono": "^4.11.4",
|
|
41
41
|
"rxjs": "7.8.1",
|
|
42
|
-
"@copilotkitnext/shared": "1.52.1"
|
|
42
|
+
"@copilotkitnext/shared": "1.52.2-next.1"
|
|
43
43
|
},
|
|
44
44
|
"peerDependencies": {
|
|
45
45
|
"@ag-ui/client": "0.0.46",
|
|
46
46
|
"@ag-ui/core": "0.0.46",
|
|
47
47
|
"@ag-ui/encoder": "0.0.46",
|
|
48
|
-
"@copilotkitnext/shared": "1.52.1"
|
|
48
|
+
"@copilotkitnext/shared": "1.52.2-next.1"
|
|
49
49
|
},
|
|
50
50
|
"peerDependenciesMeta": {},
|
|
51
51
|
"engines": {
|