@copilotkit/svelte 0.0.0-stage → 0.1.0

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 (180) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +325 -2
  3. package/dist/components/chat/CopilotChat.d.svelte.ts +1 -0
  4. package/dist/components/chat/CopilotChat.svelte.d.ts +1 -0
  5. package/dist/components/chat/CopilotChatAssistantMessage.d.svelte.ts +1 -0
  6. package/dist/components/chat/CopilotChatAssistantMessage.svelte.d.ts +1 -0
  7. package/dist/components/chat/CopilotChatAttachmentQueue.d.svelte.ts +1 -0
  8. package/dist/components/chat/CopilotChatAttachmentQueue.svelte.d.ts +1 -0
  9. package/dist/components/chat/CopilotChatInput.d.svelte.ts +1 -0
  10. package/dist/components/chat/CopilotChatInput.svelte.d.ts +1 -0
  11. package/dist/components/chat/CopilotChatMessage.d.svelte.ts +1 -0
  12. package/dist/components/chat/CopilotChatMessage.svelte.d.ts +1 -0
  13. package/dist/components/chat/CopilotChatMessageView.d.svelte.ts +1 -0
  14. package/dist/components/chat/CopilotChatMessageView.svelte.d.ts +1 -0
  15. package/dist/components/chat/CopilotChatReasoningMessage.d.svelte.ts +1 -0
  16. package/dist/components/chat/CopilotChatReasoningMessage.svelte.d.ts +1 -0
  17. package/dist/components/chat/CopilotChatSuggestionPill.d.svelte.ts +1 -0
  18. package/dist/components/chat/CopilotChatSuggestionPill.svelte.d.ts +1 -0
  19. package/dist/components/chat/CopilotChatSuggestionView.d.svelte.ts +1 -0
  20. package/dist/components/chat/CopilotChatSuggestionView.svelte.d.ts +1 -0
  21. package/dist/components/chat/CopilotChatToggleButton.d.svelte.ts +1 -0
  22. package/dist/components/chat/CopilotChatToggleButton.svelte.d.ts +1 -0
  23. package/dist/components/chat/CopilotChatToolCallsView.d.svelte.ts +1 -0
  24. package/dist/components/chat/CopilotChatToolCallsView.svelte.d.ts +1 -0
  25. package/dist/components/chat/CopilotChatUserMessage.d.svelte.ts +1 -0
  26. package/dist/components/chat/CopilotChatUserMessage.svelte.d.ts +1 -0
  27. package/dist/components/chat/CopilotChatView.d.svelte.ts +1 -0
  28. package/dist/components/chat/CopilotChatView.svelte.d.ts +1 -0
  29. package/dist/components/chat/CopilotPopup.d.svelte.ts +1 -0
  30. package/dist/components/chat/CopilotPopup.svelte.d.ts +1 -0
  31. package/dist/components/chat/CopilotSidebar.d.svelte.ts +1 -0
  32. package/dist/components/chat/CopilotSidebar.svelte.d.ts +1 -0
  33. package/dist/components/chat/StreamMarkdown.d.svelte.ts +1 -0
  34. package/dist/components/chat/StreamMarkdown.svelte.d.ts +1 -0
  35. package/dist/components/chat/chat-config-context.d.svelte.ts +10 -0
  36. package/dist/components/chat/chat-config-context.svelte.d.ts +10 -0
  37. package/dist/components/chat/chat-config-context.svelte.d.ts.map +1 -0
  38. package/dist/components/chat/dispatch-after-active-run.d.ts +3 -0
  39. package/dist/components/chat/dispatch-after-active-run.d.ts.map +1 -0
  40. package/dist/components/chat/markdown/CodeBlock.svelte.d.ts +1 -0
  41. package/dist/components/chat/markdown/CodeSpan.svelte.d.ts +1 -0
  42. package/dist/components/chat/markdown/Table.svelte.d.ts +1 -0
  43. package/dist/components/chat/markdown/TableBody.svelte.d.ts +1 -0
  44. package/dist/components/chat/markdown/TableCell.svelte.d.ts +1 -0
  45. package/dist/components/chat/markdown/TableHead.svelte.d.ts +1 -0
  46. package/dist/components/chat/markdown/TableRow.svelte.d.ts +1 -0
  47. package/dist/components/chat/markdown/highlight.d.ts +8 -0
  48. package/dist/components/chat/markdown/highlight.d.ts.map +1 -0
  49. package/dist/components/chat/media-parts.d.ts +11 -0
  50. package/dist/components/chat/media-parts.d.ts.map +1 -0
  51. package/dist/components/chat/types.d.ts +137 -0
  52. package/dist/components/chat/types.d.ts.map +1 -0
  53. package/dist/components/icons/index.d.ts +2 -0
  54. package/dist/components/icons/index.d.ts.map +1 -0
  55. package/dist/components/index.d.ts +18 -0
  56. package/dist/components/index.d.ts.map +1 -0
  57. package/dist/hooks/connect-agent-context.svelte.d.ts +9 -0
  58. package/dist/hooks/connect-agent-context.svelte.d.ts.map +1 -0
  59. package/dist/hooks/create-agent.svelte.d.ts +23 -0
  60. package/dist/hooks/create-agent.svelte.d.ts.map +1 -0
  61. package/dist/hooks/create-attachments.svelte.d.ts +33 -0
  62. package/dist/hooks/create-attachments.svelte.d.ts.map +1 -0
  63. package/dist/hooks/create-capabilities.svelte.d.ts +6 -0
  64. package/dist/hooks/create-capabilities.svelte.d.ts.map +1 -0
  65. package/dist/hooks/create-interrupt.svelte.d.ts +24 -0
  66. package/dist/hooks/create-interrupt.svelte.d.ts.map +1 -0
  67. package/dist/hooks/create-suggestions.svelte.d.ts +12 -0
  68. package/dist/hooks/create-suggestions.svelte.d.ts.map +1 -0
  69. package/dist/hooks/create-threads.svelte.d.ts +33 -0
  70. package/dist/hooks/create-threads.svelte.d.ts.map +1 -0
  71. package/dist/hooks/index.d.ts +20 -0
  72. package/dist/hooks/index.d.ts.map +1 -0
  73. package/dist/hooks/load-katex-styles.svelte.d.ts +2 -0
  74. package/dist/hooks/load-katex-styles.svelte.d.ts.map +1 -0
  75. package/dist/hooks/register-frontend-tool.svelte.d.ts +3 -0
  76. package/dist/hooks/register-frontend-tool.svelte.d.ts.map +1 -0
  77. package/dist/hooks/register-human-in-the-loop.svelte.d.ts +3 -0
  78. package/dist/hooks/register-human-in-the-loop.svelte.d.ts.map +1 -0
  79. package/dist/hooks/register-render-tool-call.svelte.d.ts +30 -0
  80. package/dist/hooks/register-render-tool-call.svelte.d.ts.map +1 -0
  81. package/dist/index.cjs +5 -0
  82. package/dist/index.cjs.map +1 -0
  83. package/dist/index.d.cts +6 -0
  84. package/dist/index.d.mts +6 -0
  85. package/dist/index.d.ts +6 -0
  86. package/dist/index.d.ts.map +1 -0
  87. package/dist/index.mjs +3037 -0
  88. package/dist/index.mjs.map +1 -0
  89. package/dist/lib/svelte-core.d.ts +53 -0
  90. package/dist/lib/svelte-core.d.ts.map +1 -0
  91. package/dist/providers/CopilotKitProvider.svelte.d.ts +1 -0
  92. package/dist/providers/CopilotKitProvider.types.d.ts +47 -0
  93. package/dist/providers/CopilotKitProvider.types.d.ts.map +1 -0
  94. package/dist/providers/context.d.ts +19 -0
  95. package/dist/providers/context.d.ts.map +1 -0
  96. package/dist/providers/index.d.ts +6 -0
  97. package/dist/providers/index.d.ts.map +1 -0
  98. package/dist/providers/useCopilotKit.d.ts +3 -0
  99. package/dist/providers/useCopilotKit.d.ts.map +1 -0
  100. package/dist/styles.css +3 -0
  101. package/dist/types/a2ui.d.ts +5 -0
  102. package/dist/types/a2ui.d.ts.map +1 -0
  103. package/dist/types/activity-message-renderer.d.ts +17 -0
  104. package/dist/types/activity-message-renderer.d.ts.map +1 -0
  105. package/dist/types/custom-message-renderer.d.ts +18 -0
  106. package/dist/types/custom-message-renderer.d.ts.map +1 -0
  107. package/dist/types/frontend-tool.d.ts +6 -0
  108. package/dist/types/frontend-tool.d.ts.map +1 -0
  109. package/dist/types/human-in-the-loop.d.ts +31 -0
  110. package/dist/types/human-in-the-loop.d.ts.map +1 -0
  111. package/dist/types/index.d.ts +9 -0
  112. package/dist/types/index.d.ts.map +1 -0
  113. package/dist/types/interrupt.d.ts +23 -0
  114. package/dist/types/interrupt.d.ts.map +1 -0
  115. package/dist/types/sandbox-function.d.ts +8 -0
  116. package/dist/types/sandbox-function.d.ts.map +1 -0
  117. package/dist/types/tool-call-renderer.d.ts +29 -0
  118. package/dist/types/tool-call-renderer.d.ts.map +1 -0
  119. package/package.json +114 -3
  120. package/src/app.d.ts +7 -0
  121. package/src/components/chat/CopilotChat.svelte +222 -0
  122. package/src/components/chat/CopilotChatAssistantMessage.svelte +295 -0
  123. package/src/components/chat/CopilotChatAttachmentQueue.svelte +241 -0
  124. package/src/components/chat/CopilotChatInput.svelte +192 -0
  125. package/src/components/chat/CopilotChatMessage.svelte +37 -0
  126. package/src/components/chat/CopilotChatMessageView.svelte +76 -0
  127. package/src/components/chat/CopilotChatReasoningMessage.svelte +210 -0
  128. package/src/components/chat/CopilotChatSuggestionPill.svelte +66 -0
  129. package/src/components/chat/CopilotChatSuggestionView.svelte +36 -0
  130. package/src/components/chat/CopilotChatToggleButton.svelte +47 -0
  131. package/src/components/chat/CopilotChatToolCallsView.svelte +187 -0
  132. package/src/components/chat/CopilotChatUserMessage.svelte +312 -0
  133. package/src/components/chat/CopilotChatView.svelte +177 -0
  134. package/src/components/chat/CopilotPopup.svelte +187 -0
  135. package/src/components/chat/CopilotSidebar.svelte +138 -0
  136. package/src/components/chat/StreamMarkdown.svelte +30 -0
  137. package/src/components/chat/chat-config-context.svelte.ts +28 -0
  138. package/src/components/chat/dispatch-after-active-run.ts +40 -0
  139. package/src/components/chat/markdown/CodeBlock.svelte +78 -0
  140. package/src/components/chat/markdown/CodeSpan.svelte +29 -0
  141. package/src/components/chat/markdown/Table.svelte +15 -0
  142. package/src/components/chat/markdown/TableBody.svelte +11 -0
  143. package/src/components/chat/markdown/TableCell.svelte +29 -0
  144. package/src/components/chat/markdown/TableHead.svelte +11 -0
  145. package/src/components/chat/markdown/TableRow.svelte +11 -0
  146. package/src/components/chat/markdown/highlight.ts +96 -0
  147. package/src/components/chat/media-parts.ts +34 -0
  148. package/src/components/chat/types.ts +176 -0
  149. package/src/components/icons/index.ts +23 -0
  150. package/src/components/index.ts +17 -0
  151. package/src/hooks/connect-agent-context.svelte.ts +46 -0
  152. package/src/hooks/create-agent.svelte.ts +420 -0
  153. package/src/hooks/create-attachments.svelte.ts +311 -0
  154. package/src/hooks/create-capabilities.svelte.ts +26 -0
  155. package/src/hooks/create-interrupt.svelte.ts +467 -0
  156. package/src/hooks/create-suggestions.svelte.ts +84 -0
  157. package/src/hooks/create-threads.svelte.ts +337 -0
  158. package/src/hooks/index.ts +45 -0
  159. package/src/hooks/load-katex-styles.svelte.ts +13 -0
  160. package/src/hooks/register-frontend-tool.svelte.ts +45 -0
  161. package/src/hooks/register-human-in-the-loop.svelte.ts +118 -0
  162. package/src/hooks/register-render-tool-call.svelte.ts +75 -0
  163. package/src/index.ts +6 -0
  164. package/src/lib/svelte-core.ts +230 -0
  165. package/src/providers/CopilotKitProvider.svelte +291 -0
  166. package/src/providers/CopilotKitProvider.types.ts +55 -0
  167. package/src/providers/context.ts +26 -0
  168. package/src/providers/index.ts +5 -0
  169. package/src/providers/useCopilotKit.ts +11 -0
  170. package/src/styles/globals.css +691 -0
  171. package/src/styles.d.ts +1 -0
  172. package/src/types/a2ui.ts +5 -0
  173. package/src/types/activity-message-renderer.ts +21 -0
  174. package/src/types/custom-message-renderer.ts +23 -0
  175. package/src/types/frontend-tool.ts +8 -0
  176. package/src/types/human-in-the-loop.ts +40 -0
  177. package/src/types/index.ts +8 -0
  178. package/src/types/interrupt.ts +32 -0
  179. package/src/types/sandbox-function.ts +8 -0
  180. package/src/types/tool-call-renderer.ts +36 -0
@@ -0,0 +1,176 @@
1
+ import type {
2
+ Message,
3
+ AssistantMessage,
4
+ UserMessage,
5
+ ToolCall,
6
+ ToolMessage,
7
+ } from "@ag-ui/core";
8
+ import type { ToolCallStatus } from "@copilotkit/core";
9
+ import type { Suggestion } from "@copilotkit/core";
10
+ import type {
11
+ Attachment,
12
+ AttachmentModality,
13
+ AttachmentsConfig,
14
+ InputContent,
15
+ } from "@copilotkit/shared";
16
+ import type { CopilotKitCoreErrorCode } from "@copilotkit/core";
17
+
18
+ export type { Attachment, AttachmentModality, AttachmentsConfig, InputContent };
19
+
20
+ export type AutoScrollMode = "pin-to-bottom" | "pin-to-send" | "none";
21
+
22
+ export function normalizeAutoScroll(
23
+ value: AutoScrollMode | boolean | undefined,
24
+ ): AutoScrollMode {
25
+ if (value === undefined || value === true) return "pin-to-bottom";
26
+ if (value === false) return "none";
27
+ return value;
28
+ }
29
+
30
+ export type CopilotChatInputMode = "input" | "transcribe" | "processing";
31
+
32
+ export type ToolsMenuItem = {
33
+ label: string;
34
+ } & (
35
+ | { action: () => void; items?: never }
36
+ | { action?: never; items: (ToolsMenuItem | "-")[] }
37
+ );
38
+
39
+ export interface CopilotChatProps {
40
+ agentId?: string;
41
+ threadId?: string;
42
+ throttleMs?: number;
43
+ labels?: Record<string, string>;
44
+ className?: string;
45
+ autoScroll?: AutoScrollMode | boolean;
46
+ welcomeScreen?: boolean;
47
+ inputValue?: string;
48
+ onInputChange?: (value: string) => void;
49
+ inputMode?: CopilotChatInputMode;
50
+ inputToolsMenu?: (ToolsMenuItem | "-")[];
51
+ attachments?: boolean | AttachmentsConfig;
52
+ onError?: (event: {
53
+ error: Error;
54
+ code: CopilotKitCoreErrorCode;
55
+ context: Record<string, unknown>;
56
+ }) => void;
57
+ }
58
+
59
+ export interface CopilotChatViewProps {
60
+ messages: Message[];
61
+ isRunning: boolean;
62
+ autoScroll?: AutoScrollMode | boolean;
63
+ welcomeScreen?: boolean;
64
+ suggestions?: Suggestion[];
65
+ attachments?: Attachment[];
66
+ inputValue?: string;
67
+ inputMode?: CopilotChatInputMode;
68
+ inputToolsMenu?: (ToolsMenuItem | "-")[];
69
+ isConnecting?: boolean;
70
+ hasExplicitThreadId?: boolean;
71
+ onSubmitMessage: (value: string) => void;
72
+ onStop?: () => void;
73
+ onInputChange: (value: string) => void;
74
+ onSelectSuggestion: (suggestion: Suggestion, index: number) => void;
75
+ onRemoveAttachment?: (id: string) => void;
76
+ onAddFile?: () => void;
77
+ }
78
+
79
+ export interface CopilotSidebarProps extends CopilotChatProps {
80
+ width?: number | string;
81
+ defaultOpen?: boolean;
82
+ }
83
+
84
+ export interface CopilotPopupProps extends CopilotChatProps {
85
+ width?: number | string;
86
+ height?: number | string;
87
+ clickOutsideToClose?: boolean;
88
+ defaultOpen?: boolean;
89
+ }
90
+
91
+ export interface CopilotChatToggleButtonProps {
92
+ isOpen: boolean;
93
+ onclick?: () => void;
94
+ }
95
+
96
+ export interface CopilotChatToolCallRenderSlotProps {
97
+ name: string;
98
+ args: unknown;
99
+ status: ToolCallStatus;
100
+ result: string | undefined;
101
+ toolCall: ToolCall;
102
+ toolMessage: ToolMessage | undefined;
103
+ }
104
+
105
+ export interface CopilotChatAssistantMessageMessageRendererSlotProps {
106
+ message: AssistantMessage;
107
+ content: string;
108
+ }
109
+
110
+ export interface CopilotChatAssistantMessageToolbarSlotProps {
111
+ message: AssistantMessage;
112
+ shouldShowToolbar: boolean;
113
+ }
114
+
115
+ export interface CopilotChatAssistantMessageCopyButtonSlotProps {
116
+ onCopy: () => Promise<void>;
117
+ copied: boolean;
118
+ label: string;
119
+ }
120
+
121
+ export interface CopilotChatAssistantMessageThumbsUpButtonSlotProps {
122
+ onThumbsUp: () => void;
123
+ label: string;
124
+ }
125
+
126
+ export interface CopilotChatAssistantMessageThumbsDownButtonSlotProps {
127
+ onThumbsDown: () => void;
128
+ label: string;
129
+ }
130
+
131
+ export interface CopilotChatAssistantMessageReadAloudButtonSlotProps {
132
+ onReadAloud: () => void;
133
+ label: string;
134
+ }
135
+
136
+ export interface CopilotChatAssistantMessageRegenerateButtonSlotProps {
137
+ onRegenerate: () => void;
138
+ label: string;
139
+ }
140
+
141
+ export interface CopilotChatAssistantMessageToolCallsViewSlotProps {
142
+ message: AssistantMessage;
143
+ messages: Message[];
144
+ }
145
+
146
+ export interface CopilotChatUserMessageMessageRendererSlotProps {
147
+ message: UserMessage;
148
+ content: string;
149
+ isMultiline: boolean;
150
+ }
151
+
152
+ export interface CopilotChatUserMessageToolbarSlotProps {
153
+ message: UserMessage;
154
+ showBranchNavigation: boolean;
155
+ hasEditAction: boolean;
156
+ }
157
+
158
+ export interface CopilotChatUserMessageCopyButtonSlotProps {
159
+ onCopy: () => Promise<void>;
160
+ copied: boolean;
161
+ label: string;
162
+ }
163
+
164
+ export interface CopilotChatUserMessageEditButtonSlotProps {
165
+ onEdit: () => void;
166
+ label: string;
167
+ }
168
+
169
+ export interface CopilotChatUserMessageBranchNavigationSlotProps {
170
+ branchIndex: number;
171
+ numberOfBranches: number;
172
+ canGoPrev: boolean;
173
+ canGoNext: boolean;
174
+ goPrev: () => void;
175
+ goNext: () => void;
176
+ }
@@ -0,0 +1,23 @@
1
+ export {
2
+ Check as IconCheck,
3
+ Copy as IconCopy,
4
+ Download as IconDownload,
5
+ SquarePen as IconEdit,
6
+ ChevronLeft as IconChevronLeft,
7
+ ChevronRight as IconChevronRight,
8
+ ChevronDown as IconChevronDown,
9
+ RefreshCw as IconRefreshCw,
10
+ Volume2 as IconVolume2,
11
+ ThumbsUp as IconThumbsUp,
12
+ ThumbsDown as IconThumbsDown,
13
+ CircleCheck as IconCheckCircle,
14
+ Circle as IconCircle,
15
+ MessageCircle as IconMessageCircle,
16
+ X as IconX,
17
+ Plus as IconPlus,
18
+ Mic as IconMic,
19
+ ArrowUp as IconArrowUp,
20
+ Square as IconSquare,
21
+ LoaderCircle as IconLoader2,
22
+ PanelLeftOpen as IconPanelLeftOpen,
23
+ } from "lucide-svelte";
@@ -0,0 +1,17 @@
1
+ export * from "./chat/types";
2
+ export { default as CopilotChat } from "./chat/CopilotChat.svelte";
3
+ export { default as CopilotChatView } from "./chat/CopilotChatView.svelte";
4
+ export { default as CopilotChatInput } from "./chat/CopilotChatInput.svelte";
5
+ export { default as CopilotChatMessage } from "./chat/CopilotChatMessage.svelte";
6
+ export { default as CopilotChatMessageView } from "./chat/CopilotChatMessageView.svelte";
7
+ export { default as CopilotChatAssistantMessage } from "./chat/CopilotChatAssistantMessage.svelte";
8
+ export { default as CopilotChatUserMessage } from "./chat/CopilotChatUserMessage.svelte";
9
+ export { default as CopilotChatReasoningMessage } from "./chat/CopilotChatReasoningMessage.svelte";
10
+ export { default as CopilotChatToolCallsView } from "./chat/CopilotChatToolCallsView.svelte";
11
+ export { default as CopilotChatSuggestionView } from "./chat/CopilotChatSuggestionView.svelte";
12
+ export { default as CopilotChatSuggestionPill } from "./chat/CopilotChatSuggestionPill.svelte";
13
+ export { default as CopilotChatAttachmentQueue } from "./chat/CopilotChatAttachmentQueue.svelte";
14
+ export { default as CopilotChatToggleButton } from "./chat/CopilotChatToggleButton.svelte";
15
+ export { default as CopilotSidebar } from "./chat/CopilotSidebar.svelte";
16
+ export { default as CopilotPopup } from "./chat/CopilotPopup.svelte";
17
+ export { default as StreamMarkdown } from "./chat/StreamMarkdown.svelte";
@@ -0,0 +1,46 @@
1
+ import { getContext } from "svelte";
2
+ import { COPILOT_KIT_KEY } from "../providers/context";
3
+ import type { CopilotKitContextValue } from "../providers/context";
4
+
5
+ export type JsonSerializable =
6
+ | string
7
+ | number
8
+ | boolean
9
+ | null
10
+ | JsonSerializable[]
11
+ | { [key: string]: JsonSerializable };
12
+
13
+ export interface AgentContextInput {
14
+ description: string;
15
+ value: JsonSerializable;
16
+ }
17
+
18
+ export function connectAgentContext(context: AgentContextInput): void {
19
+ const ctx = getContext<CopilotKitContextValue | null>(COPILOT_KIT_KEY);
20
+ if (!ctx) {
21
+ throw new Error(
22
+ "connectAgentContext must be used within CopilotKitProvider",
23
+ );
24
+ }
25
+
26
+ $effect(() => {
27
+ const core = ctx.copilotkit;
28
+ const description = context.description;
29
+ const raw = context.value;
30
+ const stringValue =
31
+ raw === undefined
32
+ ? ""
33
+ : typeof raw === "string"
34
+ ? raw
35
+ : JSON.stringify(raw);
36
+
37
+ const id = core.addContext({
38
+ description,
39
+ value: stringValue,
40
+ });
41
+
42
+ return () => {
43
+ core.removeContext(id);
44
+ };
45
+ });
46
+ }
@@ -0,0 +1,420 @@
1
+ import type { AbstractAgent } from "@ag-ui/client";
2
+ import { HttpAgent } from "@ag-ui/client";
3
+ import type { Message } from "@ag-ui/core";
4
+ import { DEFAULT_AGENT_ID } from "@copilotkit/shared";
5
+ import { ProxiedCopilotRuntimeAgent } from "@copilotkit/core";
6
+ import type { SubscribeToAgentSubscriber } from "@copilotkit/core";
7
+ import { CopilotKitCoreRuntimeConnectionStatus } from "@copilotkit/core";
8
+ import { COPILOT_KIT_KEY } from "../providers/context";
9
+ import type { CopilotKitContextValue } from "../providers/context";
10
+ import { getContext } from "svelte";
11
+ import { SvelteMap } from "svelte/reactivity";
12
+
13
+ export enum CreateAgentUpdate {
14
+ OnMessagesChanged = "OnMessagesChanged",
15
+ OnStateChanged = "OnStateChanged",
16
+ OnRunStatusChanged = "OnRunStatusChanged",
17
+ }
18
+
19
+ const ALL_UPDATES: CreateAgentUpdate[] = [
20
+ CreateAgentUpdate.OnMessagesChanged,
21
+ CreateAgentUpdate.OnStateChanged,
22
+ CreateAgentUpdate.OnRunStatusChanged,
23
+ ];
24
+
25
+ export interface CreateAgentProps {
26
+ agentId?: string;
27
+ threadId?: string;
28
+ updates?: CreateAgentUpdate[];
29
+ throttleMs?: number;
30
+ }
31
+
32
+ export const globalThreadCloneMap = new WeakMap<
33
+ AbstractAgent,
34
+ SvelteMap<string, AbstractAgent>
35
+ >();
36
+ const globalThreadCloneConsumers = new WeakMap<
37
+ AbstractAgent,
38
+ SvelteMap<string, number>
39
+ >();
40
+
41
+ const MAX_CLONES_PER_AGENT = 50;
42
+
43
+ export function getThreadClone(
44
+ registryAgent: AbstractAgent | undefined | null,
45
+ threadId: string | undefined | null,
46
+ ): AbstractAgent | undefined {
47
+ if (!registryAgent || !threadId) return undefined;
48
+ return globalThreadCloneMap.get(registryAgent)?.get(threadId);
49
+ }
50
+
51
+ function cloneForThread(
52
+ source: AbstractAgent,
53
+ threadId: string,
54
+ ): AbstractAgent {
55
+ const clone = source.clone();
56
+ if (clone === source) {
57
+ throw new Error(
58
+ `createAgent: ${source.constructor.name}.clone() returned the same instance. ` +
59
+ "clone() must return a new, independent object.",
60
+ );
61
+ }
62
+ clone.threadId = threadId;
63
+ clone.setMessages([]);
64
+ clone.setState({});
65
+ return clone;
66
+ }
67
+
68
+ function applyProviderHeaders(
69
+ core: CopilotKitContextValue["copilotkit"],
70
+ target: AbstractAgent | null | undefined,
71
+ headers: Readonly<Record<string, string>>,
72
+ ): void {
73
+ if (target instanceof HttpAgent) {
74
+ if (typeof core.applyHeadersToAgent === "function") {
75
+ core.applyHeadersToAgent(target);
76
+ } else {
77
+ // Structural test doubles and older compatible cores may not expose the
78
+ // merge helper. Preserve existing agent headers in that fallback path.
79
+ target.headers = { ...target.headers, ...headers };
80
+ }
81
+ }
82
+ }
83
+
84
+ function getOrCreateThreadClone(
85
+ core: CopilotKitContextValue["copilotkit"],
86
+ source: AbstractAgent,
87
+ threadId: string,
88
+ headers: Readonly<Record<string, string>>,
89
+ ): AbstractAgent {
90
+ let byThread = globalThreadCloneMap.get(source);
91
+ if (!byThread) {
92
+ byThread = new SvelteMap();
93
+ globalThreadCloneMap.set(source, byThread);
94
+ }
95
+ const existing = byThread.get(threadId);
96
+ if (existing) {
97
+ existing.threadId = threadId;
98
+ applyProviderHeaders(core, existing, headers);
99
+ return existing;
100
+ }
101
+ const clone = cloneForThread(source, threadId);
102
+ applyProviderHeaders(core, clone, headers);
103
+ if (byThread.size >= MAX_CLONES_PER_AGENT) {
104
+ const consumers = globalThreadCloneConsumers.get(source);
105
+ const evictable = [...byThread.keys()].find(
106
+ (candidate) => !consumers?.get(candidate),
107
+ );
108
+ if (evictable !== undefined) byThread.delete(evictable);
109
+ }
110
+ byThread.set(threadId, clone);
111
+ return clone;
112
+ }
113
+
114
+ function retainThreadClone(source: AbstractAgent, threadId: string): void {
115
+ let consumers = globalThreadCloneConsumers.get(source);
116
+ if (!consumers) {
117
+ consumers = new SvelteMap();
118
+ globalThreadCloneConsumers.set(source, consumers);
119
+ }
120
+ consumers.set(threadId, (consumers.get(threadId) ?? 0) + 1);
121
+ }
122
+
123
+ function releaseThreadClone(source: AbstractAgent, threadId: string): void {
124
+ const consumers = globalThreadCloneConsumers.get(source);
125
+ const count = consumers?.get(threadId);
126
+ if (count === undefined) return;
127
+ if (count <= 1) consumers?.delete(threadId);
128
+ else consumers?.set(threadId, count - 1);
129
+
130
+ const byThread = globalThreadCloneMap.get(source);
131
+ while (byThread && byThread.size > MAX_CLONES_PER_AGENT) {
132
+ const evictable = [...byThread.keys()].find(
133
+ (candidate) => !consumers?.get(candidate),
134
+ );
135
+ if (evictable === undefined) break;
136
+ byThread.delete(evictable);
137
+ }
138
+ }
139
+
140
+ export function createAgent(props: CreateAgentProps = {}) {
141
+ const context = getContext<CopilotKitContextValue | null>(COPILOT_KIT_KEY);
142
+ if (!context) {
143
+ throw new Error("createAgent must be used within CopilotKitProvider");
144
+ }
145
+
146
+ const agentId = $derived(props.agentId ?? DEFAULT_AGENT_ID);
147
+ const threadId = $derived(props.threadId);
148
+ const updateFlags = $derived(props.updates ?? ALL_UPDATES);
149
+ const hookThrottleMs = $derived(props.throttleMs);
150
+
151
+ let agent = $state<AbstractAgent | null>(null);
152
+ let agentIdentity: AbstractAgent | null = null;
153
+ let agentRevision = $state(0);
154
+ let agentInstanceRevision = $state(0);
155
+ let messages = $state<Message[]>([]);
156
+ let isRunning = $state(false);
157
+ let subscriptionAgent = $state<AbstractAgent | null>(null);
158
+ const provisionalAgentCache = new SvelteMap<
159
+ string,
160
+ {
161
+ agent: ProxiedCopilotRuntimeAgent;
162
+ runtimeUrl: string;
163
+ transport: CopilotKitContextValue["runtimeTransport"];
164
+ }
165
+ >();
166
+ let ownedClone: { source: AbstractAgent; threadId: string } | null = null;
167
+
168
+ function releaseOwnedClone(): void {
169
+ if (!ownedClone) return;
170
+ releaseThreadClone(ownedClone.source, ownedClone.threadId);
171
+ ownedClone = null;
172
+ }
173
+
174
+ function setResolvedAgent(next: AbstractAgent): void {
175
+ if (agentIdentity !== next) agentInstanceRevision += 1;
176
+ agentIdentity = next;
177
+ agent = next;
178
+ }
179
+
180
+ const resolveAgent = () => {
181
+ const id = agentId;
182
+ const resolvedThreadId = threadId;
183
+ const cacheKey = resolvedThreadId ? `${id}:${resolvedThreadId}` : id;
184
+ const core = context.copilotkit;
185
+ const runtimeUrl = context.runtimeUrl;
186
+ const status = context.runtimeConnectionStatus;
187
+ const transport = context.runtimeTransport;
188
+ const headers = context.headers;
189
+ const credentials =
190
+ "credentials" in context ? context.credentials : core.credentials;
191
+ const registered = context.agents ?? {};
192
+ // Reactive registry wins over mutable core fields. getAgent remains the
193
+ // core lookup when the provider has not published the agent yet.
194
+ const coreAgent = core.getAgent(id);
195
+ const existing = registered[id] ?? coreAgent;
196
+ if (existing) {
197
+ provisionalAgentCache.delete(cacheKey);
198
+ provisionalAgentCache.delete(id);
199
+ applyProviderHeaders(core, existing, headers);
200
+ let resolvedAgent: AbstractAgent;
201
+ if (resolvedThreadId) {
202
+ if (
203
+ ownedClone &&
204
+ (ownedClone.source !== existing ||
205
+ ownedClone.threadId !== resolvedThreadId)
206
+ ) {
207
+ releaseOwnedClone();
208
+ }
209
+ resolvedAgent = getOrCreateThreadClone(
210
+ core,
211
+ existing,
212
+ resolvedThreadId,
213
+ headers,
214
+ );
215
+ if (
216
+ !ownedClone ||
217
+ ownedClone.source !== existing ||
218
+ ownedClone.threadId !== resolvedThreadId
219
+ ) {
220
+ retainThreadClone(existing, resolvedThreadId);
221
+ ownedClone = { source: existing, threadId: resolvedThreadId };
222
+ }
223
+ } else {
224
+ releaseOwnedClone();
225
+ resolvedAgent = existing;
226
+ }
227
+ setResolvedAgent(resolvedAgent);
228
+ messages = [...(resolvedAgent.messages ?? [])];
229
+ isRunning = resolvedAgent.isRunning ?? false;
230
+ subscriptionAgent = resolvedAgent;
231
+ return;
232
+ }
233
+
234
+ const isRuntimeConfigured = runtimeUrl !== undefined;
235
+
236
+ if (
237
+ isRuntimeConfigured &&
238
+ (status === CopilotKitCoreRuntimeConnectionStatus.Disconnected ||
239
+ status === CopilotKitCoreRuntimeConnectionStatus.Connecting ||
240
+ status === CopilotKitCoreRuntimeConnectionStatus.Error)
241
+ ) {
242
+ releaseOwnedClone();
243
+ let cached = provisionalAgentCache.get(cacheKey);
244
+ if (
245
+ cached &&
246
+ (cached.runtimeUrl !== runtimeUrl || cached.transport !== transport)
247
+ ) {
248
+ provisionalAgentCache.delete(cacheKey);
249
+ cached = undefined;
250
+ }
251
+ if (cached) {
252
+ cached.agent.credentials = credentials;
253
+ applyProviderHeaders(core, cached.agent, headers);
254
+ if (resolvedThreadId) {
255
+ cached.agent.threadId = resolvedThreadId;
256
+ }
257
+ setResolvedAgent(cached.agent);
258
+ messages = [...(cached.agent.messages ?? [])];
259
+ isRunning = cached.agent.isRunning ?? false;
260
+ subscriptionAgent = cached.agent;
261
+ return;
262
+ }
263
+ const provisional = new ProxiedCopilotRuntimeAgent({
264
+ runtimeUrl: runtimeUrl!,
265
+ agentId: id,
266
+ transport,
267
+ runtimeMode: "pending",
268
+ credentials,
269
+ });
270
+ applyProviderHeaders(core, provisional, headers);
271
+ if (resolvedThreadId) {
272
+ provisional.threadId = resolvedThreadId;
273
+ }
274
+ provisionalAgentCache.set(cacheKey, {
275
+ agent: provisional,
276
+ runtimeUrl: runtimeUrl!,
277
+ transport,
278
+ });
279
+ setResolvedAgent(provisional);
280
+ messages = [...(provisional.messages ?? [])];
281
+ isRunning = provisional.isRunning ?? false;
282
+ subscriptionAgent = provisional;
283
+ return;
284
+ }
285
+
286
+ releaseOwnedClone();
287
+ const knownAgents = Object.keys(registered);
288
+ const runtimePart = isRuntimeConfigured
289
+ ? `runtimeUrl=${runtimeUrl}`
290
+ : "no runtimeUrl";
291
+ throw new Error(
292
+ `createAgent: Agent '${id}' not found after runtime sync (${runtimePart}). ` +
293
+ (knownAgents.length
294
+ ? `Known agents: [${knownAgents.join(", ")}]`
295
+ : "No agents registered."),
296
+ );
297
+ };
298
+
299
+ $effect(() => {
300
+ resolveAgent();
301
+ });
302
+
303
+ $effect(() => () => releaseOwnedClone());
304
+
305
+ $effect(() => {
306
+ // Track the provider getter so updates rerun this effect. The core owns
307
+ // the merge baseline and preserves each HttpAgent's construction headers.
308
+ const headers = context.headers;
309
+ const core = context.copilotkit;
310
+ applyProviderHeaders(core, subscriptionAgent, headers);
311
+ for (const registered of Object.values(context.agents ?? {})) {
312
+ applyProviderHeaders(core, registered, headers);
313
+ const clones = globalThreadCloneMap.get(registered);
314
+ if (!clones) continue;
315
+ for (const clone of clones.values()) {
316
+ applyProviderHeaders(core, clone, headers);
317
+ }
318
+ }
319
+ for (const provisional of provisionalAgentCache.values()) {
320
+ applyProviderHeaders(core, provisional.agent, headers);
321
+ }
322
+ });
323
+
324
+ $effect(() => {
325
+ const a = subscriptionAgent;
326
+ const flags = updateFlags;
327
+ const core = context.copilotkit;
328
+ if (!a || flags.length === 0) return;
329
+
330
+ let active = true;
331
+ let batchScheduled = false;
332
+ const batchedRefresh = () => {
333
+ if (!active) return;
334
+ if (!batchScheduled) {
335
+ batchScheduled = true;
336
+ queueMicrotask(() => {
337
+ batchScheduled = false;
338
+ if (active) {
339
+ agentRevision += 1;
340
+ }
341
+ });
342
+ }
343
+ };
344
+
345
+ const handlers: SubscribeToAgentSubscriber = {};
346
+
347
+ if (flags.includes(CreateAgentUpdate.OnMessagesChanged)) {
348
+ handlers.onMessagesChanged = () => {
349
+ if (active) {
350
+ messages = (a.messages ?? []).map((m) => ({ ...m }));
351
+ isRunning = a.isRunning ?? false;
352
+ agentRevision += 1;
353
+ }
354
+ };
355
+ }
356
+
357
+ if (flags.includes(CreateAgentUpdate.OnStateChanged)) {
358
+ handlers.onStateChanged = batchedRefresh;
359
+ }
360
+
361
+ if (flags.includes(CreateAgentUpdate.OnRunStatusChanged)) {
362
+ handlers.onRunInitialized = () => {
363
+ if (active) {
364
+ isRunning = true;
365
+ agent = a;
366
+ agentRevision += 1;
367
+ }
368
+ };
369
+ handlers.onRunFinalized = () => {
370
+ if (active) {
371
+ isRunning = false;
372
+ agent = a;
373
+ messages = (a.messages ?? []).map((m) => ({ ...m }));
374
+ agentRevision += 1;
375
+ }
376
+ };
377
+ handlers.onRunFailed = () => {
378
+ if (active) {
379
+ isRunning = false;
380
+ agent = a;
381
+ messages = (a.messages ?? []).map((m) => ({ ...m }));
382
+ agentRevision += 1;
383
+ }
384
+ };
385
+ handlers.onRunErrorEvent = () => {
386
+ if (active) {
387
+ isRunning = false;
388
+ agent = a;
389
+ messages = (a.messages ?? []).map((m) => ({ ...m }));
390
+ agentRevision += 1;
391
+ }
392
+ };
393
+ }
394
+
395
+ const subscription = core.subscribeToAgentWithOptions(a, handlers, {
396
+ throttleMs: hookThrottleMs,
397
+ });
398
+
399
+ return () => {
400
+ active = false;
401
+ subscription.unsubscribe();
402
+ };
403
+ });
404
+
405
+ return {
406
+ get agent() {
407
+ void agentRevision;
408
+ return agent;
409
+ },
410
+ get agentInstanceVersion() {
411
+ return agentInstanceRevision;
412
+ },
413
+ get messages() {
414
+ return messages;
415
+ },
416
+ get isRunning() {
417
+ return isRunning;
418
+ },
419
+ };
420
+ }