@builder.io/ai-utils 0.1.1 → 0.1.3

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.
@@ -0,0 +1,354 @@
1
+ import type { BuilderContent, BuilderElement } from "@builder.io/sdk";
2
+ import type { AssistantMessage } from "./messages.js";
3
+ import type { AssistantSettings } from "./settings.js";
4
+ export type BuilderAssistantEventHandler = (ev: BuilderAssistantEvent) => void;
5
+ export type BuilderAssistantEvent = AssistantCompletionResultEvent | AssistantErrorEvent | AssistantStreamErrorEvent | AppCloseEvent | AppMessagesClickEvent | AppMessagesGenerationEvent | AppMessageEditCustomInstructionsEvent | AppPromptAbortEvent | AppPromptFocusEvent | AppPromptSubmitEvent | AppReadyEvent | AppSettingsSetEvent | AppThreadNewEvent | AssistantStatsEvent | AssistantThemeEvent | BuilderEditorAuthEvent | BuilderEditorStateEvent | ContentUpdateEvent | ContentApplySnapshotEvent | ModelUndoEvent | ModelRedoEvent | ResultEvent | ThreadCreatedEvent | ThreadMessageCompletedEvent | ThreadMessageCreatedEvent | ThreadMessageDeltaEvent | ThreadMessageFeedbackEvent | ThreadRunStepCreatedEvent | ThreadRunStepDeltaEvent | AppAcceptChangeEvent | AppAcceptRejectEvent | AssistantTrackEvent | AssistantEditorAuthMessage | AppAttachmentTemplateEvent | ThreadMessageRetryEvent | AppFigmaImportEvent | AppWebImportEvent | AppAiTemplatesEvent | AssistantContentInitialEvent;
6
+ export interface AssistantCompletionResultEvent {
7
+ type: "assistant.result";
8
+ data: {
9
+ content?: BuilderContent;
10
+ stats?: AssistantStats;
11
+ };
12
+ resolveId?: string;
13
+ }
14
+ export interface AssistantError {
15
+ message: string;
16
+ status?: number;
17
+ }
18
+ export interface AssistantErrorEvent {
19
+ type: "assistant.error";
20
+ data: AssistantError;
21
+ }
22
+ export interface AssistantStreamErrorEvent {
23
+ type: "assistant.stream.error";
24
+ data: AssistantError;
25
+ }
26
+ export interface AppFigmaImportEvent {
27
+ type: "assistant.app.figmaImport";
28
+ }
29
+ export interface AppWebImportEvent {
30
+ type: "assistant.app.webImport";
31
+ }
32
+ export interface AppAiTemplatesEvent {
33
+ type: "assistant.app.aiTemplates";
34
+ }
35
+ export interface AssistantTrackEvent {
36
+ type: "assistant.track";
37
+ data: {
38
+ name: string;
39
+ properties: Record<string, any>;
40
+ };
41
+ }
42
+ export interface AssistantThemeEvent {
43
+ type: "assistant.app.theme.update";
44
+ data: {
45
+ theme: string;
46
+ };
47
+ }
48
+ export interface AppCloseEvent {
49
+ type: "assistant.app.close";
50
+ }
51
+ export interface AppMessagesClickEvent {
52
+ type: "assistant.app.messages.click";
53
+ }
54
+ export interface AppAcceptChangeEvent {
55
+ type: "assistant.app.change.accept";
56
+ }
57
+ export interface AppAcceptRejectEvent {
58
+ type: "assistant.app.change.reject";
59
+ }
60
+ export interface AppMessageEditCustomInstructionsEvent {
61
+ type: "assistant.app.messages.editCustomInstructions";
62
+ }
63
+ export interface AppAttachmentTemplateEvent {
64
+ type: "assistant.app.attachment.template";
65
+ data: {
66
+ id: number;
67
+ name: string;
68
+ };
69
+ }
70
+ export interface AppMessagesGenerationEvent {
71
+ type: "assistant.app.messages.generation";
72
+ data: {
73
+ state: GenerationState;
74
+ };
75
+ }
76
+ /**
77
+ * idle: no messages are being generated or queued to be generated
78
+ *
79
+ * queued: messages have been sent to the LLM, but no response has been received yet
80
+ *
81
+ * generating: messages are actively being generated and streaming back to the UI
82
+ */
83
+ export type GenerationState = "idle" | "queued" | "generating";
84
+ export interface AppPromptAbortEvent {
85
+ type: "assistant.app.prompt.abort";
86
+ }
87
+ export interface AppPromptFocusEvent {
88
+ type: "assistant.app.prompt.focus";
89
+ }
90
+ export interface AppPromptSubmitEvent {
91
+ type: "assistant.app.prompt.submit";
92
+ data: {
93
+ prompt: string;
94
+ attachments: any[];
95
+ };
96
+ }
97
+ export interface AppReadyEvent {
98
+ type: "assistant.app.ready";
99
+ }
100
+ export interface AppSettingsSetEvent {
101
+ type: "assistant.app.settings.set";
102
+ data: Partial<AssistantSettings>;
103
+ }
104
+ export interface AppThreadNewEvent {
105
+ type: "assistant.app.thread.new";
106
+ }
107
+ export interface AssistantEditorAuthMessage {
108
+ type: "assistant.editor.auth.update";
109
+ }
110
+ export interface BuilderEditorAuthEvent extends AwaitResultEvent {
111
+ type: "assistant.editor.auth";
112
+ }
113
+ export interface BuilderEditorStateEvent extends AwaitResultEvent {
114
+ type: "assistant.editor.state";
115
+ }
116
+ export interface AwaitResultEvent {
117
+ resolveId?: string;
118
+ }
119
+ export interface ResultEvent {
120
+ type: "assistant.result";
121
+ resolveId: string;
122
+ data: any;
123
+ }
124
+ export interface ContentCreatePatch {
125
+ parentId: string;
126
+ insertBeforeId: string;
127
+ element: BuilderElement;
128
+ }
129
+ export interface ContentApplySnapshot {
130
+ /**
131
+ * The id of the BuilderContent to apply the snapshot to
132
+ */
133
+ id: string;
134
+ /**
135
+ * Each snapshot can be either a full BuilderContent or individual BuilderElements.
136
+ * Order matters, as the snapshots will be applied in the order they are listed.
137
+ * The builder app will handle the logic of applying the snapshots in the correct order
138
+ * and to the right content/elements.
139
+ */
140
+ snapshots: (BuilderElement | BuilderContent)[];
141
+ }
142
+ export interface ContentApplySnapshotEvent {
143
+ type: "assistant.content.applysnapshot";
144
+ data: ContentApplySnapshot;
145
+ }
146
+ export interface ContentUpdateEvent {
147
+ type: "assistant.content.update";
148
+ data: ContentUpdatePatch[];
149
+ }
150
+ export type ContentUpdatePatch = ContentTsUpdateComponentPatch;
151
+ interface ContentPatchBase {
152
+ id: string;
153
+ nodeId?: string;
154
+ builderId?: string;
155
+ description?: string;
156
+ value: string;
157
+ displayValue?: string;
158
+ ts: number;
159
+ /**
160
+ * A change value is considered incomplete until we also parsed it's closing xml tag.
161
+ */
162
+ incomplete?: boolean;
163
+ /**
164
+ * If there was an error applying the patch, this will contain the error message.
165
+ */
166
+ error?: string;
167
+ }
168
+ export interface ContentTsUpdateComponentPatch extends ContentPatchBase {
169
+ type: "update_component";
170
+ }
171
+ export interface AssistantStatsEvent {
172
+ type: "assistant.stats";
173
+ data: AssistantStats;
174
+ }
175
+ export interface AssistantStats {
176
+ /**
177
+ * The unique id of the thread (not the openai threadId)
178
+ */
179
+ threadId: string;
180
+ /**
181
+ * The unique id of the completion, which is a combination of the user's prompt and assistant's response.
182
+ */
183
+ completionId: string;
184
+ /**
185
+ * The model id used to generate this completion.
186
+ */
187
+ modelId: string;
188
+ /**
189
+ * The assistant's response message.
190
+ */
191
+ assistantMessage: string;
192
+ /**
193
+ * The user's prompt message.
194
+ */
195
+ userMessage: string;
196
+ /**
197
+ * The index within the thread the assistant message is.
198
+ * For a first assistant message, the index will be 1 (the user message is index 0).
199
+ * For a second assistant message, the index will be 3 (the user message is index 2), and so on.
200
+ */
201
+ assistantMessageIndex: number;
202
+ /**
203
+ * The timestamp (Date.now()) of when the user first submitted their prompt.
204
+ */
205
+ userPromptMs: number;
206
+ /**
207
+ * The timestamp of the first assistant chunk in the response.
208
+ */
209
+ firstChunkMs: number;
210
+ /**
211
+ * The timestamp of the last assistant chunk in the response.
212
+ */
213
+ lastChunkMs: number;
214
+ /**
215
+ * The total number of chunks in the assistant's streamed response.
216
+ */
217
+ chunkCount: number;
218
+ /**
219
+ * The total number of characters in the generated prompt sent to the LLM.
220
+ */
221
+ promptLength: number;
222
+ /**
223
+ * The total number of characters in the assistant's response.
224
+ */
225
+ completionLength: number;
226
+ /**
227
+ * If the user provided custom instructions for the prompt.
228
+ */
229
+ hasCustomInstructions: boolean;
230
+ /**
231
+ * The deployed version.
232
+ */
233
+ version: string;
234
+ /**
235
+ * Error message if there was one.
236
+ */
237
+ errorMessage?: string;
238
+ /**
239
+ * Input tokens
240
+ */
241
+ inputTokens?: number;
242
+ /**
243
+ * Output tokens
244
+ */
245
+ outputTokens?: number;
246
+ /**
247
+ * Output tokens
248
+ */
249
+ completionCost?: number;
250
+ /**
251
+ * Number of streamed snapshots
252
+ */
253
+ streamedSnapshots?: number;
254
+ /**
255
+ * Number of cached input tokens
256
+ */
257
+ cacheInputTokens?: number;
258
+ /**
259
+ * Number of cached created tokens
260
+ */
261
+ cacheCreatedTokens?: number;
262
+ }
263
+ export interface ModelUndoEvent {
264
+ type: "assistant.model.undo";
265
+ }
266
+ export interface ModelRedoEvent {
267
+ type: "assistant.model.redo";
268
+ }
269
+ export interface BuilderModel {
270
+ name?: string;
271
+ friendlyName?: string;
272
+ description?: string;
273
+ type?: string;
274
+ fields?: BuilderModelField[];
275
+ }
276
+ export interface BuilderModelField {
277
+ name?: string;
278
+ type?: string;
279
+ description?: string;
280
+ }
281
+ export interface ThreadMessageFeedbackEvent {
282
+ type: "assistant.thread.message.feedback";
283
+ data: CompletionResponseFeedback;
284
+ }
285
+ export interface CompletionResponseFeedback {
286
+ userId: string;
287
+ builderUserId?: string;
288
+ builderEmail?: string;
289
+ responseId?: string;
290
+ frontendUrl: string | undefined;
291
+ frontendCommitId: string | undefined;
292
+ backendDomain?: string;
293
+ backendCommitId: string | undefined;
294
+ feedbackText: string;
295
+ sentiment?: "positive" | "negative";
296
+ }
297
+ export interface ThreadCreatedEvent {
298
+ type: "assistant.thread.created";
299
+ data: ThreadCreated;
300
+ }
301
+ export interface ThreadCreated {
302
+ platformId: string;
303
+ threadId: string;
304
+ vectorStoreId: string;
305
+ }
306
+ export interface ThreadMessageCreatedEvent {
307
+ type: "assistant.thread.message.created";
308
+ data: ThreadMessageCreated;
309
+ }
310
+ export interface ThreadMessageCreated {
311
+ id: string;
312
+ responseId: string;
313
+ threadId: string;
314
+ }
315
+ export interface ThreadMessageDeltaEvent {
316
+ type: "assistant.thread.message.delta";
317
+ data: ThreadMessageDelta;
318
+ }
319
+ export interface ThreadMessageDelta {
320
+ id: string;
321
+ text: string;
322
+ }
323
+ export interface ThreadMessageCompletedEvent {
324
+ type: "assistant.thread.message.completed";
325
+ data: ThreadMessageCompleted;
326
+ }
327
+ export interface ThreadMessageRetryEvent {
328
+ type: "assistant.thread.message.retry";
329
+ }
330
+ export interface ThreadMessageCompleted extends AssistantMessage {
331
+ platformId: string;
332
+ threadId: string;
333
+ commitId?: string;
334
+ }
335
+ export interface ThreadRunStepDeltaEvent {
336
+ type: "assistant.thread.run.step.delta";
337
+ data: ThreadMessageStepDelta;
338
+ }
339
+ export interface ThreadMessageStepDelta {
340
+ delta: any;
341
+ }
342
+ export interface ThreadRunStepCreatedEvent {
343
+ type: "assistant.thread.run.step.created";
344
+ }
345
+ export type DeepPartial<T> = T extends object ? {
346
+ [P in keyof T]?: DeepPartial<T[P]>;
347
+ } : T;
348
+ export interface AssistantContentInitialEvent {
349
+ type: "assistant.content.initial";
350
+ data: {
351
+ code: string;
352
+ };
353
+ }
354
+ export {};
package/src/events.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/src/fetch.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function fetchJsonl<T>(input: string | URL, init: RequestInit, onData: (ev: T) => void): Promise<Response>;
package/src/fetch.js ADDED
@@ -0,0 +1,83 @@
1
+ export async function fetchJsonl(input, init, onData) {
2
+ return new Promise(async (resolve, reject) => {
3
+ try {
4
+ init = {
5
+ ...init,
6
+ headers: {
7
+ accept: "application/jsonl",
8
+ "content-type": "application/json",
9
+ ...init.headers,
10
+ },
11
+ };
12
+ const rsp = await (async () => {
13
+ try {
14
+ return await fetch(input, init);
15
+ }
16
+ catch (err) {
17
+ reject(new NetworkError(`${input}, status: network failure`));
18
+ }
19
+ })();
20
+ if (!rsp) {
21
+ return;
22
+ }
23
+ if (!rsp.ok) {
24
+ reject(new APIError(`${input}, status: ${rsp.status}`));
25
+ return;
26
+ }
27
+ if (!rsp.body) {
28
+ reject(new APIError(`${input}, missing body`));
29
+ return;
30
+ }
31
+ const reader = rsp.body.getReader();
32
+ const decoder = new TextDecoder();
33
+ let data = "";
34
+ const processStream = async () => {
35
+ const { done, value } = await reader.read();
36
+ data += decoder.decode(value, { stream: !done });
37
+ if (!done) {
38
+ let lines = data.split("\n");
39
+ if (!done) {
40
+ data = lines.pop() || "";
41
+ }
42
+ for (let line of lines) {
43
+ if (line) {
44
+ try {
45
+ line = line.trim();
46
+ if (line.startsWith("{") && line.endsWith("}")) {
47
+ onData(JSON.parse(line));
48
+ }
49
+ else {
50
+ reject(`Invalid JSONL line: ${line}`);
51
+ return;
52
+ }
53
+ }
54
+ catch (e) {
55
+ console.error(`Failed to parse JSONL: ${line}`);
56
+ reject(e);
57
+ return;
58
+ }
59
+ }
60
+ }
61
+ await processStream();
62
+ }
63
+ };
64
+ await processStream();
65
+ resolve(rsp);
66
+ }
67
+ catch (e) {
68
+ reject(e);
69
+ }
70
+ });
71
+ }
72
+ class NetworkError extends Error {
73
+ constructor(message) {
74
+ super(message);
75
+ this.name = "NetworkError";
76
+ }
77
+ }
78
+ class APIError extends Error {
79
+ constructor(message) {
80
+ super(message);
81
+ this.name = "APIError";
82
+ }
83
+ }
package/src/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export * from "./completion.js";
2
+ export * from "./events.js";
3
+ export * from "./messages.js";
4
+ export * from "./settings.js";
5
+ export * from "./mapping.js";
6
+ export * from "./codegen.js";
@@ -0,0 +1,86 @@
1
+ import type { ESMImport } from "./codegen";
2
+ export interface RawFigmaJson {
3
+ documents: any[];
4
+ document?: any;
5
+ components?: Record<string, any>;
6
+ styles?: Record<string, any>;
7
+ componentSets?: Record<string, any>;
8
+ schemaVersion?: number;
9
+ }
10
+ export interface UserContext {
11
+ client: string;
12
+ clientVersion: string;
13
+ nodeVersion: string;
14
+ systemPlatform: string;
15
+ frameworks: string[];
16
+ systemEOL: string;
17
+ systemArch: string;
18
+ systemShell?: string;
19
+ inGitRepo?: boolean;
20
+ [key: string]: string | string[] | boolean | undefined;
21
+ }
22
+ export type ExportType = "default" | "named";
23
+ /**
24
+ * Gets the latest component mappings for a space
25
+ */
26
+ export interface FigmaMappingsData {
27
+ id: string;
28
+ figmaBuilderLinks: FigmaBuilderLink[];
29
+ framework: string;
30
+ version?: number;
31
+ createdDate?: string;
32
+ local: boolean;
33
+ userEmail?: string;
34
+ remoteUrl?: string;
35
+ }
36
+ export interface FigmaBuilderLink {
37
+ builderName: string;
38
+ figmaName: string;
39
+ figmaKey: string;
40
+ figmaUrl?: string;
41
+ inputMapper?: string;
42
+ originalInputMapper?: string;
43
+ exportType?: ExportType;
44
+ importName?: string;
45
+ importPath?: string;
46
+ source: string;
47
+ loc?: string;
48
+ imports?: ESMImport[];
49
+ }
50
+ export interface FigmaMapperFile {
51
+ filePath: string;
52
+ content: string;
53
+ }
54
+ export interface PublishedMapping {
55
+ figmaBuilderLinks: FigmaBuilderLink[];
56
+ mapperFiles: FigmaMapperFile[];
57
+ remoteUrl?: string;
58
+ defaultBranch?: string;
59
+ currentBranch?: string;
60
+ commit?: string;
61
+ spaceKind?: string;
62
+ userContext?: UserContext;
63
+ }
64
+ export interface FigmaComponentInfo {
65
+ documentName: string;
66
+ key: string;
67
+ tree?: string;
68
+ jsx?: string;
69
+ type: string;
70
+ name: string;
71
+ exportJson?: any;
72
+ inputs: FigmaComponentInput[];
73
+ description: string;
74
+ documentationLinks: string[];
75
+ instanceId: string;
76
+ }
77
+ export interface FigmaComponentInput {
78
+ id: string;
79
+ name: string;
80
+ value?: any;
81
+ type: string;
82
+ baseType: "text" | "variant" | "boolean" | "slot";
83
+ variantOptions?: string[];
84
+ isDefault: boolean;
85
+ ref?: string;
86
+ }
package/src/mapping.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,165 @@
1
+ import type { ContentUpdatePatch } from "./events.js";
2
+ /**
3
+ * Message param does not know the id of the message.
4
+ * This is an input message.
5
+ */
6
+ export type MessageParam = SystemMessageParam | UserMessageParam | AssistantMessageParam;
7
+ export interface ContentMessageItemText {
8
+ type: "text";
9
+ text: string;
10
+ cache?: boolean;
11
+ }
12
+ export interface ContentMessageItemImage {
13
+ type: "image";
14
+ source: ImageBase64Source | ImageUrlSource;
15
+ cache?: boolean;
16
+ }
17
+ export interface ContentMessageItemDocument {
18
+ type: "document";
19
+ source: DocumentBase64Source | DocumentUrlSource;
20
+ cache?: boolean;
21
+ }
22
+ export interface DocumentBase64Source {
23
+ type: "base64";
24
+ media_type: "application/pdf";
25
+ data: string;
26
+ }
27
+ export interface DocumentUrlSource {
28
+ type: "url";
29
+ url: string;
30
+ }
31
+ export interface ContentMessageItemToolResult {
32
+ type: "tool_result";
33
+ tool_use_id: string;
34
+ tool_name?: string;
35
+ tool_input?: string;
36
+ title?: string;
37
+ content: string;
38
+ is_error: boolean;
39
+ cache?: boolean;
40
+ }
41
+ export interface ImageBase64Source {
42
+ type: "base64";
43
+ media_type: "image/webp" | "image/png" | "image/jpeg";
44
+ data: string;
45
+ }
46
+ export interface ImageUrlSource {
47
+ type: "url";
48
+ url: string;
49
+ }
50
+ export interface ContentMessageItemThinking {
51
+ type: "thinking";
52
+ thinking: string;
53
+ signature: string;
54
+ }
55
+ export interface ContentMessageItemRedactedThinking {
56
+ type: "redacted_thinking";
57
+ data: string;
58
+ }
59
+ export interface ContentMessageItemToolUse {
60
+ type: "tool_use";
61
+ id: string;
62
+ input: unknown;
63
+ completion?: string;
64
+ name: string;
65
+ }
66
+ export type ContentMessageItem = ContentMessageItemText | ContentMessageItemImage | ContentMessageItemDocument | ContentMessageItemThinking | ContentMessageItemRedactedThinking | ContentMessageItemToolUse | ContentMessageItemToolResult;
67
+ export type ContentMessage = ContentMessageItem[];
68
+ export interface SystemMessageParam {
69
+ /**
70
+ * The contents of the system message.
71
+ */
72
+ content: string | ContentMessageItemText[];
73
+ responseId?: string;
74
+ /**
75
+ * The role of the messages author, in this case `system`.
76
+ */
77
+ role: "system";
78
+ id?: string;
79
+ }
80
+ export interface UserMessageParam {
81
+ /**
82
+ * The contents of the user message.
83
+ */
84
+ content: string | (ContentMessageItemText | ContentMessageItemImage | ContentMessageItemDocument | ContentMessageItemToolResult)[];
85
+ responseId?: string;
86
+ /**
87
+ * The role of the messages author, in this case `user`.
88
+ */
89
+ role: "user";
90
+ id?: string;
91
+ }
92
+ export interface AssistantMessageParam {
93
+ /**
94
+ * The contents of the assistant message.
95
+ */
96
+ content: string | ContentMessageItem[];
97
+ /**
98
+ * The role of the messages author, in this case `assistant`.
99
+ */
100
+ role: "assistant";
101
+ responseId?: string;
102
+ /**
103
+ * The function call name and arguments
104
+ */
105
+ action?: {
106
+ /**
107
+ * The specific function name
108
+ */
109
+ name: string;
110
+ /** This is arbitrary JSON */
111
+ arguments: any;
112
+ };
113
+ id?: string;
114
+ skipDelta?: boolean;
115
+ /**
116
+ * A summary of the patches which the assistant has made.
117
+ * Useful for genai.
118
+ */
119
+ patches?: ContentUpdatePatch[];
120
+ state?: "error";
121
+ }
122
+ export interface SystemMessage extends SystemMessageParam {
123
+ id: string;
124
+ }
125
+ export interface UserMessage extends UserMessageParam {
126
+ id: string;
127
+ }
128
+ export interface AssistantMessage extends AssistantMessageParam {
129
+ id: string;
130
+ status?: "accepted" | "rejected" | "aborted";
131
+ }
132
+ export interface AssistantActionMessage {
133
+ /**
134
+ * The role of the messages author, in this case `assistant`.
135
+ */
136
+ role: "assistant";
137
+ id: string;
138
+ }
139
+ /**
140
+ * Message DOES know the id of the message.
141
+ * This message is after an id has been assigned
142
+ * and is the output message.
143
+ */
144
+ export type Message = SystemMessage | UserMessage | AssistantMessage;
145
+ export type GeneratingMessage = null | Partial<AssistantActionMessage | AssistantMessage>;
146
+ export declare function getContentText(message: string | ContentMessage): string;
147
+ export declare function getContentAttachments(message: string | ContentMessage): (ImageBase64Source | ImageUrlSource)[];
148
+ export type Attachment = FileUpload | Template | URL;
149
+ export interface URL {
150
+ type: "url";
151
+ value: string;
152
+ }
153
+ export interface FileUpload {
154
+ type: "upload";
155
+ contentType: string;
156
+ name: string;
157
+ dataUrl: string;
158
+ size: number;
159
+ id: string;
160
+ }
161
+ export interface Template {
162
+ type: "template";
163
+ name: string;
164
+ id: number;
165
+ }