@copilotkitnext/core 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/.turbo/turbo-build.log +22 -0
  2. package/.turbo/turbo-check-types.log +4 -0
  3. package/.turbo/turbo-lint.log +12 -0
  4. package/.turbo/turbo-test.log +96 -0
  5. package/LICENSE +11 -0
  6. package/coverage/base.css +224 -0
  7. package/coverage/block-navigation.js +87 -0
  8. package/coverage/favicon.png +0 -0
  9. package/coverage/index.html +131 -0
  10. package/coverage/lcov-report/base.css +224 -0
  11. package/coverage/lcov-report/block-navigation.js +87 -0
  12. package/coverage/lcov-report/favicon.png +0 -0
  13. package/coverage/lcov-report/index.html +131 -0
  14. package/coverage/lcov-report/prettify.css +1 -0
  15. package/coverage/lcov-report/prettify.js +2 -0
  16. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  17. package/coverage/lcov-report/sorter.js +210 -0
  18. package/coverage/lcov-report/src/agent.ts.html +193 -0
  19. package/coverage/lcov-report/src/core.ts.html +919 -0
  20. package/coverage/lcov-report/src/index.html +146 -0
  21. package/coverage/lcov-report/src/types.ts.html +112 -0
  22. package/coverage/lcov-report/src/utils/index.html +116 -0
  23. package/coverage/lcov-report/src/utils/markdown.ts.html +895 -0
  24. package/coverage/lcov.info +556 -0
  25. package/coverage/prettify.css +1 -0
  26. package/coverage/prettify.js +2 -0
  27. package/coverage/sort-arrow-sprite.png +0 -0
  28. package/coverage/sorter.js +210 -0
  29. package/coverage/src/agent.ts.html +193 -0
  30. package/coverage/src/core.ts.html +919 -0
  31. package/coverage/src/index.html +146 -0
  32. package/coverage/src/types.ts.html +112 -0
  33. package/coverage/src/utils/index.html +116 -0
  34. package/coverage/src/utils/markdown.ts.html +895 -0
  35. package/dist/index.d.mts +93 -0
  36. package/dist/index.d.ts +93 -0
  37. package/dist/index.js +526 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/index.mjs +502 -0
  40. package/dist/index.mjs.map +1 -0
  41. package/eslint.config.mjs +3 -0
  42. package/package.json +46 -0
  43. package/src/__tests__/core-agent-constraints.test.ts +86 -0
  44. package/src/__tests__/core-basic-functionality.test.ts +158 -0
  45. package/src/__tests__/core-basic.test.ts +27 -0
  46. package/src/__tests__/core-edge-cases.test.ts +166 -0
  47. package/src/__tests__/core-follow-up.test.ts +216 -0
  48. package/src/__tests__/core-full.test.ts +320 -0
  49. package/src/__tests__/core-simple.test.ts +24 -0
  50. package/src/__tests__/core-tool-minimal.test.ts +41 -0
  51. package/src/__tests__/core-tool-simple.test.ts +40 -0
  52. package/src/__tests__/core-wildcard.test.ts +45 -0
  53. package/src/__tests__/import.test.ts +13 -0
  54. package/src/__tests__/simple.test.ts +7 -0
  55. package/src/__tests__/test-utils.ts +162 -0
  56. package/src/agent.ts +37 -0
  57. package/src/core.ts +336 -0
  58. package/src/index.ts +4 -0
  59. package/src/types.ts +23 -0
  60. package/src/utils/markdown.ts +271 -0
  61. package/tsconfig.json +12 -0
  62. package/tsup.config.ts +11 -0
  63. package/vitest.config.mjs +15 -0
package/src/core.ts ADDED
@@ -0,0 +1,336 @@
1
+ import {
2
+ AgentDescription,
3
+ randomUUID,
4
+ RuntimeInfo,
5
+ } from "@copilotkitnext/shared";
6
+ import { logger } from "@copilotkitnext/shared";
7
+ import { AbstractAgent, Context, HttpAgent, Message } from "@ag-ui/client";
8
+ import { FrontendTool } from "./types";
9
+ import { CopilotKitHttpAgent } from "./agent";
10
+
11
+ export interface CopilotKitCoreConfig {
12
+ runtimeUrl?: string;
13
+ agents?: Record<string, AbstractAgent>;
14
+ headers?: Record<string, string>;
15
+ properties?: Record<string, unknown>;
16
+ tools?: Record<string, FrontendTool<any>>;
17
+ }
18
+
19
+ export interface CopilotKitCoreAddAgentParams {
20
+ id: string;
21
+ agent: AbstractAgent;
22
+ }
23
+
24
+ export interface RunAgentParams {
25
+ agent: AbstractAgent;
26
+ withMessages?: Message[];
27
+ agentId?: string;
28
+ }
29
+
30
+ export interface CopilotKitCoreSubscriber {
31
+ onRuntimeLoaded?: (event: {
32
+ copilotkit: CopilotKitCore;
33
+ }) => void | Promise<void>;
34
+ onRuntimeLoadError?: (event: {
35
+ copilotkit: CopilotKitCore;
36
+ }) => void | Promise<void>;
37
+ }
38
+
39
+ export class CopilotKitCore {
40
+ runtimeUrl?: string;
41
+ didLoadRuntime: boolean = false;
42
+
43
+ context: Record<string, Context> = {};
44
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
45
+ tools: Record<string, FrontendTool<any>> = {};
46
+ agents: Record<string, AbstractAgent> = {};
47
+
48
+ headers: Record<string, string>;
49
+ properties: Record<string, unknown>;
50
+
51
+ version?: string;
52
+
53
+ private localAgents: Record<string, AbstractAgent> = {};
54
+ private remoteAgents: Record<string, AbstractAgent> = {};
55
+ private subscribers: Set<CopilotKitCoreSubscriber> = new Set();
56
+
57
+ constructor({
58
+ runtimeUrl,
59
+ headers = {},
60
+ properties = {},
61
+ agents = {},
62
+ tools = {},
63
+ }: CopilotKitCoreConfig) {
64
+ this.headers = headers;
65
+ this.properties = properties;
66
+ this.localAgents = agents;
67
+ this.agents = this.localAgents;
68
+ this.tools = tools;
69
+
70
+ this.setRuntimeUrl(runtimeUrl);
71
+ }
72
+
73
+ private async getRuntimeInfo() {
74
+ const response = await fetch(`${this.runtimeUrl}/info`, {
75
+ headers: this.headers,
76
+ });
77
+ const {
78
+ version,
79
+ ...runtimeInfo
80
+ }: {
81
+ agents: Record<string, AgentDescription>;
82
+ version: string;
83
+ } = (await response.json()) as RuntimeInfo;
84
+
85
+ const agents: Record<string, AbstractAgent> = Object.fromEntries(
86
+ Object.entries(runtimeInfo.agents).map(([id, { description }]) => {
87
+ const agent = new CopilotKitHttpAgent({
88
+ runtimeUrl: this.runtimeUrl,
89
+ agentId: id,
90
+ description: description,
91
+ });
92
+ return [id, agent];
93
+ })
94
+ );
95
+
96
+ return { agents, version };
97
+ }
98
+
99
+ private async fetchRemoteAgents() {
100
+ if (this.runtimeUrl) {
101
+ this.getRuntimeInfo()
102
+ .then(({ agents, version }) => {
103
+ this.remoteAgents = agents;
104
+ this.agents = { ...this.localAgents, ...this.remoteAgents };
105
+ this.didLoadRuntime = true;
106
+ this.version = version;
107
+
108
+ this.subscribers.forEach(async (subscriber) => {
109
+ try {
110
+ await subscriber.onRuntimeLoaded?.({ copilotkit: this });
111
+ } catch (error) {
112
+ logger.error(
113
+ "Error in CopilotKitCore subscriber (onRuntimeLoaded):",
114
+ error
115
+ );
116
+ }
117
+ });
118
+ })
119
+ .catch((error) => {
120
+ this.subscribers.forEach(async (subscriber) => {
121
+ try {
122
+ await subscriber.onRuntimeLoadError?.({ copilotkit: this });
123
+ } catch (error) {
124
+ logger.error(
125
+ "Error in CopilotKitCore subscriber (onRuntimeLoadError):",
126
+ error
127
+ );
128
+ }
129
+ });
130
+ logger.warn(`Failed to load runtime info: ${error.message}`);
131
+ });
132
+ }
133
+ }
134
+
135
+ setAgents(agents: Record<string, AbstractAgent>) {
136
+ this.localAgents = agents;
137
+ this.agents = { ...this.localAgents, ...this.remoteAgents };
138
+ }
139
+
140
+ addAgent({ id, agent }: CopilotKitCoreAddAgentParams) {
141
+ this.localAgents[id] = agent;
142
+ this.agents = { ...this.localAgents, ...this.remoteAgents };
143
+ }
144
+
145
+ removeAgent(id: string) {
146
+ delete this.localAgents[id];
147
+ this.agents = { ...this.localAgents, ...this.remoteAgents };
148
+ }
149
+
150
+ getAgent(id: string): AbstractAgent | undefined {
151
+ if (id in this.agents) {
152
+ return this.agents[id] as AbstractAgent;
153
+ } else {
154
+ if (!this.didLoadRuntime) {
155
+ return undefined;
156
+ } else {
157
+ throw new Error(`Agent ${id} not found`);
158
+ }
159
+ }
160
+ }
161
+
162
+ addContext({ description, value }: Context): string {
163
+ const id = randomUUID();
164
+ this.context[id] = { description, value };
165
+ return id;
166
+ }
167
+
168
+ removeContext(id: string) {
169
+ delete this.context[id];
170
+ }
171
+
172
+ setRuntimeUrl(runtimeUrl?: string) {
173
+ this.runtimeUrl = runtimeUrl ? runtimeUrl.replace(/\/$/, "") : undefined;
174
+ this.fetchRemoteAgents();
175
+ }
176
+
177
+ addTool<T extends Record<string, unknown> = Record<string, unknown>>(
178
+ tool: FrontendTool<T>
179
+ ) {
180
+ if (tool.name in this.tools) {
181
+ logger.warn(`Tool already exists: '${tool.name}', skipping.`);
182
+ return;
183
+ }
184
+
185
+ this.tools[tool.name] = tool;
186
+ }
187
+
188
+ removeTool(id: string) {
189
+ delete this.tools[id];
190
+ }
191
+
192
+ setHeaders(headers: Record<string, string>) {
193
+ this.headers = headers;
194
+ }
195
+
196
+ setProperties(properties: Record<string, unknown>) {
197
+ this.properties = properties;
198
+ }
199
+
200
+ subscribe(subscriber: CopilotKitCoreSubscriber): () => void {
201
+ this.subscribers.add(subscriber);
202
+
203
+ // Return unsubscribe function
204
+ return () => {
205
+ this.unsubscribe(subscriber);
206
+ };
207
+ }
208
+
209
+ unsubscribe(subscriber: CopilotKitCoreSubscriber) {
210
+ this.subscribers.delete(subscriber);
211
+ }
212
+
213
+ // TODO: AG-UI needs to expose the runAgent result type
214
+ async runAgent({
215
+ agent,
216
+ withMessages,
217
+ agentId,
218
+ }: RunAgentParams): Promise<Awaited<ReturnType<typeof agent.runAgent>>> {
219
+ if (withMessages) {
220
+ agent.addMessages(withMessages);
221
+ }
222
+
223
+ const runAgentResult = await agent.runAgent({
224
+ forwardedProps: this.properties,
225
+ });
226
+
227
+ const { newMessages } = runAgentResult;
228
+
229
+ let needsFollowUp = false;
230
+
231
+ for (const message of newMessages) {
232
+ if (message.role === "assistant") {
233
+ for (const toolCall of message.toolCalls || []) {
234
+ if (
235
+ newMessages.findIndex(
236
+ (m) => m.role === "tool" && m.toolCallId === toolCall.id
237
+ ) === -1
238
+ ) {
239
+ if (toolCall.function.name in this.tools) {
240
+ const tool = this.tools[toolCall.function.name];
241
+
242
+ // Check if tool is constrained to a specific agent
243
+ if (tool?.agentId && tool.agentId !== agentId) {
244
+ // Tool is not available for this agent, skip it
245
+ continue;
246
+ }
247
+
248
+ let toolCallResult = "";
249
+ if (tool?.handler) {
250
+ const args = JSON.parse(toolCall.function.arguments);
251
+ try {
252
+ const result = await tool.handler(args);
253
+ if (result === undefined || result === null) {
254
+ toolCallResult = "";
255
+ } else if (typeof result === "string") {
256
+ toolCallResult = result;
257
+ } else {
258
+ toolCallResult = JSON.stringify(result);
259
+ }
260
+ } catch (error) {
261
+ toolCallResult = `Error: ${error instanceof Error ? error.message : String(error)}`;
262
+ }
263
+ }
264
+
265
+ const messageIndex = agent.messages.findIndex(
266
+ (m) => m.id === message.id
267
+ );
268
+ const toolMessage = {
269
+ id: randomUUID(),
270
+ role: "tool" as const,
271
+ toolCallId: toolCall.id,
272
+ content: toolCallResult,
273
+ };
274
+ agent.messages.splice(messageIndex + 1, 0, toolMessage);
275
+
276
+ if (tool?.followUp !== false) {
277
+ needsFollowUp = true;
278
+ }
279
+ } else if ("*" in this.tools) {
280
+ // Wildcard fallback for undefined tools
281
+ const wildcardTool = this.tools["*"];
282
+
283
+ // Check if wildcard tool is constrained to a specific agent
284
+ if (wildcardTool?.agentId && wildcardTool.agentId !== agentId) {
285
+ // Wildcard tool is not available for this agent, skip it
286
+ continue;
287
+ }
288
+
289
+ let toolCallResult = "";
290
+ if (wildcardTool?.handler) {
291
+ // Pass both the tool name and original args to the wildcard handler
292
+ const wildcardArgs = {
293
+ toolName: toolCall.function.name,
294
+ args: JSON.parse(toolCall.function.arguments),
295
+ };
296
+ try {
297
+ const result = await wildcardTool.handler(wildcardArgs);
298
+ if (result === undefined || result === null) {
299
+ toolCallResult = "";
300
+ } else if (typeof result === "string") {
301
+ toolCallResult = result;
302
+ } else {
303
+ toolCallResult = JSON.stringify(result);
304
+ }
305
+ } catch (error) {
306
+ toolCallResult = `Error: ${error instanceof Error ? error.message : String(error)}`;
307
+ }
308
+ }
309
+
310
+ const messageIndex = agent.messages.findIndex(
311
+ (m) => m.id === message.id
312
+ );
313
+ const toolMessage = {
314
+ id: randomUUID(),
315
+ role: "tool" as const,
316
+ toolCallId: toolCall.id,
317
+ content: toolCallResult,
318
+ };
319
+ agent.messages.splice(messageIndex + 1, 0, toolMessage);
320
+
321
+ if (wildcardTool?.followUp !== false) {
322
+ needsFollowUp = true;
323
+ }
324
+ }
325
+ }
326
+ }
327
+ }
328
+ }
329
+
330
+ if (needsFollowUp) {
331
+ return await this.runAgent({ agent, agentId });
332
+ }
333
+
334
+ return runAgentResult;
335
+ }
336
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./core";
2
+ export * from "./types";
3
+ export * from "./agent";
4
+ export * from "./utils/markdown";
package/src/types.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * Status of a tool call execution
5
+ */
6
+ export enum ToolCallStatus {
7
+ InProgress = "inProgress",
8
+ Executing = "executing",
9
+ Complete = "complete"
10
+ }
11
+
12
+ export type FrontendTool<T extends Record<string, unknown> = Record<string, unknown>> = {
13
+ name: string;
14
+ description?: string;
15
+ parameters?: z.ZodType<T>;
16
+ handler?: (args: T) => Promise<unknown>;
17
+ followUp?: boolean;
18
+ /**
19
+ * Optional agent ID to constrain this tool to a specific agent.
20
+ * If specified, this tool will only be available to the specified agent.
21
+ */
22
+ agentId?: string;
23
+ };
@@ -0,0 +1,271 @@
1
+ export function completePartialMarkdown(input: string): string {
2
+ let s = input;
3
+
4
+ // Handle code fences first - use FIRST unmatched fence for proper nesting
5
+ const fenceMatches = Array.from(s.matchAll(/^(\s*)(`{3,}|~{3,})/gm));
6
+ if (fenceMatches.length % 2 === 1) {
7
+ const [, indent, fence] = fenceMatches[0]!;
8
+ s += `\n${indent}${fence}`;
9
+ }
10
+
11
+ // Identify incomplete links at the end and close them
12
+ const incompleteLinkMatch = s.match(/\[([^\]]*)\]\(([^)]*)$/);
13
+ if (incompleteLinkMatch) {
14
+ s += ")";
15
+ }
16
+
17
+ // State-based parsing
18
+ interface OpenElement {
19
+ type: string;
20
+ marker: string;
21
+ position: number;
22
+ }
23
+
24
+ const openElements: OpenElement[] = [];
25
+ const chars = Array.from(s);
26
+
27
+ // First pass: identify code block boundaries and inline code to avoid processing their content
28
+ const codeBlockRanges: Array<{ start: number; end: number }> = [];
29
+ const inlineCodeRanges: Array<{ start: number; end: number }> = [];
30
+
31
+ // Find code block ranges
32
+ let tempCodeFenceCount = 0;
33
+ let currentCodeBlockStart = -1;
34
+
35
+ for (let i = 0; i < chars.length; i++) {
36
+ if (i === 0 || chars[i - 1] === "\n") {
37
+ const lineMatch = s.substring(i).match(/^(\s*)(`{3,}|~{3,})/);
38
+ if (lineMatch) {
39
+ tempCodeFenceCount++;
40
+ if (tempCodeFenceCount % 2 === 1) {
41
+ currentCodeBlockStart = i;
42
+ } else if (currentCodeBlockStart !== -1) {
43
+ codeBlockRanges.push({
44
+ start: currentCodeBlockStart,
45
+ end: i + lineMatch[0].length,
46
+ });
47
+ currentCodeBlockStart = -1;
48
+ }
49
+ i += lineMatch[0].length - 1;
50
+ }
51
+ }
52
+ }
53
+
54
+ // Find inline code ranges
55
+ for (let i = 0; i < chars.length; i++) {
56
+ if (chars[i] === "`") {
57
+ // Check if escaped
58
+ let backslashCount = 0;
59
+ for (let j = i - 1; j >= 0 && chars[j] === "\\"; j--) {
60
+ backslashCount++;
61
+ }
62
+ if (backslashCount % 2 === 0) {
63
+ // Not escaped - find the closing backtick
64
+ for (let j = i + 1; j < chars.length; j++) {
65
+ if (chars[j] === "`") {
66
+ let closingBackslashCount = 0;
67
+ for (let k = j - 1; k >= 0 && chars[k] === "\\"; k--) {
68
+ closingBackslashCount++;
69
+ }
70
+ if (closingBackslashCount % 2 === 0) {
71
+ inlineCodeRanges.push({ start: i, end: j + 1 });
72
+ i = j;
73
+ break;
74
+ }
75
+ }
76
+ }
77
+ }
78
+ }
79
+ }
80
+
81
+ // Helper function to check if position is in code
82
+ const isInCode = (pos: number): boolean => {
83
+ return (
84
+ codeBlockRanges.some((range) => pos >= range.start && pos < range.end) ||
85
+ inlineCodeRanges.some((range) => pos >= range.start && pos < range.end)
86
+ );
87
+ };
88
+
89
+ // Second pass: process markdown elements, skipping code regions
90
+ for (let i = 0; i < chars.length; i++) {
91
+ const char = chars[i];
92
+ const nextChar = chars[i + 1];
93
+ const prevChar = chars[i - 1];
94
+
95
+ if (isInCode(i)) {
96
+ continue;
97
+ }
98
+
99
+ // Handle brackets (but not if they're part of already-complete links)
100
+ if (char === "[") {
101
+ // Check if this is part of a complete link [text](url)
102
+ let isCompleteLink = false;
103
+ let bracketDepth = 1;
104
+ let j = i + 1;
105
+
106
+ // Find the matching ]
107
+ while (j < chars.length && bracketDepth > 0) {
108
+ if (chars[j] === "[" && !isInCode(j)) bracketDepth++;
109
+ if (chars[j] === "]" && !isInCode(j)) bracketDepth--;
110
+ j++;
111
+ }
112
+
113
+ // Check if followed by (
114
+ if (bracketDepth === 0 && chars[j] === "(") {
115
+ // Find the closing )
116
+ let parenDepth = 1;
117
+ j++;
118
+ while (j < chars.length && parenDepth > 0) {
119
+ if (chars[j] === "(" && !isInCode(j)) parenDepth++;
120
+ if (chars[j] === ")" && !isInCode(j)) parenDepth--;
121
+ j++;
122
+ }
123
+ if (parenDepth === 0) {
124
+ isCompleteLink = true;
125
+ i = j - 1;
126
+ continue;
127
+ }
128
+ }
129
+
130
+ // This is a standalone bracket, treat as markdown
131
+ if (!isCompleteLink) {
132
+ const existingIndex = openElements.findIndex(
133
+ (el) => el.type === "bracket"
134
+ );
135
+ if (existingIndex !== -1) {
136
+ openElements.splice(existingIndex, 1);
137
+ } else {
138
+ openElements.push({ type: "bracket", marker: "[", position: i });
139
+ }
140
+ }
141
+ }
142
+
143
+ // Handle double emphasis first (**, __, ~~) - these take precedence
144
+ else if (char === "*" && nextChar === "*") {
145
+ const existingIndex = openElements.findIndex(
146
+ (el) => el.type === "bold_star"
147
+ );
148
+ if (existingIndex !== -1) {
149
+ openElements.splice(existingIndex, 1);
150
+ } else {
151
+ openElements.push({ type: "bold_star", marker: "**", position: i });
152
+ }
153
+ i++; // Skip next character
154
+ } else if (char === "_" && nextChar === "_") {
155
+ const existingIndex = openElements.findIndex(
156
+ (el) => el.type === "bold_underscore"
157
+ );
158
+ if (existingIndex !== -1) {
159
+ openElements.splice(existingIndex, 1);
160
+ } else {
161
+ openElements.push({
162
+ type: "bold_underscore",
163
+ marker: "__",
164
+ position: i,
165
+ });
166
+ }
167
+ i++; // Skip next character
168
+ } else if (char === "~" && nextChar === "~") {
169
+ const existingIndex = openElements.findIndex(
170
+ (el) => el.type === "strike"
171
+ );
172
+ if (existingIndex !== -1) {
173
+ openElements.splice(existingIndex, 1);
174
+ } else {
175
+ openElements.push({ type: "strike", marker: "~~", position: i });
176
+ }
177
+ i++; // Skip next character
178
+ }
179
+
180
+ // Handle single emphasis (*, _) - only if not part of double
181
+ else if (char === "*" && prevChar !== "*" && nextChar !== "*") {
182
+ const existingIndex = openElements.findIndex(
183
+ (el) => el.type === "italic_star"
184
+ );
185
+ if (existingIndex !== -1) {
186
+ openElements.splice(existingIndex, 1);
187
+ } else {
188
+ openElements.push({ type: "italic_star", marker: "*", position: i });
189
+ }
190
+ } else if (char === "_" && prevChar !== "_" && nextChar !== "_") {
191
+ const existingIndex = openElements.findIndex(
192
+ (el) => el.type === "italic_underscore"
193
+ );
194
+ if (existingIndex !== -1) {
195
+ openElements.splice(existingIndex, 1);
196
+ } else {
197
+ openElements.push({
198
+ type: "italic_underscore",
199
+ marker: "_",
200
+ position: i,
201
+ });
202
+ }
203
+ }
204
+ }
205
+
206
+ // Handle remaining unmatched backticks (outside of inline code ranges)
207
+ let backtickCount = 0;
208
+ for (let i = 0; i < chars.length; i++) {
209
+ if (chars[i] === "`" && !isInCode(i)) {
210
+ backtickCount++;
211
+ }
212
+ }
213
+ if (backtickCount % 2 === 1) {
214
+ s += "`";
215
+ }
216
+
217
+ // Close remaining open elements in reverse order (LIFO stack semantics)
218
+ openElements.sort((a, b) => b.position - a.position);
219
+
220
+ const closers = openElements.map((el) => {
221
+ switch (el.type) {
222
+ case "bracket":
223
+ return "]";
224
+ case "bold_star":
225
+ return "**";
226
+ case "bold_underscore":
227
+ return "__";
228
+ case "strike":
229
+ return "~~";
230
+ case "italic_star":
231
+ return "*";
232
+ case "italic_underscore":
233
+ return "_";
234
+ default:
235
+ return "";
236
+ }
237
+ });
238
+
239
+ let result = s + closers.join("");
240
+
241
+ // Handle parentheses ONLY if not inside code
242
+ const finalFenceMatches = Array.from(
243
+ result.matchAll(/^(\s*)(`{3,}|~{3,})/gm)
244
+ );
245
+ const hasUnclosedBacktick = (result.match(/`/g) || []).length % 2 === 1;
246
+ const hasUnclosedCodeFence = finalFenceMatches.length % 2 === 1;
247
+
248
+ let shouldCloseParens = !hasUnclosedBacktick && !hasUnclosedCodeFence;
249
+
250
+ if (shouldCloseParens) {
251
+ const lastOpenParen = result.lastIndexOf("(");
252
+ if (lastOpenParen !== -1) {
253
+ // Check if this paren is inside a backtick pair
254
+ const beforeParen = result.substring(0, lastOpenParen);
255
+ const backticksBeforeParen = (beforeParen.match(/`/g) || []).length;
256
+ if (backticksBeforeParen % 2 === 1) {
257
+ shouldCloseParens = false;
258
+ }
259
+ }
260
+ }
261
+
262
+ if (shouldCloseParens) {
263
+ const openParens = (result.match(/\(/g) || []).length;
264
+ const closeParens = (result.match(/\)/g) || []).length;
265
+ if (openParens > closeParens) {
266
+ result += ")".repeat(openParens - closeParens);
267
+ }
268
+ }
269
+
270
+ return result;
271
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "extends": "@copilotkitnext/typescript-config/base.json",
3
+ "compilerOptions": {
4
+ "outDir": "dist",
5
+ "rootDir": "src",
6
+ "declaration": true,
7
+ "declarationMap": true,
8
+ "sourceMap": true
9
+ },
10
+ "include": ["src/**/*"],
11
+ "exclude": ["dist", "node_modules"]
12
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { defineConfig } from 'tsup';
2
+
3
+ export default defineConfig({
4
+ entry: ['src/index.ts'],
5
+ format: ['cjs', 'esm'],
6
+ dts: true,
7
+ sourcemap: true,
8
+ clean: true,
9
+ target: 'es2022',
10
+ outDir: 'dist',
11
+ });
@@ -0,0 +1,15 @@
1
+ import { defineConfig } from "vitest/config";
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ environment: "node",
6
+ globals: true,
7
+ include: ["src/**/__tests__/**/*.{test,spec}.ts"],
8
+ coverage: {
9
+ reporter: ["text", "lcov", "html"],
10
+ include: ["src/**/*.ts"],
11
+ exclude: ["src/**/*.d.ts", "src/**/index.ts", "src/**/__tests__/**"],
12
+ },
13
+ setupFiles: [],
14
+ },
15
+ });