@chat-js/registry 0.2.0-beta.0 → 0.2.0-beta.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.
- package/README.md +1 -1
- package/dist/r/ai-titles.json +3 -0
- package/dist/r/attachment-uploads.json +6 -3
- package/dist/r/base/ai-titles.json +50 -0
- package/dist/r/base/akamai-storage.json +44 -0
- package/dist/r/base/alibaba-storage.json +44 -0
- package/dist/r/base/appwrite-storage.json +50 -0
- package/dist/r/base/archil-storage.json +52 -0
- package/dist/r/base/attachment-uploads.json +90 -0
- package/dist/r/base/azure-storage.json +51 -0
- package/dist/r/base/backblaze-b2-storage.json +44 -0
- package/dist/r/base/bunny-storage-storage.json +48 -0
- package/dist/r/base/cloudinary-storage.json +43 -0
- package/dist/r/base/code-documents.json +96 -0
- package/dist/r/base/code-execution-runtime.json +25 -0
- package/dist/r/base/code-execution-ui.json +32 -0
- package/dist/r/base/code-execution.json +69 -0
- package/dist/r/base/credits.json +103 -0
- package/dist/r/base/daytona-sandbox.json +55 -0
- package/dist/r/base/deep-research.json +224 -0
- package/dist/r/base/delete-document.json +58 -0
- package/dist/r/base/digitalocean-spaces-storage.json +44 -0
- package/dist/r/base/dropbox-storage.json +43 -0
- package/dist/r/base/exoscale-storage.json +44 -0
- package/dist/r/base/feedback.json +112 -0
- package/dist/r/base/filebase-storage.json +43 -0
- package/dist/r/base/firebase-storage-storage.json +52 -0
- package/dist/r/base/firecrawl-search.json +72 -0
- package/dist/r/base/followup-suggestions.json +152 -0
- package/dist/r/base/ftp-storage.json +54 -0
- package/dist/r/base/gcs-storage.json +33 -0
- package/dist/r/base/generate-image.json +101 -0
- package/dist/r/base/generate-video.json +70 -0
- package/dist/r/base/get-weather.json +52 -0
- package/dist/r/base/google-drive-storage.json +47 -0
- package/dist/r/base/hetzner-storage.json +44 -0
- package/dist/r/base/ibm-cos-storage.json +44 -0
- package/dist/r/base/idrive-e2-storage.json +44 -0
- package/dist/r/base/langfuse.json +63 -0
- package/dist/r/base/litellm-gateway.json +67 -0
- package/dist/r/base/mcp.json +320 -0
- package/dist/r/base/memory-storage.json +28 -0
- package/dist/r/base/minio-storage.json +44 -0
- package/dist/r/base/model-preferences.json +131 -0
- package/dist/r/base/neon-storage.json +44 -0
- package/dist/r/base/netlify-blobs-storage.json +31 -0
- package/dist/r/base/onedrive-storage.json +48 -0
- package/dist/r/base/openai-compatible-gateway.json +69 -0
- package/dist/r/base/openai-gateway.json +67 -0
- package/dist/r/base/openrouter-gateway.json +75 -0
- package/dist/r/base/oracle-cloud-storage.json +45 -0
- package/dist/r/base/ovhcloud-storage.json +44 -0
- package/dist/r/base/pocketbase-storage.json +50 -0
- package/dist/r/base/projects.json +275 -0
- package/dist/r/base/r2-storage.json +44 -0
- package/dist/r/base/read-document.json +34 -0
- package/dist/r/base/registry.json +4949 -0
- package/dist/r/base/retrieve-url.json +69 -0
- package/dist/r/base/s3-storage.json +44 -0
- package/dist/r/base/saved-code-execution.json +84 -0
- package/dist/r/base/scaleway-storage.json +44 -0
- package/dist/r/base/search.json +146 -0
- package/dist/r/base/sftp-storage.json +58 -0
- package/dist/r/base/sharepoint-storage.json +50 -0
- package/dist/r/base/sharing.json +144 -0
- package/dist/r/base/sheet-documents.json +94 -0
- package/dist/r/base/storj-storage.json +43 -0
- package/dist/r/base/supabase-storage.json +48 -0
- package/dist/r/base/tavily-search.json +72 -0
- package/dist/r/base/tencent-storage.json +44 -0
- package/dist/r/base/text-documents.json +117 -0
- package/dist/r/base/tigris-storage.json +43 -0
- package/dist/r/base/uploadthing-storage.json +38 -0
- package/dist/r/base/vercel-analytics.json +46 -0
- package/dist/r/base/vercel-blob-storage.json +42 -0
- package/dist/r/base/vercel-gateway.json +77 -0
- package/dist/r/base/vercel-sandbox.json +67 -0
- package/dist/r/base/vercel-speed-insights.json +46 -0
- package/dist/r/base/vultr-storage.json +44 -0
- package/dist/r/base/wasabi-storage.json +44 -0
- package/dist/r/base/webdav-storage.json +52 -0
- package/dist/r/base/word-count.json +51 -0
- package/dist/r/base/yandex-storage.json +43 -0
- package/dist/r/code-execution-ui.json +4 -3
- package/dist/r/code-execution.json +2 -2
- package/dist/r/credits.json +5 -0
- package/dist/r/deep-research.json +4 -0
- package/dist/r/feedback.json +7 -0
- package/dist/r/firecrawl-search.json +2 -2
- package/dist/r/followup-suggestions.json +5 -0
- package/dist/r/generate-image.json +3 -3
- package/dist/r/generate-video.json +2 -2
- package/dist/r/get-weather.json +3 -3
- package/dist/r/mcp.json +17 -1
- package/dist/r/model-preferences.json +6 -0
- package/dist/r/openai-compatible-gateway.json +1 -1
- package/dist/r/openai-gateway.json +1 -1
- package/dist/r/openrouter-gateway.json +1 -1
- package/dist/r/projects.json +9 -0
- package/dist/r/radix/ai-titles.json +50 -0
- package/dist/r/radix/akamai-storage.json +44 -0
- package/dist/r/radix/alibaba-storage.json +44 -0
- package/dist/r/radix/appwrite-storage.json +50 -0
- package/dist/r/radix/archil-storage.json +52 -0
- package/dist/r/radix/attachment-uploads.json +90 -0
- package/dist/r/radix/azure-storage.json +51 -0
- package/dist/r/radix/backblaze-b2-storage.json +44 -0
- package/dist/r/radix/bunny-storage-storage.json +48 -0
- package/dist/r/radix/cloudinary-storage.json +43 -0
- package/dist/r/radix/code-documents.json +96 -0
- package/dist/r/radix/code-execution-runtime.json +25 -0
- package/dist/r/radix/code-execution-ui.json +32 -0
- package/dist/r/radix/code-execution.json +69 -0
- package/dist/r/radix/credits.json +103 -0
- package/dist/r/radix/daytona-sandbox.json +55 -0
- package/dist/r/radix/deep-research.json +224 -0
- package/dist/r/radix/delete-document.json +58 -0
- package/dist/r/radix/digitalocean-spaces-storage.json +44 -0
- package/dist/r/radix/dropbox-storage.json +43 -0
- package/dist/r/radix/exoscale-storage.json +44 -0
- package/dist/r/radix/feedback.json +112 -0
- package/dist/r/radix/filebase-storage.json +43 -0
- package/dist/r/radix/firebase-storage-storage.json +52 -0
- package/dist/r/radix/firecrawl-search.json +72 -0
- package/dist/r/radix/followup-suggestions.json +152 -0
- package/dist/r/radix/ftp-storage.json +54 -0
- package/dist/r/radix/gcs-storage.json +33 -0
- package/dist/r/radix/generate-image.json +101 -0
- package/dist/r/radix/generate-video.json +70 -0
- package/dist/r/radix/get-weather.json +52 -0
- package/dist/r/radix/google-drive-storage.json +47 -0
- package/dist/r/radix/hetzner-storage.json +44 -0
- package/dist/r/radix/ibm-cos-storage.json +44 -0
- package/dist/r/radix/idrive-e2-storage.json +44 -0
- package/dist/r/radix/langfuse.json +63 -0
- package/dist/r/radix/litellm-gateway.json +67 -0
- package/dist/r/radix/mcp.json +320 -0
- package/dist/r/radix/memory-storage.json +28 -0
- package/dist/r/radix/minio-storage.json +44 -0
- package/dist/r/radix/model-preferences.json +131 -0
- package/dist/r/radix/neon-storage.json +44 -0
- package/dist/r/radix/netlify-blobs-storage.json +31 -0
- package/dist/r/radix/onedrive-storage.json +48 -0
- package/dist/r/radix/openai-compatible-gateway.json +69 -0
- package/dist/r/radix/openai-gateway.json +67 -0
- package/dist/r/radix/openrouter-gateway.json +75 -0
- package/dist/r/radix/oracle-cloud-storage.json +45 -0
- package/dist/r/radix/ovhcloud-storage.json +44 -0
- package/dist/r/radix/pocketbase-storage.json +50 -0
- package/dist/r/radix/projects.json +275 -0
- package/dist/r/radix/r2-storage.json +44 -0
- package/dist/r/radix/read-document.json +34 -0
- package/dist/r/radix/registry.json +4949 -0
- package/dist/r/radix/retrieve-url.json +69 -0
- package/dist/r/radix/s3-storage.json +44 -0
- package/dist/r/radix/saved-code-execution.json +84 -0
- package/dist/r/radix/scaleway-storage.json +44 -0
- package/dist/r/radix/search.json +146 -0
- package/dist/r/radix/sftp-storage.json +58 -0
- package/dist/r/radix/sharepoint-storage.json +50 -0
- package/dist/r/radix/sharing.json +144 -0
- package/dist/r/radix/sheet-documents.json +94 -0
- package/dist/r/radix/storj-storage.json +43 -0
- package/dist/r/radix/supabase-storage.json +48 -0
- package/dist/r/radix/tavily-search.json +72 -0
- package/dist/r/radix/tencent-storage.json +44 -0
- package/dist/r/radix/text-documents.json +117 -0
- package/dist/r/radix/tigris-storage.json +43 -0
- package/dist/r/radix/uploadthing-storage.json +38 -0
- package/dist/r/radix/vercel-analytics.json +46 -0
- package/dist/r/radix/vercel-blob-storage.json +42 -0
- package/dist/r/radix/vercel-gateway.json +77 -0
- package/dist/r/radix/vercel-sandbox.json +67 -0
- package/dist/r/radix/vercel-speed-insights.json +46 -0
- package/dist/r/radix/vultr-storage.json +44 -0
- package/dist/r/radix/wasabi-storage.json +44 -0
- package/dist/r/radix/webdav-storage.json +52 -0
- package/dist/r/radix/word-count.json +51 -0
- package/dist/r/radix/yandex-storage.json +43 -0
- package/dist/r/registry.json +108 -29
- package/dist/r/retrieve-url.json +5 -3
- package/dist/r/saved-code-execution.json +3 -0
- package/dist/r/search.json +7 -1
- package/dist/r/sharing.json +7 -0
- package/dist/r/sheet-documents.json +2 -1
- package/dist/r/tavily-search.json +2 -2
- package/dist/r/text-documents.json +2 -1
- package/dist/r/word-count.json +2 -2
- package/package.json +4 -1
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "archil-storage",
|
|
4
|
+
"title": "Archil",
|
|
5
|
+
"description": "Archil disks via the S3-compatible API. The disk id is the bucket and the endpoint is derived from the Archil region (aws-us-east-1, gcp-us-central1, ...).",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"files-sdk@2.5.0",
|
|
8
|
+
"@aws-sdk/client-s3@^3.1079.0",
|
|
9
|
+
"@aws-sdk/s3-presigned-post@^3.700.0",
|
|
10
|
+
"@aws-sdk/s3-request-presigner@^3.700.0",
|
|
11
|
+
"disk@^0.8.18 || ^1.0.0"
|
|
12
|
+
],
|
|
13
|
+
"files": [
|
|
14
|
+
{
|
|
15
|
+
"path": "src/storage/archil/storage-provider.ts",
|
|
16
|
+
"content": "export { archil as createStorageAdapter } from \"files-sdk/archil\";\n",
|
|
17
|
+
"type": "registry:file",
|
|
18
|
+
"target": "~/lib/storage-provider.ts"
|
|
19
|
+
}
|
|
20
|
+
],
|
|
21
|
+
"meta": {
|
|
22
|
+
"chatjs": {
|
|
23
|
+
"configKeys": [
|
|
24
|
+
"bucket"
|
|
25
|
+
],
|
|
26
|
+
"contractVersion": 1,
|
|
27
|
+
"envRequirements": [
|
|
28
|
+
{
|
|
29
|
+
"description": "Archil configuration",
|
|
30
|
+
"options": [
|
|
31
|
+
[
|
|
32
|
+
"ARCHIL_REGION"
|
|
33
|
+
]
|
|
34
|
+
]
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
"description": "Archil credentials",
|
|
38
|
+
"options": [
|
|
39
|
+
[
|
|
40
|
+
"ARCHIL_S3_ACCESS_KEY_ID",
|
|
41
|
+
"ARCHIL_S3_SECRET_ACCESS_KEY"
|
|
42
|
+
]
|
|
43
|
+
]
|
|
44
|
+
}
|
|
45
|
+
],
|
|
46
|
+
"id": "archil",
|
|
47
|
+
"kind": "storage",
|
|
48
|
+
"optionalEnv": []
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
"type": "registry:item"
|
|
52
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "attachment-uploads",
|
|
4
|
+
"description": "User attachment picker, camera, paste/drop, preprocessing and upload endpoint",
|
|
5
|
+
"dependencies": [
|
|
6
|
+
"lucide-react@0.553.0",
|
|
7
|
+
"sonner@^2.0.7",
|
|
8
|
+
"browser-image-compression@^2.0.2",
|
|
9
|
+
"react-dropzone@^14.3.8"
|
|
10
|
+
],
|
|
11
|
+
"files": [
|
|
12
|
+
{
|
|
13
|
+
"path": "src/plugins/attachment-uploads/src/controls.tsx",
|
|
14
|
+
"content": "\"use client\";\nimport { Camera, Paperclip } from \"lucide-react\";\nimport type { ComposerControlProps } from \"@/components/composer/control\";\nimport React from \"react\";\nimport { toast } from \"sonner\";\n\nimport { DropdownMenuItem } from \"@/components/ui/dropdown-menu\";\nimport { LoginPrompt } from \"@/components/upgrade-cta/login-prompt\";\nimport { installedPlugins } from \"@/composition/generated/installed\";\nimport { useIsMobile } from \"@/hooks/use-mobile\";\nimport { config } from \"@/lib/config\";\nimport { useSession } from \"@/providers/session-provider\";\n\ntype AttachControlProps = Readonly<\n Pick<ComposerControlProps, \"disabled\" | \"onAttach\">\n>;\n\nconst loginPrompt = (\n <LoginPrompt\n title=\"Sign in to attach files\"\n description=\"Sign in to use this plugin in your conversation.\"\n />\n);\n\nconst AttachFilesControl = ({\n disabled,\n onAttach,\n}: AttachControlProps): React.JSX.Element | null => {\n const { data: session } = useSession();\n if (!installedPlugins.has(\"attachment-uploads\")) {\n return null;\n }\n return (\n <DropdownMenuItem\n disabled={disabled}\n onClick={(): void => {\n if (!session?.user) {\n toast(loginPrompt);\n return;\n }\n onAttach(Object.keys(config.attachments.acceptedTypes).join(\",\"));\n }}\n >\n <Paperclip />\n Attach files\n </DropdownMenuItem>\n );\n};\n\nconst TakePhotoControl = ({\n disabled,\n onAttach,\n}: AttachControlProps): React.JSX.Element | null => {\n const mobile = useIsMobile();\n const { data: session } = useSession();\n if (!installedPlugins.has(\"attachment-uploads\") || !mobile) {\n return null;\n }\n return (\n <DropdownMenuItem\n disabled={disabled}\n onClick={(): void => {\n if (!session?.user) {\n toast(loginPrompt);\n return;\n }\n onAttach(\"image/jpeg,image/png\", \"environment\");\n }}\n >\n <Camera />\n Take photo\n </DropdownMenuItem>\n );\n};\n\nAttachFilesControl.isAvailable = (): boolean =>\n installedPlugins.has(\"attachment-uploads\");\nTakePhotoControl.isAvailable = (mobile: boolean): boolean =>\n installedPlugins.has(\"attachment-uploads\") && mobile;\nexport { AttachFilesControl, TakePhotoControl };\n",
|
|
15
|
+
"type": "registry:file",
|
|
16
|
+
"target": "~/plugins/attachment-uploads/controls.tsx"
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
"path": "src/plugins/attachment-uploads/src/integration.tsx",
|
|
20
|
+
"content": "\"use client\";\n\nimport type {\n AttachmentUploadInput,\n AttachmentUploadIntegration,\n} from \"@/lib/installation-contracts\";\n\nimport React, { useEffect, useRef, useState } from \"react\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { useDropzone } from \"react-dropzone\";\nimport { toast } from \"sonner\";\n\nimport { config } from \"@/lib/config\";\nimport { useSession } from \"@/providers/session-provider\";\n\nimport { AttachFilesControl, TakePhotoControl } from \"./controls\";\nimport { uploadAttachment } from \"./upload\";\nimport { processFilesForUpload } from \"./upload-prep\";\n\nconst withUploadCleanup = async (\n upload: () => Promise<void>,\n release: () => void\n): Promise<void> => {\n try {\n await upload();\n } finally {\n release();\n }\n};\n\ntype UploadPasteCaptureEvent = Readonly<{\n clipboardData: Readonly<{\n files: Readonly<Pick<FileList, \"length\" | typeof Symbol.iterator>>;\n }>;\n preventDefault: () => void;\n stopPropagation: () => void;\n}>;\n\ninterface UploadComposer {\n input: React.JSX.Element;\n onAttach: (accept: string, capture?: \"user\" | \"environment\") => void;\n rootProps: Readonly<Record<string, never>> | UploadComposerRootProps;\n}\n\ninterface UploadComposerRootProps {\n onPasteCapture: (event: UploadPasteCaptureEvent) => void;\n role: \"group\";\n}\n\ninterface UploadsResult {\n composer: (disabled: boolean) => UploadComposer;\n uploadQueue: string[];\n}\n\nconst useUploads = ({\n attachmentCount,\n onUploaded,\n}: ReadonlyNativeSurface<AttachmentUploadInput>): UploadsResult => {\n const [, startEventAction] = React.useTransition();\n const input = useRef<HTMLInputElement>(null);\n const { data: session } = useSession();\n const [uploadQueue, setUploadQueue] = useState<string[]>([]);\n const lock = useRef(false);\n const currentCount = useRef(attachmentCount);\n useEffect((): void => {\n currentCount.current = attachmentCount;\n }, [attachmentCount]);\n const upload = async (\n files: ReadonlyNativeSurface<File[]>\n ): Promise<void> => {\n if (lock.current || files.length === 0) {\n return;\n }\n if (!session?.user) {\n toast.error(\"Sign in to attach files.\");\n return;\n }\n if (files.length + currentCount.current > 16) {\n toast.error(\"Attach at most 16 files per message.\");\n return;\n }\n lock.current = true;\n setUploadQueue(\n files.map((file: ReadonlyNativeSurface<File>): string => file.name)\n );\n await withUploadCleanup(\n async () => {\n const result = await processFilesForUpload(files, config.attachments);\n if (\n result.stillOversized.length > 0 ||\n result.unsupportedFiles.length > 0\n ) {\n toast.error(\n \"Some files could not be attached. Use images or PDFs within the upload size limit.\"\n );\n }\n for (const file of result.files) {\n try {\n // oxlint-disable-next-line eslint/no-await-in-loop -- Serialize uploads to preserve order and bound memory.\n const attachment = await uploadAttachment(file);\n currentCount.current += 1;\n onUploaded(attachment);\n } catch (error) {\n toast.error(\n error instanceof Error ? error.message : \"Upload failed.\"\n );\n }\n }\n },\n () => {\n lock.current = false;\n setUploadQueue([]);\n }\n );\n };\n const { getRootProps } = useDropzone({\n disabled: uploadQueue.length > 0,\n noClick: true,\n noKeyboard: true,\n\n onDrop: (files: ReadonlyNativeSurface<File[]>) => {\n // Start outside the transition so the upload queue locks Send immediately.\n const completion = upload(files);\n startEventAction(async () => {\n await completion;\n });\n },\n });\n return {\n composer: (disabled: boolean) => ({\n input: (\n <input\n aria-label=\"Attach files\"\n className=\"hidden\"\n disabled={disabled}\n multiple\n ref={input}\n type=\"file\"\n\n onChange={(event: React.ChangeEvent<HTMLInputElement>) => {\n if (disabled) {\n event.target.value = \"\";\n return;\n }\n const completion = upload([...(event.target.files ?? [])]);\n startEventAction(async () => {\n await completion;\n event.target.value = \"\";\n });\n }}\n />\n ),\n onAttach: (accept: string, capture?: \"user\" | \"environment\"): void => {\n if (disabled || !input.current) {\n return;\n }\n input.current.accept = accept;\n if (capture) {\n input.current.capture = capture;\n } else {\n input.current.removeAttribute(\"capture\");\n }\n input.current.click();\n },\n rootProps: disabled\n ? {}\n : {\n ...getRootProps({ role: \"group\" }),\n onPasteCapture: (event: UploadPasteCaptureEvent): void => {\n if (event.clipboardData.files.length > 0) {\n event.preventDefault();\n event.stopPropagation();\n const completion = upload([...event.clipboardData.files]);\n startEventAction(async () => {\n await completion;\n });\n }\n },\n },\n }),\n uploadQueue,\n };\n};\n\nexport const attachmentUploads = {\n controls: [\n { Component: AttachFilesControl, id: \"attach-files\" },\n { Component: TakePhotoControl, id: \"take-photo\" },\n ],\n useUploads,\n} satisfies AttachmentUploadIntegration;\n",
|
|
21
|
+
"type": "registry:file",
|
|
22
|
+
"target": "~/plugins/attachment-uploads/integration.tsx"
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
"path": "src/plugins/attachment-uploads/src/upload.ts",
|
|
26
|
+
"content": "import { attachmentDigest, draftAttachment } from \"@/lib/eve/draft\";\nimport type { z } from \"zod\";\n\nexport const uploadAttachment = async (\n file: Readonly<File>\n): Promise<z.infer<typeof draftAttachment>> => {\n const body = new FormData();\n body.append(\"file\", file);\n const response = await fetch(\"/api/files/upload\", {\n body,\n method: \"POST\",\n });\n if (!response.ok) {\n const failure: unknown = await response.json().catch(() => null);\n throw new Error(\n failure !== null &&\n typeof failure === \"object\" &&\n \"error\" in failure &&\n typeof failure.error === \"string\"\n ? failure.error\n : `Unable to upload ${file.name}.`\n );\n }\n const uploaded: unknown = await response.json();\n if (uploaded === null || typeof uploaded !== \"object\") {\n throw new Error(`Invalid upload response for ${file.name}.`);\n }\n return draftAttachment.parse({\n ...uploaded,\n contentType: file.type,\n digest: await attachmentDigest(await file.arrayBuffer()),\n name: file.name,\n });\n};\n",
|
|
27
|
+
"type": "registry:file",
|
|
28
|
+
"target": "~/plugins/attachment-uploads/upload.ts"
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
"path": "src/plugins/attachment-uploads/src/upload-prep.ts",
|
|
32
|
+
"content": "// Utilities for client-side file preparation prior to upload\n\nimport imageCompression from \"browser-image-compression\";\n\nconst FILE_EXTENSION_REGEX = /\\.[^.]+$/u;\n\nconst imageExtension = (mimeType: string): string => {\n if (mimeType === \"image/jpeg\") {\n return \"jpg\";\n }\n if (mimeType === \"image/png\") {\n return \"png\";\n }\n const [, extension] = mimeType.split(\"/\");\n return extension ?? \"jpg\";\n};\n\nconst compressImageIfNeeded = async (\n file: Readonly<File>,\n {\n maxBytes,\n maxDimension,\n minQuality = 0.5,\n }: Readonly<{\n maxBytes: number;\n maxDimension: number;\n minQuality?: number;\n }>\n): Promise<File> => {\n if (!file.type.startsWith(\"image/\")) {\n return file;\n }\n if (file.size <= maxBytes) {\n return file;\n }\n\n // Only compress JPEG/PNG. Leave others unchanged.\n if (![\"image/jpeg\", \"image/png\"].includes(file.type)) {\n return file;\n }\n\n const outputMime = file.type;\n\n const options = {\n fileType: outputMime,\n initialQuality: Math.min(0.9, Math.max(minQuality, 0.1)),\n maxSizeMB: maxBytes / (1024 * 1024),\n maxWidthOrHeight: maxDimension,\n useWebWorker: true,\n } as const;\n\n try {\n const maybeResult = await imageCompression(file, options);\n const resultBlob =\n maybeResult instanceof File\n ? maybeResult\n : new File([maybeResult], file.name, {\n lastModified: Date.now(),\n type: outputMime,\n });\n if (resultBlob.size >= file.size) {\n return file;\n }\n\n const base = file.name.replace(FILE_EXTENSION_REGEX, \"\");\n return new File([resultBlob], `${base}.${imageExtension(outputMime)}`, {\n lastModified: Date.now(),\n type: outputMime,\n });\n } catch {\n return file;\n }\n};\n\nexport const processFilesForUpload = async (\n files: readonly Readonly<File>[],\n options: Readonly<{\n maxBytes: number;\n maxDimension: number;\n acceptedTypes: Readonly<Record<string, readonly string[]>>;\n }>\n): Promise<{\n files: File[];\n stillOversized: File[];\n unsupportedFiles: File[];\n}> => {\n const prepared: File[] = [];\n const stillOversized: File[] = [];\n const unsupportedFiles: File[] = [];\n const { maxBytes } = options;\n\n for (const file of files) {\n if (!Object.hasOwn(options.acceptedTypes, file.type)) {\n unsupportedFiles.push(file);\n } else if (file.type.startsWith(\"image/\")) {\n // oxlint-disable-next-line no-await-in-loop -- Compress one image at a time to bound browser worker and memory use.\n const maybeCompressed = await compressImageIfNeeded(file, options);\n if (maybeCompressed.size > maxBytes) {\n stillOversized.push(file);\n } else {\n prepared.push(maybeCompressed);\n }\n } else if (file.type === \"application/pdf\") {\n if (file.size > maxBytes) {\n stillOversized.push(file);\n } else {\n prepared.push(file);\n }\n } else {\n unsupportedFiles.push(file);\n }\n }\n\n return { files: prepared, stillOversized, unsupportedFiles };\n};\n",
|
|
33
|
+
"type": "registry:file",
|
|
34
|
+
"target": "~/plugins/attachment-uploads/upload-prep.ts"
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
"path": "src/plugins/attachment-uploads/adapters/app/(chat)/api/files/upload/route.ts",
|
|
38
|
+
"content": "export { POST } from \"@/plugins/attachment-uploads/routes/upload\";\n",
|
|
39
|
+
"type": "registry:file",
|
|
40
|
+
"target": "~/app/(chat)/api/files/upload/route.ts"
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
"path": "src/plugins/attachment-uploads/src/routes/upload.ts",
|
|
44
|
+
"content": "import type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { headers } from \"next/headers\";\nimport { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\n\nimport { auth } from \"@/lib/auth\";\nimport { config } from \"@/lib/config\";\nimport { reserveEveUpload, writeEveUpload } from \"@/lib/db/eve-files\";\nimport { createFileId, uploadFileAtKey } from \"@/lib/file-storage\";\n\n// Allow multipart headers and fields without buffering an unbounded request.\nconst MAX_MULTIPART_OVERHEAD_BYTES = 65_536;\nconst requestTooLarge = (): NextResponse<{ error: string }> =>\n NextResponse.json(\n { error: \"Upload request exceeds the size limit\" },\n { status: 413 }\n );\n\n// Validate uploaded bytes through the Blob interface; File extends Blob.\nconst FileSchema = z.object({\n file: z\n .instanceof(Blob)\n .refine(\n (file: Readonly<Pick<Blob, \"size\">>): boolean =>\n file.size <= config.attachments.maxBytes,\n {\n message: \"File exceeds the upload size limit\",\n }\n )\n .refine(\n (file: Readonly<Pick<Blob, \"type\">>): boolean =>\n Object.hasOwn(config.attachments.acceptedTypes, file.type),\n {\n message: \"Unsupported file type\",\n }\n ),\n});\n// Keep stream accounting synchronous; the getter observes the counter after parsing.\nconst limitUploadBody = (\n request: ReadonlyNativeSurface<Pick<Request, \"body\">>,\n maxRequestBytes: number\n): {\n readonly body: ReadableStream<Uint8Array> | undefined;\n readonly exceeded: boolean;\n} => {\n let receivedBytes = 0;\n let exceedsLimit = false;\n const body = request.body?.pipeThrough(\n new TransformStream<Uint8Array, Uint8Array>({\n transform(\n chunk: ReadonlyNativeSurface<Uint8Array>,\n controller: Readonly<\n Pick<\n TransformStreamDefaultController<Uint8Array>,\n \"error\" | \"enqueue\"\n >\n >\n ): void {\n receivedBytes += chunk.byteLength;\n if (receivedBytes > maxRequestBytes) {\n exceedsLimit = true;\n controller.error(new Error(\"Upload request exceeds the size limit\"));\n return;\n }\n controller.enqueue(chunk);\n },\n })\n );\n return {\n body,\n get exceeded(): boolean {\n return exceedsLimit;\n },\n };\n};\n\nconst validateUploadForm = (\n formData: ReadonlyNativeSurface<Pick<FormData, \"get\">>\n):\n | { readonly file: File }\n | { readonly response: ReturnType<typeof requestTooLarge> } => {\n const file = formData.get(\"file\");\n\n if (!(file instanceof File)) {\n return {\n response: NextResponse.json(\n { error: \"No file uploaded\" },\n { status: 400 }\n ),\n };\n }\n\n const validatedFile = FileSchema.safeParse({ file });\n\n if (!validatedFile.success) {\n const errorMessage = validatedFile.error.issues\n .map(\n (issue: Readonly<Pick<z.core.$ZodIssue, \"message\">>): string =>\n issue.message\n )\n .join(\", \");\n\n return {\n response: NextResponse.json({ error: errorMessage }, { status: 400 }),\n };\n }\n\n return { file };\n};\n\nexport const POST = async (\n request: ReadonlyNativeSurface<Request>\n): Promise<\n | ReturnType<typeof requestTooLarge>\n | NextResponse<Awaited<ReturnType<typeof uploadFileAtKey>>>\n> => {\n const session = await auth.api.getSession({ headers: await headers() });\n\n if (!session) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const maxRequestBytes =\n config.attachments.maxBytes + MAX_MULTIPART_OVERHEAD_BYTES;\n if (Number(request.headers.get(\"content-length\")) > maxRequestBytes) {\n return requestTooLarge();\n }\n\n const limitedBody = limitUploadBody(request, maxRequestBytes);\n const formData = await new Response(limitedBody.body, {\n headers: request.headers,\n })\n .formData()\n .catch(() => null);\n if (limitedBody.exceeded) {\n return requestTooLarge();\n }\n if (!formData) {\n return NextResponse.json({ error: \"Invalid upload form\" }, { status: 400 });\n }\n\n try {\n const validated = validateUploadForm(formData);\n if (\"response\" in validated) {\n return validated.response;\n }\n const { file } = validated;\n\n // Get filename from formData since Blob doesn't have name property\n const filename = file.name;\n const fileBuffer = await file.arrayBuffer();\n\n try {\n const key = createFileId();\n await reserveEveUpload(session.user.id, key);\n // Keep the reservation if storage fails: an uncertain write can still finish.\n const write = async (): ReturnType<typeof uploadFileAtKey> =>\n await uploadFileAtKey(key, filename, fileBuffer, file.type);\n const data = await writeEveUpload(session.user.id, key, write);\n return NextResponse.json(data);\n } catch {\n return NextResponse.json({ error: \"Upload failed\" }, { status: 500 });\n }\n } catch {\n return NextResponse.json(\n { error: \"Failed to process request\" },\n { status: 500 }\n );\n }\n};\n",
|
|
45
|
+
"type": "registry:file",
|
|
46
|
+
"target": "~/plugins/attachment-uploads/routes/upload.ts"
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
"path": "src/plugins/attachment-uploads/src/client-plugin.ts",
|
|
50
|
+
"content": "import type { ChatClientPlugin } from \"@/lib/plugin-contracts\";\nimport { attachmentUploads } from \"./integration\";\n\nexport const attachmentUploadsClient = () =>\n ({\n id: \"attachment-uploads\",\n composerControls: attachmentUploads.controls,\n uploads: attachmentUploads,\n }) satisfies ChatClientPlugin;\n",
|
|
51
|
+
"type": "registry:file",
|
|
52
|
+
"target": "~/plugins/attachment-uploads/client-plugin.ts"
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
"path": "dist/source/attachment-uploads.json",
|
|
56
|
+
"content": "{\n \"id\": \"attachment-uploads\",\n \"kind\": \"plugin\",\n \"files\": [\n \"plugins/attachment-uploads/controls.tsx\",\n \"plugins/attachment-uploads/integration.tsx\",\n \"plugins/attachment-uploads/upload.ts\",\n \"plugins/attachment-uploads/upload-prep.ts\",\n \"app/(chat)/api/files/upload/route.ts\",\n \"plugins/attachment-uploads/routes/upload.ts\",\n \"plugins/attachment-uploads/client-plugin.ts\"\n ],\n \"requiresStorage\": true,\n \"requiresPersistentSandbox\": true,\n \"client\": {\n \"export\": \"attachmentUploadsClient\",\n \"composerControls\": [\n \"attach-files\",\n \"take-photo\"\n ],\n \"settingsItems\": [],\n \"uploads\": true\n },\n \"contractVersion\": 2,\n \"uiBase\": \"radix\"\n}\n",
|
|
57
|
+
"type": "registry:file",
|
|
58
|
+
"target": "~/plugins/attachment-uploads/chatjs.json"
|
|
59
|
+
}
|
|
60
|
+
],
|
|
61
|
+
"meta": {
|
|
62
|
+
"chatjs": {
|
|
63
|
+
"id": "attachment-uploads",
|
|
64
|
+
"kind": "plugin",
|
|
65
|
+
"files": [
|
|
66
|
+
"plugins/attachment-uploads/controls.tsx",
|
|
67
|
+
"plugins/attachment-uploads/integration.tsx",
|
|
68
|
+
"plugins/attachment-uploads/upload.ts",
|
|
69
|
+
"plugins/attachment-uploads/upload-prep.ts",
|
|
70
|
+
"app/(chat)/api/files/upload/route.ts",
|
|
71
|
+
"plugins/attachment-uploads/routes/upload.ts",
|
|
72
|
+
"plugins/attachment-uploads/client-plugin.ts"
|
|
73
|
+
],
|
|
74
|
+
"requiresStorage": true,
|
|
75
|
+
"requiresPersistentSandbox": true,
|
|
76
|
+
"client": {
|
|
77
|
+
"export": "attachmentUploadsClient",
|
|
78
|
+
"composerControls": [
|
|
79
|
+
"attach-files",
|
|
80
|
+
"take-photo"
|
|
81
|
+
],
|
|
82
|
+
"settingsItems": [],
|
|
83
|
+
"uploads": true
|
|
84
|
+
},
|
|
85
|
+
"contractVersion": 2,
|
|
86
|
+
"uiBase": "radix"
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
"type": "registry:item"
|
|
90
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "azure-storage",
|
|
4
|
+
"title": "Azure Blob Storage",
|
|
5
|
+
"description": "Azure Blob Storage via @azure/storage-blob. Four credential modes - connection string, account key, SAS token, or anonymous.",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"files-sdk@2.5.0",
|
|
8
|
+
"@azure/storage-blob@^12.26.0"
|
|
9
|
+
],
|
|
10
|
+
"files": [
|
|
11
|
+
{
|
|
12
|
+
"path": "src/storage/azure/storage-provider.ts",
|
|
13
|
+
"content": "export { azure as createStorageAdapter } from \"files-sdk/azure\";\n",
|
|
14
|
+
"type": "registry:file",
|
|
15
|
+
"target": "~/lib/storage-provider.ts"
|
|
16
|
+
}
|
|
17
|
+
],
|
|
18
|
+
"meta": {
|
|
19
|
+
"chatjs": {
|
|
20
|
+
"configKeys": [
|
|
21
|
+
"container"
|
|
22
|
+
],
|
|
23
|
+
"contractVersion": 1,
|
|
24
|
+
"envRequirements": [
|
|
25
|
+
{
|
|
26
|
+
"description": "Azure Blob Storage credentials",
|
|
27
|
+
"options": [
|
|
28
|
+
[
|
|
29
|
+
"AZURE_STORAGE_CONNECTION_STRING"
|
|
30
|
+
],
|
|
31
|
+
[
|
|
32
|
+
"AZURE_STORAGE_ACCOUNT_NAME",
|
|
33
|
+
"AZURE_STORAGE_ACCOUNT_KEY"
|
|
34
|
+
],
|
|
35
|
+
[
|
|
36
|
+
"AZURE_STORAGE_ACCOUNT_NAME",
|
|
37
|
+
"AZURE_STORAGE_SAS_TOKEN"
|
|
38
|
+
],
|
|
39
|
+
[
|
|
40
|
+
"AZURE_STORAGE_ACCOUNT_NAME"
|
|
41
|
+
]
|
|
42
|
+
]
|
|
43
|
+
}
|
|
44
|
+
],
|
|
45
|
+
"id": "azure",
|
|
46
|
+
"kind": "storage",
|
|
47
|
+
"optionalEnv": []
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
"type": "registry:item"
|
|
51
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "backblaze-b2-storage",
|
|
4
|
+
"title": "Backblaze B2",
|
|
5
|
+
"description": "Backblaze B2 via the S3-compatible API. Endpoint derived from the cluster code (us-west-002, us-east-005, eu-central-003, ...).",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"files-sdk@2.5.0",
|
|
8
|
+
"@aws-sdk/client-s3@^3.1079.0",
|
|
9
|
+
"@aws-sdk/s3-presigned-post@^3.700.0",
|
|
10
|
+
"@aws-sdk/s3-request-presigner@^3.700.0"
|
|
11
|
+
],
|
|
12
|
+
"files": [
|
|
13
|
+
{
|
|
14
|
+
"path": "src/storage/backblaze-b2/storage-provider.ts",
|
|
15
|
+
"content": "export { backblazeB2 as createStorageAdapter } from \"files-sdk/backblaze-b2\";\n",
|
|
16
|
+
"type": "registry:file",
|
|
17
|
+
"target": "~/lib/storage-provider.ts"
|
|
18
|
+
}
|
|
19
|
+
],
|
|
20
|
+
"meta": {
|
|
21
|
+
"chatjs": {
|
|
22
|
+
"configKeys": [
|
|
23
|
+
"bucket",
|
|
24
|
+
"region"
|
|
25
|
+
],
|
|
26
|
+
"contractVersion": 1,
|
|
27
|
+
"envRequirements": [
|
|
28
|
+
{
|
|
29
|
+
"description": "Backblaze B2 credentials",
|
|
30
|
+
"options": [
|
|
31
|
+
[
|
|
32
|
+
"B2_APPLICATION_KEY_ID",
|
|
33
|
+
"B2_APPLICATION_KEY"
|
|
34
|
+
]
|
|
35
|
+
]
|
|
36
|
+
}
|
|
37
|
+
],
|
|
38
|
+
"id": "backblaze-b2",
|
|
39
|
+
"kind": "storage",
|
|
40
|
+
"optionalEnv": []
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
"type": "registry:item"
|
|
44
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "bunny-storage-storage",
|
|
4
|
+
"title": "Bunny Storage",
|
|
5
|
+
"description": "Bunny Storage via @bunny.net/storage-sdk. Connects to a Storage Zone with its zone password / access key; auto-loads BUNNY_STORAGE_* env vars (STORAGE_* as aliases).",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"files-sdk@2.5.0",
|
|
8
|
+
"@bunny.net/storage-sdk@^0.3.1"
|
|
9
|
+
],
|
|
10
|
+
"files": [
|
|
11
|
+
{
|
|
12
|
+
"path": "src/storage/bunny-storage/storage-provider.ts",
|
|
13
|
+
"content": "export { bunnyStorage as createStorageAdapter } from \"files-sdk/bunny-storage\";\n",
|
|
14
|
+
"type": "registry:file",
|
|
15
|
+
"target": "~/lib/storage-provider.ts"
|
|
16
|
+
}
|
|
17
|
+
],
|
|
18
|
+
"meta": {
|
|
19
|
+
"chatjs": {
|
|
20
|
+
"configKeys": [],
|
|
21
|
+
"contractVersion": 1,
|
|
22
|
+
"envRequirements": [
|
|
23
|
+
{
|
|
24
|
+
"description": "Bunny Storage configuration",
|
|
25
|
+
"options": [
|
|
26
|
+
[
|
|
27
|
+
"BUNNY_STORAGE_ZONE"
|
|
28
|
+
]
|
|
29
|
+
]
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
"description": "Bunny Storage credentials",
|
|
33
|
+
"options": [
|
|
34
|
+
[
|
|
35
|
+
"BUNNY_STORAGE_ACCESS_KEY"
|
|
36
|
+
]
|
|
37
|
+
]
|
|
38
|
+
}
|
|
39
|
+
],
|
|
40
|
+
"id": "bunny-storage",
|
|
41
|
+
"kind": "storage",
|
|
42
|
+
"optionalEnv": [
|
|
43
|
+
"BUNNY_STORAGE_REGION"
|
|
44
|
+
]
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
"type": "registry:item"
|
|
48
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "cloudinary-storage",
|
|
4
|
+
"title": "Cloudinary",
|
|
5
|
+
"description": "Cloudinary asset CDN via the official Node SDK. Defaults to resource_type: raw for arbitrary-bytes storage; switch to image/video for transforms.",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"files-sdk@2.5.0",
|
|
8
|
+
"cloudinary@^2.10.0"
|
|
9
|
+
],
|
|
10
|
+
"files": [
|
|
11
|
+
{
|
|
12
|
+
"path": "src/storage/cloudinary/storage-provider.ts",
|
|
13
|
+
"content": "export { cloudinary as createStorageAdapter } from \"files-sdk/cloudinary\";\n",
|
|
14
|
+
"type": "registry:file",
|
|
15
|
+
"target": "~/lib/storage-provider.ts"
|
|
16
|
+
}
|
|
17
|
+
],
|
|
18
|
+
"meta": {
|
|
19
|
+
"chatjs": {
|
|
20
|
+
"configKeys": [],
|
|
21
|
+
"contractVersion": 1,
|
|
22
|
+
"envRequirements": [
|
|
23
|
+
{
|
|
24
|
+
"description": "Cloudinary credentials",
|
|
25
|
+
"options": [
|
|
26
|
+
[
|
|
27
|
+
"CLOUDINARY_URL"
|
|
28
|
+
],
|
|
29
|
+
[
|
|
30
|
+
"CLOUDINARY_CLOUD_NAME",
|
|
31
|
+
"CLOUDINARY_API_KEY",
|
|
32
|
+
"CLOUDINARY_API_SECRET"
|
|
33
|
+
]
|
|
34
|
+
]
|
|
35
|
+
}
|
|
36
|
+
],
|
|
37
|
+
"id": "cloudinary",
|
|
38
|
+
"kind": "storage",
|
|
39
|
+
"optionalEnv": []
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"type": "registry:item"
|
|
43
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "code-documents",
|
|
4
|
+
"description": "Create and edit code documents with their editor UI",
|
|
5
|
+
"dependencies": [
|
|
6
|
+
"@codemirror/lang-javascript@^6.2.2",
|
|
7
|
+
"@codemirror/lang-python@^6.1.6",
|
|
8
|
+
"@codemirror/state@^6.5.0",
|
|
9
|
+
"@codemirror/theme-one-dark@^6.1.2",
|
|
10
|
+
"@codemirror/view@^6.35.3",
|
|
11
|
+
"codemirror@^6.0.1"
|
|
12
|
+
],
|
|
13
|
+
"registryDependencies": [
|
|
14
|
+
"@chatjs/read-document"
|
|
15
|
+
],
|
|
16
|
+
"files": [
|
|
17
|
+
{
|
|
18
|
+
"path": "src/tools/code-documents/tool.ts",
|
|
19
|
+
"content": "import {\n eveDocumentCreateInput,\n eveDocumentEditInput,\n eveDocumentWriteResult,\n} from \"@/lib/eve/document-contracts\";\nimport type { ToolContext } from \"eve/tools\";\nimport { codeGuidelines } from \"./guidelines\";\nimport { defineTool } from \"eve/tools\";\nimport { executeEveDocumentTool } from \"@/lib/eve/document-tools\";\nimport type { z } from \"zod\";\n\ntype CreateCodeDocumentInput = Readonly<\n Omit<z.infer<typeof eveDocumentCreateInput>, \"fileIds\"> & {\n fileIds: readonly string[];\n }\n>;\n\ntype EditCodeDocumentInput = Readonly<\n Omit<z.infer<typeof eveDocumentEditInput>, \"fileIds\"> & {\n fileIds: readonly string[];\n }\n>;\n\ntype ReadonlyDocumentToolContext = Readonly<\n Pick<ToolContext, \"callId\" | \"session\"> & {\n abortSignal: Readonly<AbortSignal>;\n }\n>;\n\nconst createCodeDocument = defineTool({\n description: `Create a new code document in this conversation. Supply the complete content and a descriptive title. ${codeGuidelines}`,\n execute: async (\n input: CreateCodeDocumentInput,\n context: ReadonlyDocumentToolContext\n ) =>\n eveDocumentWriteResult.parse(\n await executeEveDocumentTool(\"createCodeDocument\", input, context)\n ),\n inputSchema: eveDocumentCreateInput,\n outputSchema: eveDocumentWriteResult,\n});\nconst editCodeDocument = defineTool({\n description: `Edit an existing code document in this conversation. Read the document first and supply its revision ID. Supply the complete replacement content. ${codeGuidelines}`,\n execute: async (\n input: EditCodeDocumentInput,\n context: ReadonlyDocumentToolContext\n ) =>\n eveDocumentWriteResult.parse(\n await executeEveDocumentTool(\"editCodeDocument\", input, context)\n ),\n inputSchema: eveDocumentEditInput,\n outputSchema: eveDocumentWriteResult,\n});\nexport { createCodeDocument, editCodeDocument };\n",
|
|
20
|
+
"type": "registry:file",
|
|
21
|
+
"target": "~/tools/chatjs/code-documents/tool.ts"
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"path": "src/tools/code-documents/guidelines.ts",
|
|
25
|
+
"content": "export const codeGuidelines = `\nGuidelines for Python code:\n- Each snippet should be complete and runnable on its own\n- Prefer using print() statements to display outputs\n- Include helpful comments explaining the code\n- Keep snippets concise (generally under 15 lines)\n- Avoid external dependencies - use Python standard library\n- Handle potential errors gracefully\n- Return meaningful output that demonstrates the code's functionality\n- Don't use input() or other interactive functions\n- Don't access files or network resources\n- Don't use infinite loops\n\nThe title MUST include the file extension (e.g., \"script.py\", \"App.tsx\", \"utils.js\").\nThis extension determines syntax highlighting.`;\n",
|
|
26
|
+
"type": "registry:file",
|
|
27
|
+
"target": "~/tools/chatjs/code-documents/guidelines.ts"
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
"path": "src/tools/code-documents/configuration-schema.ts",
|
|
31
|
+
"content": "import { z } from \"zod\";\nimport { languageModelSchema, modelRoles } from \"@/lib/config-models\";\n\nconst configSchema = z\n .strictObject({ edits: languageModelSchema.default(modelRoles.balanced) })\n .prefault({});\nexport { configSchema };\n",
|
|
32
|
+
"type": "registry:file",
|
|
33
|
+
"target": "~/tools/chatjs/code-documents/configuration-schema.ts"
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
"path": "src/tools/code-documents/assistant-actions.ts",
|
|
37
|
+
"content": "import type { DocumentAssistantAction } from \"@/lib/eve/document-contracts\";\nimport { config } from \"@/lib/config\";\n\nconst documentAssistantActions = (): DocumentAssistantAction[] => [\n {\n instruction: \"Add comments to the code for understanding.\",\n label: \"Add comments\",\n modelId: config.ai.tools.code.edits,\n },\n {\n instruction: \"Add logs to the code for debugging.\",\n label: \"Add logs\",\n modelId: config.ai.tools.code.edits,\n },\n];\nexport { documentAssistantActions };\n",
|
|
38
|
+
"type": "registry:file",
|
|
39
|
+
"target": "~/tools/chatjs/code-documents/assistant-actions.ts"
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
"path": "src/tools/code-documents/document.tsx",
|
|
43
|
+
"content": "\"use client\";\nimport type { DocumentBodyProps, DocumentUi } from \"@/lib/eve/document-ui\";\nimport React from \"react\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { ScrollArea } from \"@/components/ui/scroll-area\";\nimport dynamic from \"next/dynamic\";\nimport { getLanguageFromFileName } from \"@/lib/file-language\";\n\nconst CodeEditor = dynamic(\n async () => {\n const { CodeEditor: Editor } = await import(\"./editor\");\n return Editor;\n },\n {\n ssr: false,\n }\n);\n\nexport const documentUi: DocumentUi = {\n Body: ({ title, editorProps }: ReadonlyNativeSurface<DocumentBodyProps>) => (\n <ScrollArea className=\"min-h-0 flex-1\">\n <CodeEditor\n {...editorProps}\n language={getLanguageFromFileName(title) || \"python\"}\n />\n </ScrollArea>\n ),\n};\n",
|
|
44
|
+
"type": "registry:file",
|
|
45
|
+
"target": "~/tools/chatjs/code-documents/document.tsx"
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
"path": "src/tools/code-documents/editor.tsx",
|
|
49
|
+
"content": "\"use client\";\n\nimport { Compartment, EditorState, Transaction } from \"@codemirror/state\";\nimport React, { memo, useEffect, useRef } from \"react\";\nimport { EditorView } from \"@codemirror/view\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport type { ViewUpdate } from \"@codemirror/view\";\nimport { javascript } from \"@codemirror/lang-javascript\";\nimport { python } from \"@codemirror/lang-python\";\nimport { oneDark } from \"@codemirror/theme-one-dark\";\nimport { basicSetup } from \"codemirror\";\n\ninterface EditorProps {\n content: string;\n currentVersionIndex: number;\n isCurrentVersion: boolean;\n isReadonly?: boolean;\n language?: string;\n onSaveContent: (updatedContent: string, debounce: boolean) => void;\n status: \"streaming\" | \"idle\";\n}\n\nconst getLanguageExtension = (language: string): ReturnType<typeof python> => {\n switch (language) {\n case \"typescript\": {\n return javascript({ jsx: false, typescript: true });\n }\n case \"javascript\": {\n return javascript({ jsx: false, typescript: false });\n }\n case \"jsx\": {\n return javascript({ jsx: true, typescript: false });\n }\n case \"tsx\": {\n return javascript({ jsx: true, typescript: true });\n }\n default: {\n return python();\n }\n }\n};\n\nconst PureCodeEditor = ({\n content,\n onSaveContent,\n isReadonly,\n language = \"python\",\n}: ReadonlyNativeSurface<EditorProps>): React.JSX.Element => {\n const containerRef = useRef<HTMLDivElement>(null);\n const editorRef = useRef<EditorView | null>(null);\n\n const configuration = useRef(new Compartment());\n\n useEffect((): (() => void) | undefined => {\n if (!containerRef.current) {\n return undefined;\n }\n const view = new EditorView({\n parent: containerRef.current,\n state: EditorState.create({\n extensions: [basicSetup, oneDark, configuration.current.of([])],\n }),\n });\n editorRef.current = view;\n return (): void => {\n view.destroy();\n editorRef.current = null;\n };\n }, []);\n\n useEffect((): void => {\n editorRef.current?.dispatch({\n effects: configuration.current.reconfigure([\n getLanguageExtension(language),\n EditorView.editable.of(!(isReadonly === true)),\n EditorState.readOnly.of(Boolean(isReadonly)),\n EditorView.updateListener.of(\n (\n update: ReadonlyNativeSurface<\n Pick<ViewUpdate, \"docChanged\" | \"state\" | \"transactions\">\n >\n ): void => {\n if (\n update.docChanged &&\n isReadonly !== true &&\n update.transactions.some(\n (transaction: ReadonlyNativeSurface<Transaction>): boolean =>\n transaction.annotation(Transaction.remote) !== true\n )\n ) {\n onSaveContent(update.state.doc.toString(), true);\n }\n }\n ),\n ]),\n });\n }, [onSaveContent, isReadonly, language]);\n\n useEffect((): void => {\n const view = editorRef.current;\n if (!view) {\n return;\n }\n const currentContent = view.state.doc.toString();\n if (currentContent !== content) {\n view.dispatch({\n annotations: [Transaction.remote.of(true)],\n changes: { from: 0, insert: content, to: currentContent.length },\n });\n }\n }, [content]);\n\n return (\n <div className=\"not-prose relative w-full text-sm\" ref={containerRef} />\n );\n};\n\nconst areEqual = (\n prevProps: ReadonlyNativeSurface<EditorProps>,\n nextProps: ReadonlyNativeSurface<EditorProps>\n): boolean => {\n if (prevProps.currentVersionIndex !== nextProps.currentVersionIndex) {\n return false;\n }\n if (prevProps.isCurrentVersion !== nextProps.isCurrentVersion) {\n return false;\n }\n if (prevProps.status === \"streaming\" && nextProps.status === \"streaming\") {\n return false;\n }\n if (prevProps.content !== nextProps.content) {\n return false;\n }\n if (prevProps.isReadonly !== nextProps.isReadonly) {\n return false;\n }\n if (prevProps.language !== nextProps.language) {\n return false;\n }\n\n return true;\n};\n\nexport const CodeEditor = memo(PureCodeEditor, areEqual);\n",
|
|
50
|
+
"type": "registry:file",
|
|
51
|
+
"target": "~/tools/chatjs/code-documents/editor.tsx"
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"path": "dist/source/code-documents.json",
|
|
55
|
+
"content": "{\n \"config\": {\n \"key\": \"code\"\n },\n \"documentActions\": true,\n \"documentKind\": \"code\",\n \"envRequirements\": [],\n \"id\": \"code-documents\",\n \"kind\": \"tool\",\n \"requiresTools\": [\n \"readDocument\"\n ],\n \"tools\": [\n {\n \"composer\": {\n \"icon\": \"Edit3\",\n \"name\": \"Canvas\",\n \"shortName\": \"Canvas\"\n },\n \"toolExport\": \"createCodeDocument\"\n },\n {\n \"composer\": {\n \"icon\": \"Edit3\",\n \"name\": \"Canvas\",\n \"shortName\": \"Canvas\"\n },\n \"toolExport\": \"editCodeDocument\"\n }\n ],\n \"contractVersion\": 2,\n \"uiBase\": \"radix\"\n}\n",
|
|
56
|
+
"type": "registry:file",
|
|
57
|
+
"target": "~/tools/chatjs/code-documents/chatjs.json"
|
|
58
|
+
}
|
|
59
|
+
],
|
|
60
|
+
"meta": {
|
|
61
|
+
"chatjs": {
|
|
62
|
+
"config": {
|
|
63
|
+
"key": "code"
|
|
64
|
+
},
|
|
65
|
+
"documentActions": true,
|
|
66
|
+
"documentKind": "code",
|
|
67
|
+
"envRequirements": [],
|
|
68
|
+
"id": "code-documents",
|
|
69
|
+
"kind": "tool",
|
|
70
|
+
"requiresTools": [
|
|
71
|
+
"readDocument"
|
|
72
|
+
],
|
|
73
|
+
"tools": [
|
|
74
|
+
{
|
|
75
|
+
"composer": {
|
|
76
|
+
"icon": "Edit3",
|
|
77
|
+
"name": "Canvas",
|
|
78
|
+
"shortName": "Canvas"
|
|
79
|
+
},
|
|
80
|
+
"toolExport": "createCodeDocument"
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
"composer": {
|
|
84
|
+
"icon": "Edit3",
|
|
85
|
+
"name": "Canvas",
|
|
86
|
+
"shortName": "Canvas"
|
|
87
|
+
},
|
|
88
|
+
"toolExport": "editCodeDocument"
|
|
89
|
+
}
|
|
90
|
+
],
|
|
91
|
+
"contractVersion": 2,
|
|
92
|
+
"uiBase": "radix"
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
"type": "registry:item"
|
|
96
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "code-execution-runtime",
|
|
4
|
+
"files": [
|
|
5
|
+
{
|
|
6
|
+
"path": "src/tools/_shared/code-execution/python.ts",
|
|
7
|
+
"content": "import type {\n CodeExecutionContext,\n CodeExecutionResult,\n ExecutionSandbox,\n} from \"./types\";\nimport { z } from \"zod\";\n\ntype PythonExecutionContext = Readonly<{\n sandbox: Readonly<ExecutionSandbox>;\n requestId: string;\n log: Readonly<Pick<CodeExecutionContext[\"log\"], \"error\" | \"info\">>;\n}>;\n\nconst pythonExecutionInfoSchema = z.looseObject({\n error: z\n .looseObject({\n name: z.string(),\n value: z.string(),\n traceback: z.string(),\n })\n .optional(),\n success: z.boolean().optional(),\n});\n\ntype PythonExecutionInfo = z.infer<typeof pythonExecutionInfoSchema>;\n\ninterface PythonExecutionOutput {\n chartData: Record<string, unknown> | null;\n execInfo: PythonExecutionInfo;\n outputText: string;\n}\n\nconst WHITESPACE_REGEX = /\\s+/u;\nconst PACKAGE_SPEC_SPLIT_RE = /[=<>![\\s]/u;\nconst isJsonObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst PROCESS_SUCCESS = 0;\nconst PACKAGE_NAME_INDEX = 0;\nconst EMPTY_PACKAGE_COUNT = 0;\nconst LAST_LINE_INDEX = -1;\nconst MISSING_CHART_INDEX = -1;\nconst CHART_LINE_COUNT = 1;\nconst EMPTY_STDERR_LENGTH = 0;\n\nconst CHART_JSON_PREFIX = \"__CHART_JSON__:\";\n\nconst packageName = (spec: string): string =>\n spec.split(PACKAGE_SPEC_SPLIT_RE)[PACKAGE_NAME_INDEX].toLowerCase();\n\nconst installBasePackages = async (\n basePackages: readonly string[],\n { sandbox, requestId, log }: PythonExecutionContext\n): Promise<{\n success: boolean;\n result?: CodeExecutionResult;\n}> => {\n const installStep = await sandbox.runCommand({\n args: [\"install\", ...basePackages],\n cmd: \"pip\",\n });\n if (installStep.exitCode !== PROCESS_SUCCESS) {\n const errorOutput = await installStep.stderr();\n const standardOutput =\n errorOutput.trim() === \"\" ? await installStep.stdout() : \"\";\n const installStderr = errorOutput.trim() || standardOutput.trim();\n log.error(\n { requestId, stderr: installStderr },\n \"base package installation failed\"\n );\n return {\n result: {\n chart: \"\",\n message: `Failed to install base packages: ${installStderr}`,\n },\n success: false,\n };\n }\n log.info({ requestId }, \"base packages installed\");\n return { success: true };\n};\n\nconst pythonPackagePlan = (\n code: string,\n basePackages: readonly string[]\n): { codeWithoutPipLines: string; extraPackages: string[] } => {\n const basePackageNames = new Set(\n basePackages.map((basePackageName) => basePackageName.toLowerCase())\n );\n const lines = code.split(\"\\n\");\n const pipLines = lines.filter((line) =>\n line.trim().startsWith(\"!pip install \")\n );\n const extraPackages = pipLines\n .flatMap((line) =>\n line\n .trim()\n .slice(\"!pip install \".length)\n .split(WHITESPACE_REGEX)\n .filter(Boolean)\n )\n .filter((spec) => !basePackageNames.has(packageName(spec)));\n\n const codeWithoutPipLines = lines\n .filter((line) => !line.trim().startsWith(\"!pip install \"))\n .join(\"\\n\");\n return { codeWithoutPipLines, extraPackages };\n};\n\ninterface PythonPackagePreparation {\n codeToRun: string;\n installResult: {\n success: boolean;\n result?: CodeExecutionResult;\n };\n}\n\nconst processExtraPackages = async (\n code: string,\n basePackages: readonly string[],\n { sandbox, requestId, log }: PythonExecutionContext\n): Promise<PythonPackagePreparation> => {\n const { codeWithoutPipLines, extraPackages } = pythonPackagePlan(\n code,\n basePackages\n );\n\n if (extraPackages.length === EMPTY_PACKAGE_COUNT) {\n return { codeToRun: codeWithoutPipLines, installResult: { success: true } };\n }\n\n log.info(\n { packageCount: extraPackages.length, requestId },\n \"installing extra packages\"\n );\n const dynamicInstall = await sandbox.runCommand({\n args: [\"install\", ...extraPackages],\n cmd: \"pip\",\n });\n if (dynamicInstall.exitCode !== PROCESS_SUCCESS) {\n const errorOutput = await dynamicInstall.stderr();\n const standardOutput =\n errorOutput.trim() === \"\" ? await dynamicInstall.stdout() : \"\";\n const stderr = errorOutput.trim() || standardOutput.trim();\n log.error(\n { exitCode: dynamicInstall.exitCode, requestId },\n \"dynamic package installation failed\"\n );\n return {\n codeToRun: code,\n installResult: {\n result: {\n chart: \"\",\n message: `Failed to install packages: ${stderr}`,\n },\n success: false,\n },\n };\n }\n\n return {\n codeToRun: codeWithoutPipLines,\n installResult: { success: true },\n };\n};\n\nconst createWrappedCode = (codeToRun: string, chartPath: string): string => `\nimport sys\nimport json\nimport traceback\n\ntry:\n import matplotlib.pyplot as _plt_module\n _orig_savefig = _plt_module.savefig\n def _intercepted_savefig(*args, **kwargs):\n _orig_savefig('${chartPath}', format='png', bbox_inches='tight', dpi=100)\n _user_target = args[0] if args else kwargs.get('fname')\n if _user_target not in (None, '${chartPath}'):\n return _orig_savefig(*args, **kwargs)\n _plt_module.savefig = _intercepted_savefig\nexcept ImportError:\n pass\n\ntry:\n exec(${JSON.stringify(codeToRun)})\n try:\n _locals = locals()\n _globals = globals()\n _chart_var = _locals.get(\"chart\") or _globals.get(\"chart\")\n if (isinstance(_chart_var, dict)\n and isinstance(_chart_var.get(\"type\"), str)\n and isinstance(_chart_var.get(\"elements\"), list)):\n print(\"__CHART_JSON__:\" + json.dumps(_chart_var))\n else:\n if \"result\" in _locals:\n print(_locals[\"result\"])\n elif \"result\" in _globals:\n print(_globals[\"result\"])\n elif \"results\" in _locals:\n print(_locals[\"results\"])\n elif \"results\" in _globals:\n print(_globals[\"results\"])\n except Exception:\n pass\n try:\n import matplotlib.pyplot as plt\n if plt.get_fignums():\n plt.savefig('${chartPath}', format='png', bbox_inches='tight', dpi=100)\n plt.close('all')\n except ImportError:\n pass\n print(json.dumps({\"success\": True}))\nexcept Exception as e:\n error_info = {\"success\": False, \"error\": {\"name\": type(e).__name__, \"value\": str(e), \"traceback\": traceback.format_exc()}}\n print(json.dumps(error_info))\n sys.exit(1)\n`;\n\nconst parseExecutionOutput = async (\n execResult: Readonly<{\n stdout: () => Promise<string>;\n exitCode: number;\n }>\n): Promise<PythonExecutionOutput> => {\n const stdout = await execResult.stdout();\n let execInfo: PythonExecutionInfo = { success: true };\n let outputText = \"\";\n let chartData: Record<string, unknown> | null = null;\n\n try {\n const outLines = (stdout ?? \"\").trim().split(\"\\n\");\n const lastLine = outLines.at(LAST_LINE_INDEX);\n execInfo = pythonExecutionInfoSchema.parse(JSON.parse(lastLine ?? \"{}\"));\n outLines.pop();\n\n const chartLineIdx = outLines.findIndex((line) =>\n line.startsWith(CHART_JSON_PREFIX)\n );\n if (chartLineIdx !== MISSING_CHART_INDEX) {\n const raw = outLines[chartLineIdx].slice(CHART_JSON_PREFIX.length);\n try {\n const value: unknown = JSON.parse(raw);\n if (isJsonObject(value)) {\n chartData = value;\n }\n } catch {\n // Ignore malformed chart JSON from the sandboxed snippet.\n }\n outLines.splice(chartLineIdx, CHART_LINE_COUNT);\n }\n\n outputText = outLines.join(\"\\n\");\n } catch {\n outputText = stdout ?? \"\";\n if (execResult.exitCode !== PROCESS_SUCCESS) {\n execInfo = {\n error: {\n name: \"SandboxExecutionError\",\n traceback: \"\",\n value: \"Execution completed without a parsable status trailer\",\n },\n success: false,\n };\n }\n }\n\n return { chartData, execInfo, outputText };\n};\n\nconst checkForChart = async (\n chartPath: string,\n { sandbox, requestId, log }: PythonExecutionContext\n): Promise<{ base64: string; format: string } | undefined> => {\n const chartCheck = await sandbox.runCommand({\n args: [\"-f\", chartPath],\n cmd: \"test\",\n });\n if (chartCheck.exitCode === PROCESS_SUCCESS) {\n const base64Command = await sandbox.runCommand({\n args: [\"-w\", \"0\", chartPath],\n cmd: \"base64\",\n });\n const b64 = await base64Command.stdout();\n log.info({ requestId }, \"chart generated\");\n return { base64: (b64 ?? \"\").trim(), format: \"png\" };\n }\n return undefined;\n};\n\nconst buildResponseMessage = ({\n outputText,\n stderr,\n execInfo,\n log,\n requestId,\n}: Readonly<{\n outputText: string;\n stderr: string;\n execInfo: Readonly<PythonExecutionInfo>;\n log: Readonly<Pick<CodeExecutionContext[\"log\"], \"error\">>;\n requestId: string;\n}>): string => {\n let message = \"\";\n\n if (outputText) {\n message += `${outputText}\\n`;\n }\n if (stderr && stderr.trim().length > EMPTY_STDERR_LENGTH) {\n message += `${stderr}\\n`;\n }\n if (execInfo.error) {\n message += `Error: ${execInfo.error.name}: ${execInfo.error.value}\\n`;\n log.error({ error: execInfo.error, requestId }, \"python execution error\");\n }\n\n return message;\n};\n\nexport const executePythonInSandbox = async ({\n sandbox,\n code,\n log,\n requestId,\n}: Readonly<\n Pick<CodeExecutionContext, \"code\" | \"requestId\"> & {\n sandbox: Readonly<Pick<CodeExecutionContext[\"sandbox\"], \"runCommand\">>;\n log: Readonly<Pick<CodeExecutionContext[\"log\"], \"error\" | \"info\">>;\n }\n>): Promise<CodeExecutionResult> => {\n const execution = { log, requestId, sandbox };\n const basePackages = [\n \"matplotlib\",\n \"pandas\",\n \"numpy\",\n \"sympy\",\n \"yfinance\",\n ] as const;\n const chartPath = \"/tmp/chart.png\";\n\n const baseInstallResult = await installBasePackages(basePackages, execution);\n if (!baseInstallResult.success) {\n return baseInstallResult.result ?? { chart: \"\", message: \"Unknown error\" };\n }\n\n const { codeToRun, installResult } = await processExtraPackages(\n code,\n basePackages,\n execution\n );\n if (!installResult.success) {\n return installResult.result ?? { chart: \"\", message: \"Unknown error\" };\n }\n\n const wrappedCode = createWrappedCode(codeToRun, chartPath);\n const execResult = await sandbox.runCommand({\n args: [\"-c\", wrappedCode],\n cmd: \"python3\",\n });\n\n const { outputText, chartData, execInfo } =\n await parseExecutionOutput(execResult);\n\n const message = buildResponseMessage({\n execInfo,\n log,\n outputText,\n requestId,\n stderr: await execResult.stderr(),\n });\n\n if (chartData) {\n log.info({ requestId }, \"interactive chart data returned\");\n return { chart: chartData, message: message.trim() };\n }\n\n const chartOut = await checkForChart(chartPath, execution);\n return {\n chart: chartOut ?? \"\",\n message: message.trim(),\n };\n};\n",
|
|
8
|
+
"type": "registry:file",
|
|
9
|
+
"target": "~/tools/chatjs/_shared/code-execution/python.ts"
|
|
10
|
+
},
|
|
11
|
+
{
|
|
12
|
+
"path": "src/tools/_shared/code-execution/javascript.ts",
|
|
13
|
+
"content": "import type { CodeExecutionContext, CodeExecutionResult } from \"./types\";\n\nconst SUCCESS_EXIT_CODE = 0;\nconst MISSING_STATUS_LINE_INDEX = -1;\nconst STATUS_TRAILER_LINE_COUNT = 1;\nconst EXECUTION_STATUS_PREFIX = \"__EXECUTION_STATUS__:\";\n\nconst JAVASCRIPT_EXECUTION_TEMPLATE = `\nimport { inspect } from \"node:util\";\n\nconst __formatOutput = (value) => {\n if (typeof value === \"string\") {\n return value;\n }\n\n return inspect(value, {\n depth: 4,\n colors: false,\n maxArrayLength: 100,\n breakLength: 120,\n });\n};\n\nconst __run = async () => {\n try {\n const __userCode = __USER_CODE_LITERAL__;\n const __execution = await (0, eval)(\n \"(async () => {\\\\n\" +\n __userCode + \"\\\\n\" +\n \"return { __kind: \\\\\"locals\\\\\",\" +\n \" result: typeof result !== \\\\\"undefined\\\\\" ? result : undefined,\" +\n \" results: typeof results !== \\\\\"undefined\\\\\" ? results : undefined };\\\\n\" +\n \"})()\"\n );\n\n const __result =\n __execution &&\n typeof __execution === \"object\" &&\n __execution.__kind === \"locals\"\n ? typeof __execution.result !== \"undefined\"\n ? __execution.result\n : typeof __execution.results !== \"undefined\"\n ? __execution.results\n : undefined\n : __execution;\n\n if (typeof __result !== \"undefined\") {\n console.log(__formatOutput(__result));\n }\n\n console.log(\"${EXECUTION_STATUS_PREFIX}\" + JSON.stringify({ success: true }));\n } catch (error) {\n const execError = error instanceof Error ? error : new Error(String(error));\n console.log(\n \"${EXECUTION_STATUS_PREFIX}\" +\n JSON.stringify({\n success: false,\n error: {\n name: execError.name,\n value: execError.message,\n traceback: execError.stack ?? execError.message,\n },\n })\n );\n process.exitCode = 1;\n }\n};\n\nawait __run();\n`;\n\nconst createWrappedCode = (code: string): string =>\n JAVASCRIPT_EXECUTION_TEMPLATE.replace(\"__USER_CODE_LITERAL__\", (): string =>\n JSON.stringify(code)\n );\n\ninterface JsExecInfo {\n success?: unknown;\n error?: unknown;\n}\n\nconst execInfoFromExitCode = (exitCode: number): JsExecInfo => {\n if (exitCode === SUCCESS_EXIT_CODE) {\n return { success: true };\n }\n return {\n error: {\n name: \"SandboxExecutionError\",\n traceback: \"\",\n value: \"Execution completed without a valid status trailer\",\n },\n success: false,\n };\n};\n\nconst readExecutionErrorField = (error: unknown, key: string): unknown =>\n Reflect.get(new Object(error), key);\n\nconst readExecutionError = (info: unknown): unknown => {\n if (info === null) {\n throw new TypeError(\"Sandbox execution status cannot be null.\");\n }\n return readExecutionErrorField(info, \"error\");\n};\n\nconst decodeExecutionTrailer = (\n raw: string\n): { valid: true; info: unknown } | { valid: false } => {\n try {\n const parsed: unknown = JSON.parse(raw);\n return { info: parsed, valid: true };\n } catch {\n return { valid: false };\n }\n};\n\nconst findExecutionTrailer = (\n lines: readonly string[]\n): { found: true; index: number; raw: string } | { found: false } => {\n // The final trailer wins over user output that happens to share the prefix.\n const index = lines.findLastIndex((line) =>\n line.startsWith(EXECUTION_STATUS_PREFIX)\n );\n if (index === MISSING_STATUS_LINE_INDEX) {\n return { found: false };\n }\n return {\n found: true,\n index,\n raw: lines[index].slice(EXECUTION_STATUS_PREFIX.length),\n };\n};\n\nconst parseExecutionOutput = async (\n execResult: Readonly<{\n stdout: () => Promise<string>;\n exitCode: number;\n }>\n): Promise<{\n outputText: string;\n execInfo: unknown;\n}> => {\n const stdout = await execResult.stdout();\n const lines = (stdout ?? \"\").split(\"\\n\");\n const trailer = findExecutionTrailer(lines);\n\n if (!trailer.found) {\n return {\n execInfo: execInfoFromExitCode(execResult.exitCode),\n outputText: stdout ?? \"\",\n };\n }\n\n const decoded = decodeExecutionTrailer(trailer.raw);\n if (!decoded.valid) {\n return {\n execInfo: execInfoFromExitCode(execResult.exitCode),\n outputText: stdout ?? \"\",\n };\n }\n lines.splice(trailer.index, STATUS_TRAILER_LINE_COUNT);\n\n return {\n execInfo: decoded.info,\n outputText: lines.join(\"\\n\").trim(),\n };\n};\nconst formatExecutionMessage = (\n parts: Readonly<{\n outputText: string;\n stderr: string;\n execInfo: unknown;\n }>,\n context: Readonly<{\n log: Readonly<Pick<CodeExecutionContext[\"log\"], \"error\">>;\n requestId: string;\n }>\n): string => {\n const lines = [parts.outputText, parts.stderr.trim()];\n const executionError = readExecutionError(parts.execInfo);\n const hasExecutionError = Boolean(executionError);\n if (hasExecutionError) {\n lines.push(\n `Error: ${String(readExecutionErrorField(executionError, \"name\"))}: ${String(readExecutionErrorField(executionError, \"value\"))}`\n );\n context.log.error(\n { error: executionError, requestId: context.requestId },\n \"javascript execution error\"\n );\n }\n return lines\n .filter((line) => line !== \"\")\n .join(\"\\n\")\n .trim();\n};\n\nexport const executeJavaScriptInSandbox = async ({\n sandbox,\n code,\n log,\n requestId,\n}: Readonly<\n Pick<CodeExecutionContext, \"code\" | \"requestId\"> & {\n sandbox: Readonly<Pick<CodeExecutionContext[\"sandbox\"], \"runCommand\">>;\n log: Readonly<Pick<CodeExecutionContext[\"log\"], \"error\">>;\n }\n>): Promise<CodeExecutionResult> => {\n const execResult = await sandbox.runCommand({\n args: [\"--input-type=module\", \"-e\", createWrappedCode(code)],\n cmd: \"node\",\n });\n\n const { outputText, execInfo } = await parseExecutionOutput(execResult);\n const stderr = await execResult.stderr();\n return {\n chart: \"\",\n message: formatExecutionMessage(\n { execInfo, outputText, stderr },\n { log, requestId }\n ),\n };\n};\n",
|
|
14
|
+
"type": "registry:file",
|
|
15
|
+
"target": "~/tools/chatjs/_shared/code-execution/javascript.ts"
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
"path": "src/tools/_shared/code-execution/types.ts",
|
|
19
|
+
"content": "import type { Sandbox } from \"@chat-js/sandboxes/provider\";\nimport type { createModuleLogger } from \"@/lib/logger\";\n\nconst supportedExecutionLanguages = [\"python\", \"javascript\"] as const;\n\ntype SupportedExecutionLanguage = (typeof supportedExecutionLanguages)[number];\n\ninterface CodeExecutionResult {\n chart: string | { base64: string; format: string } | Record<string, unknown>;\n message: string;\n}\n\ntype ExecutionSandbox = Pick<Sandbox, \"runCommand\">;\n\ninterface CodeExecutionContext {\n code: string;\n log: ReturnType<typeof createModuleLogger>;\n requestId: string;\n sandbox: ExecutionSandbox;\n}\nexport { supportedExecutionLanguages };\nexport type {\n ExecutionSandbox,\n CodeExecutionContext,\n CodeExecutionResult,\n SupportedExecutionLanguage,\n};\n",
|
|
20
|
+
"type": "registry:file",
|
|
21
|
+
"target": "~/tools/chatjs/_shared/code-execution/types.ts"
|
|
22
|
+
}
|
|
23
|
+
],
|
|
24
|
+
"type": "registry:item"
|
|
25
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "code-execution-ui",
|
|
4
|
+
"description": "Shared chart renderer for installed code execution tools",
|
|
5
|
+
"dependencies": [
|
|
6
|
+
"echarts@6.0.0",
|
|
7
|
+
"echarts-for-react@^3.0.2",
|
|
8
|
+
"motion@^12.23.24",
|
|
9
|
+
"next-themes@^0.4.6"
|
|
10
|
+
],
|
|
11
|
+
"files": [
|
|
12
|
+
{
|
|
13
|
+
"path": "src/ui/code-execution/code-execution-chart.tsx",
|
|
14
|
+
"content": "\"use client\";\nimport type { BaseChart } from \"./interactive-charts\";\nimport Image from \"next/image\";\nimport InteractiveChart from \"./interactive-charts\";\nimport React from \"react\";\nimport { z } from \"zod\";\n\nconst chartLabels = {\n title: z.string().default(\"\"),\n x_label: z.string().optional(),\n y_label: z.string().optional(),\n};\nconst series = z.array(\n z.object({\n label: z.string(),\n points: z.array(z.tuple([z.union([z.number(), z.string()]), z.number()])),\n })\n);\nconst chartSchema = z.discriminatedUnion(\"type\", [\n z.object({\n ...chartLabels,\n elements: series,\n type: z.literal(\"line\"),\n x_scale: z\n .literal(\"datetime\")\n .nullish()\n .transform((value) => value ?? undefined),\n }),\n z.object({\n ...chartLabels,\n elements: series,\n type: z.literal(\"scatter\"),\n x_scale: z\n .literal(\"datetime\")\n .nullish()\n .transform((value) => value ?? undefined),\n }),\n z.object({\n ...chartLabels,\n elements: z.array(\n z.object({ group: z.string(), label: z.string(), value: z.number() })\n ),\n type: z.literal(\"bar\"),\n }),\n]);\nconst MIN_PNG_BASE64_LENGTH = 1;\nconst pngSchema = z.object({\n base64: z.string().min(MIN_PNG_BASE64_LENGTH),\n format: z.literal(\"png\"),\n});\n\nexport const CodeExecutionChart = ({\n value,\n}: {\n readonly value: unknown;\n}): React.JSX.Element => {\n const parsedChart = chartSchema.safeParse(value);\n const chart: BaseChart | null = parsedChart.success ? parsedChart.data : null;\n const parsedPng = pngSchema.safeParse(value);\n const pngChart = parsedPng.success ? parsedPng.data : null;\n return (\n <>\n {chart && (\n <div className=\"pt-1\">\n <InteractiveChart chart={chart} />\n </div>\n )}\n\n {pngChart && (\n <div className=\"relative aspect-[4/3] w-full\">\n <Image\n alt=\"Chart output\"\n className=\"rounded-lg object-contain\"\n fill\n sizes=\"(max-width: 768px) 100vw, 768px\"\n src={`data:image/png;base64,${pngChart.base64}`}\n unoptimized\n />\n </div>\n )}\n </>\n );\n};\n",
|
|
15
|
+
"type": "registry:file",
|
|
16
|
+
"target": "~/tools/chatjs/_shared/code-execution/code-execution-chart.tsx"
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
"path": "src/ui/code-execution/interactive-charts.tsx",
|
|
20
|
+
"content": "import { Card } from \"@/components/ui/card\";\nimport React from \"react\";\nimport dynamic from \"next/dynamic\";\n\nconst ChartSkeleton = (): React.JSX.Element => (\n <Card className=\"border-border bg-card overflow-hidden\">\n <div className=\"flex h-[400px] items-center justify-center p-6\">\n <div className=\"bg-muted size-8 animate-pulse rounded-md\" />\n </div>\n </Card>\n);\n\nexport type { BaseChart } from \"./interactive-chart-impl\";\nexport default dynamic(\n async () => {\n const { default: InteractiveChart } =\n await import(\"./interactive-chart-impl\");\n return InteractiveChart;\n },\n {\n loading: () => <ChartSkeleton />,\n ssr: false,\n }\n);\n",
|
|
21
|
+
"type": "registry:file",
|
|
22
|
+
"target": "~/tools/chatjs/_shared/code-execution/interactive-charts.tsx"
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
"path": "src/ui/code-execution/interactive-chart-impl.tsx",
|
|
26
|
+
"content": "\"use client\";\nimport type {\n BarSeriesOption,\n EChartsOption,\n LineSeriesOption,\n ScatterSeriesOption,\n} from \"echarts\";\nimport { Card } from \"@/components/ui/card\";\nimport React from \"react\";\nimport ReactECharts from \"echarts-for-react/lib/index\";\nimport { motion } from \"motion/react\";\nimport { useTheme } from \"next-themes\";\n\nconst CHART_COLORS = [\n \"#22c55e\",\n \"#3b82f6\",\n \"#f59e0b\",\n \"#8b5cf6\",\n \"#ec4899\",\n \"#06b6d4\",\n \"#ef4444\",\n \"#84cc16\",\n];\n\ninterface LineScatterElement {\n readonly label: string;\n readonly points: readonly (readonly [number | string, number])[];\n}\n\ninterface BarElement {\n readonly group: string;\n readonly label: string;\n readonly value: number;\n}\n\ninterface BaseChartCommon {\n readonly title: string;\n readonly x_label?: string;\n readonly y_label?: string;\n}\n\ntype LineChart = BaseChartCommon & {\n readonly type: \"line\";\n readonly x_scale?: \"datetime\";\n readonly elements: readonly LineScatterElement[];\n};\n\ntype ScatterChart = BaseChartCommon & {\n readonly type: \"scatter\";\n readonly x_scale?: \"datetime\";\n readonly elements: readonly LineScatterElement[];\n};\n\ntype BarChart = BaseChartCommon & {\n readonly type: \"bar\";\n readonly x_scale?: undefined;\n readonly elements: readonly BarElement[];\n};\n\ntype BaseChart = LineChart | ScatterChart | BarChart;\n\nconst InteractiveChart = ({\n chart,\n}: {\n readonly chart: BaseChart;\n}): React.JSX.Element => {\n const { resolvedTheme } = useTheme();\n const isDark = resolvedTheme === \"dark\";\n const textColor = isDark ? \"#e5e5e5\" : \"#262626\";\n const gridColor = isDark ? \"rgba(255, 255, 255, 0.1)\" : \"rgba(0, 0, 0, 0.15)\";\n const tooltipBg = isDark ? \"#171717\" : \"#ffffff\";\n\n const sharedOptions: EChartsOption = {\n backgroundColor: \"transparent\",\n grid: {\n bottom: 32,\n containLabel: true,\n left: 32,\n right: 32,\n top: 50,\n },\n legend: {\n icon: \"circle\",\n itemGap: 16,\n itemHeight: 8,\n itemWidth: 8,\n textStyle: { color: textColor },\n top: 8,\n },\n tooltip: {\n backgroundColor: tooltipBg,\n borderWidth: 0,\n className: \"echarts-tooltip rounded-lg! border! border-border!\",\n padding: [6, 10],\n textStyle: {\n color: textColor,\n fontFamily: \"system-ui, -apple-system, sans-serif\",\n fontSize: 13,\n },\n trigger: \"axis\",\n },\n };\n\n const getChartOptions = (): EChartsOption => {\n const defaultAxisOptions = {\n axisLabel: {\n color: textColor,\n fontSize: 11,\n hideOverlap: true,\n margin: 8,\n },\n axisLine: { lineStyle: { color: gridColor }, show: true },\n axisTick: { show: false },\n nameTextStyle: {\n color: textColor,\n fontSize: 13,\n padding: [0, 0, 0, 0],\n },\n splitLine: {\n lineStyle: { color: gridColor, type: \"dashed\" },\n show: true,\n },\n } satisfies NonNullable<EChartsOption[\"xAxis\"]>;\n\n if (chart.type === \"line\" || chart.type === \"scatter\") {\n const series = chart.elements.map(\n (element, index): LineSeriesOption | ScatterSeriesOption => ({\n areaStyle:\n chart.type === \"line\"\n ? {\n color: {\n colorStops: [\n {\n color: `${CHART_COLORS[index % CHART_COLORS.length]}15`,\n offset: 0,\n },\n { color: \"rgba(23, 23, 23, 0)\", offset: 1 },\n ],\n type: \"linear\",\n x: 0,\n x2: 0,\n y: 0,\n y2: 1,\n },\n }\n : undefined,\n data: element.points.map(\n (point: readonly [number | string, number]) => {\n const horizontalValue =\n chart.x_scale === \"datetime\"\n ? new Date(point[0]).getTime()\n : point[0];\n return [horizontalValue, point[1]];\n }\n ),\n itemStyle: {\n color: CHART_COLORS[index % CHART_COLORS.length],\n },\n lineStyle: {\n color: CHART_COLORS[index % CHART_COLORS.length],\n width: 2,\n },\n name: element.label,\n smooth: true,\n symbolSize: chart.type === \"scatter\" ? 10 : 0,\n type: chart.type,\n })\n );\n\n return {\n ...sharedOptions,\n series,\n xAxis: {\n name: chart.x_label,\n nameGap: 40,\n nameLocation: \"middle\",\n scale: true,\n type: chart.x_scale === \"datetime\" ? \"time\" : \"value\",\n ...defaultAxisOptions,\n axisLabel: {\n ...defaultAxisOptions.axisLabel,\n formatter:\n chart.x_scale === \"datetime\"\n ? (value: number): string => {\n const date = new Date(value);\n return date.toLocaleDateString(\"en-US\", {\n month: \"short\",\n year: \"numeric\",\n });\n }\n : undefined,\n },\n },\n yAxis: {\n name: chart.y_label,\n nameGap: 50,\n nameLocation: \"middle\",\n position: \"right\",\n scale: true,\n type: \"value\",\n ...defaultAxisOptions,\n },\n };\n }\n\n if (chart.type === \"bar\") {\n const data: Record<string, BarElement[]> = {};\n for (const item of chart.elements) {\n const existingGroup = data[item.group];\n if (existingGroup === undefined) {\n data[item.group] = [];\n }\n data[item.group].push(item);\n }\n\n const series = Object.entries(data).map(\n (\n [group, elements]: readonly [string, readonly BarElement[]],\n index\n ): BarSeriesOption => ({\n data: elements.map((element: Readonly<BarElement>) => [\n element.label,\n element.value,\n ]),\n emphasis: {\n itemStyle: {\n shadowBlur: 10,\n shadowColor: \"rgba(0,0,0,0.3)\",\n },\n },\n itemStyle: {\n color: CHART_COLORS[index % CHART_COLORS.length],\n },\n name: group,\n stack: \"total\",\n type: \"bar\",\n })\n );\n\n return {\n ...sharedOptions,\n series,\n xAxis: {\n name: chart.x_label,\n nameGap: 40,\n nameLocation: \"middle\",\n type: \"category\",\n ...defaultAxisOptions,\n },\n yAxis: {\n name: chart.y_label,\n nameGap: 50,\n nameLocation: \"middle\",\n position: \"right\",\n type: \"value\",\n ...defaultAxisOptions,\n },\n };\n }\n\n return sharedOptions;\n };\n\n return (\n <motion.div\n animate={{ opacity: 1, y: 0 }}\n initial={{ opacity: 0, y: 20 }}\n transition={{ duration: 0.5 }}\n >\n <Card className=\"border-border bg-card overflow-hidden\">\n <div className=\"p-6\">\n {chart.title && (\n <h3 className=\"text-foreground mb-4 text-lg font-medium\">\n {chart.title}\n </h3>\n )}\n <ReactECharts\n notMerge\n option={getChartOptions()}\n style={{ height: \"400px\", width: \"100%\" }}\n theme={resolvedTheme === \"dark\" ? \"dark\" : undefined}\n />\n </div>\n </Card>\n </motion.div>\n );\n};\n\nexport type { BarChart, BaseChart, LineChart, ScatterChart };\nexport default InteractiveChart;\n",
|
|
27
|
+
"type": "registry:file",
|
|
28
|
+
"target": "~/tools/chatjs/_shared/code-execution/interactive-chart-impl.tsx"
|
|
29
|
+
}
|
|
30
|
+
],
|
|
31
|
+
"type": "registry:item"
|
|
32
|
+
}
|