@elyracode/web-ui 0.9.58 → 1.0.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 (95) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/components/SandboxedIframe.d.ts +15 -1
  3. package/dist/components/SandboxedIframe.d.ts.map +1 -1
  4. package/dist/components/SandboxedIframe.js +129 -67
  5. package/dist/components/SandboxedIframe.js.map +1 -1
  6. package/dist/components/sandbox/RuntimeMessageRouter.d.ts +12 -2
  7. package/dist/components/sandbox/RuntimeMessageRouter.d.ts.map +1 -1
  8. package/dist/components/sandbox/RuntimeMessageRouter.js +26 -2
  9. package/dist/components/sandbox/RuntimeMessageRouter.js.map +1 -1
  10. package/package.json +18 -8
  11. package/example/README.md +0 -61
  12. package/example/index.html +0 -13
  13. package/example/package.json +0 -25
  14. package/example/src/app.css +0 -1
  15. package/example/src/css-modules.d.ts +0 -3
  16. package/example/src/custom-messages.ts +0 -99
  17. package/example/src/main.ts +0 -421
  18. package/example/tsconfig.json +0 -23
  19. package/example/vite.config.ts +0 -6
  20. package/scripts/count-prompt-tokens.ts +0 -88
  21. package/src/ChatPanel.ts +0 -209
  22. package/src/app.css +0 -68
  23. package/src/components/AgentInterface.ts +0 -403
  24. package/src/components/AttachmentTile.ts +0 -107
  25. package/src/components/ConsoleBlock.ts +0 -72
  26. package/src/components/CustomProviderCard.ts +0 -100
  27. package/src/components/ExpandableSection.ts +0 -46
  28. package/src/components/Input.ts +0 -113
  29. package/src/components/MessageEditor.ts +0 -405
  30. package/src/components/MessageList.ts +0 -98
  31. package/src/components/Messages.ts +0 -383
  32. package/src/components/ProviderKeyInput.ts +0 -153
  33. package/src/components/SandboxedIframe.ts +0 -627
  34. package/src/components/StreamingMessageContainer.ts +0 -103
  35. package/src/components/ThinkingBlock.ts +0 -43
  36. package/src/components/message-renderer-registry.ts +0 -28
  37. package/src/components/sandbox/ArtifactsRuntimeProvider.ts +0 -226
  38. package/src/components/sandbox/AttachmentsRuntimeProvider.ts +0 -68
  39. package/src/components/sandbox/ConsoleRuntimeProvider.ts +0 -188
  40. package/src/components/sandbox/FileDownloadRuntimeProvider.ts +0 -114
  41. package/src/components/sandbox/RuntimeMessageBridge.ts +0 -82
  42. package/src/components/sandbox/RuntimeMessageRouter.ts +0 -215
  43. package/src/components/sandbox/SandboxRuntimeProvider.ts +0 -54
  44. package/src/components/sandbox/runtime-messages.ts +0 -146
  45. package/src/dialogs/ApiKeyPromptDialog.ts +0 -75
  46. package/src/dialogs/AttachmentOverlay.ts +0 -637
  47. package/src/dialogs/CustomProviderDialog.ts +0 -274
  48. package/src/dialogs/ModelSelector.ts +0 -370
  49. package/src/dialogs/PersistentStorageDialog.ts +0 -144
  50. package/src/dialogs/ProvidersModelsTab.ts +0 -212
  51. package/src/dialogs/SessionListDialog.ts +0 -150
  52. package/src/dialogs/SettingsDialog.ts +0 -218
  53. package/src/index.ts +0 -120
  54. package/src/prompts/prompts.ts +0 -282
  55. package/src/storage/app-storage.ts +0 -60
  56. package/src/storage/backends/indexeddb-storage-backend.ts +0 -193
  57. package/src/storage/store.ts +0 -33
  58. package/src/storage/stores/custom-providers-store.ts +0 -62
  59. package/src/storage/stores/provider-keys-store.ts +0 -33
  60. package/src/storage/stores/sessions-store.ts +0 -136
  61. package/src/storage/stores/settings-store.ts +0 -34
  62. package/src/storage/types.ts +0 -206
  63. package/src/tools/artifacts/ArtifactElement.ts +0 -14
  64. package/src/tools/artifacts/ArtifactPill.ts +0 -26
  65. package/src/tools/artifacts/Console.ts +0 -93
  66. package/src/tools/artifacts/DocxArtifact.ts +0 -213
  67. package/src/tools/artifacts/ExcelArtifact.ts +0 -231
  68. package/src/tools/artifacts/GenericArtifact.ts +0 -117
  69. package/src/tools/artifacts/HtmlArtifact.ts +0 -195
  70. package/src/tools/artifacts/ImageArtifact.ts +0 -116
  71. package/src/tools/artifacts/MarkdownArtifact.ts +0 -82
  72. package/src/tools/artifacts/PdfArtifact.ts +0 -202
  73. package/src/tools/artifacts/SvgArtifact.ts +0 -119
  74. package/src/tools/artifacts/TextArtifact.ts +0 -148
  75. package/src/tools/artifacts/artifacts-tool-renderer.ts +0 -310
  76. package/src/tools/artifacts/artifacts.ts +0 -713
  77. package/src/tools/artifacts/index.ts +0 -7
  78. package/src/tools/extract-document.ts +0 -275
  79. package/src/tools/index.ts +0 -46
  80. package/src/tools/javascript-repl.ts +0 -293
  81. package/src/tools/renderer-registry.ts +0 -130
  82. package/src/tools/renderers/BashRenderer.ts +0 -52
  83. package/src/tools/renderers/CalculateRenderer.ts +0 -58
  84. package/src/tools/renderers/DefaultRenderer.ts +0 -103
  85. package/src/tools/renderers/GetCurrentTimeRenderer.ts +0 -92
  86. package/src/tools/types.ts +0 -15
  87. package/src/utils/attachment-utils.ts +0 -479
  88. package/src/utils/auth-token.ts +0 -22
  89. package/src/utils/format.ts +0 -42
  90. package/src/utils/i18n.ts +0 -653
  91. package/src/utils/model-discovery.ts +0 -290
  92. package/src/utils/proxy-utils.ts +0 -139
  93. package/src/utils/test-sessions.ts +0 -2357
  94. package/tsconfig.build.json +0 -20
  95. package/tsconfig.json +0 -7
@@ -1,479 +0,0 @@
1
- import { parseAsync } from "docx-preview";
2
- import JSZip from "jszip";
3
- import type { PDFDocumentProxy } from "pdfjs-dist";
4
- import * as pdfjsLib from "pdfjs-dist";
5
- import * as XLSX from "xlsx";
6
- import { i18n } from "./i18n.js";
7
-
8
- // Configure PDF.js worker - we'll need to bundle this
9
- pdfjsLib.GlobalWorkerOptions.workerSrc = new URL("pdfjs-dist/build/pdf.worker.min.mjs", import.meta.url).toString();
10
-
11
- export interface Attachment {
12
- id: string;
13
- type: "image" | "document";
14
- fileName: string;
15
- mimeType: string;
16
- size: number;
17
- content: string; // base64 encoded original data (without data URL prefix)
18
- extractedText?: string; // For documents: <pdf filename="..."><page number="1">text</page></pdf>
19
- preview?: string; // base64 image preview (first page for PDFs, or same as content for images)
20
- }
21
-
22
- /**
23
- * Load an attachment from various sources
24
- * @param source - URL string, File, Blob, or ArrayBuffer
25
- * @param fileName - Optional filename override
26
- * @returns Promise<Attachment>
27
- * @throws Error if loading fails
28
- */
29
- export async function loadAttachment(
30
- source: string | File | Blob | ArrayBuffer,
31
- fileName?: string,
32
- ): Promise<Attachment> {
33
- let arrayBuffer: ArrayBuffer;
34
- let detectedFileName = fileName || "unnamed";
35
- let mimeType = "application/octet-stream";
36
- let size = 0;
37
-
38
- // Convert source to ArrayBuffer
39
- if (typeof source === "string") {
40
- // It's a URL - fetch it
41
- const response = await fetch(source);
42
- if (!response.ok) {
43
- throw new Error(i18n("Failed to fetch file"));
44
- }
45
- arrayBuffer = await response.arrayBuffer();
46
- size = arrayBuffer.byteLength;
47
- mimeType = response.headers.get("content-type") || mimeType;
48
- if (!fileName) {
49
- // Try to extract filename from URL
50
- const urlParts = source.split("/");
51
- detectedFileName = urlParts[urlParts.length - 1] || "document";
52
- }
53
- } else if (source instanceof File) {
54
- arrayBuffer = await source.arrayBuffer();
55
- size = source.size;
56
- mimeType = source.type || mimeType;
57
- detectedFileName = fileName || source.name;
58
- } else if (source instanceof Blob) {
59
- arrayBuffer = await source.arrayBuffer();
60
- size = source.size;
61
- mimeType = source.type || mimeType;
62
- } else if (source instanceof ArrayBuffer) {
63
- arrayBuffer = source;
64
- size = source.byteLength;
65
- } else {
66
- throw new Error(i18n("Invalid source type"));
67
- }
68
-
69
- // Convert ArrayBuffer to base64 - handle large files properly
70
- const uint8Array = new Uint8Array(arrayBuffer);
71
- let binary = "";
72
- const chunkSize = 0x8000; // Process in 32KB chunks to avoid stack overflow
73
- for (let i = 0; i < uint8Array.length; i += chunkSize) {
74
- const chunk = uint8Array.slice(i, i + chunkSize);
75
- binary += String.fromCharCode(...chunk);
76
- }
77
- const base64Content = btoa(binary);
78
-
79
- // Detect type and process accordingly
80
- const id = `${detectedFileName}_${Date.now()}_${Math.random()}`;
81
-
82
- // Check if it's a PDF
83
- if (mimeType === "application/pdf" || detectedFileName.toLowerCase().endsWith(".pdf")) {
84
- const { extractedText, preview } = await processPdf(arrayBuffer, detectedFileName);
85
- return {
86
- id,
87
- type: "document",
88
- fileName: detectedFileName,
89
- mimeType: "application/pdf",
90
- size,
91
- content: base64Content,
92
- extractedText,
93
- preview,
94
- };
95
- }
96
-
97
- // Check if it's a DOCX file
98
- if (
99
- mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
100
- detectedFileName.toLowerCase().endsWith(".docx")
101
- ) {
102
- const { extractedText } = await processDocx(arrayBuffer, detectedFileName);
103
- return {
104
- id,
105
- type: "document",
106
- fileName: detectedFileName,
107
- mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
108
- size,
109
- content: base64Content,
110
- extractedText,
111
- };
112
- }
113
-
114
- // Check if it's a PPTX file
115
- if (
116
- mimeType === "application/vnd.openxmlformats-officedocument.presentationml.presentation" ||
117
- detectedFileName.toLowerCase().endsWith(".pptx")
118
- ) {
119
- const { extractedText } = await processPptx(arrayBuffer, detectedFileName);
120
- return {
121
- id,
122
- type: "document",
123
- fileName: detectedFileName,
124
- mimeType: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
125
- size,
126
- content: base64Content,
127
- extractedText,
128
- };
129
- }
130
-
131
- // Check if it's an Excel file (XLSX/XLS)
132
- const excelMimeTypes = [
133
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
134
- "application/vnd.ms-excel",
135
- ];
136
- if (
137
- excelMimeTypes.includes(mimeType) ||
138
- detectedFileName.toLowerCase().endsWith(".xlsx") ||
139
- detectedFileName.toLowerCase().endsWith(".xls")
140
- ) {
141
- const { extractedText } = await processExcel(arrayBuffer, detectedFileName);
142
- return {
143
- id,
144
- type: "document",
145
- fileName: detectedFileName,
146
- mimeType: mimeType.startsWith("application/vnd")
147
- ? mimeType
148
- : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
149
- size,
150
- content: base64Content,
151
- extractedText,
152
- };
153
- }
154
-
155
- // Check if it's an image
156
- if (mimeType.startsWith("image/")) {
157
- return {
158
- id,
159
- type: "image",
160
- fileName: detectedFileName,
161
- mimeType,
162
- size,
163
- content: base64Content,
164
- preview: base64Content, // For images, preview is the same as content
165
- };
166
- }
167
-
168
- // Check if it's a text document
169
- const textExtensions = [
170
- ".txt",
171
- ".md",
172
- ".json",
173
- ".xml",
174
- ".html",
175
- ".css",
176
- ".js",
177
- ".ts",
178
- ".jsx",
179
- ".tsx",
180
- ".yml",
181
- ".yaml",
182
- ];
183
- const isTextFile =
184
- mimeType.startsWith("text/") || textExtensions.some((ext) => detectedFileName.toLowerCase().endsWith(ext));
185
-
186
- if (isTextFile) {
187
- const decoder = new TextDecoder();
188
- const text = decoder.decode(arrayBuffer);
189
- return {
190
- id,
191
- type: "document",
192
- fileName: detectedFileName,
193
- mimeType: mimeType.startsWith("text/") ? mimeType : "text/plain",
194
- size,
195
- content: base64Content,
196
- extractedText: text,
197
- };
198
- }
199
-
200
- throw new Error(`Unsupported file type: ${mimeType}`);
201
- }
202
-
203
- async function processPdf(
204
- arrayBuffer: ArrayBuffer,
205
- fileName: string,
206
- ): Promise<{ extractedText: string; preview?: string }> {
207
- let pdf: PDFDocumentProxy | null = null;
208
- try {
209
- pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
210
-
211
- // Extract text with page structure
212
- let extractedText = `<pdf filename="${fileName}">`;
213
- for (let i = 1; i <= pdf.numPages; i++) {
214
- const page = await pdf.getPage(i);
215
- const textContent = await page.getTextContent();
216
- const pageText = textContent.items
217
- .map((item) => ("str" in item ? item.str : ""))
218
- .filter((str) => str.trim())
219
- .join(" ");
220
- extractedText += `\n<page number="${i}">\n${pageText}\n</page>`;
221
- }
222
- extractedText += "\n</pdf>";
223
-
224
- // Generate preview from first page
225
- const preview = await generatePdfPreview(pdf);
226
-
227
- return { extractedText, preview };
228
- } catch (error) {
229
- console.error("Error processing PDF:", error);
230
- throw new Error(`Failed to process PDF: ${String(error)}`);
231
- } finally {
232
- // Clean up PDF resources
233
- if (pdf) {
234
- pdf.destroy();
235
- }
236
- }
237
- }
238
-
239
- async function generatePdfPreview(pdf: PDFDocumentProxy): Promise<string | undefined> {
240
- try {
241
- const page = await pdf.getPage(1);
242
- const viewport = page.getViewport({ scale: 1.0 });
243
-
244
- // Create canvas with reasonable size for thumbnail (160x160 max)
245
- const scale = Math.min(160 / viewport.width, 160 / viewport.height);
246
- const scaledViewport = page.getViewport({ scale });
247
-
248
- const canvas = document.createElement("canvas");
249
- const context = canvas.getContext("2d");
250
- if (!context) {
251
- return undefined;
252
- }
253
-
254
- canvas.height = scaledViewport.height;
255
- canvas.width = scaledViewport.width;
256
-
257
- const renderContext = {
258
- canvasContext: context,
259
- viewport: scaledViewport,
260
- canvas: canvas,
261
- };
262
- await page.render(renderContext).promise;
263
-
264
- // Return base64 without data URL prefix
265
- return canvas.toDataURL("image/png").split(",")[1];
266
- } catch (error) {
267
- console.error("Error generating PDF preview:", error);
268
- return undefined;
269
- }
270
- }
271
-
272
- async function processDocx(arrayBuffer: ArrayBuffer, fileName: string): Promise<{ extractedText: string }> {
273
- try {
274
- // Parse document structure
275
- const wordDoc = await parseAsync(arrayBuffer);
276
-
277
- // Extract structured text from document body
278
- let extractedText = `<docx filename="${fileName}">\n<page number="1">\n`;
279
-
280
- const body = wordDoc.documentPart?.body;
281
- if (body?.children) {
282
- // Walk through document elements and extract text
283
- const texts: string[] = [];
284
- for (const element of body.children) {
285
- const text = extractTextFromElement(element);
286
- if (text) {
287
- texts.push(text);
288
- }
289
- }
290
- extractedText += texts.join("\n");
291
- }
292
-
293
- extractedText += `\n</page>\n</docx>`;
294
- return { extractedText };
295
- } catch (error) {
296
- console.error("Error processing DOCX:", error);
297
- throw new Error(`Failed to process DOCX: ${String(error)}`);
298
- }
299
- }
300
-
301
- /** Structural shape of a docx-preview document tree node (the library types its tree as `any`). */
302
- interface DocxElement {
303
- type?: string;
304
- text?: string;
305
- children?: DocxElement[];
306
- }
307
-
308
- function extractTextFromElement(element: DocxElement): string {
309
- let text = "";
310
-
311
- // Check type with lowercase
312
- const elementType = element.type?.toLowerCase() || "";
313
-
314
- // Handle paragraphs
315
- if (elementType === "paragraph" && element.children) {
316
- for (const child of element.children) {
317
- const childType = child.type?.toLowerCase() || "";
318
- if (childType === "run" && child.children) {
319
- for (const textChild of child.children) {
320
- const textType = textChild.type?.toLowerCase() || "";
321
- if (textType === "text") {
322
- text += textChild.text || "";
323
- }
324
- }
325
- } else if (childType === "text") {
326
- text += child.text || "";
327
- }
328
- }
329
- }
330
- // Handle tables
331
- else if (elementType === "table") {
332
- if (element.children) {
333
- const tableTexts: string[] = [];
334
- for (const row of element.children) {
335
- const rowType = row.type?.toLowerCase() || "";
336
- if (rowType === "tablerow" && row.children) {
337
- const rowTexts: string[] = [];
338
- for (const cell of row.children) {
339
- const cellType = cell.type?.toLowerCase() || "";
340
- if (cellType === "tablecell" && cell.children) {
341
- const cellTexts: string[] = [];
342
- for (const cellElement of cell.children) {
343
- const cellText = extractTextFromElement(cellElement);
344
- if (cellText) cellTexts.push(cellText);
345
- }
346
- if (cellTexts.length > 0) rowTexts.push(cellTexts.join(" "));
347
- }
348
- }
349
- if (rowTexts.length > 0) tableTexts.push(rowTexts.join(" | "));
350
- }
351
- }
352
- if (tableTexts.length > 0) {
353
- text = `\n[Table]\n${tableTexts.join("\n")}\n[/Table]\n`;
354
- }
355
- }
356
- }
357
- // Recursively handle other container elements
358
- else if (element.children && Array.isArray(element.children)) {
359
- const childTexts: string[] = [];
360
- for (const child of element.children) {
361
- const childText = extractTextFromElement(child);
362
- if (childText) childTexts.push(childText);
363
- }
364
- text = childTexts.join(" ");
365
- }
366
-
367
- return text.trim();
368
- }
369
-
370
- async function processPptx(arrayBuffer: ArrayBuffer, fileName: string): Promise<{ extractedText: string }> {
371
- try {
372
- // Load the PPTX file as a ZIP
373
- const zip = await JSZip.loadAsync(arrayBuffer);
374
-
375
- // PPTX slides are stored in ppt/slides/slide[n].xml
376
- let extractedText = `<pptx filename="${fileName}">`;
377
-
378
- // Get all slide files and sort them numerically
379
- const slideFiles = Object.keys(zip.files)
380
- .filter((name) => name.match(/ppt\/slides\/slide\d+\.xml$/))
381
- .sort((a, b) => {
382
- const numA = Number.parseInt(a.match(/slide(\d+)\.xml$/)?.[1] || "0", 10);
383
- const numB = Number.parseInt(b.match(/slide(\d+)\.xml$/)?.[1] || "0", 10);
384
- return numA - numB;
385
- });
386
-
387
- // Extract text from each slide
388
- for (let i = 0; i < slideFiles.length; i++) {
389
- const slideFile = zip.file(slideFiles[i]);
390
- if (slideFile) {
391
- const slideXml = await slideFile.async("text");
392
-
393
- // Extract text from XML (simple regex approach)
394
- // Looking for <a:t> tags which contain text in PPTX
395
- const textMatches = slideXml.match(/<a:t[^>]*>([^<]+)<\/a:t>/g);
396
-
397
- if (textMatches) {
398
- extractedText += `\n<slide number="${i + 1}">`;
399
- const slideTexts = textMatches
400
- .map((match) => {
401
- const textMatch = match.match(/<a:t[^>]*>([^<]+)<\/a:t>/);
402
- return textMatch ? textMatch[1] : "";
403
- })
404
- .filter((t) => t.trim());
405
-
406
- if (slideTexts.length > 0) {
407
- extractedText += `\n${slideTexts.join("\n")}`;
408
- }
409
- extractedText += "\n</slide>";
410
- }
411
- }
412
- }
413
-
414
- // Also try to extract text from notes
415
- const notesFiles = Object.keys(zip.files)
416
- .filter((name) => name.match(/ppt\/notesSlides\/notesSlide\d+\.xml$/))
417
- .sort((a, b) => {
418
- const numA = Number.parseInt(a.match(/notesSlide(\d+)\.xml$/)?.[1] || "0", 10);
419
- const numB = Number.parseInt(b.match(/notesSlide(\d+)\.xml$/)?.[1] || "0", 10);
420
- return numA - numB;
421
- });
422
-
423
- if (notesFiles.length > 0) {
424
- extractedText += "\n<notes>";
425
- for (const noteFile of notesFiles) {
426
- const file = zip.file(noteFile);
427
- if (file) {
428
- const noteXml = await file.async("text");
429
- const textMatches = noteXml.match(/<a:t[^>]*>([^<]+)<\/a:t>/g);
430
- if (textMatches) {
431
- const noteTexts = textMatches
432
- .map((match) => {
433
- const textMatch = match.match(/<a:t[^>]*>([^<]+)<\/a:t>/);
434
- return textMatch ? textMatch[1] : "";
435
- })
436
- .filter((t) => t.trim());
437
-
438
- if (noteTexts.length > 0) {
439
- const slideNum = noteFile.match(/notesSlide(\d+)\.xml$/)?.[1];
440
- extractedText += `\n[Slide ${slideNum} notes]: ${noteTexts.join(" ")}`;
441
- }
442
- }
443
- }
444
- }
445
- extractedText += "\n</notes>";
446
- }
447
-
448
- extractedText += "\n</pptx>";
449
- return { extractedText };
450
- } catch (error) {
451
- console.error("Error processing PPTX:", error);
452
- throw new Error(`Failed to process PPTX: ${String(error)}`);
453
- }
454
- }
455
-
456
- async function processExcel(arrayBuffer: ArrayBuffer, fileName: string): Promise<{ extractedText: string }> {
457
- try {
458
- // Read the workbook
459
- const workbook = XLSX.read(arrayBuffer, { type: "array" });
460
-
461
- let extractedText = `<excel filename="${fileName}">`;
462
-
463
- // Process each sheet
464
- for (const [index, sheetName] of workbook.SheetNames.entries()) {
465
- const worksheet = workbook.Sheets[sheetName];
466
-
467
- // Extract text as CSV for the extractedText field
468
- const csvText = XLSX.utils.sheet_to_csv(worksheet);
469
- extractedText += `\n<sheet name="${sheetName}" index="${index + 1}">\n${csvText}\n</sheet>`;
470
- }
471
-
472
- extractedText += "\n</excel>";
473
-
474
- return { extractedText };
475
- } catch (error) {
476
- console.error("Error processing Excel:", error);
477
- throw new Error(`Failed to process Excel: ${String(error)}`);
478
- }
479
- }
@@ -1,22 +0,0 @@
1
- import PromptDialog from "@elyracode/mini-lit/dist/PromptDialog.js";
2
- import { i18n } from "./i18n.js";
3
-
4
- export async function getAuthToken(): Promise<string | undefined> {
5
- let authToken: string | undefined = localStorage.getItem(`auth-token`) || "";
6
- if (authToken) return authToken;
7
-
8
- while (true) {
9
- authToken = (
10
- await PromptDialog.ask(i18n("Enter Auth Token"), i18n("Please enter your auth token."), "", true)
11
- )?.trim();
12
- if (authToken) {
13
- localStorage.setItem(`auth-token`, authToken);
14
- break;
15
- }
16
- }
17
- return authToken?.trim() || undefined;
18
- }
19
-
20
- export async function clearAuthToken() {
21
- localStorage.removeItem(`auth-token`);
22
- }
@@ -1,42 +0,0 @@
1
- import type { Api, Model, Usage } from "@elyracode/ai";
2
- import { i18n } from "@elyracode/mini-lit";
3
-
4
- export function formatCost(cost: number): string {
5
- return `$${cost.toFixed(4)}`;
6
- }
7
-
8
- export function formatModelCost(cost: Model<Api>["cost"] | undefined): string {
9
- if (!cost) return i18n("Free");
10
- const input = cost.input || 0;
11
- const output = cost.output || 0;
12
- if (input === 0 && output === 0) return i18n("Free");
13
-
14
- // Format numbers with appropriate precision
15
- const formatNum = (num: number): string => {
16
- if (num >= 100) return num.toFixed(0);
17
- if (num >= 10) return num.toFixed(1).replace(/\.0$/, "");
18
- if (num >= 1) return num.toFixed(2).replace(/\.?0+$/, "");
19
- return num.toFixed(3).replace(/\.?0+$/, "");
20
- };
21
-
22
- return `$${formatNum(input)}/$${formatNum(output)}`;
23
- }
24
-
25
- export function formatUsage(usage: Usage) {
26
- if (!usage) return "";
27
-
28
- const parts = [];
29
- if (usage.input) parts.push(`↑${formatTokenCount(usage.input)}`);
30
- if (usage.output) parts.push(`↓${formatTokenCount(usage.output)}`);
31
- if (usage.cacheRead) parts.push(`R${formatTokenCount(usage.cacheRead)}`);
32
- if (usage.cacheWrite) parts.push(`W${formatTokenCount(usage.cacheWrite)}`);
33
- if (usage.cost?.total) parts.push(formatCost(usage.cost.total));
34
-
35
- return parts.join(" ");
36
- }
37
-
38
- export function formatTokenCount(count: number): string {
39
- if (count < 1000) return count.toString();
40
- if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
41
- return `${Math.round(count / 1000)}k`;
42
- }