@copilotkitnext/core 0.0.0-max-changeset-20260109174803

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1926 @@
1
+ // src/core/agent-registry.ts
2
+ import { HttpAgent as HttpAgent2 } from "@ag-ui/client";
3
+ import { logger } from "@copilotkitnext/shared";
4
+
5
+ // src/agent.ts
6
+ import {
7
+ HttpAgent,
8
+ runHttpRequest,
9
+ transformHttpEventStream
10
+ } from "@ag-ui/client";
11
+ var ProxiedCopilotRuntimeAgent = class extends HttpAgent {
12
+ runtimeUrl;
13
+ transport;
14
+ singleEndpointUrl;
15
+ constructor(config) {
16
+ const normalizedRuntimeUrl = config.runtimeUrl ? config.runtimeUrl.replace(/\/$/, "") : void 0;
17
+ const transport = config.transport ?? "rest";
18
+ const runUrl = transport === "single" ? normalizedRuntimeUrl ?? config.runtimeUrl ?? "" : `${normalizedRuntimeUrl ?? config.runtimeUrl}/agent/${encodeURIComponent(config.agentId ?? "")}/run`;
19
+ if (!runUrl) {
20
+ throw new Error("ProxiedCopilotRuntimeAgent requires a runtimeUrl when transport is set to 'single'.");
21
+ }
22
+ super({
23
+ ...config,
24
+ url: runUrl
25
+ });
26
+ this.runtimeUrl = normalizedRuntimeUrl ?? config.runtimeUrl;
27
+ this.transport = transport;
28
+ if (this.transport === "single") {
29
+ this.singleEndpointUrl = this.runtimeUrl;
30
+ }
31
+ }
32
+ abortRun() {
33
+ if (!this.agentId || !this.threadId) {
34
+ return;
35
+ }
36
+ if (typeof fetch === "undefined") {
37
+ return;
38
+ }
39
+ if (this.transport === "single") {
40
+ if (!this.singleEndpointUrl) {
41
+ return;
42
+ }
43
+ const headers = new Headers({ ...this.headers, "Content-Type": "application/json" });
44
+ void fetch(this.singleEndpointUrl, {
45
+ method: "POST",
46
+ headers,
47
+ body: JSON.stringify({
48
+ method: "agent/stop",
49
+ params: {
50
+ agentId: this.agentId,
51
+ threadId: this.threadId
52
+ }
53
+ })
54
+ }).catch((error) => {
55
+ console.error("ProxiedCopilotRuntimeAgent: stop request failed", error);
56
+ });
57
+ return;
58
+ }
59
+ if (!this.runtimeUrl) {
60
+ return;
61
+ }
62
+ const stopPath = `${this.runtimeUrl}/agent/${encodeURIComponent(this.agentId)}/stop/${encodeURIComponent(this.threadId)}`;
63
+ const origin = typeof window !== "undefined" && window.location ? window.location.origin : "http://localhost";
64
+ const base = new URL(this.runtimeUrl, origin);
65
+ const stopUrl = new URL(stopPath, base);
66
+ void fetch(stopUrl.toString(), {
67
+ method: "POST",
68
+ headers: {
69
+ "Content-Type": "application/json",
70
+ ...this.headers
71
+ }
72
+ }).catch((error) => {
73
+ console.error("ProxiedCopilotRuntimeAgent: stop request failed", error);
74
+ });
75
+ }
76
+ connect(input) {
77
+ if (this.transport === "single") {
78
+ if (!this.singleEndpointUrl) {
79
+ throw new Error("Single endpoint transport requires a runtimeUrl");
80
+ }
81
+ const requestInit = this.createSingleRouteRequestInit(input, "agent/connect", {
82
+ agentId: this.agentId
83
+ });
84
+ const httpEvents2 = runHttpRequest(this.singleEndpointUrl, requestInit);
85
+ return transformHttpEventStream(httpEvents2);
86
+ }
87
+ const httpEvents = runHttpRequest(`${this.runtimeUrl}/agent/${this.agentId}/connect`, this.requestInit(input));
88
+ return transformHttpEventStream(httpEvents);
89
+ }
90
+ run(input) {
91
+ if (this.transport === "single") {
92
+ if (!this.singleEndpointUrl) {
93
+ throw new Error("Single endpoint transport requires a runtimeUrl");
94
+ }
95
+ const requestInit = this.createSingleRouteRequestInit(input, "agent/run", {
96
+ agentId: this.agentId
97
+ });
98
+ const httpEvents = runHttpRequest(this.singleEndpointUrl, requestInit);
99
+ return transformHttpEventStream(httpEvents);
100
+ }
101
+ return super.run(input);
102
+ }
103
+ clone() {
104
+ const cloned = super.clone();
105
+ cloned.runtimeUrl = this.runtimeUrl;
106
+ cloned.transport = this.transport;
107
+ cloned.singleEndpointUrl = this.singleEndpointUrl;
108
+ return cloned;
109
+ }
110
+ createSingleRouteRequestInit(input, method, params) {
111
+ if (!this.agentId) {
112
+ throw new Error("ProxiedCopilotRuntimeAgent requires agentId to make runtime requests");
113
+ }
114
+ const baseInit = super.requestInit(input);
115
+ const headers = new Headers(baseInit.headers ?? {});
116
+ headers.set("Content-Type", "application/json");
117
+ headers.set("Accept", headers.get("Accept") ?? "text/event-stream");
118
+ let originalBody = void 0;
119
+ if (typeof baseInit.body === "string") {
120
+ try {
121
+ originalBody = JSON.parse(baseInit.body);
122
+ } catch (error) {
123
+ console.warn("ProxiedCopilotRuntimeAgent: failed to parse request body for single route transport", error);
124
+ originalBody = void 0;
125
+ }
126
+ }
127
+ const envelope = {
128
+ method
129
+ };
130
+ if (params && Object.keys(params).length > 0) {
131
+ envelope.params = params;
132
+ }
133
+ if (originalBody !== void 0) {
134
+ envelope.body = originalBody;
135
+ }
136
+ return {
137
+ ...baseInit,
138
+ headers,
139
+ body: JSON.stringify(envelope)
140
+ };
141
+ }
142
+ };
143
+
144
+ // src/core/agent-registry.ts
145
+ var AgentRegistry = class {
146
+ constructor(core) {
147
+ this.core = core;
148
+ }
149
+ _agents = {};
150
+ localAgents = {};
151
+ remoteAgents = {};
152
+ _runtimeUrl;
153
+ _runtimeVersion;
154
+ _runtimeConnectionStatus = "disconnected" /* Disconnected */;
155
+ _runtimeTransport = "rest";
156
+ /**
157
+ * Get all agents as a readonly record
158
+ */
159
+ get agents() {
160
+ return this._agents;
161
+ }
162
+ get runtimeUrl() {
163
+ return this._runtimeUrl;
164
+ }
165
+ get runtimeVersion() {
166
+ return this._runtimeVersion;
167
+ }
168
+ get runtimeConnectionStatus() {
169
+ return this._runtimeConnectionStatus;
170
+ }
171
+ get runtimeTransport() {
172
+ return this._runtimeTransport;
173
+ }
174
+ /**
175
+ * Initialize agents from configuration
176
+ */
177
+ initialize(agents) {
178
+ this.localAgents = this.assignAgentIds(agents);
179
+ this.applyHeadersToAgents(this.localAgents);
180
+ this._agents = this.localAgents;
181
+ }
182
+ /**
183
+ * Set the runtime URL and update connection
184
+ */
185
+ setRuntimeUrl(runtimeUrl) {
186
+ const normalizedRuntimeUrl = runtimeUrl ? runtimeUrl.replace(/\/$/, "") : void 0;
187
+ if (this._runtimeUrl === normalizedRuntimeUrl) {
188
+ return;
189
+ }
190
+ this._runtimeUrl = normalizedRuntimeUrl;
191
+ void this.updateRuntimeConnection();
192
+ }
193
+ setRuntimeTransport(runtimeTransport) {
194
+ if (this._runtimeTransport === runtimeTransport) {
195
+ return;
196
+ }
197
+ this._runtimeTransport = runtimeTransport;
198
+ void this.updateRuntimeConnection();
199
+ }
200
+ /**
201
+ * Set all agents at once (for development use)
202
+ */
203
+ setAgents__unsafe_dev_only(agents) {
204
+ Object.entries(agents).forEach(([id, agent]) => {
205
+ if (agent) {
206
+ this.validateAndAssignAgentId(id, agent);
207
+ }
208
+ });
209
+ this.localAgents = agents;
210
+ this._agents = { ...this.localAgents, ...this.remoteAgents };
211
+ this.applyHeadersToAgents(this._agents);
212
+ void this.notifyAgentsChanged();
213
+ }
214
+ /**
215
+ * Add a single agent (for development use)
216
+ */
217
+ addAgent__unsafe_dev_only({ id, agent }) {
218
+ this.validateAndAssignAgentId(id, agent);
219
+ this.localAgents[id] = agent;
220
+ this.applyHeadersToAgent(agent);
221
+ this._agents = { ...this.localAgents, ...this.remoteAgents };
222
+ void this.notifyAgentsChanged();
223
+ }
224
+ /**
225
+ * Remove an agent by ID (for development use)
226
+ */
227
+ removeAgent__unsafe_dev_only(id) {
228
+ delete this.localAgents[id];
229
+ this._agents = { ...this.localAgents, ...this.remoteAgents };
230
+ void this.notifyAgentsChanged();
231
+ }
232
+ /**
233
+ * Get an agent by ID
234
+ */
235
+ getAgent(id) {
236
+ if (id in this._agents) {
237
+ return this._agents[id];
238
+ }
239
+ if (this.runtimeUrl !== void 0 && (this.runtimeConnectionStatus === "disconnected" /* Disconnected */ || this.runtimeConnectionStatus === "connecting" /* Connecting */)) {
240
+ return void 0;
241
+ }
242
+ console.warn(`Agent ${id} not found`);
243
+ return void 0;
244
+ }
245
+ /**
246
+ * Apply current headers to an agent
247
+ */
248
+ applyHeadersToAgent(agent) {
249
+ if (agent instanceof HttpAgent2) {
250
+ agent.headers = { ...this.core.headers };
251
+ }
252
+ }
253
+ /**
254
+ * Apply current headers to all agents
255
+ */
256
+ applyHeadersToAgents(agents) {
257
+ Object.values(agents).forEach((agent) => {
258
+ this.applyHeadersToAgent(agent);
259
+ });
260
+ }
261
+ /**
262
+ * Update runtime connection and fetch remote agents
263
+ */
264
+ async updateRuntimeConnection() {
265
+ if (typeof window === "undefined") {
266
+ return;
267
+ }
268
+ if (!this.runtimeUrl) {
269
+ this._runtimeConnectionStatus = "disconnected" /* Disconnected */;
270
+ this._runtimeVersion = void 0;
271
+ this.remoteAgents = {};
272
+ this._agents = this.localAgents;
273
+ await this.notifyRuntimeStatusChanged("disconnected" /* Disconnected */);
274
+ await this.notifyAgentsChanged();
275
+ return;
276
+ }
277
+ this._runtimeConnectionStatus = "connecting" /* Connecting */;
278
+ await this.notifyRuntimeStatusChanged("connecting" /* Connecting */);
279
+ try {
280
+ const runtimeInfoResponse = await this.fetchRuntimeInfo();
281
+ const {
282
+ version,
283
+ ...runtimeInfo
284
+ } = runtimeInfoResponse;
285
+ const agents = Object.fromEntries(
286
+ Object.entries(runtimeInfo.agents).map(([id, { description }]) => {
287
+ const agent = new ProxiedCopilotRuntimeAgent({
288
+ runtimeUrl: this.runtimeUrl,
289
+ agentId: id,
290
+ // Runtime agents always have their ID set correctly
291
+ description,
292
+ transport: this._runtimeTransport
293
+ });
294
+ this.applyHeadersToAgent(agent);
295
+ return [id, agent];
296
+ })
297
+ );
298
+ this.remoteAgents = agents;
299
+ this._agents = { ...this.localAgents, ...this.remoteAgents };
300
+ this._runtimeConnectionStatus = "connected" /* Connected */;
301
+ this._runtimeVersion = version;
302
+ await this.notifyRuntimeStatusChanged("connected" /* Connected */);
303
+ await this.notifyAgentsChanged();
304
+ } catch (error) {
305
+ this._runtimeConnectionStatus = "error" /* Error */;
306
+ this._runtimeVersion = void 0;
307
+ this.remoteAgents = {};
308
+ this._agents = this.localAgents;
309
+ await this.notifyRuntimeStatusChanged("error" /* Error */);
310
+ await this.notifyAgentsChanged();
311
+ const message = error instanceof Error ? error.message : JSON.stringify(error);
312
+ logger.warn(`Failed to load runtime info (${this.runtimeUrl}/info): ${message}`);
313
+ const runtimeError = error instanceof Error ? error : new Error(String(error));
314
+ await this.core.emitError({
315
+ error: runtimeError,
316
+ code: "runtime_info_fetch_failed" /* RUNTIME_INFO_FETCH_FAILED */,
317
+ context: {
318
+ runtimeUrl: this.runtimeUrl
319
+ }
320
+ });
321
+ }
322
+ }
323
+ async fetchRuntimeInfo() {
324
+ if (!this.runtimeUrl) {
325
+ throw new Error("Runtime URL is not set");
326
+ }
327
+ const baseHeaders = this.core.headers;
328
+ const headers = {
329
+ ...baseHeaders
330
+ };
331
+ if (this._runtimeTransport === "single") {
332
+ if (!headers["Content-Type"]) {
333
+ headers["Content-Type"] = "application/json";
334
+ }
335
+ const response2 = await fetch(this.runtimeUrl, {
336
+ method: "POST",
337
+ headers,
338
+ body: JSON.stringify({ method: "info" })
339
+ });
340
+ if ("ok" in response2 && !response2.ok) {
341
+ throw new Error(`Runtime info request failed with status ${response2.status}`);
342
+ }
343
+ return await response2.json();
344
+ }
345
+ const response = await fetch(`${this.runtimeUrl}/info`, {
346
+ headers
347
+ });
348
+ if ("ok" in response && !response.ok) {
349
+ throw new Error(`Runtime info request failed with status ${response.status}`);
350
+ }
351
+ return await response.json();
352
+ }
353
+ /**
354
+ * Assign agent IDs to a record of agents
355
+ */
356
+ assignAgentIds(agents) {
357
+ Object.entries(agents).forEach(([id, agent]) => {
358
+ if (agent) {
359
+ this.validateAndAssignAgentId(id, agent);
360
+ }
361
+ });
362
+ return agents;
363
+ }
364
+ /**
365
+ * Validate and assign an agent ID
366
+ */
367
+ validateAndAssignAgentId(registrationId, agent) {
368
+ if (agent.agentId && agent.agentId !== registrationId) {
369
+ throw new Error(
370
+ `Agent registration mismatch: Agent with ID "${agent.agentId}" cannot be registered under key "${registrationId}". The agent ID must match the registration key or be undefined.`
371
+ );
372
+ }
373
+ if (!agent.agentId) {
374
+ agent.agentId = registrationId;
375
+ }
376
+ }
377
+ /**
378
+ * Notify subscribers of runtime status changes
379
+ */
380
+ async notifyRuntimeStatusChanged(status) {
381
+ await this.core.notifySubscribers(
382
+ (subscriber) => subscriber.onRuntimeConnectionStatusChanged?.({
383
+ copilotkit: this.core,
384
+ status
385
+ }),
386
+ "Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):"
387
+ );
388
+ }
389
+ /**
390
+ * Notify subscribers of agent changes
391
+ */
392
+ async notifyAgentsChanged() {
393
+ await this.core.notifySubscribers(
394
+ (subscriber) => subscriber.onAgentsChanged?.({
395
+ copilotkit: this.core,
396
+ agents: this._agents
397
+ }),
398
+ "Subscriber onAgentsChanged error:"
399
+ );
400
+ }
401
+ };
402
+
403
+ // src/core/context-store.ts
404
+ import { randomUUID } from "@copilotkitnext/shared";
405
+ var ContextStore = class {
406
+ constructor(core) {
407
+ this.core = core;
408
+ }
409
+ _context = {};
410
+ /**
411
+ * Get all context entries as a readonly record
412
+ */
413
+ get context() {
414
+ return this._context;
415
+ }
416
+ /**
417
+ * Add a new context entry
418
+ * @returns The ID of the created context entry
419
+ */
420
+ addContext({ description, value }) {
421
+ const id = randomUUID();
422
+ this._context[id] = { description, value };
423
+ void this.notifySubscribers();
424
+ return id;
425
+ }
426
+ /**
427
+ * Remove a context entry by ID
428
+ */
429
+ removeContext(id) {
430
+ delete this._context[id];
431
+ void this.notifySubscribers();
432
+ }
433
+ /**
434
+ * Notify all subscribers of context changes
435
+ */
436
+ async notifySubscribers() {
437
+ await this.core.notifySubscribers(
438
+ (subscriber) => subscriber.onContextChanged?.({
439
+ copilotkit: this.core,
440
+ context: this._context
441
+ }),
442
+ "Subscriber onContextChanged error:"
443
+ );
444
+ }
445
+ };
446
+
447
+ // src/core/suggestion-engine.ts
448
+ import { randomUUID as randomUUID2, partialJSONParse } from "@copilotkitnext/shared";
449
+ var SuggestionEngine = class {
450
+ constructor(core) {
451
+ this.core = core;
452
+ }
453
+ _suggestionsConfig = {};
454
+ _suggestions = {};
455
+ _runningSuggestions = {};
456
+ /**
457
+ * Initialize with suggestion configs
458
+ */
459
+ initialize(suggestionsConfig) {
460
+ for (const config of suggestionsConfig) {
461
+ this._suggestionsConfig[randomUUID2()] = config;
462
+ }
463
+ }
464
+ /**
465
+ * Add a suggestion configuration
466
+ * @returns The ID of the created config
467
+ */
468
+ addSuggestionsConfig(config) {
469
+ const id = randomUUID2();
470
+ this._suggestionsConfig[id] = config;
471
+ void this.notifySuggestionsConfigChanged();
472
+ return id;
473
+ }
474
+ /**
475
+ * Remove a suggestion configuration by ID
476
+ */
477
+ removeSuggestionsConfig(id) {
478
+ delete this._suggestionsConfig[id];
479
+ void this.notifySuggestionsConfigChanged();
480
+ }
481
+ /**
482
+ * Reload suggestions for a specific agent
483
+ * This triggers generation of new suggestions based on current configs
484
+ */
485
+ reloadSuggestions(agentId) {
486
+ this.clearSuggestions(agentId);
487
+ const agent = this.core.getAgent(agentId);
488
+ if (!agent) {
489
+ return;
490
+ }
491
+ const messageCount = agent.messages?.length ?? 0;
492
+ let hasAnySuggestions = false;
493
+ for (const config of Object.values(this._suggestionsConfig)) {
494
+ if (config.consumerAgentId !== void 0 && config.consumerAgentId !== "*" && config.consumerAgentId !== agentId) {
495
+ continue;
496
+ }
497
+ if (!this.shouldShowSuggestions(config, messageCount)) {
498
+ continue;
499
+ }
500
+ const suggestionId = randomUUID2();
501
+ if (isDynamicSuggestionsConfig(config)) {
502
+ if (!hasAnySuggestions) {
503
+ hasAnySuggestions = true;
504
+ void this.notifySuggestionsStartedLoading(agentId);
505
+ }
506
+ void this.generateSuggestions(suggestionId, config, agentId);
507
+ } else if (isStaticSuggestionsConfig(config)) {
508
+ this.addStaticSuggestions(suggestionId, config, agentId);
509
+ }
510
+ }
511
+ }
512
+ /**
513
+ * Clear all suggestions for a specific agent
514
+ */
515
+ clearSuggestions(agentId) {
516
+ const runningAgents = this._runningSuggestions[agentId];
517
+ if (runningAgents) {
518
+ for (const agent of runningAgents) {
519
+ agent.abortRun();
520
+ }
521
+ delete this._runningSuggestions[agentId];
522
+ }
523
+ this._suggestions[agentId] = {};
524
+ void this.notifySuggestionsChanged(agentId, []);
525
+ }
526
+ /**
527
+ * Get current suggestions for an agent
528
+ */
529
+ getSuggestions(agentId) {
530
+ const suggestions = Object.values(this._suggestions[agentId] ?? {}).flat();
531
+ const isLoading = (this._runningSuggestions[agentId]?.length ?? 0) > 0;
532
+ return { suggestions, isLoading };
533
+ }
534
+ /**
535
+ * Generate suggestions using a provider agent
536
+ */
537
+ async generateSuggestions(suggestionId, config, consumerAgentId) {
538
+ let agent = void 0;
539
+ try {
540
+ const suggestionsProviderAgent = this.core.getAgent(
541
+ config.providerAgentId ?? "default"
542
+ );
543
+ if (!suggestionsProviderAgent) {
544
+ throw new Error(`Suggestions provider agent not found: ${config.providerAgentId}`);
545
+ }
546
+ const suggestionsConsumerAgent = this.core.getAgent(consumerAgentId);
547
+ if (!suggestionsConsumerAgent) {
548
+ throw new Error(`Suggestions consumer agent not found: ${consumerAgentId}`);
549
+ }
550
+ const clonedAgent = suggestionsProviderAgent.clone();
551
+ agent = clonedAgent;
552
+ agent.threadId = suggestionId;
553
+ agent.messages = JSON.parse(JSON.stringify(suggestionsConsumerAgent.messages));
554
+ agent.state = JSON.parse(JSON.stringify(suggestionsConsumerAgent.state));
555
+ this._suggestions[consumerAgentId] = {
556
+ ...this._suggestions[consumerAgentId] ?? {},
557
+ [suggestionId]: []
558
+ };
559
+ this._runningSuggestions[consumerAgentId] = [...this._runningSuggestions[consumerAgentId] ?? [], agent];
560
+ agent.addMessage({
561
+ id: suggestionId,
562
+ role: "user",
563
+ content: [
564
+ `Suggest what the user could say next. Provide clear, highly relevant suggestions by calling the \`copilotkitSuggest\` tool.`,
565
+ `Provide at least ${config.minSuggestions ?? 1} and at most ${config.maxSuggestions ?? 3} suggestions.`,
566
+ `The user has the following tools available: ${JSON.stringify(this.core.buildFrontendTools(consumerAgentId))}.`,
567
+ ` ${config.instructions}`
568
+ ].join("\n")
569
+ });
570
+ await agent.runAgent(
571
+ {
572
+ context: Object.values(this.core.context),
573
+ forwardedProps: {
574
+ ...this.core.properties,
575
+ toolChoice: { type: "function", function: { name: "copilotkitSuggest" } }
576
+ },
577
+ tools: [SUGGEST_TOOL]
578
+ },
579
+ {
580
+ onMessagesChanged: ({ messages }) => {
581
+ this.extractSuggestions(messages, suggestionId, consumerAgentId, true);
582
+ }
583
+ }
584
+ );
585
+ } catch (error) {
586
+ console.warn("Error generating suggestions:", error);
587
+ } finally {
588
+ this.finalizeSuggestions(suggestionId, consumerAgentId);
589
+ const runningAgents = this._runningSuggestions[consumerAgentId];
590
+ if (agent && runningAgents) {
591
+ const filteredAgents = runningAgents.filter((a) => a !== agent);
592
+ this._runningSuggestions[consumerAgentId] = filteredAgents;
593
+ if (filteredAgents.length === 0) {
594
+ delete this._runningSuggestions[consumerAgentId];
595
+ await this.notifySuggestionsFinishedLoading(consumerAgentId);
596
+ }
597
+ }
598
+ }
599
+ }
600
+ /**
601
+ * Finalize suggestions by marking them as no longer loading
602
+ */
603
+ finalizeSuggestions(suggestionId, consumerAgentId) {
604
+ const agentSuggestions = this._suggestions[consumerAgentId];
605
+ const currentSuggestions = agentSuggestions?.[suggestionId];
606
+ if (agentSuggestions && currentSuggestions && currentSuggestions.length > 0) {
607
+ const finalizedSuggestions = currentSuggestions.filter((suggestion) => suggestion.title !== "" || suggestion.message !== "").map((suggestion) => ({
608
+ ...suggestion,
609
+ isLoading: false
610
+ }));
611
+ if (finalizedSuggestions.length > 0) {
612
+ agentSuggestions[suggestionId] = finalizedSuggestions;
613
+ } else {
614
+ delete agentSuggestions[suggestionId];
615
+ }
616
+ const allSuggestions = Object.values(this._suggestions[consumerAgentId] ?? {}).flat();
617
+ void this.notifySuggestionsChanged(consumerAgentId, allSuggestions, "finalized");
618
+ }
619
+ }
620
+ /**
621
+ * Extract suggestions from messages (called during streaming)
622
+ */
623
+ extractSuggestions(messages, suggestionId, consumerAgentId, isRunning) {
624
+ const idx = messages.findIndex((message) => message.id === suggestionId);
625
+ if (idx == -1) {
626
+ return;
627
+ }
628
+ const suggestions = [];
629
+ const newMessages = messages.slice(idx + 1);
630
+ for (const message of newMessages) {
631
+ if (message.role === "assistant" && message.toolCalls) {
632
+ for (const toolCall of message.toolCalls) {
633
+ if (toolCall.function.name === "copilotkitSuggest") {
634
+ const fullArgs = Array.isArray(toolCall.function.arguments) ? toolCall.function.arguments.join("") : toolCall.function.arguments;
635
+ const parsed = partialJSONParse(fullArgs);
636
+ if (parsed && typeof parsed === "object" && "suggestions" in parsed) {
637
+ const parsedSuggestions = parsed.suggestions;
638
+ if (Array.isArray(parsedSuggestions)) {
639
+ for (const item of parsedSuggestions) {
640
+ if (item && typeof item === "object" && "title" in item) {
641
+ suggestions.push({
642
+ title: item.title ?? "",
643
+ message: item.message ?? "",
644
+ isLoading: false
645
+ // Will be set correctly below
646
+ });
647
+ }
648
+ }
649
+ }
650
+ }
651
+ }
652
+ }
653
+ }
654
+ }
655
+ if (isRunning && suggestions.length > 0) {
656
+ suggestions[suggestions.length - 1].isLoading = true;
657
+ }
658
+ const agentSuggestions = this._suggestions[consumerAgentId];
659
+ if (agentSuggestions) {
660
+ agentSuggestions[suggestionId] = suggestions;
661
+ const allSuggestions = Object.values(this._suggestions[consumerAgentId] ?? {}).flat();
662
+ void this.notifySuggestionsChanged(consumerAgentId, allSuggestions, "suggestions changed");
663
+ }
664
+ }
665
+ /**
666
+ * Notify subscribers of suggestions config changes
667
+ */
668
+ async notifySuggestionsConfigChanged() {
669
+ await this.core.notifySubscribers(
670
+ (subscriber) => subscriber.onSuggestionsConfigChanged?.({
671
+ copilotkit: this.core,
672
+ suggestionsConfig: this._suggestionsConfig
673
+ }),
674
+ "Subscriber onSuggestionsConfigChanged error:"
675
+ );
676
+ }
677
+ /**
678
+ * Notify subscribers of suggestions changes
679
+ */
680
+ async notifySuggestionsChanged(agentId, suggestions, context = "") {
681
+ await this.core.notifySubscribers(
682
+ (subscriber) => subscriber.onSuggestionsChanged?.({
683
+ copilotkit: this.core,
684
+ agentId,
685
+ suggestions
686
+ }),
687
+ `Subscriber onSuggestionsChanged error: ${context}`
688
+ );
689
+ }
690
+ /**
691
+ * Notify subscribers that suggestions started loading
692
+ */
693
+ async notifySuggestionsStartedLoading(agentId) {
694
+ await this.core.notifySubscribers(
695
+ (subscriber) => subscriber.onSuggestionsStartedLoading?.({
696
+ copilotkit: this.core,
697
+ agentId
698
+ }),
699
+ "Subscriber onSuggestionsStartedLoading error:"
700
+ );
701
+ }
702
+ /**
703
+ * Notify subscribers that suggestions finished loading
704
+ */
705
+ async notifySuggestionsFinishedLoading(agentId) {
706
+ await this.core.notifySubscribers(
707
+ (subscriber) => subscriber.onSuggestionsFinishedLoading?.({
708
+ copilotkit: this.core,
709
+ agentId
710
+ }),
711
+ "Subscriber onSuggestionsFinishedLoading error:"
712
+ );
713
+ }
714
+ /**
715
+ * Check if suggestions should be shown based on availability and message count
716
+ */
717
+ shouldShowSuggestions(config, messageCount) {
718
+ const availability = config.available;
719
+ if (!availability) {
720
+ if (isDynamicSuggestionsConfig(config)) {
721
+ return messageCount > 0;
722
+ } else {
723
+ return messageCount === 0;
724
+ }
725
+ }
726
+ switch (availability) {
727
+ case "disabled":
728
+ return false;
729
+ case "before-first-message":
730
+ return messageCount === 0;
731
+ case "after-first-message":
732
+ return messageCount > 0;
733
+ case "always":
734
+ return true;
735
+ default:
736
+ return false;
737
+ }
738
+ }
739
+ /**
740
+ * Add static suggestions directly without AI generation
741
+ */
742
+ addStaticSuggestions(suggestionId, config, consumerAgentId) {
743
+ const suggestions = config.suggestions.map((s) => ({
744
+ ...s,
745
+ isLoading: false
746
+ }));
747
+ this._suggestions[consumerAgentId] = {
748
+ ...this._suggestions[consumerAgentId] ?? {},
749
+ [suggestionId]: suggestions
750
+ };
751
+ const allSuggestions = Object.values(this._suggestions[consumerAgentId] ?? {}).flat();
752
+ void this.notifySuggestionsChanged(consumerAgentId, allSuggestions, "static suggestions added");
753
+ }
754
+ };
755
+ function isDynamicSuggestionsConfig(config) {
756
+ return "instructions" in config;
757
+ }
758
+ function isStaticSuggestionsConfig(config) {
759
+ return "suggestions" in config;
760
+ }
761
+ var SUGGEST_TOOL = {
762
+ name: "copilotkitSuggest",
763
+ description: "Suggest what the user could say next",
764
+ parameters: {
765
+ type: "object",
766
+ properties: {
767
+ suggestions: {
768
+ type: "array",
769
+ description: "List of suggestions shown to the user as buttons.",
770
+ items: {
771
+ type: "object",
772
+ properties: {
773
+ title: {
774
+ type: "string",
775
+ description: "The title of the suggestion. This is shown as a button and should be short."
776
+ },
777
+ message: {
778
+ type: "string",
779
+ description: "The message to send when the suggestion is clicked. This should be a clear, complete sentence and will be sent as an instruction to the AI."
780
+ }
781
+ },
782
+ required: ["title", "message"]
783
+ }
784
+ }
785
+ },
786
+ required: ["suggestions"]
787
+ }
788
+ };
789
+
790
+ // src/core/run-handler.ts
791
+ import { HttpAgent as HttpAgent3 } from "@ag-ui/client";
792
+ import { randomUUID as randomUUID3, logger as logger2 } from "@copilotkitnext/shared";
793
+ import { zodToJsonSchema } from "zod-to-json-schema";
794
+ var RunHandler = class {
795
+ constructor(core) {
796
+ this.core = core;
797
+ }
798
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
799
+ _tools = [];
800
+ /**
801
+ * Get all tools as a readonly array
802
+ */
803
+ get tools() {
804
+ return this._tools;
805
+ }
806
+ /**
807
+ * Initialize with tools
808
+ */
809
+ initialize(tools) {
810
+ this._tools = tools;
811
+ }
812
+ /**
813
+ * Add a tool to the registry
814
+ */
815
+ addTool(tool) {
816
+ const existingToolIndex = this._tools.findIndex((t) => t.name === tool.name && t.agentId === tool.agentId);
817
+ if (existingToolIndex !== -1) {
818
+ logger2.warn(`Tool already exists: '${tool.name}' for agent '${tool.agentId || "global"}', skipping.`);
819
+ return;
820
+ }
821
+ this._tools.push(tool);
822
+ }
823
+ /**
824
+ * Remove a tool by name and optionally by agentId
825
+ */
826
+ removeTool(id, agentId) {
827
+ this._tools = this._tools.filter((tool) => {
828
+ if (agentId !== void 0) {
829
+ return !(tool.name === id && tool.agentId === agentId);
830
+ }
831
+ return !(tool.name === id && !tool.agentId);
832
+ });
833
+ }
834
+ /**
835
+ * Get a tool by name and optionally by agentId.
836
+ * If agentId is provided, it will first look for an agent-specific tool,
837
+ * then fall back to a global tool with the same name.
838
+ */
839
+ getTool(params) {
840
+ const { toolName, agentId } = params;
841
+ if (agentId) {
842
+ const agentTool = this._tools.find((tool) => tool.name === toolName && tool.agentId === agentId);
843
+ if (agentTool) {
844
+ return agentTool;
845
+ }
846
+ }
847
+ return this._tools.find((tool) => tool.name === toolName && !tool.agentId);
848
+ }
849
+ /**
850
+ * Set all tools at once. Replaces existing tools.
851
+ */
852
+ setTools(tools) {
853
+ this._tools = [...tools];
854
+ }
855
+ /**
856
+ * Connect an agent (establish initial connection)
857
+ */
858
+ async connectAgent({ agent }) {
859
+ try {
860
+ await agent.detachActiveRun();
861
+ agent.setMessages([]);
862
+ agent.setState({});
863
+ if (agent instanceof HttpAgent3) {
864
+ agent.headers = { ...this.core.headers };
865
+ }
866
+ const runAgentResult = await agent.connectAgent(
867
+ {
868
+ forwardedProps: this.core.properties,
869
+ tools: this.buildFrontendTools(agent.agentId)
870
+ },
871
+ this.createAgentErrorSubscriber(agent)
872
+ );
873
+ return this.processAgentResult({ runAgentResult, agent });
874
+ } catch (error) {
875
+ const connectError = error instanceof Error ? error : new Error(String(error));
876
+ const context = {};
877
+ if (agent.agentId) {
878
+ context.agentId = agent.agentId;
879
+ }
880
+ await this.core.emitError({
881
+ error: connectError,
882
+ code: "agent_connect_failed" /* AGENT_CONNECT_FAILED */,
883
+ context
884
+ });
885
+ throw error;
886
+ }
887
+ }
888
+ /**
889
+ * Run an agent
890
+ */
891
+ async runAgent({ agent }) {
892
+ if (agent.agentId) {
893
+ void this.core.suggestionEngine.clearSuggestions(agent.agentId);
894
+ }
895
+ if (agent instanceof HttpAgent3) {
896
+ agent.headers = { ...this.core.headers };
897
+ }
898
+ try {
899
+ const runAgentResult = await agent.runAgent(
900
+ {
901
+ forwardedProps: this.core.properties,
902
+ tools: this.buildFrontendTools(agent.agentId),
903
+ context: Object.values(this.core.context)
904
+ },
905
+ this.createAgentErrorSubscriber(agent)
906
+ );
907
+ return this.processAgentResult({ runAgentResult, agent });
908
+ } catch (error) {
909
+ const runError = error instanceof Error ? error : new Error(String(error));
910
+ const context = {};
911
+ if (agent.agentId) {
912
+ context.agentId = agent.agentId;
913
+ }
914
+ await this.core.emitError({
915
+ error: runError,
916
+ code: "agent_run_failed" /* AGENT_RUN_FAILED */,
917
+ context
918
+ });
919
+ throw error;
920
+ }
921
+ }
922
+ /**
923
+ * Process agent result and execute tools
924
+ */
925
+ async processAgentResult({
926
+ runAgentResult,
927
+ agent
928
+ }) {
929
+ const { newMessages } = runAgentResult;
930
+ const agentId = agent.agentId;
931
+ let needsFollowUp = false;
932
+ for (const message of newMessages) {
933
+ if (message.role === "assistant") {
934
+ for (const toolCall of message.toolCalls || []) {
935
+ if (newMessages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id) === -1) {
936
+ const tool = this.getTool({
937
+ toolName: toolCall.function.name,
938
+ agentId: agent.agentId
939
+ });
940
+ if (tool) {
941
+ const followUp = await this.executeSpecificTool(tool, toolCall, message, agent, agentId);
942
+ if (followUp) {
943
+ needsFollowUp = true;
944
+ }
945
+ } else {
946
+ const wildcardTool = this.getTool({ toolName: "*", agentId: agent.agentId });
947
+ if (wildcardTool) {
948
+ const followUp = await this.executeWildcardTool(wildcardTool, toolCall, message, agent, agentId);
949
+ if (followUp) {
950
+ needsFollowUp = true;
951
+ }
952
+ }
953
+ }
954
+ }
955
+ }
956
+ }
957
+ }
958
+ if (needsFollowUp) {
959
+ return await this.runAgent({ agent });
960
+ }
961
+ void this.core.suggestionEngine.reloadSuggestions(agentId);
962
+ return runAgentResult;
963
+ }
964
+ /**
965
+ * Execute a specific tool
966
+ */
967
+ async executeSpecificTool(tool, toolCall, message, agent, agentId) {
968
+ if (tool?.agentId && tool.agentId !== agent.agentId) {
969
+ return false;
970
+ }
971
+ let toolCallResult = "";
972
+ let errorMessage;
973
+ let isArgumentError = false;
974
+ if (tool?.handler) {
975
+ let parsedArgs;
976
+ try {
977
+ parsedArgs = JSON.parse(toolCall.function.arguments);
978
+ } catch (error) {
979
+ const parseError = error instanceof Error ? error : new Error(String(error));
980
+ errorMessage = parseError.message;
981
+ isArgumentError = true;
982
+ await this.core.emitError({
983
+ error: parseError,
984
+ code: "tool_argument_parse_failed" /* TOOL_ARGUMENT_PARSE_FAILED */,
985
+ context: {
986
+ agentId,
987
+ toolCallId: toolCall.id,
988
+ toolName: toolCall.function.name,
989
+ rawArguments: toolCall.function.arguments,
990
+ toolType: "specific",
991
+ messageId: message.id
992
+ }
993
+ });
994
+ }
995
+ await this.core.notifySubscribers(
996
+ (subscriber) => subscriber.onToolExecutionStart?.({
997
+ copilotkit: this.core,
998
+ toolCallId: toolCall.id,
999
+ agentId,
1000
+ toolName: toolCall.function.name,
1001
+ args: parsedArgs
1002
+ }),
1003
+ "Subscriber onToolExecutionStart error:"
1004
+ );
1005
+ if (!errorMessage) {
1006
+ try {
1007
+ const result = await tool.handler(parsedArgs, toolCall);
1008
+ if (result === void 0 || result === null) {
1009
+ toolCallResult = "";
1010
+ } else if (typeof result === "string") {
1011
+ toolCallResult = result;
1012
+ } else {
1013
+ toolCallResult = JSON.stringify(result);
1014
+ }
1015
+ } catch (error) {
1016
+ const handlerError = error instanceof Error ? error : new Error(String(error));
1017
+ errorMessage = handlerError.message;
1018
+ await this.core.emitError({
1019
+ error: handlerError,
1020
+ code: "tool_handler_failed" /* TOOL_HANDLER_FAILED */,
1021
+ context: {
1022
+ agentId,
1023
+ toolCallId: toolCall.id,
1024
+ toolName: toolCall.function.name,
1025
+ parsedArgs,
1026
+ toolType: "specific",
1027
+ messageId: message.id
1028
+ }
1029
+ });
1030
+ }
1031
+ }
1032
+ if (errorMessage) {
1033
+ toolCallResult = `Error: ${errorMessage}`;
1034
+ }
1035
+ await this.core.notifySubscribers(
1036
+ (subscriber) => subscriber.onToolExecutionEnd?.({
1037
+ copilotkit: this.core,
1038
+ toolCallId: toolCall.id,
1039
+ agentId,
1040
+ toolName: toolCall.function.name,
1041
+ result: errorMessage ? "" : toolCallResult,
1042
+ error: errorMessage
1043
+ }),
1044
+ "Subscriber onToolExecutionEnd error:"
1045
+ );
1046
+ if (isArgumentError) {
1047
+ throw new Error(errorMessage ?? "Tool execution failed");
1048
+ }
1049
+ }
1050
+ if (!errorMessage || !isArgumentError) {
1051
+ const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
1052
+ const toolMessage = {
1053
+ id: randomUUID3(),
1054
+ role: "tool",
1055
+ toolCallId: toolCall.id,
1056
+ content: toolCallResult
1057
+ };
1058
+ agent.messages.splice(messageIndex + 1, 0, toolMessage);
1059
+ if (!errorMessage && tool?.followUp !== false) {
1060
+ return true;
1061
+ }
1062
+ }
1063
+ return false;
1064
+ }
1065
+ /**
1066
+ * Execute a wildcard tool
1067
+ */
1068
+ async executeWildcardTool(wildcardTool, toolCall, message, agent, agentId) {
1069
+ if (wildcardTool?.agentId && wildcardTool.agentId !== agent.agentId) {
1070
+ return false;
1071
+ }
1072
+ let toolCallResult = "";
1073
+ let errorMessage;
1074
+ let isArgumentError = false;
1075
+ if (wildcardTool?.handler) {
1076
+ let parsedArgs;
1077
+ try {
1078
+ parsedArgs = JSON.parse(toolCall.function.arguments);
1079
+ } catch (error) {
1080
+ const parseError = error instanceof Error ? error : new Error(String(error));
1081
+ errorMessage = parseError.message;
1082
+ isArgumentError = true;
1083
+ await this.core.emitError({
1084
+ error: parseError,
1085
+ code: "tool_argument_parse_failed" /* TOOL_ARGUMENT_PARSE_FAILED */,
1086
+ context: {
1087
+ agentId,
1088
+ toolCallId: toolCall.id,
1089
+ toolName: toolCall.function.name,
1090
+ rawArguments: toolCall.function.arguments,
1091
+ toolType: "wildcard",
1092
+ messageId: message.id
1093
+ }
1094
+ });
1095
+ }
1096
+ const wildcardArgs = {
1097
+ toolName: toolCall.function.name,
1098
+ args: parsedArgs
1099
+ };
1100
+ await this.core.notifySubscribers(
1101
+ (subscriber) => subscriber.onToolExecutionStart?.({
1102
+ copilotkit: this.core,
1103
+ toolCallId: toolCall.id,
1104
+ agentId,
1105
+ toolName: toolCall.function.name,
1106
+ args: wildcardArgs
1107
+ }),
1108
+ "Subscriber onToolExecutionStart error:"
1109
+ );
1110
+ if (!errorMessage) {
1111
+ try {
1112
+ const result = await wildcardTool.handler(wildcardArgs, toolCall);
1113
+ if (result === void 0 || result === null) {
1114
+ toolCallResult = "";
1115
+ } else if (typeof result === "string") {
1116
+ toolCallResult = result;
1117
+ } else {
1118
+ toolCallResult = JSON.stringify(result);
1119
+ }
1120
+ } catch (error) {
1121
+ const handlerError = error instanceof Error ? error : new Error(String(error));
1122
+ errorMessage = handlerError.message;
1123
+ await this.core.emitError({
1124
+ error: handlerError,
1125
+ code: "tool_handler_failed" /* TOOL_HANDLER_FAILED */,
1126
+ context: {
1127
+ agentId,
1128
+ toolCallId: toolCall.id,
1129
+ toolName: toolCall.function.name,
1130
+ parsedArgs: wildcardArgs,
1131
+ toolType: "wildcard",
1132
+ messageId: message.id
1133
+ }
1134
+ });
1135
+ }
1136
+ }
1137
+ if (errorMessage) {
1138
+ toolCallResult = `Error: ${errorMessage}`;
1139
+ }
1140
+ await this.core.notifySubscribers(
1141
+ (subscriber) => subscriber.onToolExecutionEnd?.({
1142
+ copilotkit: this.core,
1143
+ toolCallId: toolCall.id,
1144
+ agentId,
1145
+ toolName: toolCall.function.name,
1146
+ result: errorMessage ? "" : toolCallResult,
1147
+ error: errorMessage
1148
+ }),
1149
+ "Subscriber onToolExecutionEnd error:"
1150
+ );
1151
+ if (isArgumentError) {
1152
+ throw new Error(errorMessage ?? "Tool execution failed");
1153
+ }
1154
+ }
1155
+ if (!errorMessage || !isArgumentError) {
1156
+ const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
1157
+ const toolMessage = {
1158
+ id: randomUUID3(),
1159
+ role: "tool",
1160
+ toolCallId: toolCall.id,
1161
+ content: toolCallResult
1162
+ };
1163
+ agent.messages.splice(messageIndex + 1, 0, toolMessage);
1164
+ if (!errorMessage && wildcardTool?.followUp !== false) {
1165
+ return true;
1166
+ }
1167
+ }
1168
+ return false;
1169
+ }
1170
+ /**
1171
+ * Build frontend tools for an agent
1172
+ */
1173
+ buildFrontendTools(agentId) {
1174
+ return this._tools.filter((tool) => !tool.agentId || tool.agentId === agentId).map((tool) => ({
1175
+ name: tool.name,
1176
+ description: tool.description ?? "",
1177
+ parameters: createToolSchema(tool)
1178
+ }));
1179
+ }
1180
+ /**
1181
+ * Create an agent error subscriber
1182
+ */
1183
+ createAgentErrorSubscriber(agent) {
1184
+ const emitAgentError = async (error, code, extraContext = {}) => {
1185
+ const context = { ...extraContext };
1186
+ if (agent.agentId) {
1187
+ context.agentId = agent.agentId;
1188
+ }
1189
+ await this.core.emitError({
1190
+ error,
1191
+ code,
1192
+ context
1193
+ });
1194
+ };
1195
+ return {
1196
+ onRunFailed: async ({ error }) => {
1197
+ await emitAgentError(error, "agent_run_failed_event" /* AGENT_RUN_FAILED_EVENT */, {
1198
+ source: "onRunFailed"
1199
+ });
1200
+ },
1201
+ onRunErrorEvent: async ({ event }) => {
1202
+ const eventError = event?.rawEvent instanceof Error ? event.rawEvent : event?.rawEvent?.error instanceof Error ? event.rawEvent.error : void 0;
1203
+ const errorMessage = typeof event?.rawEvent?.error === "string" ? event.rawEvent.error : event?.message ?? "Agent run error";
1204
+ const rawError = eventError ?? new Error(errorMessage);
1205
+ if (event?.code && !rawError.code) {
1206
+ rawError.code = event.code;
1207
+ }
1208
+ await emitAgentError(rawError, "agent_run_error_event" /* AGENT_RUN_ERROR_EVENT */, {
1209
+ source: "onRunErrorEvent",
1210
+ event,
1211
+ runtimeErrorCode: event?.code
1212
+ });
1213
+ }
1214
+ };
1215
+ }
1216
+ };
1217
+ var EMPTY_TOOL_SCHEMA = {
1218
+ type: "object",
1219
+ properties: {}
1220
+ };
1221
+ function createToolSchema(tool) {
1222
+ if (!tool.parameters) {
1223
+ return { ...EMPTY_TOOL_SCHEMA };
1224
+ }
1225
+ const rawSchema = zodToJsonSchema(tool.parameters, {
1226
+ $refStrategy: "none"
1227
+ });
1228
+ if (!rawSchema || typeof rawSchema !== "object") {
1229
+ return { ...EMPTY_TOOL_SCHEMA };
1230
+ }
1231
+ const { $schema, ...schema } = rawSchema;
1232
+ if (typeof schema.type !== "string") {
1233
+ schema.type = "object";
1234
+ }
1235
+ if (typeof schema.properties !== "object" || schema.properties === null) {
1236
+ schema.properties = {};
1237
+ }
1238
+ stripAdditionalProperties(schema);
1239
+ return schema;
1240
+ }
1241
+ function stripAdditionalProperties(schema) {
1242
+ if (!schema || typeof schema !== "object") {
1243
+ return;
1244
+ }
1245
+ if (Array.isArray(schema)) {
1246
+ schema.forEach(stripAdditionalProperties);
1247
+ return;
1248
+ }
1249
+ const record = schema;
1250
+ if (record.additionalProperties !== void 0) {
1251
+ delete record.additionalProperties;
1252
+ }
1253
+ for (const value of Object.values(record)) {
1254
+ stripAdditionalProperties(value);
1255
+ }
1256
+ }
1257
+
1258
+ // src/core/state-manager.ts
1259
+ var StateManager = class {
1260
+ constructor(core) {
1261
+ this.core = core;
1262
+ }
1263
+ // State tracking: agentId -> threadId -> runId -> state
1264
+ stateByRun = /* @__PURE__ */ new Map();
1265
+ // Message tracking: agentId -> threadId -> messageId -> runId
1266
+ messageToRun = /* @__PURE__ */ new Map();
1267
+ // Agent subscriptions for cleanup
1268
+ agentSubscriptions = /* @__PURE__ */ new Map();
1269
+ /**
1270
+ * Initialize state tracking for an agent
1271
+ */
1272
+ initialize() {
1273
+ }
1274
+ /**
1275
+ * Subscribe to an agent's events to track state and messages
1276
+ */
1277
+ subscribeToAgent(agent) {
1278
+ if (!agent.agentId) {
1279
+ return;
1280
+ }
1281
+ const agentId = agent.agentId;
1282
+ this.unsubscribeFromAgent(agentId);
1283
+ const { unsubscribe } = agent.subscribe({
1284
+ onRunStartedEvent: ({ event, state }) => {
1285
+ this.handleRunStarted(agent, event, state);
1286
+ },
1287
+ onRunFinishedEvent: ({ event, state }) => {
1288
+ this.handleRunFinished(agent, event, state);
1289
+ },
1290
+ onStateSnapshotEvent: ({ event, input, state }) => {
1291
+ this.handleStateSnapshot(agent, event, input, state);
1292
+ },
1293
+ onStateDeltaEvent: ({ event, input, state }) => {
1294
+ this.handleStateDelta(agent, event, input, state);
1295
+ },
1296
+ onMessagesSnapshotEvent: ({ event, input, messages }) => {
1297
+ this.handleMessagesSnapshot(agent, event, input, messages);
1298
+ },
1299
+ onNewMessage: ({ message, input }) => {
1300
+ this.handleNewMessage(agent, message, input);
1301
+ }
1302
+ });
1303
+ this.agentSubscriptions.set(agentId, unsubscribe);
1304
+ }
1305
+ /**
1306
+ * Unsubscribe from an agent's events
1307
+ */
1308
+ unsubscribeFromAgent(agentId) {
1309
+ const unsubscribe = this.agentSubscriptions.get(agentId);
1310
+ if (unsubscribe) {
1311
+ unsubscribe();
1312
+ this.agentSubscriptions.delete(agentId);
1313
+ }
1314
+ }
1315
+ /**
1316
+ * Get state for a specific run
1317
+ * Returns a deep copy to prevent external mutations
1318
+ */
1319
+ getStateByRun(agentId, threadId, runId) {
1320
+ const state = this.stateByRun.get(agentId)?.get(threadId)?.get(runId);
1321
+ if (!state) return void 0;
1322
+ return JSON.parse(JSON.stringify(state));
1323
+ }
1324
+ /**
1325
+ * Get runId associated with a message
1326
+ */
1327
+ getRunIdForMessage(agentId, threadId, messageId) {
1328
+ return this.messageToRun.get(agentId)?.get(threadId)?.get(messageId);
1329
+ }
1330
+ /**
1331
+ * Get all states for an agent's thread
1332
+ */
1333
+ getStatesForThread(agentId, threadId) {
1334
+ return this.stateByRun.get(agentId)?.get(threadId) ?? /* @__PURE__ */ new Map();
1335
+ }
1336
+ /**
1337
+ * Get all run IDs for an agent's thread
1338
+ */
1339
+ getRunIdsForThread(agentId, threadId) {
1340
+ const threadStates = this.stateByRun.get(agentId)?.get(threadId);
1341
+ return threadStates ? Array.from(threadStates.keys()) : [];
1342
+ }
1343
+ /**
1344
+ * Handle run started event
1345
+ */
1346
+ handleRunStarted(agent, event, state) {
1347
+ if (!agent.agentId) return;
1348
+ const { threadId, runId } = event;
1349
+ this.saveState(agent.agentId, threadId, runId, state);
1350
+ }
1351
+ /**
1352
+ * Handle run finished event
1353
+ */
1354
+ handleRunFinished(agent, event, state) {
1355
+ if (!agent.agentId) return;
1356
+ const { threadId, runId } = event;
1357
+ this.saveState(agent.agentId, threadId, runId, state);
1358
+ }
1359
+ /**
1360
+ * Handle state snapshot event
1361
+ */
1362
+ handleStateSnapshot(agent, event, input, state) {
1363
+ if (!agent.agentId) return;
1364
+ const { threadId, runId } = input;
1365
+ const mergedState = { ...state, ...event.snapshot };
1366
+ this.saveState(agent.agentId, threadId, runId, mergedState);
1367
+ }
1368
+ /**
1369
+ * Handle state delta event
1370
+ */
1371
+ handleStateDelta(agent, event, input, state) {
1372
+ if (!agent.agentId) return;
1373
+ const { threadId, runId } = input;
1374
+ this.saveState(agent.agentId, threadId, runId, state);
1375
+ }
1376
+ /**
1377
+ * Handle messages snapshot event
1378
+ */
1379
+ handleMessagesSnapshot(agent, event, input, messages) {
1380
+ if (!agent.agentId) return;
1381
+ const { threadId, runId } = input;
1382
+ for (const message of event.messages) {
1383
+ this.associateMessageWithRun(agent.agentId, threadId, message.id, runId);
1384
+ }
1385
+ }
1386
+ /**
1387
+ * Handle new message event
1388
+ */
1389
+ handleNewMessage(agent, message, input) {
1390
+ if (!agent.agentId || !input) return;
1391
+ const { threadId, runId } = input;
1392
+ this.associateMessageWithRun(agent.agentId, threadId, message.id, runId);
1393
+ }
1394
+ /**
1395
+ * Save state for a specific run
1396
+ */
1397
+ saveState(agentId, threadId, runId, state) {
1398
+ if (!this.stateByRun.has(agentId)) {
1399
+ this.stateByRun.set(agentId, /* @__PURE__ */ new Map());
1400
+ }
1401
+ const agentStates = this.stateByRun.get(agentId);
1402
+ if (!agentStates.has(threadId)) {
1403
+ agentStates.set(threadId, /* @__PURE__ */ new Map());
1404
+ }
1405
+ const threadStates = agentStates.get(threadId);
1406
+ threadStates.set(runId, JSON.parse(JSON.stringify(state)));
1407
+ }
1408
+ /**
1409
+ * Associate a message with a run
1410
+ */
1411
+ associateMessageWithRun(agentId, threadId, messageId, runId) {
1412
+ if (!this.messageToRun.has(agentId)) {
1413
+ this.messageToRun.set(agentId, /* @__PURE__ */ new Map());
1414
+ }
1415
+ const agentMessages = this.messageToRun.get(agentId);
1416
+ if (!agentMessages.has(threadId)) {
1417
+ agentMessages.set(threadId, /* @__PURE__ */ new Map());
1418
+ }
1419
+ const threadMessages = agentMessages.get(threadId);
1420
+ threadMessages.set(messageId, runId);
1421
+ }
1422
+ /**
1423
+ * Clear all state for an agent
1424
+ */
1425
+ clearAgentState(agentId) {
1426
+ this.stateByRun.delete(agentId);
1427
+ this.messageToRun.delete(agentId);
1428
+ }
1429
+ /**
1430
+ * Clear all state for a thread
1431
+ */
1432
+ clearThreadState(agentId, threadId) {
1433
+ this.stateByRun.get(agentId)?.delete(threadId);
1434
+ this.messageToRun.get(agentId)?.delete(threadId);
1435
+ }
1436
+ };
1437
+
1438
+ // src/core/core.ts
1439
+ var CopilotKitCoreErrorCode = /* @__PURE__ */ ((CopilotKitCoreErrorCode2) => {
1440
+ CopilotKitCoreErrorCode2["RUNTIME_INFO_FETCH_FAILED"] = "runtime_info_fetch_failed";
1441
+ CopilotKitCoreErrorCode2["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
1442
+ CopilotKitCoreErrorCode2["AGENT_RUN_FAILED"] = "agent_run_failed";
1443
+ CopilotKitCoreErrorCode2["AGENT_RUN_FAILED_EVENT"] = "agent_run_failed_event";
1444
+ CopilotKitCoreErrorCode2["AGENT_RUN_ERROR_EVENT"] = "agent_run_error_event";
1445
+ CopilotKitCoreErrorCode2["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
1446
+ CopilotKitCoreErrorCode2["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
1447
+ return CopilotKitCoreErrorCode2;
1448
+ })(CopilotKitCoreErrorCode || {});
1449
+ var CopilotKitCoreRuntimeConnectionStatus = /* @__PURE__ */ ((CopilotKitCoreRuntimeConnectionStatus2) => {
1450
+ CopilotKitCoreRuntimeConnectionStatus2["Disconnected"] = "disconnected";
1451
+ CopilotKitCoreRuntimeConnectionStatus2["Connected"] = "connected";
1452
+ CopilotKitCoreRuntimeConnectionStatus2["Connecting"] = "connecting";
1453
+ CopilotKitCoreRuntimeConnectionStatus2["Error"] = "error";
1454
+ return CopilotKitCoreRuntimeConnectionStatus2;
1455
+ })(CopilotKitCoreRuntimeConnectionStatus || {});
1456
+ var CopilotKitCore = class {
1457
+ _headers;
1458
+ _properties;
1459
+ subscribers = /* @__PURE__ */ new Set();
1460
+ // Delegate classes
1461
+ agentRegistry;
1462
+ contextStore;
1463
+ suggestionEngine;
1464
+ runHandler;
1465
+ stateManager;
1466
+ constructor({
1467
+ runtimeUrl,
1468
+ runtimeTransport = "rest",
1469
+ headers = {},
1470
+ properties = {},
1471
+ agents__unsafe_dev_only = {},
1472
+ tools = [],
1473
+ suggestionsConfig = []
1474
+ }) {
1475
+ this._headers = headers;
1476
+ this._properties = properties;
1477
+ this.agentRegistry = new AgentRegistry(this);
1478
+ this.contextStore = new ContextStore(this);
1479
+ this.suggestionEngine = new SuggestionEngine(this);
1480
+ this.runHandler = new RunHandler(this);
1481
+ this.stateManager = new StateManager(this);
1482
+ this.agentRegistry.initialize(agents__unsafe_dev_only);
1483
+ this.runHandler.initialize(tools);
1484
+ this.suggestionEngine.initialize(suggestionsConfig);
1485
+ this.stateManager.initialize();
1486
+ this.agentRegistry.setRuntimeTransport(runtimeTransport);
1487
+ this.agentRegistry.setRuntimeUrl(runtimeUrl);
1488
+ this.subscribe({
1489
+ onAgentsChanged: ({ agents }) => {
1490
+ Object.values(agents).forEach((agent) => {
1491
+ if (agent.agentId) {
1492
+ this.stateManager.subscribeToAgent(agent);
1493
+ }
1494
+ });
1495
+ }
1496
+ });
1497
+ }
1498
+ /**
1499
+ * Internal method used by delegate classes and subclasses to notify subscribers
1500
+ */
1501
+ async notifySubscribers(handler, errorMessage) {
1502
+ await Promise.all(
1503
+ Array.from(this.subscribers).map(async (subscriber) => {
1504
+ try {
1505
+ await handler(subscriber);
1506
+ } catch (error) {
1507
+ console.error(errorMessage, error);
1508
+ }
1509
+ })
1510
+ );
1511
+ }
1512
+ /**
1513
+ * Internal method used by delegate classes to emit errors
1514
+ */
1515
+ async emitError({
1516
+ error,
1517
+ code,
1518
+ context = {}
1519
+ }) {
1520
+ await this.notifySubscribers(
1521
+ (subscriber) => subscriber.onError?.({
1522
+ copilotkit: this,
1523
+ error,
1524
+ code,
1525
+ context
1526
+ }),
1527
+ "Subscriber onError error:"
1528
+ );
1529
+ }
1530
+ /**
1531
+ * Snapshot accessors
1532
+ */
1533
+ get context() {
1534
+ return this.contextStore.context;
1535
+ }
1536
+ get agents() {
1537
+ return this.agentRegistry.agents;
1538
+ }
1539
+ get tools() {
1540
+ return this.runHandler.tools;
1541
+ }
1542
+ get runtimeUrl() {
1543
+ return this.agentRegistry.runtimeUrl;
1544
+ }
1545
+ setRuntimeUrl(runtimeUrl) {
1546
+ this.agentRegistry.setRuntimeUrl(runtimeUrl);
1547
+ }
1548
+ get runtimeTransport() {
1549
+ return this.agentRegistry.runtimeTransport;
1550
+ }
1551
+ setRuntimeTransport(runtimeTransport) {
1552
+ this.agentRegistry.setRuntimeTransport(runtimeTransport);
1553
+ }
1554
+ get runtimeVersion() {
1555
+ return this.agentRegistry.runtimeVersion;
1556
+ }
1557
+ get headers() {
1558
+ return this._headers;
1559
+ }
1560
+ get properties() {
1561
+ return this._properties;
1562
+ }
1563
+ get runtimeConnectionStatus() {
1564
+ return this.agentRegistry.runtimeConnectionStatus;
1565
+ }
1566
+ /**
1567
+ * Configuration updates
1568
+ */
1569
+ setHeaders(headers) {
1570
+ this._headers = headers;
1571
+ this.agentRegistry.applyHeadersToAgents(this.agentRegistry.agents);
1572
+ void this.notifySubscribers(
1573
+ (subscriber) => subscriber.onHeadersChanged?.({
1574
+ copilotkit: this,
1575
+ headers: this.headers
1576
+ }),
1577
+ "Subscriber onHeadersChanged error:"
1578
+ );
1579
+ }
1580
+ setProperties(properties) {
1581
+ this._properties = properties;
1582
+ void this.notifySubscribers(
1583
+ (subscriber) => subscriber.onPropertiesChanged?.({
1584
+ copilotkit: this,
1585
+ properties: this.properties
1586
+ }),
1587
+ "Subscriber onPropertiesChanged error:"
1588
+ );
1589
+ }
1590
+ /**
1591
+ * Agent management (delegated to AgentRegistry)
1592
+ */
1593
+ setAgents__unsafe_dev_only(agents) {
1594
+ this.agentRegistry.setAgents__unsafe_dev_only(agents);
1595
+ }
1596
+ addAgent__unsafe_dev_only(params) {
1597
+ this.agentRegistry.addAgent__unsafe_dev_only(params);
1598
+ }
1599
+ removeAgent__unsafe_dev_only(id) {
1600
+ this.agentRegistry.removeAgent__unsafe_dev_only(id);
1601
+ }
1602
+ getAgent(id) {
1603
+ return this.agentRegistry.getAgent(id);
1604
+ }
1605
+ /**
1606
+ * Context management (delegated to ContextStore)
1607
+ */
1608
+ addContext(context) {
1609
+ return this.contextStore.addContext(context);
1610
+ }
1611
+ removeContext(id) {
1612
+ this.contextStore.removeContext(id);
1613
+ }
1614
+ /**
1615
+ * Suggestions management (delegated to SuggestionEngine)
1616
+ */
1617
+ addSuggestionsConfig(config) {
1618
+ return this.suggestionEngine.addSuggestionsConfig(config);
1619
+ }
1620
+ removeSuggestionsConfig(id) {
1621
+ this.suggestionEngine.removeSuggestionsConfig(id);
1622
+ }
1623
+ reloadSuggestions(agentId) {
1624
+ this.suggestionEngine.reloadSuggestions(agentId);
1625
+ }
1626
+ clearSuggestions(agentId) {
1627
+ this.suggestionEngine.clearSuggestions(agentId);
1628
+ }
1629
+ getSuggestions(agentId) {
1630
+ return this.suggestionEngine.getSuggestions(agentId);
1631
+ }
1632
+ /**
1633
+ * Tool management (delegated to RunHandler)
1634
+ */
1635
+ addTool(tool) {
1636
+ this.runHandler.addTool(tool);
1637
+ }
1638
+ removeTool(id, agentId) {
1639
+ this.runHandler.removeTool(id, agentId);
1640
+ }
1641
+ getTool(params) {
1642
+ return this.runHandler.getTool(params);
1643
+ }
1644
+ setTools(tools) {
1645
+ this.runHandler.setTools(tools);
1646
+ }
1647
+ /**
1648
+ * Subscription lifecycle
1649
+ */
1650
+ subscribe(subscriber) {
1651
+ this.subscribers.add(subscriber);
1652
+ return {
1653
+ unsubscribe: () => {
1654
+ this.subscribers.delete(subscriber);
1655
+ }
1656
+ };
1657
+ }
1658
+ /**
1659
+ * Agent connectivity (delegated to RunHandler)
1660
+ */
1661
+ async connectAgent(params) {
1662
+ return this.runHandler.connectAgent(params);
1663
+ }
1664
+ stopAgent(params) {
1665
+ params.agent.abortRun();
1666
+ }
1667
+ async runAgent(params) {
1668
+ return this.runHandler.runAgent(params);
1669
+ }
1670
+ /**
1671
+ * State management (delegated to StateManager)
1672
+ */
1673
+ getStateByRun(agentId, threadId, runId) {
1674
+ return this.stateManager.getStateByRun(agentId, threadId, runId);
1675
+ }
1676
+ getRunIdForMessage(agentId, threadId, messageId) {
1677
+ return this.stateManager.getRunIdForMessage(agentId, threadId, messageId);
1678
+ }
1679
+ getRunIdsForThread(agentId, threadId) {
1680
+ return this.stateManager.getRunIdsForThread(agentId, threadId);
1681
+ }
1682
+ /**
1683
+ * Internal method used by RunHandler to build frontend tools
1684
+ */
1685
+ buildFrontendTools(agentId) {
1686
+ return this.runHandler.buildFrontendTools(agentId);
1687
+ }
1688
+ };
1689
+
1690
+ // src/types.ts
1691
+ var ToolCallStatus = /* @__PURE__ */ ((ToolCallStatus2) => {
1692
+ ToolCallStatus2["InProgress"] = "inProgress";
1693
+ ToolCallStatus2["Executing"] = "executing";
1694
+ ToolCallStatus2["Complete"] = "complete";
1695
+ return ToolCallStatus2;
1696
+ })(ToolCallStatus || {});
1697
+
1698
+ // src/utils/markdown.ts
1699
+ function completePartialMarkdown(input) {
1700
+ let s = input;
1701
+ const fenceMatches = Array.from(s.matchAll(/^(\s*)(`{3,}|~{3,})/gm));
1702
+ if (fenceMatches.length % 2 === 1) {
1703
+ const [, indent, fence] = fenceMatches[0];
1704
+ s += `
1705
+ ${indent}${fence}`;
1706
+ }
1707
+ const incompleteLinkMatch = s.match(/\[([^\]]*)\]\(([^)]*)$/);
1708
+ if (incompleteLinkMatch) {
1709
+ s += ")";
1710
+ }
1711
+ const openElements = [];
1712
+ const chars = Array.from(s);
1713
+ const codeBlockRanges = [];
1714
+ const inlineCodeRanges = [];
1715
+ let tempCodeFenceCount = 0;
1716
+ let currentCodeBlockStart = -1;
1717
+ for (let i = 0; i < chars.length; i++) {
1718
+ if (i === 0 || chars[i - 1] === "\n") {
1719
+ const lineMatch = s.substring(i).match(/^(\s*)(`{3,}|~{3,})/);
1720
+ if (lineMatch) {
1721
+ tempCodeFenceCount++;
1722
+ if (tempCodeFenceCount % 2 === 1) {
1723
+ currentCodeBlockStart = i;
1724
+ } else if (currentCodeBlockStart !== -1) {
1725
+ codeBlockRanges.push({
1726
+ start: currentCodeBlockStart,
1727
+ end: i + lineMatch[0].length
1728
+ });
1729
+ currentCodeBlockStart = -1;
1730
+ }
1731
+ i += lineMatch[0].length - 1;
1732
+ }
1733
+ }
1734
+ }
1735
+ for (let i = 0; i < chars.length; i++) {
1736
+ if (chars[i] === "`") {
1737
+ let backslashCount = 0;
1738
+ for (let j = i - 1; j >= 0 && chars[j] === "\\"; j--) {
1739
+ backslashCount++;
1740
+ }
1741
+ if (backslashCount % 2 === 0) {
1742
+ for (let j = i + 1; j < chars.length; j++) {
1743
+ if (chars[j] === "`") {
1744
+ let closingBackslashCount = 0;
1745
+ for (let k = j - 1; k >= 0 && chars[k] === "\\"; k--) {
1746
+ closingBackslashCount++;
1747
+ }
1748
+ if (closingBackslashCount % 2 === 0) {
1749
+ inlineCodeRanges.push({ start: i, end: j + 1 });
1750
+ i = j;
1751
+ break;
1752
+ }
1753
+ }
1754
+ }
1755
+ }
1756
+ }
1757
+ }
1758
+ const isInCode = (pos) => {
1759
+ return codeBlockRanges.some((range) => pos >= range.start && pos < range.end) || inlineCodeRanges.some((range) => pos >= range.start && pos < range.end);
1760
+ };
1761
+ for (let i = 0; i < chars.length; i++) {
1762
+ const char = chars[i];
1763
+ const nextChar = chars[i + 1];
1764
+ const prevChar = chars[i - 1];
1765
+ if (isInCode(i)) {
1766
+ continue;
1767
+ }
1768
+ if (char === "[") {
1769
+ let isCompleteLink = false;
1770
+ let bracketDepth = 1;
1771
+ let j = i + 1;
1772
+ while (j < chars.length && bracketDepth > 0) {
1773
+ if (chars[j] === "[" && !isInCode(j)) bracketDepth++;
1774
+ if (chars[j] === "]" && !isInCode(j)) bracketDepth--;
1775
+ j++;
1776
+ }
1777
+ if (bracketDepth === 0 && chars[j] === "(") {
1778
+ let parenDepth = 1;
1779
+ j++;
1780
+ while (j < chars.length && parenDepth > 0) {
1781
+ if (chars[j] === "(" && !isInCode(j)) parenDepth++;
1782
+ if (chars[j] === ")" && !isInCode(j)) parenDepth--;
1783
+ j++;
1784
+ }
1785
+ if (parenDepth === 0) {
1786
+ isCompleteLink = true;
1787
+ i = j - 1;
1788
+ continue;
1789
+ }
1790
+ }
1791
+ if (!isCompleteLink) {
1792
+ const existingIndex = openElements.findIndex(
1793
+ (el) => el.type === "bracket"
1794
+ );
1795
+ if (existingIndex !== -1) {
1796
+ openElements.splice(existingIndex, 1);
1797
+ } else {
1798
+ openElements.push({ type: "bracket", marker: "[", position: i });
1799
+ }
1800
+ }
1801
+ } else if (char === "*" && nextChar === "*") {
1802
+ const existingIndex = openElements.findIndex(
1803
+ (el) => el.type === "bold_star"
1804
+ );
1805
+ if (existingIndex !== -1) {
1806
+ openElements.splice(existingIndex, 1);
1807
+ } else {
1808
+ openElements.push({ type: "bold_star", marker: "**", position: i });
1809
+ }
1810
+ i++;
1811
+ } else if (char === "_" && nextChar === "_") {
1812
+ const existingIndex = openElements.findIndex(
1813
+ (el) => el.type === "bold_underscore"
1814
+ );
1815
+ if (existingIndex !== -1) {
1816
+ openElements.splice(existingIndex, 1);
1817
+ } else {
1818
+ openElements.push({
1819
+ type: "bold_underscore",
1820
+ marker: "__",
1821
+ position: i
1822
+ });
1823
+ }
1824
+ i++;
1825
+ } else if (char === "~" && nextChar === "~") {
1826
+ const existingIndex = openElements.findIndex(
1827
+ (el) => el.type === "strike"
1828
+ );
1829
+ if (existingIndex !== -1) {
1830
+ openElements.splice(existingIndex, 1);
1831
+ } else {
1832
+ openElements.push({ type: "strike", marker: "~~", position: i });
1833
+ }
1834
+ i++;
1835
+ } else if (char === "*" && prevChar !== "*" && nextChar !== "*") {
1836
+ const existingIndex = openElements.findIndex(
1837
+ (el) => el.type === "italic_star"
1838
+ );
1839
+ if (existingIndex !== -1) {
1840
+ openElements.splice(existingIndex, 1);
1841
+ } else {
1842
+ openElements.push({ type: "italic_star", marker: "*", position: i });
1843
+ }
1844
+ } else if (char === "_" && prevChar !== "_" && nextChar !== "_") {
1845
+ const existingIndex = openElements.findIndex(
1846
+ (el) => el.type === "italic_underscore"
1847
+ );
1848
+ if (existingIndex !== -1) {
1849
+ openElements.splice(existingIndex, 1);
1850
+ } else {
1851
+ openElements.push({
1852
+ type: "italic_underscore",
1853
+ marker: "_",
1854
+ position: i
1855
+ });
1856
+ }
1857
+ }
1858
+ }
1859
+ let backtickCount = 0;
1860
+ for (let i = 0; i < chars.length; i++) {
1861
+ if (chars[i] === "`" && !isInCode(i)) {
1862
+ backtickCount++;
1863
+ }
1864
+ }
1865
+ if (backtickCount % 2 === 1) {
1866
+ s += "`";
1867
+ }
1868
+ openElements.sort((a, b) => b.position - a.position);
1869
+ const closers = openElements.map((el) => {
1870
+ switch (el.type) {
1871
+ case "bracket":
1872
+ return "]";
1873
+ case "bold_star":
1874
+ return "**";
1875
+ case "bold_underscore":
1876
+ return "__";
1877
+ case "strike":
1878
+ return "~~";
1879
+ case "italic_star":
1880
+ return "*";
1881
+ case "italic_underscore":
1882
+ return "_";
1883
+ default:
1884
+ return "";
1885
+ }
1886
+ });
1887
+ let result = s + closers.join("");
1888
+ const finalFenceMatches = Array.from(
1889
+ result.matchAll(/^(\s*)(`{3,}|~{3,})/gm)
1890
+ );
1891
+ const hasUnclosedBacktick = (result.match(/`/g) || []).length % 2 === 1;
1892
+ const hasUnclosedCodeFence = finalFenceMatches.length % 2 === 1;
1893
+ let shouldCloseParens = !hasUnclosedBacktick && !hasUnclosedCodeFence;
1894
+ if (shouldCloseParens) {
1895
+ const lastOpenParen = result.lastIndexOf("(");
1896
+ if (lastOpenParen !== -1) {
1897
+ const beforeParen = result.substring(0, lastOpenParen);
1898
+ const backticksBeforeParen = (beforeParen.match(/`/g) || []).length;
1899
+ if (backticksBeforeParen % 2 === 1) {
1900
+ shouldCloseParens = false;
1901
+ }
1902
+ }
1903
+ }
1904
+ if (shouldCloseParens) {
1905
+ const openParens = (result.match(/\(/g) || []).length;
1906
+ const closeParens = (result.match(/\)/g) || []).length;
1907
+ if (openParens > closeParens) {
1908
+ result += ")".repeat(openParens - closeParens);
1909
+ }
1910
+ }
1911
+ return result;
1912
+ }
1913
+ export {
1914
+ AgentRegistry,
1915
+ ContextStore,
1916
+ CopilotKitCore,
1917
+ CopilotKitCoreErrorCode,
1918
+ CopilotKitCoreRuntimeConnectionStatus,
1919
+ ProxiedCopilotRuntimeAgent,
1920
+ RunHandler,
1921
+ StateManager,
1922
+ SuggestionEngine,
1923
+ ToolCallStatus,
1924
+ completePartialMarkdown
1925
+ };
1926
+ //# sourceMappingURL=index.mjs.map