@copilotkit/runtime 2.0.0-rc.13 → 2.0.0-rc.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/dist/agent/converters/aisdk.cjs +0 -1
  2. package/dist/agent/converters/aisdk.cjs.map +1 -1
  3. package/dist/agent/converters/tanstack.cjs +0 -1
  4. package/dist/agent/converters/tanstack.cjs.map +1 -1
  5. package/dist/agent/index.cjs +0 -1
  6. package/dist/agent/index.cjs.map +1 -1
  7. package/dist/agent/learned-skills.cjs +0 -1
  8. package/dist/agent/learned-skills.cjs.map +1 -1
  9. package/dist/agent/state-delta.cjs +0 -1
  10. package/dist/agent/state-delta.cjs.map +1 -1
  11. package/dist/agent/url-download.cjs +0 -1
  12. package/dist/agent/url-download.cjs.map +1 -1
  13. package/dist/index.cjs +8 -9
  14. package/dist/runtime/core/channel-manager.cjs +0 -1
  15. package/dist/runtime/core/channel-manager.cjs.map +1 -1
  16. package/dist/runtime/core/debug-event-bus.cjs +0 -1
  17. package/dist/runtime/core/debug-event-bus.cjs.map +1 -1
  18. package/dist/runtime/core/fetch-handler.cjs +3 -4
  19. package/dist/runtime/core/fetch-handler.cjs.map +1 -1
  20. package/dist/runtime/core/logger.cjs +85 -10
  21. package/dist/runtime/core/logger.cjs.map +1 -1
  22. package/dist/runtime/core/logger.d.cts +21 -8
  23. package/dist/runtime/core/logger.d.cts.map +1 -1
  24. package/dist/runtime/core/logger.d.mts +21 -8
  25. package/dist/runtime/core/logger.d.mts.map +1 -1
  26. package/dist/runtime/core/logger.mjs +85 -8
  27. package/dist/runtime/core/logger.mjs.map +1 -1
  28. package/dist/runtime/core/middleware-sse-parser.cjs +0 -1
  29. package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -1
  30. package/dist/runtime/core/middleware.cjs +0 -1
  31. package/dist/runtime/core/middleware.cjs.map +1 -1
  32. package/dist/runtime/core/package-info.cjs +1 -1
  33. package/dist/runtime/core/package-info.mjs +1 -1
  34. package/dist/runtime/core/runtime.cjs +0 -1
  35. package/dist/runtime/core/runtime.cjs.map +1 -1
  36. package/dist/runtime/endpoints/auto-start-channels.cjs +0 -1
  37. package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -1
  38. package/dist/runtime/endpoints/node-fetch-handler.cjs +0 -1
  39. package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
  40. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs +60 -69
  41. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs.map +1 -1
  42. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts +4 -3
  43. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts.map +1 -1
  44. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts +4 -3
  45. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts.map +1 -1
  46. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs +60 -67
  47. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs.map +1 -1
  48. package/dist/runtime/event-transforms/recorded-events.cjs +0 -1
  49. package/dist/runtime/event-transforms/recorded-events.cjs.map +1 -1
  50. package/dist/runtime/event-transforms/streaming-json-scanner.cjs +289 -0
  51. package/dist/runtime/event-transforms/streaming-json-scanner.cjs.map +1 -0
  52. package/dist/runtime/event-transforms/streaming-json-scanner.mjs +288 -0
  53. package/dist/runtime/event-transforms/streaming-json-scanner.mjs.map +1 -0
  54. package/dist/runtime/generative-ui/generative-ui-middleware.cjs +0 -1
  55. package/dist/runtime/generative-ui/generative-ui-middleware.cjs.map +1 -1
  56. package/dist/runtime/generative-ui/surface-writer.cjs +0 -1
  57. package/dist/runtime/generative-ui/surface-writer.cjs.map +1 -1
  58. package/dist/runtime/handlers/handle-inspector-learning.cjs +2 -3
  59. package/dist/runtime/handlers/handle-inspector-learning.cjs.map +1 -1
  60. package/dist/runtime/handlers/handle-inspector-metadata.cjs +2 -3
  61. package/dist/runtime/handlers/handle-inspector-metadata.cjs.map +1 -1
  62. package/dist/runtime/handlers/handle-run.cjs +3 -4
  63. package/dist/runtime/handlers/handle-run.cjs.map +1 -1
  64. package/dist/runtime/handlers/handle-stop.cjs +3 -4
  65. package/dist/runtime/handlers/handle-stop.cjs.map +1 -1
  66. package/dist/runtime/handlers/handle-suggest.cjs +0 -1
  67. package/dist/runtime/handlers/handle-suggest.cjs.map +1 -1
  68. package/dist/runtime/handlers/handle-transcribe.cjs +0 -1
  69. package/dist/runtime/handlers/handle-transcribe.cjs.map +1 -1
  70. package/dist/runtime/handlers/intelligence/annotate.cjs +2 -3
  71. package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -1
  72. package/dist/runtime/handlers/intelligence/memories.cjs +7 -8
  73. package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
  74. package/dist/runtime/handlers/intelligence/run.cjs +0 -1
  75. package/dist/runtime/handlers/intelligence/run.cjs.map +1 -1
  76. package/dist/runtime/handlers/intelligence/thread-names.cjs +0 -1
  77. package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
  78. package/dist/runtime/handlers/intelligence/threads.cjs +6 -7
  79. package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
  80. package/dist/runtime/handlers/shared/agent-utils.cjs +5 -6
  81. package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  82. package/dist/runtime/handlers/shared/cloud-telemetry.cjs +0 -1
  83. package/dist/runtime/handlers/shared/cloud-telemetry.cjs.map +1 -1
  84. package/dist/runtime/handlers/shared/sse-response.cjs +0 -1
  85. package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -1
  86. package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -1
  87. package/dist/runtime/handlers/sse/run.cjs.map +1 -1
  88. package/dist/runtime/handlers/sse/run.mjs.map +1 -1
  89. package/dist/runtime/intelligence-platform/client.cjs +0 -1
  90. package/dist/runtime/intelligence-platform/client.cjs.map +1 -1
  91. package/dist/runtime/intelligence-platform/learning-management.cjs +0 -1
  92. package/dist/runtime/intelligence-platform/learning-management.cjs.map +1 -1
  93. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs +0 -1
  94. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -1
  95. package/dist/runtime/intelligence-platform/skill-registry/config.cjs +0 -1
  96. package/dist/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -1
  97. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs +0 -1
  98. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -1
  99. package/dist/runtime/intelligence-platform/trajectories.cjs +0 -1
  100. package/dist/runtime/intelligence-platform/trajectories.cjs.map +1 -1
  101. package/dist/runtime/runner/agent-runner.cjs +0 -1
  102. package/dist/runtime/runner/agent-runner.cjs.map +1 -1
  103. package/dist/runtime/runner/in-memory.cjs +0 -1
  104. package/dist/runtime/runner/in-memory.cjs.map +1 -1
  105. package/dist/runtime/runner/intelligence.cjs +0 -1
  106. package/dist/runtime/runner/intelligence.cjs.map +1 -1
  107. package/dist/runtime/telemetry/disclosure.cjs +0 -1
  108. package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
  109. package/dist/runtime/telemetry/telemetry-client.cjs +0 -1
  110. package/dist/runtime/telemetry/telemetry-client.cjs.map +1 -1
  111. package/dist/runtime/telemetry/telemetry-identity.cjs +0 -1
  112. package/dist/runtime/telemetry/telemetry-identity.cjs.map +1 -1
  113. package/package.json +4 -7
  114. package/dist/_virtual/_rolldown/runtime.cjs +0 -29
@@ -1 +1 @@
1
- {"version":3,"file":"generative-ui-middleware.cjs","names":["GENERATIVE_UI_RENDER_TOOL","GENERATIVE_UI_CONTEXT_DESCRIPTION","Middleware","Observable","EventType","GENERATIVE_UI_ACTIVITY_TYPE","GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE","RenderUIArgsStream"],"sources":["../../../src/runtime/generative-ui/generative-ui-middleware.ts"],"sourcesContent":["import { EventType, Middleware } from \"@ag-ui/client\";\nimport type {\n AbstractAgent,\n BaseEvent,\n Message,\n RunAgentInput,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n} from \"@ag-ui/client\";\nimport { Observable } from \"rxjs\";\nimport {\n GENERATIVE_UI_ACTIVITY_TYPE,\n GENERATIVE_UI_CONTEXT_DESCRIPTION,\n GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE,\n GENERATIVE_UI_RENDER_TOOL,\n RenderUIArgsStream,\n buildGenerativeUIPrompt,\n envelopeToManifest,\n generativeUIFunctionCallMessageId,\n generativeUISurfaceMessageId,\n getOperationKind,\n getOperationSurfaceId,\n randomUUID,\n readCopilotKitUIEnvelope,\n validateOperation,\n} from \"@copilotkit/shared\";\nimport type {\n A2UIOperation,\n GenerativeUIFunctionCallContent,\n GenerativeUIManifest,\n GenerativeUIRejectedOperation,\n GenerativeUISurfaceContent,\n} from \"@copilotkit/shared\";\n\ntype EventWithState = { event: BaseEvent; messages: Message[] };\ntype JsonPatchOperation = {\n op: \"add\" | \"replace\";\n path: string;\n value: unknown;\n};\n\ninterface RenderCallState {\n stream: RenderUIArgsStream;\n target?: string;\n buffered: Array<Record<string, unknown> | null>;\n nextIndex: number;\n /** Accepted surface operations. */\n applied: number;\n /** Accepted `callRendererFunction` operations. */\n calls: number;\n rejected: GenerativeUIRejectedOperation[];\n touched: Set<string>;\n finished: boolean;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Builds the manifest from the generative UI envelope\n * (`forwardedProps.copilotkit.ui`). The client sends the envelope, so it is\n * not trusted: `readCopilotKitUIEnvelope` checks every field, and\n * `envelopeToManifest` turns it into the manifest. Returns\n * `undefined` (the run passes through) when:\n * - there is no valid envelope;\n * - the transport is \"markdown\" (the model writes fences, not render_ui);\n * - the catalog has no components (the server cannot validate operations).\n */\nfunction readManifest(forwardedProps: unknown) {\n const envelope = readCopilotKitUIEnvelope(forwardedProps);\n if (!envelope) return undefined;\n const manifest = envelopeToManifest(envelope);\n const isToolRun = manifest.transport === \"tool\" && manifest.hasComponents;\n return isToolRun ? manifest : undefined;\n}\n\nfunction prepareInput(input: RunAgentInput, manifest: GenerativeUIManifest) {\n const tools = (input.tools ?? []).filter(\n (t) => t.name !== GENERATIVE_UI_RENDER_TOOL,\n );\n tools.push({\n name: GENERATIVE_UI_RENDER_TOOL,\n description:\n \"Render or update generative UI surfaces, or call app functions, with A2UI v1.0 operations. Follow the generative UI guide in context.\",\n parameters: {\n type: \"object\",\n properties: {\n target: {\n type: \"string\",\n enum: manifest.targets.map((t) => t.id),\n description:\n 'Where the surface is shown: \"chat\" or a named inline target.',\n },\n operations: {\n type: \"array\",\n description: \"A2UI v1.0 operations, applied in order.\",\n items: { type: \"object\" },\n },\n },\n required: [\"target\", \"operations\"],\n },\n });\n const context = (input.context ?? []).filter(\n (c) => c.description !== GENERATIVE_UI_CONTEXT_DESCRIPTION,\n );\n context.push({\n description: GENERATIVE_UI_CONTEXT_DESCRIPTION,\n value: buildGenerativeUIPrompt(manifest),\n });\n return { ...input, tools, context };\n}\n\n/**\n * Experimental. Lets an agent render CopilotKit generative UI surfaces via the\n * `render_ui` tool. It applies only to runs whose generative UI envelope uses\n * the \"tool\" transport. Each complete operation in the streamed arguments is\n * validated against the catalog in the envelope and committed immediately:\n * - `ACTIVITY_SNAPSHOT` for a new surface, `ACTIVITY_DELTA` for every further\n * operation on it.\n * - One `ACTIVITY_SNAPSHOT` of type `generative-ui-function-call` for each\n * `callRendererFunction`. The client runs the function.\n */\nexport class GenerativeUIMiddleware extends Middleware {\n run(input: RunAgentInput, next: AbstractAgent): Observable<BaseEvent> {\n const manifest = readManifest(input.forwardedProps);\n if (!manifest) return this.runNext(input, next);\n return processStream(\n this.runNextWithState(\n prepareInput(input, manifest),\n next,\n ) as Observable<EventWithState>,\n manifest,\n );\n }\n}\n\n/**\n * The first time a render_ui call touches an existing surface, mark it\n * streaming and clear its rejection list: earlier calls' rejections were\n * already reported to the model in their own tool results, and a repaired\n * surface must not keep showing them. A surface created by this call starts\n * with an empty list in its snapshot.\n */\nfunction beginSurfaceUpdate(\n state: RenderCallState,\n surfaceId: string,\n): JsonPatchOperation[] {\n if (state.touched.has(surfaceId)) return [];\n state.touched.add(surfaceId);\n return [\n { op: \"replace\", path: \"/status\", value: \"streaming\" },\n { op: \"replace\", path: \"/rejected\", value: [] },\n ];\n}\n\nfunction processStream(\n source: Observable<EventWithState>,\n manifest: GenerativeUIManifest,\n) {\n return new Observable<BaseEvent>((subscriber) => {\n const entries = Object.entries(manifest.surfaces);\n // Only live surfaces take updates. A surface that the client deleted, or\n // that was never created, has a `status`.\n const surfaces = new Map<string, string>(\n entries.filter(([, s]) => !s.status).map(([id, s]) => [id, s.target]),\n );\n // A surface id is unique for the life of the page. Keep the ids that were\n // created, also after deleteSurface (in this run or an earlier one), so a\n // second createSurface is rejected. A failed create can be sent again.\n const createdSurfaces = new Set(\n entries.filter(([, s]) => s.status !== \"failed\").map(([id]) => id),\n );\n // The targets that limit their components, by target id.\n const targetComponents = new Map(\n manifest.targets\n .filter((t) => t.components !== undefined)\n .map((t) => [t.id, new Set(t.components)]),\n );\n const functionCallIds = new Set<string>();\n const calls = new Map<string, RenderCallState>();\n let heldFinish: EventWithState | null = null;\n\n const emit = (event: BaseEvent) => subscriber.next(event);\n const patch = (surfaceId: string, ops: JsonPatchOperation[]) =>\n emit({\n type: EventType.ACTIVITY_DELTA,\n messageId: generativeUISurfaceMessageId(surfaceId),\n activityType: GENERATIVE_UI_ACTIVITY_TYPE,\n patch: ops,\n });\n\n const processOperation = (\n state: RenderCallState,\n op: Record<string, unknown> | null,\n ) => {\n const index = state.nextIndex++;\n const reject = (reason: string, surfaceId?: string) => {\n const entry = { index, reason };\n state.rejected.push(entry);\n if (surfaceId && surfaces.has(surfaceId)) {\n patch(surfaceId, [\n ...beginSurfaceUpdate(state, surfaceId),\n { op: \"add\", path: \"/rejected/-\", value: entry },\n ]);\n }\n };\n if (op === null) return reject(\"operation is not valid JSON\");\n let surfaceId: string | undefined;\n try {\n surfaceId = getOperationSurfaceId(op);\n applyOperation(state, withCatalogId(op), surfaceId, reject);\n } catch (error) {\n // Never let one bad operation take down the run: report it to the\n // model through the tool result instead.\n reject(\n `operation could not be processed: ${error instanceof Error ? error.message : String(error)}`,\n surfaceId,\n );\n }\n };\n\n /**\n * The model does not have to name the catalog. A createSurface keeps a\n * catalogId that the envelope lists, and gets the catalog id of the run\n * for any other value. The whole operation, with its inline components\n * and data model, stays in the snapshot.\n */\n const catalogIds = manifest.catalogIds ?? [manifest.catalogId];\n const withCatalogId = (op: Record<string, unknown>) => {\n const create = op.createSurface;\n if (!isRecord(create)) return op;\n const catalogId = catalogIds.includes(create.catalogId as string)\n ? create.catalogId\n : manifest.catalogId;\n return { ...op, createSurface: { ...create, catalogId } };\n };\n\n /**\n * The components that the target of the surface takes. A createSurface\n * goes to the target of the render_ui call. Every other operation goes to\n * the target that the surface was created on.\n */\n const allowedComponentsFor = (\n state: RenderCallState,\n op: Record<string, unknown>,\n surfaceId: string | undefined,\n ) => {\n const target =\n getOperationKind(op) === \"createSurface\"\n ? state.target\n : surfaces.get(surfaceId);\n const names = targetComponents.get(target);\n return names && { target, names };\n };\n\n const applyOperation = (\n state: RenderCallState,\n op: Record<string, unknown>,\n surfaceId: string | undefined,\n reject: (reason: string, surfaceId?: string) => void,\n ) => {\n const validation = validateOperation(op, {\n manifest,\n knownSurfaces: new Set(surfaces.keys()),\n createdSurfaces,\n functions: manifest.functions,\n allowedComponents: allowedComponentsFor(state, op, surfaceId),\n });\n // `=== false` (not `!ok`): runtime is compiled non-strict, where `!ok`\n // does not narrow the discriminated union.\n if (validation.ok === false) return reject(validation.reason, surfaceId);\n // validateOperation checked the shape of the operation.\n const accepted = op as A2UIOperation;\n if (\"callRendererFunction\" in accepted) {\n return callRendererFunction(\n state,\n accepted.callRendererFunction,\n reject,\n );\n }\n if (\"createSurface\" in accepted) {\n return createSurface(state, surfaceId, accepted, reject);\n }\n patch(surfaceId, [\n ...beginSurfaceUpdate(state, surfaceId),\n { op: \"add\", path: \"/operations/-\", value: accepted },\n ]);\n if (\"deleteSurface\" in accepted) surfaces.delete(surfaceId);\n state.applied++;\n };\n\n const createSurface = (\n state: RenderCallState,\n surfaceId: string,\n op: A2UIOperation,\n reject: (reason: string) => void,\n ) => {\n const { target } = state;\n if (target === undefined) {\n return reject(\"render_ui was called without a target\");\n }\n if (!manifest.targets.some((t) => t.id === target)) {\n return reject(`target \"${target}\" is not mounted`);\n }\n surfaces.set(surfaceId, target);\n createdSurfaces.add(surfaceId);\n const content: GenerativeUISurfaceContent = {\n surfaceId,\n target,\n catalogId:\n (\"createSurface\" in op && op.createSurface.catalogId) ||\n manifest.catalogId,\n operations: [op],\n status: \"streaming\",\n rejected: [],\n };\n emit({\n type: EventType.ACTIVITY_SNAPSHOT,\n messageId: generativeUISurfaceMessageId(surfaceId),\n activityType: GENERATIVE_UI_ACTIVITY_TYPE,\n content,\n replace: true,\n });\n state.touched.add(surfaceId);\n state.applied++;\n };\n\n /**\n * Sends one function call to the client, which runs it. A function call\n * needs no target and no surface. Each `functionCallId` runs once.\n */\n const callRendererFunction = (\n state: RenderCallState,\n content: GenerativeUIFunctionCallContent,\n reject: (reason: string) => void,\n ) => {\n const { functionCallId } = content;\n if (functionCallIds.has(functionCallId)) {\n return reject(\n `functionCallId \"${functionCallId}\" was used before; use a new functionCallId`,\n );\n }\n functionCallIds.add(functionCallId);\n emit({\n type: EventType.ACTIVITY_SNAPSHOT,\n messageId: generativeUIFunctionCallMessageId(functionCallId),\n activityType: GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE,\n content: {\n functionCallId,\n callFunction: content.callFunction,\n } satisfies GenerativeUIFunctionCallContent,\n replace: true,\n });\n state.calls++;\n };\n\n /** Same buffering rule as streamed ops: hold them until the target is known. */\n const acceptOperation = (\n state: RenderCallState,\n op: Record<string, unknown> | null,\n ) => {\n if (state.target === undefined) state.buffered.push(op);\n else processOperation(state, op);\n };\n\n /**\n * The streaming parser found no operations at all. Models sometimes send\n * `operations` as a JSON-encoded string; recover those from the complete\n * arguments. Anything still unusable leaves the call with zero operations,\n * which the tool result reports as an error.\n */\n const recoverOperations = (state: RenderCallState) => {\n let args: unknown;\n try {\n args = JSON.parse(state.stream.text);\n } catch {\n return;\n }\n if (!isRecord(args)) return;\n if (state.target === undefined && typeof args.target === \"string\") {\n state.target = args.target;\n }\n let operations = args.operations;\n if (typeof operations === \"string\") {\n try {\n operations = JSON.parse(operations);\n } catch {\n return;\n }\n }\n if (!Array.isArray(operations)) return;\n for (const op of operations)\n acceptOperation(state, isRecord(op) ? op : null);\n };\n\n const finishCall = (state: RenderCallState) => {\n if (state.finished) return;\n state.finished = true;\n if (state.nextIndex === 0 && state.buffered.length === 0)\n recoverOperations(state);\n if (state.target === undefined) {\n // A function call needs no target, so it still runs. Every other\n // operation is rejected.\n const buffered = state.buffered;\n state.buffered = [];\n for (const op of buffered) {\n if (getOperationKind(op) === \"callRendererFunction\") {\n processOperation(state, op);\n continue;\n }\n state.rejected.push({\n index: state.nextIndex++,\n reason: \"render_ui was called without a target\",\n });\n }\n }\n if (state.stream.hasIncompleteOperation) {\n // The arguments ended inside an element (for example the model hit its\n // output limit): report it instead of silently dropping it.\n state.rejected.push({\n index: state.nextIndex++,\n reason: \"operation was truncated\",\n });\n }\n for (const id of state.touched) {\n patch(id, [{ op: \"replace\", path: \"/status\", value: \"ready\" }]);\n }\n };\n\n const flushFinish = () => {\n if (heldFinish) {\n emit(heldFinish.event);\n heldFinish = null;\n }\n };\n\n const handleEvent = ({ event, messages }: EventWithState) => {\n flushFinish();\n if (event.type === EventType.RUN_FINISHED) {\n heldFinish = { event, messages };\n return;\n }\n emit(event);\n if (event.type === EventType.TOOL_CALL_START) {\n const start = event as ToolCallStartEvent;\n if (start.toolCallName === GENERATIVE_UI_RENDER_TOOL) {\n calls.set(start.toolCallId, {\n stream: new RenderUIArgsStream(),\n buffered: [],\n nextIndex: 0,\n applied: 0,\n calls: 0,\n rejected: [],\n touched: new Set(),\n finished: false,\n });\n }\n } else if (event.type === EventType.TOOL_CALL_ARGS) {\n const args = event as ToolCallArgsEvent;\n const state = calls.get(args.toolCallId);\n if (!state || state.finished) return;\n const { target, newOperations } = state.stream.push(args.delta);\n if (target !== undefined && state.target === undefined) {\n state.target = target;\n const buffered = state.buffered;\n state.buffered = [];\n for (const op of buffered) processOperation(state, op);\n }\n for (const op of newOperations) acceptOperation(state, op);\n } else if (event.type === EventType.TOOL_CALL_END) {\n const state = calls.get((event as ToolCallEndEvent).toolCallId);\n if (state) finishCall(state);\n }\n };\n\n const completeRun = () => {\n for (const state of calls.values()) finishCall(state);\n if (heldFinish) {\n const answered = new Set(\n heldFinish.messages\n .filter((m) => m.role === \"tool\")\n .map((m) => (m as { toolCallId: string }).toolCallId),\n );\n for (const [toolCallId, state] of calls) {\n if (answered.has(toolCallId)) continue;\n const nothingParsed =\n state.applied === 0 &&\n state.calls === 0 &&\n state.rejected.length === 0;\n // `applied` counts the surface operations, `calls` the function calls.\n emit({\n type: EventType.TOOL_CALL_RESULT,\n messageId: randomUUID(),\n toolCallId,\n content: JSON.stringify(\n nothingParsed\n ? {\n status: \"error\",\n applied: 0,\n calls: 0,\n rejected: [],\n reason:\n \"operations must be a JSON array of A2UI operation objects; nothing was rendered\",\n }\n : {\n status: \"rendered\",\n applied: state.applied,\n calls: state.calls,\n rejected: state.rejected,\n },\n ),\n });\n }\n flushFinish();\n }\n subscriber.complete();\n };\n\n let failed = false;\n const subscription = source.subscribe({\n next: (item) => {\n if (failed) return;\n try {\n handleEvent(item);\n } catch (error) {\n // Anything unexpected must reach the consumer as an error instead of\n // escaping this callback, where RxJS would rethrow it asynchronously\n // as an uncaught exception.\n failed = true;\n subscriber.error(error);\n }\n },\n error: (error) => {\n flushFinish();\n subscriber.error(error);\n },\n complete: () => {\n if (failed) return;\n try {\n completeRun();\n } catch (error) {\n failed = true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d,QAAI,OAAQ;AACZ,QAAI;AACF,iBAAY,KAAK;aACV,OAAO;AAId,cAAS;AACT,gBAAW,MAAM,MAAM;;;GAG3B,QAAQ,UAAU;AAChB,iBAAa;AACb,eAAW,MAAM,MAAM;;GAEzB,gBAAgB;AACd,QAAI,OAAQ;AACZ,QAAI;AACF,kBAAa;aACN,OAAO;AACd,cAAS;AACT,gBAAW,MAAM,MAAM;;;GAG5B,CAAC;AACF,eAAa,aAAa,aAAa;GACvC"}
1
+ {"version":3,"file":"generative-ui-middleware.cjs","names":["GENERATIVE_UI_RENDER_TOOL","GENERATIVE_UI_CONTEXT_DESCRIPTION","Middleware","Observable","EventType","GENERATIVE_UI_ACTIVITY_TYPE","GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE","RenderUIArgsStream"],"sources":["../../../src/runtime/generative-ui/generative-ui-middleware.ts"],"sourcesContent":["import { EventType, Middleware } from \"@ag-ui/client\";\nimport type {\n AbstractAgent,\n BaseEvent,\n Message,\n RunAgentInput,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n} from \"@ag-ui/client\";\nimport { Observable } from \"rxjs\";\nimport {\n GENERATIVE_UI_ACTIVITY_TYPE,\n GENERATIVE_UI_CONTEXT_DESCRIPTION,\n GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE,\n GENERATIVE_UI_RENDER_TOOL,\n RenderUIArgsStream,\n buildGenerativeUIPrompt,\n envelopeToManifest,\n generativeUIFunctionCallMessageId,\n generativeUISurfaceMessageId,\n getOperationKind,\n getOperationSurfaceId,\n randomUUID,\n readCopilotKitUIEnvelope,\n validateOperation,\n} from \"@copilotkit/shared\";\nimport type {\n A2UIOperation,\n GenerativeUIFunctionCallContent,\n GenerativeUIManifest,\n GenerativeUIRejectedOperation,\n GenerativeUISurfaceContent,\n} from \"@copilotkit/shared\";\n\ntype EventWithState = { event: BaseEvent; messages: Message[] };\ntype JsonPatchOperation = {\n op: \"add\" | \"replace\";\n path: string;\n value: unknown;\n};\n\ninterface RenderCallState {\n stream: RenderUIArgsStream;\n target?: string;\n buffered: Array<Record<string, unknown> | null>;\n nextIndex: number;\n /** Accepted surface operations. */\n applied: number;\n /** Accepted `callRendererFunction` operations. */\n calls: number;\n rejected: GenerativeUIRejectedOperation[];\n touched: Set<string>;\n finished: boolean;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Builds the manifest from the generative UI envelope\n * (`forwardedProps.copilotkit.ui`). The client sends the envelope, so it is\n * not trusted: `readCopilotKitUIEnvelope` checks every field, and\n * `envelopeToManifest` turns it into the manifest. Returns\n * `undefined` (the run passes through) when:\n * - there is no valid envelope;\n * - the transport is \"markdown\" (the model writes fences, not render_ui);\n * - the catalog has no components (the server cannot validate operations).\n */\nfunction readManifest(forwardedProps: unknown) {\n const envelope = readCopilotKitUIEnvelope(forwardedProps);\n if (!envelope) return undefined;\n const manifest = envelopeToManifest(envelope);\n const isToolRun = manifest.transport === \"tool\" && manifest.hasComponents;\n return isToolRun ? manifest : undefined;\n}\n\nfunction prepareInput(input: RunAgentInput, manifest: GenerativeUIManifest) {\n const tools = (input.tools ?? []).filter(\n (t) => t.name !== GENERATIVE_UI_RENDER_TOOL,\n );\n tools.push({\n name: GENERATIVE_UI_RENDER_TOOL,\n description:\n \"Render or update generative UI surfaces, or call app functions, with A2UI v1.0 operations. Follow the generative UI guide in context.\",\n parameters: {\n type: \"object\",\n properties: {\n target: {\n type: \"string\",\n enum: manifest.targets.map((t) => t.id),\n description:\n 'Where the surface is shown: \"chat\" or a named inline target.',\n },\n operations: {\n type: \"array\",\n description: \"A2UI v1.0 operations, applied in order.\",\n items: { type: \"object\" },\n },\n },\n required: [\"target\", \"operations\"],\n },\n });\n const context = (input.context ?? []).filter(\n (c) => c.description !== GENERATIVE_UI_CONTEXT_DESCRIPTION,\n );\n context.push({\n description: GENERATIVE_UI_CONTEXT_DESCRIPTION,\n value: buildGenerativeUIPrompt(manifest),\n });\n return { ...input, tools, context };\n}\n\n/**\n * Experimental. Lets an agent render CopilotKit generative UI surfaces via the\n * `render_ui` tool. It applies only to runs whose generative UI envelope uses\n * the \"tool\" transport. Each complete operation in the streamed arguments is\n * validated against the catalog in the envelope and committed immediately:\n * - `ACTIVITY_SNAPSHOT` for a new surface, `ACTIVITY_DELTA` for every further\n * operation on it.\n * - One `ACTIVITY_SNAPSHOT` of type `generative-ui-function-call` for each\n * `callRendererFunction`. The client runs the function.\n */\nexport class GenerativeUIMiddleware extends Middleware {\n run(input: RunAgentInput, next: AbstractAgent): Observable<BaseEvent> {\n const manifest = readManifest(input.forwardedProps);\n if (!manifest) return this.runNext(input, next);\n return processStream(\n this.runNextWithState(\n prepareInput(input, manifest),\n next,\n ) as Observable<EventWithState>,\n manifest,\n );\n }\n}\n\n/**\n * The first time a render_ui call touches an existing surface, mark it\n * streaming and clear its rejection list: earlier calls' rejections were\n * already reported to the model in their own tool results, and a repaired\n * surface must not keep showing them. A surface created by this call starts\n * with an empty list in its snapshot.\n */\nfunction beginSurfaceUpdate(\n state: RenderCallState,\n surfaceId: string,\n): JsonPatchOperation[] {\n if (state.touched.has(surfaceId)) return [];\n state.touched.add(surfaceId);\n return [\n { op: \"replace\", path: \"/status\", value: \"streaming\" },\n { op: \"replace\", path: \"/rejected\", value: [] },\n ];\n}\n\nfunction processStream(\n source: Observable<EventWithState>,\n manifest: GenerativeUIManifest,\n) {\n return new Observable<BaseEvent>((subscriber) => {\n const entries = Object.entries(manifest.surfaces);\n // Only live surfaces take updates. A surface that the client deleted, or\n // that was never created, has a `status`.\n const surfaces = new Map<string, string>(\n entries.filter(([, s]) => !s.status).map(([id, s]) => [id, s.target]),\n );\n // A surface id is unique for the life of the page. Keep the ids that were\n // created, also after deleteSurface (in this run or an earlier one), so a\n // second createSurface is rejected. A failed create can be sent again.\n const createdSurfaces = new Set(\n entries.filter(([, s]) => s.status !== \"failed\").map(([id]) => id),\n );\n // The targets that limit their components, by target id.\n const targetComponents = new Map(\n manifest.targets\n .filter((t) => t.components !== undefined)\n .map((t) => [t.id, new Set(t.components)]),\n );\n const functionCallIds = new Set<string>();\n const calls = new Map<string, RenderCallState>();\n let heldFinish: EventWithState | null = null;\n\n const emit = (event: BaseEvent) => subscriber.next(event);\n const patch = (surfaceId: string, ops: JsonPatchOperation[]) =>\n emit({\n type: EventType.ACTIVITY_DELTA,\n messageId: generativeUISurfaceMessageId(surfaceId),\n activityType: GENERATIVE_UI_ACTIVITY_TYPE,\n patch: ops,\n });\n\n const processOperation = (\n state: RenderCallState,\n op: Record<string, unknown> | null,\n ) => {\n const index = state.nextIndex++;\n const reject = (reason: string, surfaceId?: string) => {\n const entry = { index, reason };\n state.rejected.push(entry);\n if (surfaceId && surfaces.has(surfaceId)) {\n patch(surfaceId, [\n ...beginSurfaceUpdate(state, surfaceId),\n { op: \"add\", path: \"/rejected/-\", value: entry },\n ]);\n }\n };\n if (op === null) return reject(\"operation is not valid JSON\");\n let surfaceId: string | undefined;\n try {\n surfaceId = getOperationSurfaceId(op);\n applyOperation(state, withCatalogId(op), surfaceId, reject);\n } catch (error) {\n // Never let one bad operation take down the run: report it to the\n // model through the tool result instead.\n reject(\n `operation could not be processed: ${error instanceof Error ? error.message : String(error)}`,\n surfaceId,\n );\n }\n };\n\n /**\n * The model does not have to name the catalog. A createSurface keeps a\n * catalogId that the envelope lists, and gets the catalog id of the run\n * for any other value. The whole operation, with its inline components\n * and data model, stays in the snapshot.\n */\n const catalogIds = manifest.catalogIds ?? [manifest.catalogId];\n const withCatalogId = (op: Record<string, unknown>) => {\n const create = op.createSurface;\n if (!isRecord(create)) return op;\n const catalogId = catalogIds.includes(create.catalogId as string)\n ? create.catalogId\n : manifest.catalogId;\n return { ...op, createSurface: { ...create, catalogId } };\n };\n\n /**\n * The components that the target of the surface takes. A createSurface\n * goes to the target of the render_ui call. Every other operation goes to\n * the target that the surface was created on.\n */\n const allowedComponentsFor = (\n state: RenderCallState,\n op: Record<string, unknown>,\n surfaceId: string | undefined,\n ) => {\n const target =\n getOperationKind(op) === \"createSurface\"\n ? state.target\n : surfaces.get(surfaceId);\n const names = targetComponents.get(target);\n return names && { target, names };\n };\n\n const applyOperation = (\n state: RenderCallState,\n op: Record<string, unknown>,\n surfaceId: string | undefined,\n reject: (reason: string, surfaceId?: string) => void,\n ) => {\n const validation = validateOperation(op, {\n manifest,\n knownSurfaces: new Set(surfaces.keys()),\n createdSurfaces,\n functions: manifest.functions,\n allowedComponents: allowedComponentsFor(state, op, surfaceId),\n });\n // `=== false` (not `!ok`): runtime is compiled non-strict, where `!ok`\n // does not narrow the discriminated union.\n if (validation.ok === false) return reject(validation.reason, surfaceId);\n // validateOperation checked the shape of the operation.\n const accepted = op as A2UIOperation;\n if (\"callRendererFunction\" in accepted) {\n return callRendererFunction(\n state,\n accepted.callRendererFunction,\n reject,\n );\n }\n if (\"createSurface\" in accepted) {\n return createSurface(state, surfaceId, accepted, reject);\n }\n patch(surfaceId, [\n ...beginSurfaceUpdate(state, surfaceId),\n { op: \"add\", path: \"/operations/-\", value: accepted },\n ]);\n if (\"deleteSurface\" in accepted) surfaces.delete(surfaceId);\n state.applied++;\n };\n\n const createSurface = (\n state: RenderCallState,\n surfaceId: string,\n op: A2UIOperation,\n reject: (reason: string) => void,\n ) => {\n const { target } = state;\n if (target === undefined) {\n return reject(\"render_ui was called without a target\");\n }\n if (!manifest.targets.some((t) => t.id === target)) {\n return reject(`target \"${target}\" is not mounted`);\n }\n surfaces.set(surfaceId, target);\n createdSurfaces.add(surfaceId);\n const content: GenerativeUISurfaceContent = {\n surfaceId,\n target,\n catalogId:\n (\"createSurface\" in op && op.createSurface.catalogId) ||\n manifest.catalogId,\n operations: [op],\n status: \"streaming\",\n rejected: [],\n };\n emit({\n type: EventType.ACTIVITY_SNAPSHOT,\n messageId: generativeUISurfaceMessageId(surfaceId),\n activityType: GENERATIVE_UI_ACTIVITY_TYPE,\n content,\n replace: true,\n });\n state.touched.add(surfaceId);\n state.applied++;\n };\n\n /**\n * Sends one function call to the client, which runs it. A function call\n * needs no target and no surface. Each `functionCallId` runs once.\n */\n const callRendererFunction = (\n state: RenderCallState,\n content: GenerativeUIFunctionCallContent,\n reject: (reason: string) => void,\n ) => {\n const { functionCallId } = content;\n if (functionCallIds.has(functionCallId)) {\n return reject(\n `functionCallId \"${functionCallId}\" was used before; use a new functionCallId`,\n );\n }\n functionCallIds.add(functionCallId);\n emit({\n type: EventType.ACTIVITY_SNAPSHOT,\n messageId: generativeUIFunctionCallMessageId(functionCallId),\n activityType: GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE,\n content: {\n functionCallId,\n callFunction: content.callFunction,\n } satisfies GenerativeUIFunctionCallContent,\n replace: true,\n });\n state.calls++;\n };\n\n /** Same buffering rule as streamed ops: hold them until the target is known. */\n const acceptOperation = (\n state: RenderCallState,\n op: Record<string, unknown> | null,\n ) => {\n if (state.target === undefined) state.buffered.push(op);\n else processOperation(state, op);\n };\n\n /**\n * The streaming parser found no operations at all. Models sometimes send\n * `operations` as a JSON-encoded string; recover those from the complete\n * arguments. Anything still unusable leaves the call with zero operations,\n * which the tool result reports as an error.\n */\n const recoverOperations = (state: RenderCallState) => {\n let args: unknown;\n try {\n args = JSON.parse(state.stream.text);\n } catch {\n return;\n }\n if (!isRecord(args)) return;\n if (state.target === undefined && typeof args.target === \"string\") {\n state.target = args.target;\n }\n let operations = args.operations;\n if (typeof operations === \"string\") {\n try {\n operations = JSON.parse(operations);\n } catch {\n return;\n }\n }\n if (!Array.isArray(operations)) return;\n for (const op of operations)\n acceptOperation(state, isRecord(op) ? op : null);\n };\n\n const finishCall = (state: RenderCallState) => {\n if (state.finished) return;\n state.finished = true;\n if (state.nextIndex === 0 && state.buffered.length === 0)\n recoverOperations(state);\n if (state.target === undefined) {\n // A function call needs no target, so it still runs. Every other\n // operation is rejected.\n const buffered = state.buffered;\n state.buffered = [];\n for (const op of buffered) {\n if (getOperationKind(op) === \"callRendererFunction\") {\n processOperation(state, op);\n continue;\n }\n state.rejected.push({\n index: state.nextIndex++,\n reason: \"render_ui was called without a target\",\n });\n }\n }\n if (state.stream.hasIncompleteOperation) {\n // The arguments ended inside an element (for example the model hit its\n // output limit): report it instead of silently dropping it.\n state.rejected.push({\n index: state.nextIndex++,\n reason: \"operation was truncated\",\n });\n }\n for (const id of state.touched) {\n patch(id, [{ op: \"replace\", path: \"/status\", value: \"ready\" }]);\n }\n };\n\n const flushFinish = () => {\n if (heldFinish) {\n emit(heldFinish.event);\n heldFinish = null;\n }\n };\n\n const handleEvent = ({ event, messages }: EventWithState) => {\n flushFinish();\n if (event.type === EventType.RUN_FINISHED) {\n heldFinish = { event, messages };\n return;\n }\n emit(event);\n if (event.type === EventType.TOOL_CALL_START) {\n const start = event as ToolCallStartEvent;\n if (start.toolCallName === GENERATIVE_UI_RENDER_TOOL) {\n calls.set(start.toolCallId, {\n stream: new RenderUIArgsStream(),\n buffered: [],\n nextIndex: 0,\n applied: 0,\n calls: 0,\n rejected: [],\n touched: new Set(),\n finished: false,\n });\n }\n } else if (event.type === EventType.TOOL_CALL_ARGS) {\n const args = event as ToolCallArgsEvent;\n const state = calls.get(args.toolCallId);\n if (!state || state.finished) return;\n const { target, newOperations } = state.stream.push(args.delta);\n if (target !== undefined && state.target === undefined) {\n state.target = target;\n const buffered = state.buffered;\n state.buffered = [];\n for (const op of buffered) processOperation(state, op);\n }\n for (const op of newOperations) acceptOperation(state, op);\n } else if (event.type === EventType.TOOL_CALL_END) {\n const state = calls.get((event as ToolCallEndEvent).toolCallId);\n if (state) finishCall(state);\n }\n };\n\n const completeRun = () => {\n for (const state of calls.values()) finishCall(state);\n if (heldFinish) {\n const answered = new Set(\n heldFinish.messages\n .filter((m) => m.role === \"tool\")\n .map((m) => (m as { toolCallId: string }).toolCallId),\n );\n for (const [toolCallId, state] of calls) {\n if (answered.has(toolCallId)) continue;\n const nothingParsed =\n state.applied === 0 &&\n state.calls === 0 &&\n state.rejected.length === 0;\n // `applied` counts the surface operations, `calls` the function calls.\n emit({\n type: EventType.TOOL_CALL_RESULT,\n messageId: randomUUID(),\n toolCallId,\n content: JSON.stringify(\n nothingParsed\n ? {\n status: \"error\",\n applied: 0,\n calls: 0,\n rejected: [],\n reason:\n \"operations must be a JSON array of A2UI operation objects; nothing was rendered\",\n }\n : {\n status: \"rendered\",\n applied: state.applied,\n calls: state.calls,\n rejected: state.rejected,\n },\n ),\n });\n }\n flushFinish();\n }\n subscriber.complete();\n };\n\n let failed = false;\n const subscription = source.subscribe({\n next: (item) => {\n if (failed) return;\n try {\n handleEvent(item);\n } catch (error) {\n // Anything unexpected must reach the consumer as an error instead of\n // escaping this callback, where RxJS would rethrow it asynchronously\n // as an uncaught exception.\n failed = true;\n subscriber.error(error);\n }\n },\n error: (error) => {\n flushFinish();\n subscriber.error(error);\n },\n complete: () => {\n if (failed) return;\n try {\n completeRun();\n } catch (error) {\n failed = true;\n subscriber.error(error);\n }\n },\n });\n return () => subscription.unsubscribe();\n });\n}\n"],"mappings":";;;;;AAwDA,SAAS,SAAS,OAAkD;AAClE,QAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,MAAM;;;;;;;;;;;;AAa7E,SAAS,aAAa,gBAAyB;CAC7C,MAAM,4DAAoC,eAAe;AACzD,KAAI,CAAC,SAAU,QAAO;CACtB,MAAM,sDAA8B,SAAS;AAE7C,QADkB,SAAS,cAAc,UAAU,SAAS,gBACzC,WAAW;;AAGhC,SAAS,aAAa,OAAsB,UAAgC;CAC1E,MAAM,SAAS,MAAM,SAAS,EAAE,EAAE,QAC/B,MAAM,EAAE,SAASA,6CACnB;AACD,OAAM,KAAK;EACT,MAAMA;EACN,aACE;EACF,YAAY;GACV,MAAM;GACN,YAAY;IACV,QAAQ;KACN,MAAM;KACN,MAAM,SAAS,QAAQ,KAAK,MAAM,EAAE,GAAG;KACvC,aACE;KACH;IACD,YAAY;KACV,MAAM;KACN,aAAa;KACb,OAAO,EAAE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B,WAAW,SACR,QAAQ,MAAM,EAAE,SAAS,OAAO,CAChC,KAAK,MAAO,EAA6B,WAAW,CACxD;AACD,SAAK,MAAM,CAAC,YAAY,UAAU,OAAO;AACvC,SAAI,SAAS,IAAI,WAAW,CAAE;KAC9B,MAAM,gBACJ,MAAM,YAAY,KAClB,MAAM,UAAU,KAChB,MAAM,SAAS,WAAW;AAE5B,UAAK;MACH,MAAMA,wBAAU;MAChB,+CAAuB;MACvB;MACA,SAAS,KAAK,UACZ,gBACI;OACE,QAAQ;OACR,SAAS;OACT,OAAO;OACP,UAAU,EAAE;OACZ,QACE;OACH,GACD;OACE,QAAQ;OACR,SAAS,MAAM;OACf,OAAO,MAAM;OACb,UAAU,MAAM;OACjB,CACN;MACF,CAAC;;AAEJ,iBAAa;;AAEf,cAAW,UAAU;;EAGvB,IAAI,SAAS;EACb,MAAM,eAAe,OAAO,UAAU;GACpC,OAAO,SAAS;AACd,QAAI,OAAQ;AACZ,QAAI;AACF,iBAAY,KAAK;aACV,OAAO;AAId,cAAS;AACT,gBAAW,MAAM,MAAM;;;GAG3B,QAAQ,UAAU;AAChB,iBAAa;AACb,eAAW,MAAM,MAAM;;GAEzB,gBAAgB;AACd,QAAI,OAAQ;AACZ,QAAI;AACF,kBAAa;aACN,OAAO;AACd,cAAS;AACT,gBAAW,MAAM,MAAM;;;GAG5B,CAAC;AACF,eAAa,aAAa,aAAa;GACvC"}
@@ -1,4 +1,3 @@
1
- const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
2
1
  let _copilotkit_shared = require("@copilotkit/shared");
3
2
  let _ag_ui_client = require("@ag-ui/client");
4
3
 
@@ -1 +1 @@
1
- {"version":3,"file":"surface-writer.cjs","names":["EventType","GENERATIVE_UI_ACTIVITY_TYPE","GENERATIVE_UI_ROOT_ID"],"sources":["../../../src/runtime/generative-ui/surface-writer.ts"],"sourcesContent":["import { EventType } from \"@ag-ui/client\";\nimport type { BaseEvent } from \"@ag-ui/client\";\nimport {\n GENERATIVE_UI_ACTIVITY_TYPE,\n GENERATIVE_UI_ROOT_ID,\n generativeUISurfaceMessageId,\n} from \"@copilotkit/shared\";\nimport type {\n A2UIComponentNode,\n A2UIOperation,\n GenerativeUISurfaceContent,\n} from \"@copilotkit/shared\";\n\nexport interface GenerativeUISurfaceWriter {\n setRoot(node: Omit<A2UIComponentNode, \"id\">): void;\n upsert(...nodes: A2UIComponentNode[]): void;\n /** Sets `value` at `path`. A `null` value deletes the key at `path`. */\n updateData(path: string, value: unknown): void;\n close(): void;\n}\n\n/**\n * Experimental. Programmatic façade for custom agents and workflows: emits the\n * same `generative-ui-surface` activity events as `render_ui`, one per call.\n * Every operation is A2UI v1.0.\n * Does not validate against the browser manifest; the client still validates\n * every operation before applying it.\n */\nexport function createSurfaceWriter(emit: (event: BaseEvent) => void) {\n return {\n openSurface({\n target,\n surfaceId,\n catalog,\n }: {\n target: string;\n surfaceId: string;\n catalog: string;\n }): GenerativeUISurfaceWriter {\n const messageId = generativeUISurfaceMessageId(surfaceId);\n const patch = (ops: unknown[]) =>\n emit({\n type: EventType.ACTIVITY_DELTA,\n messageId,\n activityType: GENERATIVE_UI_ACTIVITY_TYPE,\n patch: ops,\n });\n const append = (op: A2UIOperation) =>\n patch([{ op: \"add\", path: \"/operations/-\", value: op }]);\n const content: GenerativeUISurfaceContent = {\n surfaceId,\n target,\n catalogId: catalog,\n operations: [\n { version: \"v1.0\", createSurface: { surfaceId, catalogId: catalog } },\n ],\n status: \"streaming\",\n rejected: [],\n };\n emit({\n type: EventType.ACTIVITY_SNAPSHOT,\n messageId,\n activityType: GENERATIVE_UI_ACTIVITY_TYPE,\n content,\n replace: true,\n });\n return {\n setRoot: (node) =>\n append({\n version: \"v1.0\",\n updateComponents: {\n surfaceId,\n components: [\n { ...node, id: GENERATIVE_UI_ROOT_ID } as A2UIComponentNode,\n ],\n },\n }),\n upsert: (...nodes) =>\n append({\n version: \"v1.0\",\n updateComponents: { surfaceId, components: nodes },\n }),\n updateData: (path, value) =>\n append({\n version: \"v1.0\",\n updateDataModel: { surfaceId, path, value },\n }),\n close: () =>\n patch([{ op: \"replace\", path: \"/status\", value: \"ready\" }]),\n };\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AA4BA,SAAgB,oBAAoB,MAAkC;AACpE,QAAO,EACL,YAAY,EACV,QACA,WACA,WAK4B;EAC5B,MAAM,iEAAyC,UAAU;EACzD,MAAM,SAAS,QACb,KAAK;GACH,MAAMA,wBAAU;GAChB;GACA,cAAcC;GACd,OAAO;GACR,CAAC;EACJ,MAAM,UAAU,OACd,MAAM,CAAC;GAAE,IAAI;GAAO,MAAM;GAAiB,OAAO;GAAI,CAAC,CAAC;EAC1D,MAAM,UAAsC;GAC1C;GACA;GACA,WAAW;GACX,YAAY,CACV;IAAE,SAAS;IAAQ,eAAe;KAAE;KAAW,WAAW;KAAS;IAAE,CACtE;GACD,QAAQ;GACR,UAAU,EAAE;GACb;AACD,OAAK;GACH,MAAMD,wBAAU;GAChB;GACA,cAAcC;GACd;GACA,SAAS;GACV,CAAC;AACF,SAAO;GACL,UAAU,SACR,OAAO;IACL,SAAS;IACT,kBAAkB;KAChB;KACA,YAAY,CACV;MAAE,GAAG;MAAM,IAAIC;MAAuB,CACvC;KACF;IACF,CAAC;GACJ,SAAS,GAAG,UACV,OAAO;IACL,SAAS;IACT,kBAAkB;KAAE;KAAW,YAAY;KAAO;IACnD,CAAC;GACJ,aAAa,MAAM,UACjB,OAAO;IACL,SAAS;IACT,iBAAiB;KAAE;KAAW;KAAM;KAAO;IAC5C,CAAC;GACJ,aACE,MAAM,CAAC;IAAE,IAAI;IAAW,MAAM;IAAW,OAAO;IAAS,CAAC,CAAC;GAC9D;IAEJ"}
1
+ {"version":3,"file":"surface-writer.cjs","names":["EventType","GENERATIVE_UI_ACTIVITY_TYPE","GENERATIVE_UI_ROOT_ID"],"sources":["../../../src/runtime/generative-ui/surface-writer.ts"],"sourcesContent":["import { EventType } from \"@ag-ui/client\";\nimport type { BaseEvent } from \"@ag-ui/client\";\nimport {\n GENERATIVE_UI_ACTIVITY_TYPE,\n GENERATIVE_UI_ROOT_ID,\n generativeUISurfaceMessageId,\n} from \"@copilotkit/shared\";\nimport type {\n A2UIComponentNode,\n A2UIOperation,\n GenerativeUISurfaceContent,\n} from \"@copilotkit/shared\";\n\nexport interface GenerativeUISurfaceWriter {\n setRoot(node: Omit<A2UIComponentNode, \"id\">): void;\n upsert(...nodes: A2UIComponentNode[]): void;\n /** Sets `value` at `path`. A `null` value deletes the key at `path`. */\n updateData(path: string, value: unknown): void;\n close(): void;\n}\n\n/**\n * Experimental. Programmatic façade for custom agents and workflows: emits the\n * same `generative-ui-surface` activity events as `render_ui`, one per call.\n * Every operation is A2UI v1.0.\n * Does not validate against the browser manifest; the client still validates\n * every operation before applying it.\n */\nexport function createSurfaceWriter(emit: (event: BaseEvent) => void) {\n return {\n openSurface({\n target,\n surfaceId,\n catalog,\n }: {\n target: string;\n surfaceId: string;\n catalog: string;\n }): GenerativeUISurfaceWriter {\n const messageId = generativeUISurfaceMessageId(surfaceId);\n const patch = (ops: unknown[]) =>\n emit({\n type: EventType.ACTIVITY_DELTA,\n messageId,\n activityType: GENERATIVE_UI_ACTIVITY_TYPE,\n patch: ops,\n });\n const append = (op: A2UIOperation) =>\n patch([{ op: \"add\", path: \"/operations/-\", value: op }]);\n const content: GenerativeUISurfaceContent = {\n surfaceId,\n target,\n catalogId: catalog,\n operations: [\n { version: \"v1.0\", createSurface: { surfaceId, catalogId: catalog } },\n ],\n status: \"streaming\",\n rejected: [],\n };\n emit({\n type: EventType.ACTIVITY_SNAPSHOT,\n messageId,\n activityType: GENERATIVE_UI_ACTIVITY_TYPE,\n content,\n replace: true,\n });\n return {\n setRoot: (node) =>\n append({\n version: \"v1.0\",\n updateComponents: {\n surfaceId,\n components: [\n { ...node, id: GENERATIVE_UI_ROOT_ID } as A2UIComponentNode,\n ],\n },\n }),\n upsert: (...nodes) =>\n append({\n version: \"v1.0\",\n updateComponents: { surfaceId, components: nodes },\n }),\n updateData: (path, value) =>\n append({\n version: \"v1.0\",\n updateDataModel: { surfaceId, path, value },\n }),\n close: () =>\n patch([{ op: \"replace\", path: \"/status\", value: \"ready\" }]),\n };\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AA4BA,SAAgB,oBAAoB,MAAkC;AACpE,QAAO,EACL,YAAY,EACV,QACA,WACA,WAK4B;EAC5B,MAAM,iEAAyC,UAAU;EACzD,MAAM,SAAS,QACb,KAAK;GACH,MAAMA,wBAAU;GAChB;GACA,cAAcC;GACd,OAAO;GACR,CAAC;EACJ,MAAM,UAAU,OACd,MAAM,CAAC;GAAE,IAAI;GAAO,MAAM;GAAiB,OAAO;GAAI,CAAC,CAAC;EAC1D,MAAM,UAAsC;GAC1C;GACA;GACA,WAAW;GACX,YAAY,CACV;IAAE,SAAS;IAAQ,eAAe;KAAE;KAAW,WAAW;KAAS;IAAE,CACtE;GACD,QAAQ;GACR,UAAU,EAAE;GACb;AACD,OAAK;GACH,MAAMD,wBAAU;GAChB;GACA,cAAcC;GACd;GACA,SAAS;GACV,CAAC;AACF,SAAO;GACL,UAAU,SACR,OAAO;IACL,SAAS;IACT,kBAAkB;KAChB;KACA,YAAY,CACV;MAAE,GAAG;MAAM,IAAIC;MAAuB,CACvC;KACF;IACF,CAAC;GACJ,SAAS,GAAG,UACV,OAAO;IACL,SAAS;IACT,kBAAkB;KAAE;KAAW,YAAY;KAAO;IACnD,CAAC;GACJ,aAAa,MAAM,UACjB,OAAO;IACL,SAAS;IACT,iBAAiB;KAAE;KAAW;KAAM;KAAO;IAC5C,CAAC;GACJ,aACE,MAAM,CAAC;IAAE,IAAI;IAAW,MAAM;IAAW,OAAO;IAAS,CAAC,CAAC;GAC9D;IAEJ"}
@@ -1,8 +1,7 @@
1
- const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
2
1
  const require_learning = require('../core/learning.cjs');
3
2
  const require_client = require('../intelligence-platform/client.cjs');
4
3
  const require_resolve_intelligence_user = require('./shared/resolve-intelligence-user.cjs');
5
- const require_runtime$1 = require('../core/runtime.cjs');
4
+ const require_runtime = require('../core/runtime.cjs');
6
5
  let _copilotkit_shared = require("@copilotkit/shared");
7
6
 
8
7
  //#region src/runtime/handlers/handle-inspector-learning.ts
@@ -17,7 +16,7 @@ const errorResponse = (status, message) => new Response(JSON.stringify({ error:
17
16
  const queryPage = (value) => value === null ? void 0 : Number(value);
18
17
  /** Proxies a bounded Learning read through the runtime's server-held credential. */
19
18
  async function handleInspectorLearning({ runtime, request }) {
20
- if (!require_runtime$1.isIntelligenceRuntime(runtime) || !require_learning.hasLearningContainerConfiguration(runtime)) return errorResponse(404, "Not found");
19
+ if (!require_runtime.isIntelligenceRuntime(runtime) || !require_learning.hasLearningContainerConfiguration(runtime)) return errorResponse(404, "Not found");
21
20
  const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
22
21
  runtime,
23
22
  request
@@ -1 +1 @@
1
- {"version":3,"file":"handle-inspector-learning.cjs","names":["isIntelligenceRuntime","hasLearningContainerConfiguration","resolveIntelligenceUser","PlatformRequestError"],"sources":["../../../src/runtime/handlers/handle-inspector-learning.ts"],"sourcesContent":["import {\n parseInspectorLearningRequestV1,\n parseInspectorLearningSnapshotV1,\n} from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { hasLearningContainerConfiguration } from \"../core/learning\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport { PlatformRequestError } from \"../intelligence-platform/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\n\nconst headers = {\n \"Cache-Control\": \"no-store, private\",\n \"Content-Type\": \"application/json\",\n} as const;\n\nconst errorResponse = (status: number, message: string) =>\n new Response(JSON.stringify({ error: message }), { status, headers });\n\nconst queryPage = (value: string | null): number | undefined =>\n value === null ? undefined : Number(value);\n\n/** Proxies a bounded Learning read through the runtime's server-held credential. */\nexport async function handleInspectorLearning({\n runtime,\n request,\n}: {\n readonly runtime: CopilotRuntimeLike;\n readonly request: Request;\n}): Promise<Response> {\n if (\n !isIntelligenceRuntime(runtime) ||\n !hasLearningContainerConfiguration(runtime)\n ) {\n return errorResponse(404, \"Not found\");\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n if (user instanceof Response) return user;\n const url = new URL(request.url);\n if (\n [...url.searchParams.keys()].some(\n (key) => ![\"agentId\", \"skillsPage\", \"insightsPage\"].includes(key),\n )\n ) {\n return errorResponse(400, \"Invalid Inspector Learning request\");\n }\n const parsedRequest = parseInspectorLearningRequestV1({\n agentId: url.searchParams.get(\"agentId\") ?? undefined,\n skillsPage: queryPage(url.searchParams.get(\"skillsPage\")),\n insightsPage: queryPage(url.searchParams.get(\"insightsPage\")),\n });\n if (!parsedRequest)\n return errorResponse(400, \"Invalid Inspector Learning request\");\n\n try {\n const snapshot = parseInspectorLearningSnapshotV1(\n await runtime.intelligence.getInspectorLearning({\n ...parsedRequest,\n ...(typeof runtime.learning?.containerId === \"string\"\n ? { runtimeContainerId: runtime.learning.containerId }\n : {}),\n }),\n );\n if (!snapshot)\n return errorResponse(502, \"Invalid Inspector Learning response\");\n return new Response(JSON.stringify(snapshot), { status: 200, headers });\n } catch (error) {\n if (error instanceof PlatformRequestError && error.status === 404) {\n return errorResponse(404, \"Not found\");\n }\n return errorResponse(503, \"Inspector Learning is temporarily unavailable\");\n }\n}\n"],"mappings":";;;;;;;;AAUA,MAAM,UAAU;CACd,iBAAiB;CACjB,gBAAgB;CACjB;AAED,MAAM,iBAAiB,QAAgB,YACrC,IAAI,SAAS,KAAK,UAAU,EAAE,OAAO,SAAS,CAAC,EAAE;CAAE;CAAQ;CAAS,CAAC;AAEvE,MAAM,aAAa,UACjB,UAAU,OAAO,SAAY,OAAO,MAAM;;AAG5C,eAAsB,wBAAwB,EAC5C,SACA,WAIoB;AACpB,KACE,CAACA,wCAAsB,QAAQ,IAC/B,CAACC,mDAAkC,QAAQ,CAE3C,QAAO,cAAc,KAAK,YAAY;CAExC,MAAM,OAAO,MAAMC,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,gBAAgB,SAAU,QAAO;CACrC,MAAM,MAAM,IAAI,IAAI,QAAQ,IAAI;AAChC,KACE,CAAC,GAAG,IAAI,aAAa,MAAM,CAAC,CAAC,MAC1B,QAAQ,CAAC;EAAC;EAAW;EAAc;EAAe,CAAC,SAAS,IAAI,CAClE,CAED,QAAO,cAAc,KAAK,qCAAqC;CAEjE,MAAM,wEAAgD;EACpD,SAAS,IAAI,aAAa,IAAI,UAAU,IAAI;EAC5C,YAAY,UAAU,IAAI,aAAa,IAAI,aAAa,CAAC;EACzD,cAAc,UAAU,IAAI,aAAa,IAAI,eAAe,CAAC;EAC9D,CAAC;AACF,KAAI,CAAC,cACH,QAAO,cAAc,KAAK,qCAAqC;AAEjE,KAAI;EACF,MAAM,oEACJ,MAAM,QAAQ,aAAa,qBAAqB;GAC9C,GAAG;GACH,GAAI,OAAO,QAAQ,UAAU,gBAAgB,WACzC,EAAE,oBAAoB,QAAQ,SAAS,aAAa,GACpD,EAAE;GACP,CAAC,CACH;AACD,MAAI,CAAC,SACH,QAAO,cAAc,KAAK,sCAAsC;AAClE,SAAO,IAAI,SAAS,KAAK,UAAU,SAAS,EAAE;GAAE,QAAQ;GAAK;GAAS,CAAC;UAChE,OAAO;AACd,MAAI,iBAAiBC,uCAAwB,MAAM,WAAW,IAC5D,QAAO,cAAc,KAAK,YAAY;AAExC,SAAO,cAAc,KAAK,gDAAgD"}
1
+ {"version":3,"file":"handle-inspector-learning.cjs","names":["isIntelligenceRuntime","hasLearningContainerConfiguration","resolveIntelligenceUser","PlatformRequestError"],"sources":["../../../src/runtime/handlers/handle-inspector-learning.ts"],"sourcesContent":["import {\n parseInspectorLearningRequestV1,\n parseInspectorLearningSnapshotV1,\n} from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { hasLearningContainerConfiguration } from \"../core/learning\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport { PlatformRequestError } from \"../intelligence-platform/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\n\nconst headers = {\n \"Cache-Control\": \"no-store, private\",\n \"Content-Type\": \"application/json\",\n} as const;\n\nconst errorResponse = (status: number, message: string) =>\n new Response(JSON.stringify({ error: message }), { status, headers });\n\nconst queryPage = (value: string | null): number | undefined =>\n value === null ? undefined : Number(value);\n\n/** Proxies a bounded Learning read through the runtime's server-held credential. */\nexport async function handleInspectorLearning({\n runtime,\n request,\n}: {\n readonly runtime: CopilotRuntimeLike;\n readonly request: Request;\n}): Promise<Response> {\n if (\n !isIntelligenceRuntime(runtime) ||\n !hasLearningContainerConfiguration(runtime)\n ) {\n return errorResponse(404, \"Not found\");\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n if (user instanceof Response) return user;\n const url = new URL(request.url);\n if (\n [...url.searchParams.keys()].some(\n (key) => ![\"agentId\", \"skillsPage\", \"insightsPage\"].includes(key),\n )\n ) {\n return errorResponse(400, \"Invalid Inspector Learning request\");\n }\n const parsedRequest = parseInspectorLearningRequestV1({\n agentId: url.searchParams.get(\"agentId\") ?? undefined,\n skillsPage: queryPage(url.searchParams.get(\"skillsPage\")),\n insightsPage: queryPage(url.searchParams.get(\"insightsPage\")),\n });\n if (!parsedRequest)\n return errorResponse(400, \"Invalid Inspector Learning request\");\n\n try {\n const snapshot = parseInspectorLearningSnapshotV1(\n await runtime.intelligence.getInspectorLearning({\n ...parsedRequest,\n ...(typeof runtime.learning?.containerId === \"string\"\n ? { runtimeContainerId: runtime.learning.containerId }\n : {}),\n }),\n );\n if (!snapshot)\n return errorResponse(502, \"Invalid Inspector Learning response\");\n return new Response(JSON.stringify(snapshot), { status: 200, headers });\n } catch (error) {\n if (error instanceof PlatformRequestError && error.status === 404) {\n return errorResponse(404, \"Not found\");\n }\n return errorResponse(503, \"Inspector Learning is temporarily unavailable\");\n }\n}\n"],"mappings":";;;;;;;AAUA,MAAM,UAAU;CACd,iBAAiB;CACjB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Ac,KAAK,gDAAgD"}
@@ -1,5 +1,4 @@
1
- const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
2
- const require_runtime$1 = require('../core/runtime.cjs');
1
+ const require_runtime = require('../core/runtime.cjs');
3
2
  let _copilotkit_shared = require("@copilotkit/shared");
4
3
 
5
4
  //#region src/runtime/handlers/handle-inspector-metadata.ts
@@ -15,7 +14,7 @@ function emptyInspectorMetadataResponse() {
15
14
  * failures or forwarding any browser request credentials to Intelligence.
16
15
  */
17
16
  async function handleInspectorMetadata({ runtime }) {
18
- if (!require_runtime$1.isIntelligenceRuntime(runtime)) return emptyInspectorMetadataResponse();
17
+ if (!require_runtime.isIntelligenceRuntime(runtime)) return emptyInspectorMetadataResponse();
19
18
  try {
20
19
  const metadata = (0, _copilotkit_shared.parseInspectorMetadataV1)(await runtime.intelligence.getInspectorMetadata());
21
20
  if (metadata === void 0) return emptyInspectorMetadataResponse();
@@ -1 +1 @@
1
- {"version":3,"file":"handle-inspector-metadata.cjs","names":["isIntelligenceRuntime"],"sources":["../../../src/runtime/handlers/handle-inspector-metadata.ts"],"sourcesContent":["import { parseInspectorMetadataV1 } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\n\nconst PRIVATE_NO_STORE_HEADERS = {\n \"Cache-Control\": \"no-store, private\",\n} as const;\n\ninterface HandleInspectorMetadataParameters {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\nfunction emptyInspectorMetadataResponse(): Response {\n return new Response(null, {\n status: 204,\n headers: PRIVATE_NO_STORE_HEADERS,\n });\n}\n\n/**\n * Returns trusted, sanitized Inspector metadata without exposing provider\n * failures or forwarding any browser request credentials to Intelligence.\n */\nexport async function handleInspectorMetadata({\n runtime,\n}: HandleInspectorMetadataParameters): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return emptyInspectorMetadataResponse();\n }\n\n try {\n const metadata = parseInspectorMetadataV1(\n await runtime.intelligence.getInspectorMetadata(),\n );\n if (metadata === undefined) {\n return emptyInspectorMetadataResponse();\n }\n\n return new Response(JSON.stringify(metadata), {\n status: 200,\n headers: {\n ...PRIVATE_NO_STORE_HEADERS,\n \"Content-Type\": \"application/json\",\n },\n });\n } catch {\n return emptyInspectorMetadataResponse();\n }\n}\n"],"mappings":";;;;;AAIA,MAAM,2BAA2B,EAC/B,iBAAiB,qBAClB;AAOD,SAAS,iCAA2C;AAClD,QAAO,IAAI,SAAS,MAAM;EACxB,QAAQ;EACR,SAAS;EACV,CAAC;;;;;;AAOJ,eAAsB,wBAAwB,EAC5C,WACuD;AACvD,KAAI,CAACA,wCAAsB,QAAQ,CACjC,QAAO,gCAAgC;AAGzC,KAAI;EACF,MAAM,4DACJ,MAAM,QAAQ,aAAa,sBAAsB,CAClD;AACD,MAAI,aAAa,OACf,QAAO,gCAAgC;AAGzC,SAAO,IAAI,SAAS,KAAK,UAAU,SAAS,EAAE;GAC5C,QAAQ;GACR,SAAS;IACP,GAAG;IACH,gBAAgB;IACjB;GACF,CAAC;SACI;AACN,SAAO,gCAAgC"}
1
+ {"version":3,"file":"handle-inspector-metadata.cjs","names":["isIntelligenceRuntime"],"sources":["../../../src/runtime/handlers/handle-inspector-metadata.ts"],"sourcesContent":["import { parseInspectorMetadataV1 } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\n\nconst PRIVATE_NO_STORE_HEADERS = {\n \"Cache-Control\": \"no-store, private\",\n} as const;\n\ninterface HandleInspectorMetadataParameters {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\nfunction emptyInspectorMetadataResponse(): Response {\n return new Response(null, {\n status: 204,\n headers: PRIVATE_NO_STORE_HEADERS,\n });\n}\n\n/**\n * Returns trusted, sanitized Inspector metadata without exposing provider\n * failures or forwarding any browser request credentials to Intelligence.\n */\nexport async function handleInspectorMetadata({\n runtime,\n}: HandleInspectorMetadataParameters): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return emptyInspectorMetadataResponse();\n }\n\n try {\n const metadata = parseInspectorMetadataV1(\n await runtime.intelligence.getInspectorMetadata(),\n );\n if (metadata === undefined) {\n return emptyInspectorMetadataResponse();\n }\n\n return new Response(JSON.stringify(metadata), {\n status: 200,\n headers: {\n ...PRIVATE_NO_STORE_HEADERS,\n \"Content-Type\": \"application/json\",\n },\n });\n } catch {\n return emptyInspectorMetadataResponse();\n }\n}\n"],"mappings":";;;;AAIA,MAAM,2BAA2B,EAC/B,iBAAiB,qBAClB;AAOD,SAAS,iCAA2C;AAClD,QAAO,IAAI,SAAS,MAAM;EACxB,QAAQ;EACR,SAAS;EACV,CAAC;;;;;;AAOJ,eAAsB,wBAAwB,EAC5C,WACuD;AACvD,KAAI,CAACA,sCAAsB,QAAQ,CACjC,QAAO,gCAAgC;AAGzC,KAAI;EACF,MAAM,4DACJ,MAAM,QAAQ,aAAa,sBAAsB,CAClD;AACD,MAAI,aAAa,OACf,QAAO,gCAAgC;AAGzC,SAAO,IAAI,SAAS,KAAK,UAAU,SAAS,EAAE;GAC5C,QAAQ;GACR,SAAS;IACP,GAAG;IACH,gBAAgB;IACjB;GACF,CAAC;SACI;AACN,SAAO,gCAAgC"}
@@ -1,9 +1,8 @@
1
- const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
2
1
  const require_agent_runner = require('../runner/agent-runner.cjs');
3
2
  const require_thread_access = require('./shared/thread-access.cjs');
4
3
  const require_telemetry_client = require('../telemetry/telemetry-client.cjs');
5
4
  const require_runtime_error_reporter = require('../core/runtime-error-reporter.cjs');
6
- const require_runtime$1 = require('../core/runtime.cjs');
5
+ const require_runtime = require('../core/runtime.cjs');
7
6
  const require_cloud_telemetry = require('./shared/cloud-telemetry.cjs');
8
7
  const require_agent_utils = require('./shared/agent-utils.cjs');
9
8
  const require_run = require('./intelligence/run.cjs');
@@ -27,7 +26,7 @@ async function handleRunAgent({ runtime, request, agentId }) {
27
26
  const input = await require_agent_utils.parseRunRequest(request.clone());
28
27
  if (input instanceof Response) return input;
29
28
  let ownerId;
30
- if (!require_runtime$1.isIntelligenceRuntime(runtime)) {
29
+ if (!require_runtime.isIntelligenceRuntime(runtime)) {
31
30
  const owner = await require_thread_access.resolveLocalThreadOwner({
32
31
  runtime,
33
32
  request,
@@ -61,7 +60,7 @@ async function handleRunAgent({ runtime, request, agentId }) {
61
60
  agentName: agentId,
62
61
  threadId: input.threadId
63
62
  }, "Agent run started");
64
- if (require_runtime$1.isIntelligenceRuntime(runtime)) return require_run.handleIntelligenceRun({
63
+ if (require_runtime.isIntelligenceRuntime(runtime)) return require_run.handleIntelligenceRun({
65
64
  runtime,
66
65
  request,
67
66
  agentId,
@@ -1 +1 @@
1
- {"version":3,"file":"handle-run.cjs","names":["telemetry","readGuardrailsEnabled","cloneAgentForRequest","parseRunRequest","isIntelligenceRuntime","resolveLocalThreadOwner","enforcesThreadOwnership","threadAccessDeniedResponse","attachIntelligenceEnterpriseLearning","handleIntelligenceRun","handleSseRun"],"sources":["../../../src/runtime/handlers/handle-run.ts"],"sourcesContent":["import { readCopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport { readGuardrailsEnabled } from \"./shared/cloud-telemetry\";\nimport type { RunAgentParameters } from \"./shared/agent-utils\";\nimport {\n attachIntelligenceEnterpriseLearning,\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\nimport { getRuntimeErrorReporter } from \"../core/runtime-error-reporter\";\nimport { enforcesThreadOwnership } from \"../runner/agent-runner\";\nimport {\n resolveLocalThreadOwner,\n threadAccessDeniedResponse,\n} from \"./shared/thread-access\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n const startTime = Date.now();\n const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n (runtime.telemetry ?? telemetry).capture(\n \"oss.runtime.copilot_request_created\",\n {\n \"cloud.guardrails.enabled\": await readGuardrailsEnabled(request),\n requestType: \"run\",\n \"cloud.api_key_provided\": !!publicApiKey,\n ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\n },\n );\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n // Parse the body before configuring middleware: middleware configuration\n // needs the A2UI catalog signal the React provider forwards (see\n // `a2uiCatalogAvailable` below). Middleware is applied to the agent here;\n // the run itself is kicked off later, so this is safe. The body is read\n // from a clone, so `identifyUser` can still read the original request.\n const input = await parseRunRequest(request.clone());\n if (input instanceof Response) {\n return input;\n }\n\n // A thread belongs to the identity of its first run. Running needs no\n // configured identity (anonymous runs keep working), but nobody may add to\n // a thread that another identity owns.\n let ownerId: string | undefined;\n if (!isIntelligenceRuntime(runtime)) {\n const owner = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"run\",\n });\n if (owner instanceof Response) return owner;\n if (\n enforcesThreadOwnership(runtime.runner) &&\n !(await runtime.runner.isThreadAccessible(input.threadId, {\n ownerId: owner,\n }))\n ) {\n return threadAccessDeniedResponse();\n }\n ownerId = owner;\n }\n\n // `<CopilotKit a2ui={{ catalog }}>` forwards this flag on every run. Its\n // presence alone is enough to turn A2UI on end-to-end — no runtime-side\n // `a2ui` config required.\n const providerA2UIHasCatalog =\n (input.forwardedProps as Record<string, unknown> | undefined)\n ?.a2uiCatalogAvailable === true;\n // The generative UI envelope (`forwardedProps.copilotkit.ui`) picks the\n // transport of this run.\n const providerGenerativeUITransport = readCopilotKitUIEnvelope(\n input.forwardedProps,\n )?.metadata.extensions.copilotkit_transport;\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n providerA2UIHasCatalog,\n providerGenerativeUITransport,\n isMcpProxyRequest: Object.prototype.hasOwnProperty.call(\n input.forwardedProps ?? {},\n \"__proxiedMCPRequest\",\n ),\n });\n const memoryResponse = await attachIntelligenceEnterpriseLearning({\n runtime,\n request,\n agent,\n });\n if (memoryResponse instanceof Response) return memoryResponse;\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (runtime.debug?.lifecycle && runtime.debugLogger) {\n runtime.debugLogger.debug(\n { agentName: agentId, threadId: input.threadId },\n \"Agent run started\",\n );\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n startTime,\n });\n }\n\n return handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug: runtime.debug,\n logger: runtime.debugLogger,\n startTime,\n ownerId,\n });\n } catch (error) {\n getRuntimeErrorReporter(runtime)?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n phase: \"common\",\n startTime,\n });\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAoBA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;CACrB,MAAM,YAAY,KAAK,KAAK;CAC5B,MAAM,eAAe,QAAQ,QAAQ,IAAI,gCAAgC;AACzE,EAAC,QAAQ,aAAaA,kCAAW,QAC/B,uCACA;EACE,4BAA4B,MAAMC,8CAAsB,QAAQ;EAChE,aAAa;EACb,0BAA0B,CAAC,CAAC;EAC5B,GAAI,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;GAChB;GACA;GACD,CAAC;UACK,OAAO;AACd,yDAAwB,QAAQ,EAAE,OAAO;GACvC;GACA;GACA,WAAW;GACX;GACA,OAAO;GACP;GACD,CAAC;AACF,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;GAC/C,CAAC;AAEF,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"handle-run.cjs","names":["telemetry","readGuardrailsEnabled","cloneAgentForRequest","parseRunRequest","isIntelligenceRuntime","resolveLocalThreadOwner","enforcesThreadOwnership","threadAccessDeniedResponse","attachIntelligenceEnterpriseLearning","handleIntelligenceRun","handleSseRun"],"sources":["../../../src/runtime/handlers/handle-run.ts"],"sourcesContent":["import { readCopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport { readGuardrailsEnabled } from \"./shared/cloud-telemetry\";\nimport type { RunAgentParameters } from \"./shared/agent-utils\";\nimport {\n attachIntelligenceEnterpriseLearning,\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\nimport { getRuntimeErrorReporter } from \"../core/runtime-error-reporter\";\nimport { enforcesThreadOwnership } from \"../runner/agent-runner\";\nimport {\n resolveLocalThreadOwner,\n threadAccessDeniedResponse,\n} from \"./shared/thread-access\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n const startTime = Date.now();\n const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n (runtime.telemetry ?? telemetry).capture(\n \"oss.runtime.copilot_request_created\",\n {\n \"cloud.guardrails.enabled\": await readGuardrailsEnabled(request),\n requestType: \"run\",\n \"cloud.api_key_provided\": !!publicApiKey,\n ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\n },\n );\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n // Parse the body before configuring middleware: middleware configuration\n // needs the A2UI catalog signal the React provider forwards (see\n // `a2uiCatalogAvailable` below). Middleware is applied to the agent here;\n // the run itself is kicked off later, so this is safe. The body is read\n // from a clone, so `identifyUser` can still read the original request.\n const input = await parseRunRequest(request.clone());\n if (input instanceof Response) {\n return input;\n }\n\n // A thread belongs to the identity of its first run. Running needs no\n // configured identity (anonymous runs keep working), but nobody may add to\n // a thread that another identity owns.\n let ownerId: string | undefined;\n if (!isIntelligenceRuntime(runtime)) {\n const owner = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"run\",\n });\n if (owner instanceof Response) return owner;\n if (\n enforcesThreadOwnership(runtime.runner) &&\n !(await runtime.runner.isThreadAccessible(input.threadId, {\n ownerId: owner,\n }))\n ) {\n return threadAccessDeniedResponse();\n }\n ownerId = owner;\n }\n\n // `<CopilotKit a2ui={{ catalog }}>` forwards this flag on every run. Its\n // presence alone is enough to turn A2UI on end-to-end — no runtime-side\n // `a2ui` config required.\n const providerA2UIHasCatalog =\n (input.forwardedProps as Record<string, unknown> | undefined)\n ?.a2uiCatalogAvailable === true;\n // The generative UI envelope (`forwardedProps.copilotkit.ui`) picks the\n // transport of this run.\n const providerGenerativeUITransport = readCopilotKitUIEnvelope(\n input.forwardedProps,\n )?.metadata.extensions.copilotkit_transport;\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n providerA2UIHasCatalog,\n providerGenerativeUITransport,\n isMcpProxyRequest: Object.prototype.hasOwnProperty.call(\n input.forwardedProps ?? {},\n \"__proxiedMCPRequest\",\n ),\n });\n const memoryResponse = await attachIntelligenceEnterpriseLearning({\n runtime,\n request,\n agent,\n });\n if (memoryResponse instanceof Response) return memoryResponse;\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (runtime.debug?.lifecycle && runtime.debugLogger) {\n runtime.debugLogger.debug(\n { agentName: agentId, threadId: input.threadId },\n \"Agent run started\",\n );\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n startTime,\n });\n }\n\n return handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug: runtime.debug,\n logger: runtime.debugLogger,\n startTime,\n ownerId,\n });\n } catch (error) {\n getRuntimeErrorReporter(runtime)?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n phase: \"common\",\n startTime,\n });\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;CACrB,MAAM,YAAY,KAAK,KAAK;CAC5B,MAAM,eAAe,QAAQ,QAAQ,IAAI,gCAAgC;AACzE,EAAC,QAAQ,aAAaA,kCAAW,QAC/B,uCACA;EACE,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AAGJ,SAAOC,2BAAa;GAClB;GACA;GACA;GACA;GACA;GACA,OAAO,QAAQ;GACf,QAAQ,QAAQ;GAChB;GACA;GACD,CAAC;UACK,OAAO;AACd,yDAAwB,QAAQ,EAAE,OAAO;GACvC;GACA;GACA,WAAW;GACX;GACA,OAAO;GACP;GACD,CAAC;AACF,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;GAC/C,CAAC;AAEF,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -1,9 +1,8 @@
1
- const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
2
1
  const require_json_response = require('./shared/json-response.cjs');
3
2
  const require_intelligence_utils = require('./shared/intelligence-utils.cjs');
4
3
  const require_resolve_intelligence_user = require('./shared/resolve-intelligence-user.cjs');
5
4
  const require_thread_access = require('./shared/thread-access.cjs');
6
- const require_runtime$1 = require('../core/runtime.cjs');
5
+ const require_runtime = require('../core/runtime.cjs');
7
6
  let _ag_ui_client = require("@ag-ui/client");
8
7
 
9
8
  //#region src/runtime/handlers/handle-stop.ts
@@ -29,7 +28,7 @@ async function handleStopAgent({ runtime, request, agentId, threadId }) {
29
28
  const { runId } = scope;
30
29
  let stopThreadId = threadId;
31
30
  let ownerId;
32
- if (!require_runtime$1.isIntelligenceRuntime(runtime)) {
31
+ if (!require_runtime.isIntelligenceRuntime(runtime)) {
33
32
  const owner = await require_thread_access.resolveLocalThreadOwner({
34
33
  runtime,
35
34
  request,
@@ -56,7 +55,7 @@ async function handleStopAgent({ runtime, request, agentId, threadId }) {
56
55
  return Response.json({ error: "Thread access denied" }, { status: status && status >= 400 && status < 500 ? status : 502 });
57
56
  }
58
57
  }
59
- if (!(await require_runtime$1.resolveAgents(runtime.agents, request))[agentId]) return new Response(JSON.stringify({
58
+ if (!(await require_runtime.resolveAgents(runtime.agents, request))[agentId]) return new Response(JSON.stringify({
60
59
  error: "Agent not found",
61
60
  message: `Agent '${agentId}' does not exist`
62
61
  }), {
@@ -1 +1 @@
1
- {"version":3,"file":"handle-stop.cjs","names":["isHandlerResponse","isIntelligenceRuntime","resolveLocalThreadOwner","resolveIntelligenceUser","getPlatformErrorStatus","resolveAgents","EventType"],"sources":["../../../src/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\nimport { resolveLocalThreadOwner } from \"./shared/thread-access\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */\nasync function parseStopScope(\n request: Request,\n): Promise<{ runId?: string } | Response> {\n try {\n const raw = await request.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n // Only `runId` is allowed. A misspelt key must not fall through to a\n // thread-wide stop, because a stop cannot be undone.\n if (Object.keys(body).some((key) => key !== \"runId\")) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n if (!(\"runId\" in body)) return {};\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n return { runId: body.runId };\n } catch {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n // Parse the optional run scope for every runtime kind, from a clone so an\n // identity callback can still read the original body. No body or `{}`\n // keeps the thread-wide stop existing clients rely on.\n const scope = await parseStopScope(request.clone());\n if (isHandlerResponse(scope)) return scope;\n const { runId } = scope;\n let stopThreadId = threadId;\n let ownerId: string | undefined;\n if (!isIntelligenceRuntime(runtime)) {\n // A run on another identity's thread reports \"no active run\".\n const owner = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"stop\",\n });\n if (isHandlerResponse(owner)) return owner;\n ownerId = owner;\n } else {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message:\n runId === undefined\n ? `No active run for thread '${threadId}'.`\n : `Run '${runId}' is not the active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAgBA,eAAe,eACb,SACwC;AACxC,KAAI;EACF,MAAM,MAAM,MAAM,QAAQ,MAAM;EAChC,MAAM,OAAgB,IAAI,MAAM,GAAG,KAAK,MAAM,IAAI,GAAG,EAAE;AACvD,MAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,KAAK,CAClE,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAI1E,MAAI,OAAO,KAAK,KAAK,CAAC,MAAM,QAAQ,QAAQ,QAAQ,CAClD,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAE1E,MAAI,EAAE,WAAW,MAAO,QAAO,EAAE;AACjC,MAAI,OAAO,KAAK,UAAU,YAAY,CAAC,KAAK,MAAM,MAAM,CACtD,QAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAEnE,SAAO,EAAE,OAAO,KAAK,OAAO;SACtB;AACN,SAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;;;;AAK5E,eAAsB,gBAAgB,EACpC,SACA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UAAU,SAAY,EAAE,GAAG,EAAE,OAAO;GACxC,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAC7C,CAAC,CAGA,QAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,SACE,UAAU,SACN,6BAA6B,SAAS,MACtC,QAAQ,MAAM,sCAAsC,SAAS;GACpE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAGH,SAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,WAAW;IACT,MAAMC,wBAAU;IAChB,SAAS;IACT,MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"handle-stop.cjs","names":["isHandlerResponse","isIntelligenceRuntime","resolveLocalThreadOwner","resolveIntelligenceUser","getPlatformErrorStatus","resolveAgents","EventType"],"sources":["../../../src/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\nimport { resolveLocalThreadOwner } from \"./shared/thread-access\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */\nasync function parseStopScope(\n request: Request,\n): Promise<{ runId?: string } | Response> {\n try {\n const raw = await request.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n // Only `runId` is allowed. A misspelt key must not fall through to a\n // thread-wide stop, because a stop cannot be undone.\n if (Object.keys(body).some((key) => key !== \"runId\")) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n if (!(\"runId\" in body)) return {};\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n return { runId: body.runId };\n } catch {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n // Parse the optional run scope for every runtime kind, from a clone so an\n // identity callback can still read the original body. No body or `{}`\n // keeps the thread-wide stop existing clients rely on.\n const scope = await parseStopScope(request.clone());\n if (isHandlerResponse(scope)) return scope;\n const { runId } = scope;\n let stopThreadId = threadId;\n let ownerId: string | undefined;\n if (!isIntelligenceRuntime(runtime)) {\n // A run on another identity's thread reports \"no active run\".\n const owner = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"stop\",\n });\n if (isHandlerResponse(owner)) return owner;\n ownerId = owner;\n } else {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message:\n runId === undefined\n ? `No active run for thread '${threadId}'.`\n : `Run '${runId}' is not the active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;AAgBA,eAAe,eACb,SACwC;AACxC,KAAI;EACF,MAAM,MAAM,MAAM,QAAQ,MAAM;EAChC,MAAM,OAAgB,IAAI,MAAM,GAAG,KAAK,MAAM,IAAI,GAAG,EAAE;AACvD,MAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,KAAK,CAClE,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAI1E,MAAI,OAAO,KAAK,KAAK,CAAC,MAAM,QAAQ,QAAQ,QAAQ,CAClD,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAA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wB,EACjC,EAAE,QAAQ,UAAU,UAAU,OAAO,SAAS,MAAM,SAAS,KAAK,CACnE;;;AAKL,MAAI,EAFW,MAAMC,8BAAc,QAAQ,QAAQ,QAAQ,EAE/C,SACV,QAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,UAAU,QAAQ;GAC5B,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AASH,MAAI,CANY,MAAM,QAAQ,OAAO,KAAK;GACxC,UAAU;GACV,GAAI,UAAU,SAAY,EAAE,GAAG,EAAE,OAAO;GACxC,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAC7C,CAAC,CAGA,QAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,SACE,UAAU,SACN,6BAA6B,SAAS,MACtC,QAAQ,MAAM,sCAAsC,SAAS;GACpE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAGH,SAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,WAAW;IACT,MAAMC,wBAAU;IAChB,SAAS;IACT,MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -1,4 +1,3 @@
1
- const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
2
1
  const require_header_utils = require('./header-utils.cjs');
3
2
  const require_agent_utils = require('./shared/agent-utils.cjs');
4
3
  const require_sse_response = require('./shared/sse-response.cjs');
@@ -1 +1 @@
1
- {"version":3,"file":"handle-suggest.cjs","names":["cloneAgentForRequest","parseRunRequest","mergeForwardableHeaders","resolveForwardHeadersPolicy","createSseEventResponse","Observable"],"sources":["../../../src/runtime/handlers/handle-suggest.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent } from \"@ag-ui/client\";\nimport { createRunEventFinalizer } from \"@copilotkit/shared\";\nimport { Observable } from \"rxjs\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"./header-utils\";\nimport { cloneAgentForRequest, parseRunRequest } from \"./shared/agent-utils\";\nimport { createSseEventResponse } from \"./shared/sse-response\";\n\n/**\n * Parameters for {@link handleSuggestAgent}.\n */\ninterface SuggestAgentParameters {\n /** The runtime whose registry the agent is resolved from. */\n runtime: CopilotRuntimeLike;\n /** The incoming `POST /agent/:agentId/suggest` request. */\n request: Request;\n /** The route-resolved agent id to run. */\n agentId: string;\n}\n\n/**\n * Stateless suggestion run.\n *\n * Executes the provider agent **directly** and streams its AG-UI events back as\n * SSE — the same wire format as `/agent/:id/run`, so the client consumes it with\n * the stock `HttpAgent` transport and chips fill in as the provider emits them.\n * It deliberately does not go through `runtime.runner`: the runner's\n * `run()` writes to a module-level store keyed by threadId (backing the SSE\n * runtime's local thread endpoints), which would leak the throwaway suggestion\n * thread. This handler runs the agent's event pipeline **without** that\n * persistence — no thread, lock, gateway, name-gen, or run telemetry — so\n * dynamic suggestions are side-effect-free in every runtime mode.\n *\n * The only per-request configuration it applies is forwarding the request's\n * allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does\n * **not** attach any request middleware — no A2UI, no MCPApps, no\n * OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**\n * (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the\n * request body; this handler does not set tool choice itself and relies on it\n * being present in the incoming `input`. Given that forced tool choice, any\n * middleware-injected tools are dead weight, and MCPApps setup can incur a\n * `listTools` network round-trip per suggestion under `available: \"always\"` — a\n * side effect this path must never pay.\n *\n * When the client aborts the HTTP request (via its `AbortController`), the\n * server-side run is cancelled best-effort so an aborted suggestion does not\n * keep running a provider call to completion.\n *\n * @param params - The runtime, request, and resolved agent id.\n * @returns A `text/event-stream` `Response` of the provider agent's AG-UI events\n * on success, or the resolution `Response` (e.g. 404/400) when agent/body\n * resolution fails before streaming begins.\n */\nexport async function handleSuggestAgent({\n runtime,\n request,\n agentId,\n}: SuggestAgentParameters): Promise<Response> {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Carry the registry key onto the clone so any framework relying on it during\n // the run sees the correct agentId.\n agent.agentId = agentId;\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // Forward eligible inbound headers onto the clone under the runtime's resolved\n // forwarding policy (same helper the run handler uses: `authorization` /\n // custom `x-*`, infra/proxy/platform headers denylisted, server-set headers\n // winning on collision — #5712). Unlike a full agent run, the suggest path\n // intentionally attaches no middleware (see the handler docblock): the forced\n // `copilotkitSuggest` tool choice makes any middleware-injected tools dead\n // weight, and MCPApps setup can trigger a `listTools` network round-trip we\n // must never incur per suggestion.\n //\n // `AbstractAgent` doesn't declare `headers` on its base type (concrete\n // framework agents add it), so narrow to the header-carrying shape rather\n // than casting to `any`.\n const headerCarryingAgent = agent as AbstractAgent & {\n headers?: Record<string, string>;\n };\n headerCarryingAgent.headers = mergeForwardableHeaders(\n headerCarryingAgent.headers,\n request,\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n // Stream the provider agent's events over SSE without persistence. This is\n // the runner's event pipeline (`agent.runAgent({ onEvent })` + terminal-event\n // finalization) minus the `GLOBAL_STORE` writes that would leak a thread.\n // `captureTelemetry: false` keeps suggestions out of run telemetry; omitting\n // `debugEventBus` keeps them out of the inspector's run trace.\n return createSseEventResponse({\n request,\n agentId,\n captureTelemetry: false,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n new Observable<BaseEvent>((subscriber) => {\n // Tracks open message/tool lifecycles so the missing terminal events\n // (an unclosed message/tool call, or a `RUN_FINISHED`) can be appended\n // — the same closure the runner applies — so the client sees a\n // well-formed AG-UI sequence. Nothing is persisted here, so only the\n // open ids are kept, never the streamed events themselves.\n const finalizer = createRunEventFinalizer();\n let settled = false;\n\n void agent\n .runAgent(input, {\n onEvent: ({ event }) => {\n finalizer.observe(event);\n subscriber.next(event);\n },\n })\n .then(() => {\n for (const event of finalizer.finalize({ stopRequested: false })) {\n subscriber.next(event);\n }\n settled = true;\n subscriber.complete();\n })\n .catch((error: unknown) => {\n settled = true;\n subscriber.error(error);\n });\n\n // Teardown fires when the response stream is torn down (client abort /\n // disconnect). Cancel the still-running provider call best-effort.\n return () => {\n if (!settled && typeof agent.abortRun === \"function\") {\n try {\n agent.abortRun();\n } catch {\n // best-effort — nothing actionable if aborting the run fails.\n }\n }\n };\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,eAAsB,mBAAmB,EACvC,SACA,SACA,WAC4C;CAC5C,MAAM,QAAQ,MAAMA,yCAAqB,SAAS,SAAS,QAAQ;AACnE,KAAI,iBAAiB,SACnB,QAAO;AAKT,OAAM,UAAU;CAEhB,MAAM,QAAQ,MAAMC,oCAAgB,QAAQ;AAC5C,KAAI,iBAAiB,SACnB,QAAO;CAeT,MAAM,sBAAsB;AAG5B,qBAAoB,UAAUC,6CAC5B,oBAAoB,SACpB,SACA,QAAQ,wBAAwBC,iDAA4B,OAAU,CACvE;AAED,OAAM,YAAY,MAAM,SAAS;AACjC,OAAM,SAAS,MAAM,MAAM;AAC3B,OAAM,WAAW,MAAM;AAOvB,QAAOC,4CAAuB;EAC5B;EACA;EACA,kBAAkB;EAClB,0BAA0B,QAAQ;EAClC,yBACE,IAAIC,iBAAuB,eAAe;GAMxC,MAAM,6DAAqC;GAC3C,IAAI,UAAU;AAEd,GAAK,MACF,SAAS,OAAO,EACf,UAAU,EAAE,YAAY;AACtB,cAAU,QAAQ,MAAM;AACxB,eAAW,KAAK,MAAM;MAEzB,CAAC,CACD,WAAW;AACV,SAAK,MAAM,SAAS,UAAU,SAAS,EAAE,eAAe,OAAO,CAAC,CAC9D,YAAW,KAAK,MAAM;AAExB,cAAU;AACV,eAAW,UAAU;KACrB,CACD,OAAO,UAAmB;AACzB,cAAU;AACV,eAAW,MAAM,MAAM;KACvB;AAIJ,gBAAa;AACX,QAAI,CAAC,WAAW,OAAO,MAAM,aAAa,WACxC,KAAI;AACF,WAAM,UAAU;YACV;;IAKZ;EACL,CAAC"}
1
+ {"version":3,"file":"handle-suggest.cjs","names":["cloneAgentForRequest","parseRunRequest","mergeForwardableHeaders","resolveForwardHeadersPolicy","createSseEventResponse","Observable"],"sources":["../../../src/runtime/handlers/handle-suggest.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent } from \"@ag-ui/client\";\nimport { createRunEventFinalizer } from \"@copilotkit/shared\";\nimport { Observable } from \"rxjs\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"./header-utils\";\nimport { cloneAgentForRequest, parseRunRequest } from \"./shared/agent-utils\";\nimport { createSseEventResponse } from \"./shared/sse-response\";\n\n/**\n * Parameters for {@link handleSuggestAgent}.\n */\ninterface SuggestAgentParameters {\n /** The runtime whose registry the agent is resolved from. */\n runtime: CopilotRuntimeLike;\n /** The incoming `POST /agent/:agentId/suggest` request. */\n request: Request;\n /** The route-resolved agent id to run. */\n agentId: string;\n}\n\n/**\n * Stateless suggestion run.\n *\n * Executes the provider agent **directly** and streams its AG-UI events back as\n * SSE — the same wire format as `/agent/:id/run`, so the client consumes it with\n * the stock `HttpAgent` transport and chips fill in as the provider emits them.\n * It deliberately does not go through `runtime.runner`: the runner's\n * `run()` writes to a module-level store keyed by threadId (backing the SSE\n * runtime's local thread endpoints), which would leak the throwaway suggestion\n * thread. This handler runs the agent's event pipeline **without** that\n * persistence — no thread, lock, gateway, name-gen, or run telemetry — so\n * dynamic suggestions are side-effect-free in every runtime mode.\n *\n * The only per-request configuration it applies is forwarding the request's\n * allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does\n * **not** attach any request middleware — no A2UI, no MCPApps, no\n * OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**\n * (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the\n * request body; this handler does not set tool choice itself and relies on it\n * being present in the incoming `input`. Given that forced tool choice, any\n * middleware-injected tools are dead weight, and MCPApps setup can incur a\n * `listTools` network round-trip per suggestion under `available: \"always\"` — a\n * side effect this path must never pay.\n *\n * When the client aborts the HTTP request (via its `AbortController`), the\n * server-side run is cancelled best-effort so an aborted suggestion does not\n * keep running a provider call to completion.\n *\n * @param params - The runtime, request, and resolved agent id.\n * @returns A `text/event-stream` `Response` of the provider agent's AG-UI events\n * on success, or the resolution `Response` (e.g. 404/400) when agent/body\n * resolution fails before streaming begins.\n */\nexport async function handleSuggestAgent({\n runtime,\n request,\n agentId,\n}: SuggestAgentParameters): Promise<Response> {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Carry the registry key onto the clone so any framework relying on it during\n // the run sees the correct agentId.\n agent.agentId = agentId;\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // Forward eligible inbound headers onto the clone under the runtime's resolved\n // forwarding policy (same helper the run handler uses: `authorization` /\n // custom `x-*`, infra/proxy/platform headers denylisted, server-set headers\n // winning on collision — #5712). Unlike a full agent run, the suggest path\n // intentionally attaches no middleware (see the handler docblock): the forced\n // `copilotkitSuggest` tool choice makes any middleware-injected tools dead\n // weight, and MCPApps setup can trigger a `listTools` network round-trip we\n // must never incur per suggestion.\n //\n // `AbstractAgent` doesn't declare `headers` on its base type (concrete\n // framework agents add it), so narrow to the header-carrying shape rather\n // than casting to `any`.\n const headerCarryingAgent = agent as AbstractAgent & {\n headers?: Record<string, string>;\n };\n headerCarryingAgent.headers = mergeForwardableHeaders(\n headerCarryingAgent.headers,\n request,\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n // Stream the provider agent's events over SSE without persistence. This is\n // the runner's event pipeline (`agent.runAgent({ onEvent })` + terminal-event\n // finalization) minus the `GLOBAL_STORE` writes that would leak a thread.\n // `captureTelemetry: false` keeps suggestions out of run telemetry; omitting\n // `debugEventBus` keeps them out of the inspector's run trace.\n return createSseEventResponse({\n request,\n agentId,\n captureTelemetry: false,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n new Observable<BaseEvent>((subscriber) => {\n // Tracks open message/tool lifecycles so the missing terminal events\n // (an unclosed message/tool call, or a `RUN_FINISHED`) can be appended\n // — the same closure the runner applies — so the client sees a\n // well-formed AG-UI sequence. Nothing is persisted here, so only the\n // open ids are kept, never the streamed events themselves.\n const finalizer = createRunEventFinalizer();\n let settled = false;\n\n void agent\n .runAgent(input, {\n onEvent: ({ event }) => {\n finalizer.observe(event);\n subscriber.next(event);\n },\n })\n .then(() => {\n for (const event of finalizer.finalize({ stopRequested: false })) {\n subscriber.next(event);\n }\n settled = true;\n subscriber.complete();\n })\n .catch((error: unknown) => {\n settled = true;\n subscriber.error(error);\n });\n\n // Teardown fires when the response stream is torn down (client abort /\n // disconnect). Cancel the still-running provider call best-effort.\n return () => {\n if (!settled && typeof agent.abortRun === \"function\") {\n try {\n agent.abortRun();\n } catch {\n // best-effort — nothing actionable if aborting the run fails.\n }\n }\n };\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,eAAsB,mBAAmB,EACvC,SACA,SACA,WAC4C;CAC5C,MAAM,QAAQ,MAAMA,yCAAqB,SAAS,SAAS,QAAQ;AACnE,KAAI,iBAAiB,SACnB,QAAO;AAKT,OAAM,UAAU;CAEhB,MAAM,QAAQ,MAAMC,oCAAgB,QAAQ;AAC5C,KAAI,iBAAiB,SACnB,QAAO;CAeT,MAAM,sBAAsB;AAG5B,qBAAoB,UAAUC,6CAC5B,oBAAoB,SACpB,SACA,QAAQ,wBAAwBC,iDAA4B,OAAU,CACvE;AAED,OAAM,YAAY,MAAM,SAAS;AACjC,OAAM,SAAS,MAAM,MAAM;AAC3B,OAAM,WAAW,MAAM;AAOvB,QAAOC,4CAAuB;EAC5B;EACA;EACA,kBAAkB;EAClB,0BAA0B,QAAQ;EAClC,yBACE,IAAIC,iBAAuB,eAAe;GAMxC,MAAM,6DAAqC;GAC3C,IAAI,UAAU;AAEd,GAAK,MACF,SAAS,OAAO,EACf,UAAU,EAAE,YAAY;AACtB,cAAU,QAAQ,MAAM;AACxB,eAAW,KAAK,MAAM;MAEzB,CAAC,CACD,WAAW;AACV,SAAK,MAAM,SAAS,UAAU,SAAS,EAAE,eAAe,OAAO,CAAC,CAC9D,YAAW,KAAK,MAAM;AAExB,cAAU;AACV,eAAW,UAAU;KACrB,CACD,OAAO,UAAmB;AACzB,cAAU;AACV,eAAW,MAAM,MAAM;KACvB;AAIJ,gBAAa;AACX,QAAI,CAAC,WAAW,OAAO,MAAM,aAAa,WACxC,KAAI;AACF,WAAM,UAAU;YACV;;IAKZ;EACL,CAAC"}
@@ -1,4 +1,3 @@
1
- const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
2
1
  let _copilotkit_shared = require("@copilotkit/shared");
3
2
 
4
3
  //#region src/runtime/handlers/handle-transcribe.ts
@@ -1 +1 @@
1
- {"version":3,"file":"handle-transcribe.cjs","names":["TranscriptionErrorCode","TranscriptionErrors"],"sources":["../../../src/runtime/handlers/handle-transcribe.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n TranscriptionErrorCode,\n TranscriptionErrors,\n} from \"@copilotkit/shared\";\nimport type { TranscriptionErrorResponse } from \"@copilotkit/shared\";\n\n/**\n * HTTP status codes for transcription error codes\n */\nconst ERROR_STATUS_CODES: Record<TranscriptionErrorCode, number> = {\n [TranscriptionErrorCode.SERVICE_NOT_CONFIGURED]: 503,\n [TranscriptionErrorCode.INVALID_AUDIO_FORMAT]: 400,\n [TranscriptionErrorCode.AUDIO_TOO_LONG]: 400,\n [TranscriptionErrorCode.AUDIO_TOO_SHORT]: 400,\n [TranscriptionErrorCode.RATE_LIMITED]: 429,\n [TranscriptionErrorCode.AUTH_FAILED]: 401,\n [TranscriptionErrorCode.PROVIDER_ERROR]: 500,\n [TranscriptionErrorCode.NETWORK_ERROR]: 502,\n [TranscriptionErrorCode.INVALID_REQUEST]: 400,\n};\n\ninterface HandleTranscribeParameters {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface Base64AudioInput {\n audio: string; // base64-encoded audio data\n mimeType: string;\n filename?: string;\n}\n\nconst VALID_AUDIO_TYPES = [\n \"audio/mpeg\",\n \"audio/mp3\",\n \"audio/mp4\",\n \"audio/wav\",\n \"audio/webm\",\n \"audio/ogg\",\n \"audio/flac\",\n \"audio/aac\",\n];\n\nfunction isValidAudioType(type: string): boolean {\n // Extract base MIME type (before semicolon) to handle types like \"audio/webm; codecs=opus\"\n const baseType = type.split(\";\")[0]?.trim() ?? \"\";\n return (\n VALID_AUDIO_TYPES.includes(baseType) ||\n baseType === \"\" ||\n baseType === \"application/octet-stream\"\n );\n}\n\nfunction createErrorResponse(\n errorResponse: TranscriptionErrorResponse,\n): Response {\n const status = ERROR_STATUS_CODES[errorResponse.error] ?? 500;\n return new Response(JSON.stringify(errorResponse), {\n status,\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n\nfunction base64ToFile(\n base64: string,\n mimeType: string,\n filename: string,\n): File {\n // Remove data URL prefix if present (e.g., \"data:audio/webm;base64,\")\n const base64Data = base64.includes(\",\")\n ? (base64.split(\",\")[1] ?? base64)\n : base64;\n\n // Decode base64 to binary\n const binaryString = atob(base64Data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n\n // Create File object\n return new File([bytes], filename, { type: mimeType });\n}\n\nasync function extractAudioFromFormData(\n request: Request,\n): Promise<{ file: File } | { error: Response }> {\n const formData = await request.formData();\n let audioFile = formData.get(\"audio\") as File | null;\n\n if (!audioFile || !(audioFile instanceof File)) {\n const err = TranscriptionErrors.invalidRequest(\n \"No audio file found in form data. Please include an 'audio' field.\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!isValidAudioType(audioFile.type)) {\n const err = TranscriptionErrors.invalidAudioFormat(\n audioFile.type,\n VALID_AUDIO_TYPES,\n );\n return { error: createErrorResponse(err) };\n }\n\n // Browser MediaRecorder Blobs often arrive at the server with their\n // `type` field empty (and `application/octet-stream` is also accepted by\n // isValidAudioType for compatibility). OpenAI Whisper rejects files\n // without a recognizable MIME / extension with a 502 \"Invalid file\n // format\" — even though the bytes themselves are valid WebM Opus.\n // Stamp `audio/webm` (the standard MediaRecorder default in Chromium /\n // Firefox / Safari) so Whisper can pick the right decoder.\n if (!audioFile.type || audioFile.type === \"application/octet-stream\") {\n audioFile = new File([audioFile], audioFile.name || \"recording.webm\", {\n type: \"audio/webm\",\n });\n }\n\n return { file: audioFile };\n}\n\nasync function extractAudioFromJson(\n request: Request,\n): Promise<{ file: File } | { error: Response }> {\n let body: Base64AudioInput;\n\n try {\n body = await request.json();\n } catch {\n const err = TranscriptionErrors.invalidRequest(\n \"Request body must be valid JSON\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!body.audio || typeof body.audio !== \"string\") {\n const err = TranscriptionErrors.invalidRequest(\n \"Request must include 'audio' field with base64-encoded audio data\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!body.mimeType || typeof body.mimeType !== \"string\") {\n const err = TranscriptionErrors.invalidRequest(\n \"Request must include 'mimeType' field (e.g., 'audio/webm')\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!isValidAudioType(body.mimeType)) {\n const err = TranscriptionErrors.invalidAudioFormat(\n body.mimeType,\n VALID_AUDIO_TYPES,\n );\n return { error: createErrorResponse(err) };\n }\n\n try {\n const filename = body.filename || \"recording.webm\";\n const file = base64ToFile(body.audio, body.mimeType, filename);\n return { file };\n } catch {\n const err = TranscriptionErrors.invalidRequest(\n \"Failed to decode base64 audio data\",\n );\n return { error: createErrorResponse(err) };\n }\n}\n\n/**\n * Categorize provider errors into appropriate transcription error responses.\n */\nfunction categorizeProviderError(error: unknown): TranscriptionErrorResponse {\n const message =\n error instanceof Error ? error.message : \"Unknown error occurred\";\n const errorStr = String(error).toLowerCase();\n\n // Check for rate limiting\n if (\n errorStr.includes(\"rate\") ||\n errorStr.includes(\"429\") ||\n errorStr.includes(\"too many\")\n ) {\n return TranscriptionErrors.rateLimited();\n }\n\n // Check for auth errors\n if (\n errorStr.includes(\"auth\") ||\n errorStr.includes(\"401\") ||\n errorStr.includes(\"api key\") ||\n errorStr.includes(\"unauthorized\")\n ) {\n return TranscriptionErrors.authFailed();\n }\n\n // Check for audio too long\n if (\n errorStr.includes(\"too long\") ||\n errorStr.includes(\"duration\") ||\n errorStr.includes(\"length\")\n ) {\n return TranscriptionErrors.audioTooLong();\n }\n\n // Default to provider error\n return TranscriptionErrors.providerError(message);\n}\n\nexport async function handleTranscribe({\n runtime,\n request,\n}: HandleTranscribeParameters) {\n try {\n // Check if transcription service is configured\n if (!runtime.transcriptionService) {\n const err = TranscriptionErrors.serviceNotConfigured();\n return createErrorResponse(err);\n }\n\n // Determine input type based on content-type header\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n let extractResult: { file: File } | { error: Response };\n\n if (contentType.includes(\"multipart/form-data\")) {\n // Handle multipart/form-data (REST mode)\n extractResult = await extractAudioFromFormData(request);\n } else if (contentType.includes(\"application/json\")) {\n // Handle JSON with base64 audio (single-endpoint mode)\n extractResult = await extractAudioFromJson(request);\n } else {\n const err = TranscriptionErrors.invalidRequest(\n \"Request must be multipart/form-data or application/json with base64 audio\",\n );\n return createErrorResponse(err);\n }\n\n // Check for extraction errors\n if (\"error\" in extractResult) {\n return extractResult.error;\n }\n\n const audioFile = extractResult.file;\n\n // Transcribe the audio file\n const transcription = await runtime.transcriptionService.transcribeFile({\n audioFile,\n mimeType: audioFile.type,\n size: audioFile.size,\n });\n\n return new Response(\n JSON.stringify({\n text: transcription,\n size: audioFile.size,\n type: audioFile.type,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n // Categorize the error for better client-side handling\n return createErrorResponse(categorizeProviderError(error));\n }\n}\n"],"mappings":";;;;;;;AAUA,MAAM,qBAA6D;EAChEA,0CAAuB,yBAAyB;EAChDA,0CAAuB,uBAAuB;EAC9CA,0CAAuB,iBAAiB;EACxCA,0CAAuB,kBAAkB;EACzCA,0CAAuB,eAAe;EACtCA,0CAAuB,cAAc;EACrCA,0CAAuB,iBAAiB;EACxCA,0CAAuB,gBAAgB;EACvCA,0CAAuB,kBAAkB;CAC3C;AAaD,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,SAAS,iBAAiB,MAAuB;CAE/C,MAAM,WAAW,KAAK,MAAM,IAAI,CAAC,IAAI,MAAM,IAAI;AAC/C,QACE,kBAAkB,SAAS,SAAS,IACpC,aAAa,MACb,aAAa;;AAIjB,SAAS,oBACP,eACU;CACV,MAAM,SAAS,mBAAmB,cAAc,UAAU;AAC1D,QAAO,IAAI,SAAS,KAAK,UAAU,cAAc,EAAE;EACjD;EACA,SAAS,EAAE,gBAAgB,oBAAoB;EAChD,CAAC;;AAGJ,SAAS,aACP,QACA,UACA,UACM;CAEN,MAAM,aAAa,OAAO,SAAS,IAAI,GAClC,OAAO,MAAM,IAAI,CAAC,MAAM,SACzB;CAGJ,MAAM,eAAe,KAAK,WAAW;CACrC,MAAM,QAAQ,IAAI,WAAW,aAAa,OAAO;AACj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GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AAEd,SAAO,oBAAoB,wBAAwB,MAAM,CAAC"}
1
+ {"version":3,"file":"handle-transcribe.cjs","names":["TranscriptionErrorCode","TranscriptionErrors"],"sources":["../../../src/runtime/handlers/handle-transcribe.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n TranscriptionErrorCode,\n TranscriptionErrors,\n} from \"@copilotkit/shared\";\nimport type { TranscriptionErrorResponse } from \"@copilotkit/shared\";\n\n/**\n * HTTP status codes for transcription error codes\n */\nconst ERROR_STATUS_CODES: Record<TranscriptionErrorCode, number> = {\n [TranscriptionErrorCode.SERVICE_NOT_CONFIGURED]: 503,\n [TranscriptionErrorCode.INVALID_AUDIO_FORMAT]: 400,\n [TranscriptionErrorCode.AUDIO_TOO_LONG]: 400,\n [TranscriptionErrorCode.AUDIO_TOO_SHORT]: 400,\n [TranscriptionErrorCode.RATE_LIMITED]: 429,\n [TranscriptionErrorCode.AUTH_FAILED]: 401,\n [TranscriptionErrorCode.PROVIDER_ERROR]: 500,\n [TranscriptionErrorCode.NETWORK_ERROR]: 502,\n [TranscriptionErrorCode.INVALID_REQUEST]: 400,\n};\n\ninterface HandleTranscribeParameters {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface Base64AudioInput {\n audio: string; // base64-encoded audio data\n mimeType: string;\n filename?: string;\n}\n\nconst VALID_AUDIO_TYPES = [\n \"audio/mpeg\",\n \"audio/mp3\",\n \"audio/mp4\",\n \"audio/wav\",\n \"audio/webm\",\n \"audio/ogg\",\n \"audio/flac\",\n \"audio/aac\",\n];\n\nfunction isValidAudioType(type: string): boolean {\n // Extract base MIME type (before semicolon) to handle types like \"audio/webm; codecs=opus\"\n const baseType = type.split(\";\")[0]?.trim() ?? \"\";\n return (\n VALID_AUDIO_TYPES.includes(baseType) ||\n baseType === \"\" ||\n baseType === \"application/octet-stream\"\n );\n}\n\nfunction createErrorResponse(\n errorResponse: TranscriptionErrorResponse,\n): Response {\n const status = ERROR_STATUS_CODES[errorResponse.error] ?? 500;\n return new Response(JSON.stringify(errorResponse), {\n status,\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n\nfunction base64ToFile(\n base64: string,\n mimeType: string,\n filename: string,\n): File {\n // Remove data URL prefix if present (e.g., \"data:audio/webm;base64,\")\n const base64Data = base64.includes(\",\")\n ? (base64.split(\",\")[1] ?? base64)\n : base64;\n\n // Decode base64 to binary\n const binaryString = atob(base64Data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n\n // Create File object\n return new File([bytes], filename, { type: mimeType });\n}\n\nasync function extractAudioFromFormData(\n request: Request,\n): Promise<{ file: File } | { error: Response }> {\n const formData = await request.formData();\n let audioFile = formData.get(\"audio\") as File | null;\n\n if (!audioFile || !(audioFile instanceof File)) {\n const err = TranscriptionErrors.invalidRequest(\n \"No audio file found in form data. Please include an 'audio' field.\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!isValidAudioType(audioFile.type)) {\n const err = TranscriptionErrors.invalidAudioFormat(\n audioFile.type,\n VALID_AUDIO_TYPES,\n );\n return { error: createErrorResponse(err) };\n }\n\n // Browser MediaRecorder Blobs often arrive at the server with their\n // `type` field empty (and `application/octet-stream` is also accepted by\n // isValidAudioType for compatibility). OpenAI Whisper rejects files\n // without a recognizable MIME / extension with a 502 \"Invalid file\n // format\" — even though the bytes themselves are valid WebM Opus.\n // Stamp `audio/webm` (the standard MediaRecorder default in Chromium /\n // Firefox / Safari) so Whisper can pick the right decoder.\n if (!audioFile.type || audioFile.type === \"application/octet-stream\") {\n audioFile = new File([audioFile], audioFile.name || \"recording.webm\", {\n type: \"audio/webm\",\n });\n }\n\n return { file: audioFile };\n}\n\nasync function extractAudioFromJson(\n request: Request,\n): Promise<{ file: File } | { error: Response }> {\n let body: Base64AudioInput;\n\n try {\n body = await request.json();\n } catch {\n const err = TranscriptionErrors.invalidRequest(\n \"Request body must be valid JSON\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!body.audio || typeof body.audio !== \"string\") {\n const err = TranscriptionErrors.invalidRequest(\n \"Request must include 'audio' field with base64-encoded audio data\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!body.mimeType || typeof body.mimeType !== \"string\") {\n const err = TranscriptionErrors.invalidRequest(\n \"Request must include 'mimeType' field (e.g., 'audio/webm')\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!isValidAudioType(body.mimeType)) {\n const err = TranscriptionErrors.invalidAudioFormat(\n body.mimeType,\n VALID_AUDIO_TYPES,\n );\n return { error: createErrorResponse(err) };\n }\n\n try {\n const filename = body.filename || \"recording.webm\";\n const file = base64ToFile(body.audio, body.mimeType, filename);\n return { file };\n } catch {\n const err = TranscriptionErrors.invalidRequest(\n \"Failed to decode base64 audio data\",\n );\n return { error: createErrorResponse(err) };\n }\n}\n\n/**\n * Categorize provider errors into appropriate transcription error responses.\n */\nfunction categorizeProviderError(error: unknown): TranscriptionErrorResponse {\n const message =\n error instanceof Error ? error.message : \"Unknown error occurred\";\n const errorStr = String(error).toLowerCase();\n\n // Check for rate limiting\n if (\n errorStr.includes(\"rate\") ||\n errorStr.includes(\"429\") ||\n errorStr.includes(\"too many\")\n ) {\n return TranscriptionErrors.rateLimited();\n }\n\n // Check for auth errors\n if (\n errorStr.includes(\"auth\") ||\n errorStr.includes(\"401\") ||\n errorStr.includes(\"api key\") ||\n errorStr.includes(\"unauthorized\")\n ) {\n return TranscriptionErrors.authFailed();\n }\n\n // Check for audio too long\n if (\n errorStr.includes(\"too long\") ||\n errorStr.includes(\"duration\") ||\n errorStr.includes(\"length\")\n ) {\n return TranscriptionErrors.audioTooLong();\n }\n\n // Default to provider error\n return TranscriptionErrors.providerError(message);\n}\n\nexport async function handleTranscribe({\n runtime,\n request,\n}: HandleTranscribeParameters) {\n try {\n // Check if transcription service is configured\n if (!runtime.transcriptionService) {\n const err = TranscriptionErrors.serviceNotConfigured();\n return createErrorResponse(err);\n }\n\n // Determine input type based on content-type header\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n let extractResult: { file: File } | { error: Response };\n\n if (contentType.includes(\"multipart/form-data\")) {\n // Handle multipart/form-data (REST mode)\n extractResult = await extractAudioFromFormData(request);\n } else if (contentType.includes(\"application/json\")) {\n // Handle JSON with base64 audio (single-endpoint mode)\n extractResult = await extractAudioFromJson(request);\n } else {\n const err = TranscriptionErrors.invalidRequest(\n \"Request must be multipart/form-data or application/json with base64 audio\",\n );\n return createErrorResponse(err);\n }\n\n // Check for extraction errors\n if (\"error\" in extractResult) {\n return extractResult.error;\n }\n\n const audioFile = extractResult.file;\n\n // Transcribe the audio file\n const transcription = await runtime.transcriptionService.transcribeFile({\n audioFile,\n mimeType: audioFile.type,\n size: audioFile.size,\n });\n\n return new Response(\n JSON.stringify({\n text: transcription,\n size: audioFile.size,\n type: audioFile.type,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n // Categorize the error for better client-side handling\n return createErrorResponse(categorizeProviderError(error));\n }\n}\n"],"mappings":";;;;;;AAUA,MAAM,qBAA6D;EAChEA,0CAAuB,yBAAyB;EAChDA,0CAAuB,uBAAuB;EAC9CA,0CAAuB,iBAAiB;EACxCA,0CAAuB,kBAAkB;EACzCA,0CAAuB,eAAe;EACtCA,0CAAuB,cAAc;EACrCA,0CAAuB,iBAAiB;EACxCA,0CAAuB,gBAAgB;EACvCA,0CAAuB,kBAAkB;CAC3C;AAaD,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,SAAS,iBAAiB,MAAuB;CAE/C,MAAM,WAAW,KAAK,MAAM,IAAI,CAAC,IAAI,MAAM,IAAI;AAC/C,QACE,kBAAkB,SAAS,SAAS,IACpC,aAAa,MACb,aAAa;;AAIjB,SAAS,oBACP,eACU;CACV,MAAM,SAAS,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MAKnD,QAAO,oBAHKA,uCAAoB,eAC9B,4EACD,CAC8B;AAIjC,MAAI,WAAW,cACb,QAAO,cAAc;EAGvB,MAAM,YAAY,cAAc;EAGhC,MAAM,gBAAgB,MAAM,QAAQ,qBAAqB,eAAe;GACtE;GACA,UAAU,UAAU;GACpB,MAAM,UAAU;GACjB,CAAC;AAEF,SAAO,IAAI,SACT,KAAK,UAAU;GACb,MAAM;GACN,MAAM,UAAU;GAChB,MAAM,UAAU;GACjB,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AAEd,SAAO,oBAAoB,wBAAwB,MAAM,CAAC"}
@@ -1,8 +1,7 @@
1
- const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
2
1
  const require_json_response = require('../shared/json-response.cjs');
3
2
  const require_client = require('../../intelligence-platform/client.cjs');
4
3
  const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
5
- const require_runtime$1 = require('../../core/runtime.cjs');
4
+ const require_runtime = require('../../core/runtime.cjs');
6
5
  let _copilotkit_shared = require("@copilotkit/shared");
7
6
 
8
7
  //#region src/runtime/handlers/intelligence/annotate.ts
@@ -15,7 +14,7 @@ async function parseJsonBody(request) {
15
14
  }
16
15
  }
17
16
  function requireIntelligenceRuntime(runtime) {
18
- if (!require_runtime$1.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
17
+ if (!require_runtime.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
19
18
  return runtime;
20
19
  }
21
20
  function isNonEmptyString(value) {
@@ -1 +1 @@
1
- {"version":3,"file":"annotate.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","PlatformRequestError"],"sources":["../../../../src/runtime/handlers/intelligence/annotate.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface AnnotateHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface AnnotateBody {\n /** Discriminator identifying the annotation type (e.g. `\"user_action\"`). */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /** The thread the annotation is associated with. */\n threadId: string;\n /** Caller-supplied idempotency key. Optional — platform auto-generates one when absent. */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in annotate body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n return runtime;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/**\n * `POST /annotate` handler.\n *\n * Three-tier flow:\n * recordAnnotation() (frontend lib; called by useLearnFromUserAction)\n * → POST ${runtimeUrl}/annotate\n * → this handler resolves the Intel user from BFF auth\n * → intelligence.annotate(...)\n * → PUT ${apiUrl}/connector/annotate/:clientEventId\n *\n * The frontend hook may auto-generate a UUID `clientEventId` per call\n * so retries are idempotent end-to-end (the platform collapses to the\n * original row).\n */\nexport async function handleAnnotate({\n runtime,\n request,\n}: AnnotateHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;\n\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const parsed = parseAnnotateBody(body);\n if (isHandlerResponse(parsed)) return parsed;\n\n try {\n const result = await intelligenceRuntime.intelligence.annotate({\n userId: user.id,\n threadId: parsed.threadId,\n type: parsed.type,\n payload: parsed.payload,\n clientEventId: parsed.clientEventId,\n occurredAt: parsed.occurredAt,\n });\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (err) {\n logger.error({ err }, \"annotate: platform call failed\");\n // Forward the platform's HTTP status when it's a client error\n // (4xx) so the SDK author sees an actionable response instead of\n // a generic 502. 5xx and non-platform errors collapse to 502\n // (\"Bad Gateway\") because the upstream is genuinely at fault.\n if (\n err instanceof PlatformRequestError &&\n err.status >= 400 &&\n err.status < 500\n ) {\n return errorResponse(err.message, err.status);\n }\n return errorResponse(\"Failed to annotate\", 502);\n }\n}\n\nfunction parseAnnotateBody(\n body: Record<string, unknown>,\n): AnnotateBody | Response {\n if (!isNonEmptyString(body.threadId)) {\n return errorResponse(\"Valid threadId is required\", 400);\n }\n if (!isNonEmptyString(body.type)) {\n return errorResponse(\"Valid type is required\", 400);\n }\n return {\n type: body.type,\n payload: body.payload,\n threadId: body.threadId,\n clientEventId: isNonEmptyString(body.clientEventId)\n ? body.clientEventId\n : undefined,\n occurredAt: isNonEmptyString(body.occurredAt) ? body.occurredAt : undefined,\n };\n}\n"],"mappings":";;;;;;;;AA4BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAA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AAEzD,KAAI,CAAC,iBAAiB,KAAK,KAAK,CAC9B,QAAOA,oCAAc,0BAA0B,IAAI;AAErD,QAAO;EACL,MAAM,KAAK;EACX,SAAS,KAAK;EACd,UAAU,KAAK;EACf,eAAe,iBAAiB,KAAK,cAAc,GAC/C,KAAK,gBACL;EACJ,YAAY,iBAAiB,KAAK,WAAW,GAAG,KAAK,aAAa;EACnE"}
1
+ {"version":3,"file":"annotate.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","PlatformRequestError"],"sources":["../../../../src/runtime/handlers/intelligence/annotate.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface AnnotateHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface AnnotateBody {\n /** Discriminator identifying the annotation type (e.g. `\"user_action\"`). */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /** The thread the annotation is associated with. */\n threadId: string;\n /** Caller-supplied idempotency key. Optional — platform auto-generates one when absent. */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in annotate body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n return runtime;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/**\n * `POST /annotate` handler.\n *\n * Three-tier flow:\n * recordAnnotation() (frontend lib; called by useLearnFromUserAction)\n * → POST ${runtimeUrl}/annotate\n * → this handler resolves the Intel user from BFF auth\n * → intelligence.annotate(...)\n * → PUT ${apiUrl}/connector/annotate/:clientEventId\n *\n * The frontend hook may auto-generate a UUID `clientEventId` per call\n * so retries are idempotent end-to-end (the platform collapses to the\n * original row).\n */\nexport async function handleAnnotate({\n runtime,\n request,\n}: AnnotateHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;\n\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const parsed = parseAnnotateBody(body);\n if (isHandlerResponse(parsed)) return parsed;\n\n try {\n const result = await intelligenceRuntime.intelligence.annotate({\n userId: user.id,\n threadId: parsed.threadId,\n type: parsed.type,\n payload: parsed.payload,\n clientEventId: parsed.clientEventId,\n occurredAt: parsed.occurredAt,\n });\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (err) {\n logger.error({ err }, \"annotate: platform call failed\");\n // Forward the platform's HTTP status when it's a client error\n // (4xx) so the SDK author sees an actionable response instead of\n // a generic 502. 5xx and non-platform errors collapse to 502\n // (\"Bad Gateway\") because the upstream is genuinely at fault.\n if (\n err instanceof PlatformRequestError &&\n err.status >= 400 &&\n err.status < 500\n ) {\n return errorResponse(err.message, err.status);\n }\n return errorResponse(\"Failed to annotate\", 502);\n }\n}\n\nfunction parseAnnotateBody(\n body: Record<string, unknown>,\n): AnnotateBody | Response {\n if (!isNonEmptyString(body.threadId)) {\n return errorResponse(\"Valid threadId is required\", 400);\n }\n if (!isNonEmptyString(body.type)) {\n return errorResponse(\"Valid type is required\", 400);\n }\n return {\n type: body.type,\n payload: body.payload,\n threadId: body.threadId,\n clientEventId: isNonEmptyString(body.clientEventId)\n ? body.clientEventId\n : undefined,\n occurredAt: isNonEmptyString(body.occurredAt) ? body.occurredAt : undefined,\n };\n}\n"],"mappings":";;;;;;;AA4BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,kCAAkC;AAC/D,SAAOA,oCAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAACC,sCAAsB,QAAQ,CACjC,QAAOD,oCACL,+IACA,IACD;AAEH,QAAO;;AAGT,SAAS,iBAAiB,OAAiC;AACzD,QAAO,OAAO,UAAU,YAAY,MAAM,SAAS;;;;;;;;;;;;;;;;AAiBrD,eAAsB,eAAe,EACnC,SACA,WAC2C;CAC3C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAIE,wCAAkB,oBAAoB,CAAE,QAAO;CAEnD,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAIA,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAMC,0DAAwB;EACzC,SAAS;EACT;EACD,CAAC;AACF,KAAID,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,SAAS,kBAAkB,KAAK;AACtC,KAAIA,wCAAkB,OAAO,CAAE,QAAO;AAEtC,KAAI;EACF,MAAM,SAAS,MAAM,oBAAoB,aAAa,SAAS;GAC7D,QAAQ,KAAK;GACb,UAAU,OAAO;GACjB,MAAM,OAAO;GACb,SAAS,OAAO;GAChB,eAAe,OAAO;GACtB,YAAY,OAAO;GACpB,CAAC;AACF,SAAO,IAAI,SAAS,KAAK,UAAU,OAAO,EAAE;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