@copilotkit/mcp-apps-renderer 1.76.0 → 1.77.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"content-schema.d.mts","names":[],"sources":["../src/content-schema.ts"],"mappings":";;;;;AAOA;;;cAAa,4BAAA,EAA4B,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAgB7B,sBAAA,GAAyB,CAAA,CAAE,KAAA,QAC9B,4BAAA"}
1
+ {"version":3,"file":"content-schema.d.mts","names":[],"sources":["../src/content-schema.ts"],"mappings":";;;;cA8Fa,4BAAA,EAA4B,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAU7B,sBAAA,GAAyB,CAAA,CAAE,KAAA,QAC9B,4BAAA"}
@@ -1,17 +1,80 @@
1
1
  import { z } from "zod";
2
2
 
3
3
  //#region src/content-schema.ts
4
- /**
5
- * Zod schema for MCP Apps activity content (middleware 0.0.2 format). The
6
- * framework activity registries validate the activity content with this before
7
- * handing it to the renderer/session.
8
- */
9
- const MCPAppsActivityContentSchema = z.object({
10
- result: z.object({
11
- content: z.array(z.any()).optional(),
12
- structuredContent: z.any().optional(),
13
- isError: z.boolean().optional()
4
+ const looseObject = (shape) => z.object(shape).passthrough();
5
+ const metaSchema = z.record(z.string(), z.unknown());
6
+ const annotationsSchema = looseObject({
7
+ audience: z.array(z.enum(["user", "assistant"])).optional(),
8
+ priority: z.number().min(0).max(1).optional(),
9
+ lastModified: z.string().optional()
10
+ });
11
+ const base64Schema = z.string().refine((value) => {
12
+ try {
13
+ atob(value);
14
+ return true;
15
+ } catch {
16
+ return false;
17
+ }
18
+ }, "Expected base64-encoded data");
19
+ const resourceContentsSchema = z.union([looseObject({
20
+ uri: z.string(),
21
+ mimeType: z.string().optional(),
22
+ text: z.string(),
23
+ _meta: metaSchema.optional()
24
+ }), looseObject({
25
+ uri: z.string(),
26
+ mimeType: z.string().optional(),
27
+ blob: base64Schema,
28
+ _meta: metaSchema.optional()
29
+ })]);
30
+ const contentItemSchema = z.discriminatedUnion("type", [
31
+ looseObject({
32
+ type: z.literal("text"),
33
+ text: z.string(),
34
+ annotations: annotationsSchema.optional(),
35
+ _meta: metaSchema.optional()
36
+ }),
37
+ looseObject({
38
+ type: z.literal("image"),
39
+ data: base64Schema,
40
+ mimeType: z.string(),
41
+ annotations: annotationsSchema.optional(),
42
+ _meta: metaSchema.optional()
43
+ }),
44
+ looseObject({
45
+ type: z.literal("audio"),
46
+ data: base64Schema,
47
+ mimeType: z.string(),
48
+ annotations: annotationsSchema.optional(),
49
+ _meta: metaSchema.optional()
14
50
  }),
51
+ looseObject({
52
+ type: z.literal("resource"),
53
+ resource: resourceContentsSchema,
54
+ annotations: annotationsSchema.optional(),
55
+ _meta: metaSchema.optional()
56
+ }),
57
+ looseObject({
58
+ type: z.literal("resource_link"),
59
+ uri: z.string(),
60
+ name: z.string(),
61
+ title: z.string().optional(),
62
+ description: z.string().optional(),
63
+ mimeType: z.string().optional(),
64
+ size: z.number().optional(),
65
+ annotations: annotationsSchema.optional(),
66
+ _meta: metaSchema.optional()
67
+ })
68
+ ]);
69
+ const callToolResultSchema = looseObject({
70
+ content: z.array(contentItemSchema).default([]),
71
+ structuredContent: z.record(z.string(), z.unknown()).optional(),
72
+ isError: z.boolean().optional(),
73
+ _meta: z.record(z.string(), z.unknown()).optional()
74
+ });
75
+ /** Activity input accepts an omitted result.content; validation defaults it to []. */
76
+ const MCPAppsActivityContentSchema = looseObject({
77
+ result: callToolResultSchema,
15
78
  resourceUri: z.string(),
16
79
  serverHash: z.string(),
17
80
  serverId: z.string().optional(),
@@ -1 +1 @@
1
- {"version":3,"file":"content-schema.mjs","names":[],"sources":["../src/content-schema.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * Zod schema for MCP Apps activity content (middleware 0.0.2 format). The\n * framework activity registries validate the activity content with this before\n * handing it to the renderer/session.\n */\nexport const MCPAppsActivityContentSchema = z.object({\n result: z.object({\n content: z.array(z.any()).optional(),\n structuredContent: z.any().optional(),\n isError: z.boolean().optional(),\n }),\n // Resource URI to fetch (e.g., \"ui://server/dashboard\")\n resourceUri: z.string(),\n // MD5 hash of server config (renamed from serverId in 0.0.1)\n serverHash: z.string(),\n // Optional stable server ID from config (takes precedence over serverHash)\n serverId: z.string().optional(),\n // Original tool input arguments\n toolInput: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type MCPAppsActivityContent = z.infer<\n typeof MCPAppsActivityContentSchema\n>;\n"],"mappings":";;;;;;;;AAOA,MAAa,+BAA+B,EAAE,OAAO;CACnD,QAAQ,EAAE,OAAO;EACf,SAAS,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,UAAU;EACpC,mBAAmB,EAAE,KAAK,CAAC,UAAU;EACrC,SAAS,EAAE,SAAS,CAAC,UAAU;EAChC,CAAC;CAEF,aAAa,EAAE,QAAQ;CAEvB,YAAY,EAAE,QAAQ;CAEtB,UAAU,EAAE,QAAQ,CAAC,UAAU;CAE/B,WAAW,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,SAAS,CAAC,CAAC,UAAU;CACxD,CAAC"}
1
+ {"version":3,"file":"content-schema.mjs","names":[],"sources":["../src/content-schema.ts"],"sourcesContent":["import { z } from \"zod\";\n\n// Keep /activity bridge-free: the MCP SDK is only used as a test oracle.\n// This is the Angular host's content contract, expressed using our zod API.\nconst looseObject = <T extends z.ZodRawShape>(shape: T) =>\n z.object(shape).passthrough();\n\n// `_meta` is an extension channel, so its CONTENTS stay unconstrained - but the\n// SDK still requires it to be an object, and a string or array there is a bug\n// worth catching rather than forwarding.\nconst metaSchema = z.record(z.string(), z.unknown());\n\nconst annotationsSchema = looseObject({\n audience: z.array(z.enum([\"user\", \"assistant\"])).optional(),\n priority: z.number().min(0).max(1).optional(),\n lastModified: z.string().optional(),\n});\n\n// Validated by decoding, mirroring the MCP SDK's own base64 check, rather than\n// by pattern. The pattern this replaces additionally required canonical padding,\n// which the SDK does not: it accepts an unpadded payload that we rejected. Since\n// one bad block fails the whole content array, that cost the entire widget.\nconst base64Schema = z.string().refine((value) => {\n try {\n atob(value);\n return true;\n } catch {\n return false;\n }\n}, \"Expected base64-encoded data\");\n\nconst resourceContentsSchema = z.union([\n looseObject({\n uri: z.string(),\n mimeType: z.string().optional(),\n text: z.string(),\n _meta: metaSchema.optional(),\n }),\n looseObject({\n uri: z.string(),\n mimeType: z.string().optional(),\n blob: base64Schema,\n _meta: metaSchema.optional(),\n }),\n]);\n\nconst contentItemSchema = z.discriminatedUnion(\"type\", [\n looseObject({\n type: z.literal(\"text\"),\n text: z.string(),\n annotations: annotationsSchema.optional(),\n _meta: metaSchema.optional(),\n }),\n looseObject({\n type: z.literal(\"image\"),\n data: base64Schema,\n mimeType: z.string(),\n annotations: annotationsSchema.optional(),\n _meta: metaSchema.optional(),\n }),\n looseObject({\n type: z.literal(\"audio\"),\n data: base64Schema,\n mimeType: z.string(),\n annotations: annotationsSchema.optional(),\n _meta: metaSchema.optional(),\n }),\n looseObject({\n type: z.literal(\"resource\"),\n resource: resourceContentsSchema,\n annotations: annotationsSchema.optional(),\n _meta: metaSchema.optional(),\n }),\n looseObject({\n type: z.literal(\"resource_link\"),\n uri: z.string(),\n name: z.string(),\n title: z.string().optional(),\n description: z.string().optional(),\n mimeType: z.string().optional(),\n size: z.number().optional(),\n annotations: annotationsSchema.optional(),\n _meta: metaSchema.optional(),\n }),\n]);\n\nconst callToolResultSchema = looseObject({\n content: z.array(contentItemSchema).default([]),\n structuredContent: z.record(z.string(), z.unknown()).optional(),\n isError: z.boolean().optional(),\n _meta: z.record(z.string(), z.unknown()).optional(),\n});\n\n/** Activity input accepts an omitted result.content; validation defaults it to []. */\nexport const MCPAppsActivityContentSchema = looseObject({\n result: callToolResultSchema,\n resourceUri: z.string(),\n serverHash: z.string(),\n serverId: z.string().optional(),\n toolInput: z.record(z.string(), z.unknown()).optional(),\n});\n\n// Keep the public input contract compatible with structured-only results.\n// Parsed output is normalized before it crosses the bridge.\nexport type MCPAppsActivityContent = z.input<\n typeof MCPAppsActivityContentSchema\n>;\n"],"mappings":";;;AAIA,MAAM,eAAwC,UAC5C,EAAE,OAAO,MAAM,CAAC,aAAa;AAK/B,MAAM,aAAa,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,SAAS,CAAC;AAEpD,MAAM,oBAAoB,YAAY;CACpC,UAAU,EAAE,MAAM,EAAE,KAAK,CAAC,QAAQ,YAAY,CAAC,CAAC,CAAC,UAAU;CAC3D,UAAU,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,UAAU;CAC7C,cAAc,EAAE,QAAQ,CAAC,UAAU;CACpC,CAAC;AAMF,MAAM,eAAe,EAAE,QAAQ,CAAC,QAAQ,UAAU;AAChD,KAAI;AACF,OAAK,MAAM;AACX,SAAO;SACD;AACN,SAAO;;GAER,+BAA+B;AAElC,MAAM,yBAAyB,EAAE,MAAM,CACrC,YAAY;CACV,KAAK,EAAE,QAAQ;CACf,UAAU,EAAE,QAAQ,CAAC,UAAU;CAC/B,MAAM,EAAE,QAAQ;CAChB,OAAO,WAAW,UAAU;CAC7B,CAAC,EACF,YAAY;CACV,KAAK,EAAE,QAAQ;CACf,UAAU,EAAE,QAAQ,CAAC,UAAU;CAC/B,MAAM;CACN,OAAO,WAAW,UAAU;CAC7B,CAAC,CACH,CAAC;AAEF,MAAM,oBAAoB,E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Y,EAAE,QAAQ;CACtB,UAAU,EAAE,QAAQ,CAAC,UAAU;CAC/B,WAAW,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,SAAS,CAAC,CAAC,UAAU;CACxD,CAAC"}
package/dist/index.d.mts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { MCPAppsActivityType, MCP_OPEN_LINK_BLOCKED_SCHEMES } from "./constants.mjs";
2
2
  import { MCPAppsActivityContent, MCPAppsActivityContentSchema } from "./content-schema.mjs";
3
3
  import { buildSandboxHTML } from "./sandbox.mjs";
4
- import { MCPAppsRequestQueue, mcpAppsRequestQueue } from "./request-queue.mjs";
4
+ import { MCPAppsEnqueueOptions, MCPAppsQueueThreadChangedError, MCPAppsRequestQueue, MCP_APPS_QUEUE_IDLE_TIMEOUT_MS, mcpAppsRequestQueue } from "./request-queue.mjs";
5
5
  import { ɵMcpFollowUpHost, ɵrunMcpFollowUp } from "./follow-up.mjs";
6
- import { BindMcpAppOptions, FetchedResource, MCP_APPS_PROTOCOL_VERSION, McpAppSession, McpAppSessionHooks, bindMcpApp } from "./session.mjs";
7
- export { BindMcpAppOptions, FetchedResource, MCPAppsActivityContent, MCPAppsActivityContentSchema, MCPAppsActivityType, MCPAppsRequestQueue, MCP_APPS_PROTOCOL_VERSION, MCP_OPEN_LINK_BLOCKED_SCHEMES, McpAppSession, McpAppSessionHooks, bindMcpApp, buildSandboxHTML, mcpAppsRequestQueue, ɵMcpFollowUpHost, ɵrunMcpFollowUp };
6
+ import { BindMcpAppOptions, FetchedResource, MCP_APPS_PROTOCOL_VERSION, MCP_APPS_SESSION_DEFAULTS, McpAppHostInfo, McpAppOpenLinkPolicy, McpAppSession, McpAppSessionHooks, McpAppSessionOptions, bindMcpApp, denyDangerousSchemes, ɵdecodeBase64 } from "./session.mjs";
7
+ export { BindMcpAppOptions, FetchedResource, MCPAppsActivityContent, MCPAppsActivityContentSchema, MCPAppsActivityType, MCPAppsEnqueueOptions, MCPAppsQueueThreadChangedError, MCPAppsRequestQueue, MCP_APPS_PROTOCOL_VERSION, MCP_APPS_QUEUE_IDLE_TIMEOUT_MS, MCP_APPS_SESSION_DEFAULTS, MCP_OPEN_LINK_BLOCKED_SCHEMES, McpAppHostInfo, McpAppOpenLinkPolicy, McpAppSession, McpAppSessionHooks, McpAppSessionOptions, bindMcpApp, buildSandboxHTML, denyDangerousSchemes, mcpAppsRequestQueue, ɵMcpFollowUpHost, ɵdecodeBase64, ɵrunMcpFollowUp };
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  import { MCPAppsActivityType, MCP_OPEN_LINK_BLOCKED_SCHEMES } from "./constants.mjs";
2
2
  import { MCPAppsActivityContentSchema } from "./content-schema.mjs";
3
3
  import { buildSandboxHTML } from "./sandbox.mjs";
4
- import { MCPAppsRequestQueue, mcpAppsRequestQueue } from "./request-queue.mjs";
4
+ import { MCPAppsQueueThreadChangedError, MCPAppsRequestQueue, MCP_APPS_QUEUE_IDLE_TIMEOUT_MS, mcpAppsRequestQueue } from "./request-queue.mjs";
5
5
  import { ɵrunMcpFollowUp } from "./follow-up.mjs";
6
- import { MCP_APPS_PROTOCOL_VERSION, bindMcpApp } from "./session.mjs";
6
+ import { MCP_APPS_PROTOCOL_VERSION, MCP_APPS_SESSION_DEFAULTS, bindMcpApp, denyDangerousSchemes, ɵdecodeBase64 } from "./session.mjs";
7
7
 
8
- export { MCPAppsActivityContentSchema, MCPAppsActivityType, MCPAppsRequestQueue, MCP_APPS_PROTOCOL_VERSION, MCP_OPEN_LINK_BLOCKED_SCHEMES, bindMcpApp, buildSandboxHTML, mcpAppsRequestQueue, ɵrunMcpFollowUp };
8
+ export { MCPAppsActivityContentSchema, MCPAppsActivityType, MCPAppsQueueThreadChangedError, MCPAppsRequestQueue, MCP_APPS_PROTOCOL_VERSION, MCP_APPS_QUEUE_IDLE_TIMEOUT_MS, MCP_APPS_SESSION_DEFAULTS, MCP_OPEN_LINK_BLOCKED_SCHEMES, bindMcpApp, buildSandboxHTML, denyDangerousSchemes, mcpAppsRequestQueue, ɵdecodeBase64, ɵrunMcpFollowUp };
@@ -1,6 +1,48 @@
1
1
  import { AbstractAgent, RunAgentResult } from "@ag-ui/client";
2
2
 
3
3
  //#region src/request-queue.d.ts
4
+ /**
5
+ * How long a queued request waits for a busy agent before it is rejected.
6
+ * A stuck run would otherwise hold the whole queue (and the widget's loading
7
+ * state) forever. The Vue host enforced this before the shared extraction; it
8
+ * now applies to every frontend.
9
+ */
10
+ declare const MCP_APPS_QUEUE_IDLE_TIMEOUT_MS = 30000;
11
+ /**
12
+ * Raised when queued work is dropped because the agent moved to another thread
13
+ * between enqueue and execution. Distinguishable so callers can answer the
14
+ * requester explicitly instead of leaving it waiting.
15
+ */
16
+ declare class MCPAppsQueueThreadChangedError extends Error {
17
+ readonly originThreadId: string;
18
+ readonly currentThreadId: string;
19
+ constructor(originThreadId: string, currentThreadId: string);
20
+ }
21
+ /** Options accepted by {@link MCPAppsRequestQueue.enqueue}. */
22
+ interface MCPAppsEnqueueOptions {
23
+ /**
24
+ * Identifies the caller that owns this request, so `cancelOwner` can drop the
25
+ * work of a single widget without touching requests queued by other widgets
26
+ * (the pre-extraction `cancel(threadId)` was too broad: it rejected everything
27
+ * sharing a thread).
28
+ */
29
+ owner?: object;
30
+ /** Override the busy-agent wait timeout. Defaults to 30s. */
31
+ timeoutMs?: number;
32
+ /** Also release an executing request's wait on owner cancellation (does not stop its run). */
33
+ cancelRunningWait?: boolean;
34
+ /**
35
+ * Drop the request instead of running it when the agent has switched threads
36
+ * since it was enqueued.
37
+ *
38
+ * The queue is keyed by agent AND thread, but that only decides which FIFO the
39
+ * work joins: a single shared agent object can have its `threadId` mutated in
40
+ * place while the work waits, so executing later would run a thread-1 request
41
+ * against thread-2 - and stream into it (issue #5819's failure mode, applied
42
+ * to the proxy paths).
43
+ */
44
+ dropAfterThreadSwitch?: boolean;
45
+ }
4
46
  /**
5
47
  * Queue for serializing MCP app requests to an agent.
6
48
  * Ensures requests wait for the agent to stop running and are processed one at a time.
@@ -12,20 +54,31 @@ declare class MCPAppsRequestQueue {
12
54
  * Add a request to the queue for a specific agent thread.
13
55
  * Returns a promise that resolves when the request completes.
14
56
  */
15
- enqueue(agent: AbstractAgent, request: () => Promise<RunAgentResult>): Promise<RunAgentResult>;
57
+ enqueue(agent: AbstractAgent, request: (signal: AbortSignal) => Promise<RunAgentResult>, options?: MCPAppsEnqueueOptions): Promise<RunAgentResult>;
58
+ /**
59
+ * Drop every request queued by `owner` that has not started executing yet,
60
+ * rejecting its promise. Used by a widget teardown so work that only exists to
61
+ * feed a now-unmounted iframe does not run against the agent later.
62
+ *
63
+ * By default this cancels waiting work only. `cancelRunningWait` also
64
+ * releases an executing caller's wait and signals its callback; it does not
65
+ * itself stop a runAgent call. The next item still waits for agent idle.
66
+ */
67
+ cancelOwner(owner: object): void;
16
68
  /**
17
- * Drain a thread's queue one request at a time, waiting for the agent to go
18
- * idle before each. Re-entrant-safe (a single processor per thread) and drops
19
- * the thread's map entries once fully drained to keep the shared queue bounded.
69
+ * Drain a queue one request at a time, waiting for the agent to go idle before
70
+ * each. Re-entrant-safe (a single processor per key) and drops the entries once
71
+ * fully drained to keep the shared queue bounded.
20
72
  */
21
73
  private processQueue;
22
74
  /**
23
75
  * Resolve once the agent is not running. Subscribes to run-finalized/failed and
24
76
  * also polls as a fallback for reconnect scenarios where events do not fire.
77
+ * Rejects after `timeoutMs` so a stuck run cannot block the queue forever.
25
78
  */
26
79
  private waitForAgentIdle;
27
80
  }
28
81
  declare const mcpAppsRequestQueue: MCPAppsRequestQueue;
29
82
  //#endregion
30
- export { MCPAppsRequestQueue, mcpAppsRequestQueue };
83
+ export { MCPAppsEnqueueOptions, MCPAppsQueueThreadChangedError, MCPAppsRequestQueue, MCP_APPS_QUEUE_IDLE_TIMEOUT_MS, mcpAppsRequestQueue };
31
84
  //# sourceMappingURL=request-queue.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"request-queue.d.mts","names":[],"sources":["../src/request-queue.ts"],"mappings":";;;;;AAMA;;cAAa,mBAAA;EAAA,QACH,MAAA;EAAA,QAQA,UAAA;EAQS;;;;EAFX,OAAA,CACJ,KAAA,EAAO,aAAA,EACP,OAAA,QAAe,OAAA,CAAQ,cAAA,IACtB,OAAA,CAAQ,cAAA;EAjBH;;;;;EAAA,QAyCM,YAAA;EAzBW;;;;EAAA,QA6EjB,gBAAA;AAAA;AAAA,cA8BG,mBAAA,EAAmB,mBAAA"}
1
+ {"version":3,"file":"request-queue.d.mts","names":[],"sources":["../src/request-queue.ts"],"mappings":";;;;;AAQA;;;;cAAa,8BAAA;AAOb;;;;;AAAA,cAAa,8BAAA,SAAuC,KAAA;EAAA,SAEvC,cAAA;EAAA,SACA,eAAA;cADA,cAAA,UACA,eAAA;AAAA;;UAUI,qBAAA;EAAA;;;;;;EAOf,KAAA;EAeA;EAbA,SAAA;EAaqB;EAXrB,iBAAA;EAqD8B;;;;;;;;;;EA1C9B,qBAAA;AAAA;;;;;cA0CW,mBAAA;EAAA,QACH,MAAA;EAAA,QACA,UAAA;EAQoC;;;;EAFtC,OAAA,CACJ,KAAA,EAAO,aAAA,EACP,OAAA,GAAU,MAAA,EAAQ,WAAA,KAAgB,OAAA,CAAQ,cAAA,GAC1C,OAAA,GAAU,qBAAA,GACT,OAAA,CAAQ,cAAA;EAAA;;;;;;;AAmNb;;EA7KE,WAAA,CAAY,KAAA;EA6KkB;;;;;EAAA,QApJhB,YAAA;;;;;;UA0FN,gBAAA;AAAA;AAAA,cA0DG,mBAAA,EAAmB,mBAAA"}
@@ -1,5 +1,36 @@
1
1
  //#region src/request-queue.ts
2
2
  /**
3
+ * How long a queued request waits for a busy agent before it is rejected.
4
+ * A stuck run would otherwise hold the whole queue (and the widget's loading
5
+ * state) forever. The Vue host enforced this before the shared extraction; it
6
+ * now applies to every frontend.
7
+ */
8
+ const MCP_APPS_QUEUE_IDLE_TIMEOUT_MS = 3e4;
9
+ /**
10
+ * Raised when queued work is dropped because the agent moved to another thread
11
+ * between enqueue and execution. Distinguishable so callers can answer the
12
+ * requester explicitly instead of leaving it waiting.
13
+ */
14
+ var MCPAppsQueueThreadChangedError = class extends Error {
15
+ constructor(originThreadId, currentThreadId) {
16
+ super(`[CopilotKit] MCP app request dropped: the agent moved from thread "${originThreadId}" to "${currentThreadId}" while it was queued.`);
17
+ this.originThreadId = originThreadId;
18
+ this.currentThreadId = currentThreadId;
19
+ this.name = "MCPAppsQueueThreadChangedError";
20
+ }
21
+ };
22
+ /** Stable per-agent id, so two agents sharing a threadId keep separate queues. */
23
+ const agentKeys = /* @__PURE__ */ new WeakMap();
24
+ let nextAgentKey = 0;
25
+ function keyFor(agent) {
26
+ let key = agentKeys.get(agent);
27
+ if (!key) {
28
+ key = `agent-${nextAgentKey++}`;
29
+ agentKeys.set(agent, key);
30
+ }
31
+ return `${key}::${agent.threadId || "default"}`;
32
+ }
33
+ /**
3
34
  * Queue for serializing MCP app requests to an agent.
4
35
  * Ensures requests wait for the agent to stop running and are processed one at a time.
5
36
  */
@@ -12,38 +43,77 @@ var MCPAppsRequestQueue = class {
12
43
  * Add a request to the queue for a specific agent thread.
13
44
  * Returns a promise that resolves when the request completes.
14
45
  */
15
- async enqueue(agent, request) {
16
- const threadId = agent.threadId || "default";
46
+ async enqueue(agent, request, options) {
47
+ const key = keyFor(agent);
17
48
  return new Promise((resolve, reject) => {
18
- let queue = this.queues.get(threadId);
49
+ let queue = this.queues.get(key);
19
50
  if (!queue) {
20
51
  queue = [];
21
- this.queues.set(threadId, queue);
52
+ this.queues.set(key, queue);
22
53
  }
23
54
  queue.push({
24
55
  execute: request,
56
+ cancelRunningWait: options?.cancelRunningWait,
25
57
  resolve,
26
- reject
58
+ reject,
59
+ owner: options?.owner,
60
+ timeoutMs: options?.timeoutMs ?? MCP_APPS_QUEUE_IDLE_TIMEOUT_MS,
61
+ controller: new AbortController(),
62
+ originThreadId: agent.threadId || "default",
63
+ dropAfterThreadSwitch: options?.dropAfterThreadSwitch
27
64
  });
28
- this.processQueue(threadId, agent);
65
+ this.processQueue(key, agent);
29
66
  });
30
67
  }
31
68
  /**
32
- * Drain a thread's queue one request at a time, waiting for the agent to go
33
- * idle before each. Re-entrant-safe (a single processor per thread) and drops
34
- * the thread's map entries once fully drained to keep the shared queue bounded.
69
+ * Drop every request queued by `owner` that has not started executing yet,
70
+ * rejecting its promise. Used by a widget teardown so work that only exists to
71
+ * feed a now-unmounted iframe does not run against the agent later.
72
+ *
73
+ * By default this cancels waiting work only. `cancelRunningWait` also
74
+ * releases an executing caller's wait and signals its callback; it does not
75
+ * itself stop a runAgent call. The next item still waits for agent idle.
76
+ */
77
+ cancelOwner(owner) {
78
+ for (const queue of this.queues.values()) for (const item of queue) {
79
+ if (item.owner !== owner || item.executing && !item.cancelRunningWait || item.cancelled) continue;
80
+ item.cancelled = true;
81
+ item.controller.abort();
82
+ item.reject(/* @__PURE__ */ new Error("[CopilotKit] MCP app request cancelled on teardown"));
83
+ }
84
+ }
85
+ /**
86
+ * Drain a queue one request at a time, waiting for the agent to go idle before
87
+ * each. Re-entrant-safe (a single processor per key) and drops the entries once
88
+ * fully drained to keep the shared queue bounded.
35
89
  */
36
- async processQueue(threadId, agent) {
37
- if (this.processing.get(threadId)) return;
38
- this.processing.set(threadId, true);
90
+ async processQueue(key, agent) {
91
+ if (this.processing.get(key)) return;
92
+ this.processing.set(key, true);
39
93
  try {
40
- const queue = this.queues.get(threadId);
94
+ const queue = this.queues.get(key);
41
95
  if (!queue) return;
42
96
  while (queue.length > 0) {
43
97
  const item = queue[0];
98
+ if (item.cancelled) {
99
+ queue.shift();
100
+ continue;
101
+ }
44
102
  try {
45
- await this.waitForAgentIdle(agent);
46
- const result = await item.execute();
103
+ await this.waitForAgentIdle(agent, item.timeoutMs, item.controller.signal);
104
+ if (item.cancelled) {
105
+ queue.shift();
106
+ continue;
107
+ }
108
+ const currentThreadId = agent.threadId || "default";
109
+ if (item.dropAfterThreadSwitch && currentThreadId !== item.originThreadId) {
110
+ item.reject(new MCPAppsQueueThreadChangedError(item.originThreadId, currentThreadId));
111
+ queue.shift();
112
+ continue;
113
+ }
114
+ item.executing = true;
115
+ const execution = item.execute(item.controller.signal);
116
+ const result = item.cancelRunningWait ? await waitWithAbort(execution, item.controller.signal) : await execution;
47
117
  item.resolve(result);
48
118
  } catch (error) {
49
119
  item.reject(error instanceof Error ? error : new Error(String(error)));
@@ -51,31 +121,41 @@ var MCPAppsRequestQueue = class {
51
121
  queue.shift();
52
122
  }
53
123
  } finally {
54
- const queue = this.queues.get(threadId);
124
+ const queue = this.queues.get(key);
55
125
  if (!queue || queue.length === 0) {
56
- this.queues.delete(threadId);
57
- this.processing.delete(threadId);
58
- } else this.processing.set(threadId, false);
126
+ this.queues.delete(key);
127
+ this.processing.delete(key);
128
+ } else this.processing.set(key, false);
59
129
  }
60
130
  }
61
131
  /**
62
132
  * Resolve once the agent is not running. Subscribes to run-finalized/failed and
63
133
  * also polls as a fallback for reconnect scenarios where events do not fire.
134
+ * Rejects after `timeoutMs` so a stuck run cannot block the queue forever.
64
135
  */
65
- waitForAgentIdle(agent) {
66
- return new Promise((resolve) => {
136
+ waitForAgentIdle(agent, timeoutMs, signal) {
137
+ return new Promise((resolve, reject) => {
67
138
  if (!agent.isRunning) {
68
139
  resolve();
69
140
  return;
70
141
  }
142
+ if (signal?.aborted) {
143
+ reject(/* @__PURE__ */ new Error("[CopilotKit] MCP app request cancelled on teardown"));
144
+ return;
145
+ }
71
146
  let done = false;
72
- const finish = () => {
147
+ const settle = (fn) => {
73
148
  if (done) return;
74
149
  done = true;
150
+ clearTimeout(timer);
75
151
  clearInterval(checkInterval);
76
152
  sub.unsubscribe();
77
- resolve();
153
+ signal?.removeEventListener("abort", onAbort);
154
+ fn();
78
155
  };
156
+ const onAbort = () => settle(() => reject(/* @__PURE__ */ new Error("[CopilotKit] MCP app request cancelled on teardown")));
157
+ signal?.addEventListener("abort", onAbort);
158
+ const finish = () => settle(resolve);
79
159
  const sub = agent.subscribe({
80
160
  onRunFinalized: finish,
81
161
  onRunFailed: finish
@@ -83,11 +163,23 @@ var MCPAppsRequestQueue = class {
83
163
  const checkInterval = setInterval(() => {
84
164
  if (!agent.isRunning) finish();
85
165
  }, 500);
166
+ const timer = setTimeout(() => {
167
+ settle(() => reject(/* @__PURE__ */ new Error("[CopilotKit] Timed out waiting for agent to become idle")));
168
+ }, timeoutMs);
86
169
  });
87
170
  }
88
171
  };
89
172
  const mcpAppsRequestQueue = new MCPAppsRequestQueue();
173
+ /** Release only the caller's wait; the underlying run may still be active. */
174
+ function waitWithAbort(promise, signal) {
175
+ return new Promise((resolve, reject) => {
176
+ const cancel = () => reject(/* @__PURE__ */ new Error("[CopilotKit] MCP app request cancelled on teardown"));
177
+ signal.addEventListener("abort", cancel, { once: true });
178
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", cancel));
179
+ if (signal.aborted) cancel();
180
+ });
181
+ }
90
182
 
91
183
  //#endregion
92
- export { MCPAppsRequestQueue, mcpAppsRequestQueue };
184
+ export { MCPAppsQueueThreadChangedError, MCPAppsRequestQueue, MCP_APPS_QUEUE_IDLE_TIMEOUT_MS, mcpAppsRequestQueue };
93
185
  //# sourceMappingURL=request-queue.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"request-queue.mjs","names":[],"sources":["../src/request-queue.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentResult } from \"@ag-ui/client\";\n\n/**\n * Queue for serializing MCP app requests to an agent.\n * Ensures requests wait for the agent to stop running and are processed one at a time.\n */\nexport class MCPAppsRequestQueue {\n private queues = new Map<\n string,\n Array<{\n execute: () => Promise<RunAgentResult>;\n resolve: (result: RunAgentResult) => void;\n reject: (error: Error) => void;\n }>\n >();\n private processing = new Map<string, boolean>();\n\n /**\n * Add a request to the queue for a specific agent thread.\n * Returns a promise that resolves when the request completes.\n */\n async enqueue(\n agent: AbstractAgent,\n request: () => Promise<RunAgentResult>,\n ): Promise<RunAgentResult> {\n const threadId = agent.threadId || \"default\";\n\n return new Promise((resolve, reject) => {\n // Get or create queue for this thread\n let queue = this.queues.get(threadId);\n if (!queue) {\n queue = [];\n this.queues.set(threadId, queue);\n }\n\n // Add request to queue\n queue.push({ execute: request, resolve, reject });\n\n // Start processing if not already running\n this.processQueue(threadId, agent);\n });\n }\n\n /**\n * Drain a thread's queue one request at a time, waiting for the agent to go\n * idle before each. Re-entrant-safe (a single processor per thread) and drops\n * the thread's map entries once fully drained to keep the shared queue bounded.\n */\n private async processQueue(\n threadId: string,\n agent: AbstractAgent,\n ): Promise<void> {\n // If already processing this queue, return\n if (this.processing.get(threadId)) {\n return;\n }\n\n this.processing.set(threadId, true);\n\n try {\n const queue = this.queues.get(threadId);\n if (!queue) return;\n\n while (queue.length > 0) {\n const item = queue[0]!;\n\n try {\n // Wait for any active run to complete before processing\n await this.waitForAgentIdle(agent);\n\n // Execute the request\n const result = await item.execute();\n item.resolve(result);\n } catch (error) {\n item.reject(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n\n // Remove processed item\n queue.shift();\n }\n } finally {\n // Drop the drained thread entries from both maps. `mcpAppsRequestQueue` is\n // shared for the page lifetime, so retaining an entry per thread id would\n // grow unbounded as threads come and go.\n const queue = this.queues.get(threadId);\n if (!queue || queue.length === 0) {\n this.queues.delete(threadId);\n this.processing.delete(threadId);\n } else {\n this.processing.set(threadId, false);\n }\n }\n }\n\n /**\n * Resolve once the agent is not running. Subscribes to run-finalized/failed and\n * also polls as a fallback for reconnect scenarios where events do not fire.\n */\n private waitForAgentIdle(agent: AbstractAgent): Promise<void> {\n return new Promise((resolve) => {\n if (!agent.isRunning) {\n resolve();\n return;\n }\n\n let done = false;\n const finish = () => {\n if (done) return;\n done = true;\n clearInterval(checkInterval);\n sub.unsubscribe();\n resolve();\n };\n\n const sub = agent.subscribe({\n onRunFinalized: finish,\n onRunFailed: finish,\n });\n\n // Fallback for reconnect scenarios where events don't fire\n const checkInterval = setInterval(() => {\n if (!agent.isRunning) finish();\n }, 500);\n });\n }\n}\n\n//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;AACT;;GAGF,IAAI,OAAO;GACX,MAAM,eAAe;AACnB,QAAI,KAAM;AACV,WAAO;AACP,kBAAc,cAAc;AAC5B,QAAI,aAAa;AACjB,aAAS;;GAGX,MAAM,MAAM,MAAM,UAAU;IAC1B,gBAAgB;IAChB,aAAa;IACd,CAAC;GAGF,MAAM,gBAAgB,kBAAkB;AACtC,QAAI,CAAC,MAAM,UAAW,SAAQ;MAC7B,IAAI;IACP;;;AAKN,MAAa,sBAAsB,IAAI,qBAAqB"}
1
+ {"version":3,"file":"request-queue.mjs","names":[],"sources":["../src/request-queue.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentResult } from \"@ag-ui/client\";\n\n/**\n * How long a queued request waits for a busy agent before it is rejected.\n * A stuck run would otherwise hold the whole queue (and the widget's loading\n * state) forever. The Vue host enforced this before the shared extraction; it\n * now applies to every frontend.\n */\nexport const MCP_APPS_QUEUE_IDLE_TIMEOUT_MS = 30_000;\n\n/**\n * Raised when queued work is dropped because the agent moved to another thread\n * between enqueue and execution. Distinguishable so callers can answer the\n * requester explicitly instead of leaving it waiting.\n */\nexport class MCPAppsQueueThreadChangedError extends Error {\n constructor(\n readonly originThreadId: string,\n readonly currentThreadId: string,\n ) {\n super(\n `[CopilotKit] MCP app request dropped: the agent moved from thread \"${originThreadId}\" to \"${currentThreadId}\" while it was queued.`,\n );\n this.name = \"MCPAppsQueueThreadChangedError\";\n }\n}\n\n/** Options accepted by {@link MCPAppsRequestQueue.enqueue}. */\nexport interface MCPAppsEnqueueOptions {\n /**\n * Identifies the caller that owns this request, so `cancelOwner` can drop the\n * work of a single widget without touching requests queued by other widgets\n * (the pre-extraction `cancel(threadId)` was too broad: it rejected everything\n * sharing a thread).\n */\n owner?: object;\n /** Override the busy-agent wait timeout. Defaults to 30s. */\n timeoutMs?: number;\n /** Also release an executing request's wait on owner cancellation (does not stop its run). */\n cancelRunningWait?: boolean;\n /**\n * Drop the request instead of running it when the agent has switched threads\n * since it was enqueued.\n *\n * The queue is keyed by agent AND thread, but that only decides which FIFO the\n * work joins: a single shared agent object can have its `threadId` mutated in\n * place while the work waits, so executing later would run a thread-1 request\n * against thread-2 - and stream into it (issue #5819's failure mode, applied\n * to the proxy paths).\n */\n dropAfterThreadSwitch?: boolean;\n}\n\ninterface QueueItem {\n execute: (signal: AbortSignal) => Promise<RunAgentResult>;\n cancelRunningWait?: boolean;\n resolve: (result: RunAgentResult) => void;\n reject: (error: Error) => void;\n owner?: object;\n timeoutMs: number;\n /** Aborted by `cancelOwner`, so an active idle wait stops immediately. */\n controller: AbortController;\n /** Thread the agent was on when this work was enqueued. */\n originThreadId: string;\n dropAfterThreadSwitch?: boolean;\n /**\n * Set once `execute()` has actually been invoked. The run itself can no longer\n * be cancelled (runAgent exposes no abort), but the caller's WAIT still can:\n * with `cancelRunningWait`, `cancelOwner` aborts the signal and settles the\n * requester instead of leaving it pending.\n */\n executing?: boolean;\n /** Set by `cancelOwner` for work that must not run. */\n cancelled?: boolean;\n}\n\n/** Stable per-agent id, so two agents sharing a threadId keep separate queues. */\nconst agentKeys = new WeakMap<AbstractAgent, string>();\nlet nextAgentKey = 0;\nfunction keyFor(agent: AbstractAgent): string {\n let key = agentKeys.get(agent);\n if (!key) {\n key = `agent-${nextAgentKey++}`;\n agentKeys.set(agent, key);\n }\n return `${key}::${agent.threadId || \"default\"}`;\n}\n\n/**\n * Queue for serializing MCP app requests to an agent.\n * Ensures requests wait for the agent to stop running and are processed one at a time.\n */\nexport class MCPAppsRequestQueue {\n private queues = new Map<string, QueueItem[]>();\n private processing = new Map<string, boolean>();\n\n /**\n * Add a request to the queue for a specific agent thread.\n * Returns a promise that resolves when the request completes.\n */\n async enqueue(\n agent: AbstractAgent,\n request: (signal: AbortSignal) => Promise<RunAgentResult>,\n options?: MCPAppsEnqueueOptions,\n ): Promise<RunAgentResult> {\n // Keyed by agent AND thread: a shared thread id must not serialize (or\n // cancel) work belonging to a different agent.\n const key = keyFor(agent);\n\n return new Promise((resolve, reject) => {\n let queue = this.queues.get(key);\n if (!queue) {\n queue = [];\n this.queues.set(key, queue);\n }\n\n queue.push({\n execute: request,\n cancelRunningWait: options?.cancelRunningWait,\n resolve,\n reject,\n owner: options?.owner,\n timeoutMs: options?.timeoutMs ?? MCP_APPS_QUEUE_IDLE_TIMEOUT_MS,\n controller: new AbortController(),\n originThreadId: agent.threadId || \"default\",\n dropAfterThreadSwitch: options?.dropAfterThreadSwitch,\n });\n\n // Start processing if not already running\n this.processQueue(key, agent);\n });\n }\n\n /**\n * Drop every request queued by `owner` that has not started executing yet,\n * rejecting its promise. Used by a widget teardown so work that only exists to\n * feed a now-unmounted iframe does not run against the agent later.\n *\n * By default this cancels waiting work only. `cancelRunningWait` also\n * releases an executing caller's wait and signals its callback; it does not\n * itself stop a runAgent call. The next item still waits for agent idle.\n */\n cancelOwner(owner: object): void {\n for (const queue of this.queues.values()) {\n for (const item of queue) {\n if (\n item.owner !== owner ||\n (item.executing && !item.cancelRunningWait) ||\n item.cancelled\n )\n continue;\n item.cancelled = true;\n // Abort first: an item already waiting on a busy agent must release its\n // timer and agent subscription now, not when the agent finally frees up.\n item.controller.abort();\n item.reject(\n new Error(\"[CopilotKit] MCP app request cancelled on teardown\"),\n );\n }\n }\n }\n\n /**\n * Drain a queue one request at a time, waiting for the agent to go idle before\n * each. Re-entrant-safe (a single processor per key) and drops the entries once\n * fully drained to keep the shared queue bounded.\n */\n private async processQueue(key: string, agent: AbstractAgent): Promise<void> {\n // If already processing this queue, return\n if (this.processing.get(key)) {\n return;\n }\n\n this.processing.set(key, true);\n\n try {\n const queue = this.queues.get(key);\n if (!queue) return;\n\n while (queue.length > 0) {\n const item = queue[0]!;\n\n // Cancelled before it got its turn: its promise is already rejected.\n if (item.cancelled) {\n queue.shift();\n continue;\n }\n\n try {\n // Wait for any active run to complete before processing\n await this.waitForAgentIdle(\n agent,\n item.timeoutMs,\n item.controller.signal,\n );\n\n // The owner may have torn down while we waited for the agent.\n if (item.cancelled) {\n queue.shift();\n continue;\n }\n\n // Thread guard: the agent object is shared and its `threadId` can be\n // mutated in place while work waits, so re-check right before running.\n // The queue key only decided which FIFO this joined, it does not pin\n // the agent's current thread.\n const currentThreadId = agent.threadId || \"default\";\n if (\n item.dropAfterThreadSwitch &&\n currentThreadId !== item.originThreadId\n ) {\n item.reject(\n new MCPAppsQueueThreadChangedError(\n item.originThreadId,\n currentThreadId,\n ),\n );\n queue.shift();\n continue;\n }\n\n // Execution itself is not aborted; callers may opt into releasing\n // their wait on teardown (the legacy Angular contract).\n item.executing = true;\n const execution = item.execute(item.controller.signal);\n const result = item.cancelRunningWait\n ? await waitWithAbort(execution, item.controller.signal)\n : await execution;\n item.resolve(result);\n } catch (error) {\n item.reject(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n\n // Remove processed item\n queue.shift();\n }\n } finally {\n // Drop the drained entries from both maps. `mcpAppsRequestQueue` is shared\n // for the page lifetime, so retaining an entry per agent/thread would grow\n // unbounded as threads come and go.\n const queue = this.queues.get(key);\n if (!queue || queue.length === 0) {\n this.queues.delete(key);\n this.processing.delete(key);\n } else {\n this.processing.set(key, false);\n }\n }\n }\n\n /**\n * Resolve once the agent is not running. Subscribes to run-finalized/failed and\n * also polls as a fallback for reconnect scenarios where events do not fire.\n * Rejects after `timeoutMs` so a stuck run cannot block the queue forever.\n */\n private waitForAgentIdle(\n agent: AbstractAgent,\n timeoutMs: number,\n signal?: AbortSignal,\n ): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!agent.isRunning) {\n resolve();\n return;\n }\n if (signal?.aborted) {\n reject(new Error(\"[CopilotKit] MCP app request cancelled on teardown\"));\n return;\n }\n\n let done = false;\n const settle = (fn: () => void) => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n clearInterval(checkInterval);\n sub.unsubscribe();\n signal?.removeEventListener(\"abort\", onAbort);\n fn();\n };\n const onAbort = () =>\n settle(() =>\n reject(\n new Error(\"[CopilotKit] MCP app request cancelled on teardown\"),\n ),\n );\n signal?.addEventListener(\"abort\", onAbort);\n const finish = () => settle(resolve);\n\n const sub = agent.subscribe({\n onRunFinalized: finish,\n onRunFailed: finish,\n });\n\n // Fallback for reconnect scenarios where events don't fire\n const checkInterval = setInterval(() => {\n if (!agent.isRunning) finish();\n }, 500);\n\n const timer = setTimeout(() => {\n settle(() =>\n reject(\n new Error(\n \"[CopilotKit] Timed out waiting for agent to become idle\",\n ),\n ),\n );\n }, timeoutMs);\n });\n }\n}\n\n// Shared per-thread queue instance for all MCP app requests.\nexport const mcpAppsRequestQueue = new MCPAppsRequestQueue();\n\n/** Release only the caller's wait; the underlying run may still be active. */\nfunction waitWithAbort<T>(\n promise: Promise<T>,\n signal: AbortSignal,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n const cancel = () =>\n reject(new Error(\"[CopilotKit] MCP app request cancelled on teardown\"));\n signal.addEventListener(\"abort\", cancel, { once: true });\n promise\n .then(resolve, reject)\n .finally(() => signal.removeEventListener(\"abort\", cancel));\n if (signal.aborted) cancel();\n });\n}\n"],"mappings":";;;;;;;AAQA,MAAa,iCAAiC;;;;;;AAO9C,IAAa,iCAAb,cAAoD,MAAM;CACxD,YACE,AAAS,gBACT,AAAS,iBACT;AACA,QACE,sEAAsE,eAAe,QAAQ,gBAAgB,wBAC9G;EALQ;EACA;AAKT,OAAK,OAAO;;;;AAsDhB,MAAM,4BAAY,IAAI,SAAgC;AACtD,IAAI,eAAe;AACnB,SAAS,OAAO,OAA8B;CAC5C,IAAI,MAAM,UAAU,IAAI,MAAM;AAC9B,KAAI,CAAC,KAAK;AACR,QAAM,SAAS;AACf,YAAU,IAAI,OAAO,IAAI;;AAE3B,QAAO,GAAG,IAAI,IAAI,MAAM,YAAY;;;;;;AAOtC,IAAa,sBAAb,MAAiC;;gCACd,IAAI,KAA0B;oCAC1B,IAAI,KAAsB;;;;;;CAM/C,MAAM,QACJ,OACA,SACA,SACyB;EAGzB,MAAM,MAAM,OAAO,MAAM;AAEzB,SAAO,IAAI,SAAS,SAAS,WAAW;GACtC,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