@chat-js/registry 0.2.0-beta.1 → 0.2.0-beta.10
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 +16 -12
- package/dist/r/ai-titles.json +14 -17
- package/dist/r/akamai-storage.json +13 -1
- package/dist/r/alibaba-storage.json +13 -1
- package/dist/r/appwrite-storage.json +8 -1
- package/dist/r/archil-storage.json +8 -1
- package/dist/r/attach-workspace-file.json +82 -0
- package/dist/r/attachment-uploads.json +24 -35
- package/dist/r/azure-storage.json +8 -1
- package/dist/r/backblaze-b2-storage.json +13 -1
- package/dist/r/base/ai-titles.json +14 -17
- package/dist/r/base/akamai-storage.json +13 -1
- package/dist/r/base/alibaba-storage.json +13 -1
- package/dist/r/base/appwrite-storage.json +8 -1
- package/dist/r/base/archil-storage.json +8 -1
- package/dist/r/base/attach-workspace-file.json +82 -0
- package/dist/r/base/attachment-uploads.json +24 -35
- package/dist/r/base/azure-storage.json +8 -1
- package/dist/r/base/backblaze-b2-storage.json +13 -1
- package/dist/r/base/bunny-storage-storage.json +2 -1
- package/dist/r/base/cloudinary-storage.json +2 -1
- package/dist/r/base/credits.json +24 -46
- package/dist/r/base/deep-research.json +55 -141
- package/dist/r/base/default-sandbox.json +35 -0
- package/dist/r/base/desktop.json +129 -0
- package/dist/r/base/digitalocean-spaces-storage.json +13 -1
- package/dist/r/base/docker-sandbox.json +35 -0
- package/dist/r/base/dropbox-storage.json +2 -1
- package/dist/r/base/exoscale-storage.json +13 -1
- package/dist/r/base/feedback.json +31 -53
- package/dist/r/base/filebase-storage.json +8 -1
- package/dist/r/base/firebase-storage-storage.json +2 -1
- package/dist/r/base/followup-suggestions.json +44 -66
- package/dist/r/base/ftp-storage.json +18 -1
- package/dist/r/base/gcs-storage.json +8 -1
- package/dist/r/base/generate-image.json +22 -16
- package/dist/r/base/generate-video.json +16 -10
- package/dist/r/base/google-drive-storage.json +2 -1
- package/dist/r/base/guest-chat.json +166 -0
- package/dist/r/base/hetzner-storage.json +13 -1
- package/dist/r/base/ibm-cos-storage.json +13 -1
- package/dist/r/base/idrive-e2-storage.json +13 -1
- package/dist/r/base/image-viewer.json +49 -0
- package/dist/r/base/just-bash-sandbox.json +32 -0
- package/dist/r/base/litellm-gateway.json +5 -8
- package/dist/r/base/mcp.json +128 -121
- package/dist/r/base/memory-storage.json +5 -3
- package/dist/r/base/minio-storage.json +13 -1
- package/dist/r/base/model-preferences.json +41 -55
- package/dist/r/base/neon-storage.json +8 -1
- package/dist/r/base/netlify-blobs-storage.json +10 -2
- package/dist/r/base/onedrive-storage.json +2 -1
- package/dist/r/base/openai-compatible-gateway.json +5 -8
- package/dist/r/base/openai-gateway.json +5 -8
- package/dist/r/base/openrouter-gateway.json +4 -8
- package/dist/r/base/oracle-cloud-storage.json +18 -1
- package/dist/r/base/ovhcloud-storage.json +13 -1
- package/dist/r/base/pocketbase-storage.json +2 -1
- package/dist/r/base/projects.json +107 -108
- package/dist/r/base/r2-storage.json +9 -1
- package/dist/r/base/registry.json +2340 -2555
- package/dist/r/base/s3-storage.json +15 -1
- package/dist/r/base/scaleway-storage.json +13 -1
- package/dist/r/base/search.json +74 -66
- package/dist/r/base/sftp-storage.json +18 -1
- package/dist/r/base/sharepoint-storage.json +2 -1
- package/dist/r/base/sharing.json +58 -64
- package/dist/r/base/spreadsheet-grid.json +20 -0
- package/dist/r/base/spreadsheet-viewer.json +62 -0
- package/dist/r/base/storj-storage.json +8 -1
- package/dist/r/base/streamdown-math.json +35 -0
- package/dist/r/base/streamdown-mermaid.json +34 -0
- package/dist/r/base/supabase-storage.json +8 -1
- package/dist/r/base/tencent-storage.json +13 -1
- package/dist/r/base/tigris-storage.json +8 -1
- package/dist/r/base/uploadthing-storage.json +2 -1
- package/dist/r/base/vercel-blob-storage.json +3 -1
- package/dist/r/base/vercel-gateway.json +7 -9
- package/dist/r/base/vercel-sandbox.json +8 -26
- package/dist/r/base/video-viewer.json +42 -0
- package/dist/r/base/vultr-storage.json +13 -1
- package/dist/r/base/wasabi-storage.json +13 -1
- package/dist/r/base/webdav-storage.json +13 -1
- package/dist/r/base/yandex-storage.json +8 -1
- package/dist/r/bunny-storage-storage.json +2 -1
- package/dist/r/cloudinary-storage.json +2 -1
- package/dist/r/credits.json +24 -46
- package/dist/r/deep-research.json +55 -141
- package/dist/r/default-sandbox.json +35 -0
- package/dist/r/desktop.json +129 -0
- package/dist/r/digitalocean-spaces-storage.json +13 -1
- package/dist/r/docker-sandbox.json +35 -0
- package/dist/r/dropbox-storage.json +2 -1
- package/dist/r/eve/deep-research.json +47 -0
- package/dist/r/eve/registry.json +53 -0
- package/dist/r/exoscale-storage.json +13 -1
- package/dist/r/feedback.json +31 -53
- package/dist/r/filebase-storage.json +8 -1
- package/dist/r/firebase-storage-storage.json +2 -1
- package/dist/r/followup-suggestions.json +44 -66
- package/dist/r/ftp-storage.json +18 -1
- package/dist/r/gcs-storage.json +8 -1
- package/dist/r/generate-image.json +22 -16
- package/dist/r/generate-video.json +16 -10
- package/dist/r/google-drive-storage.json +2 -1
- package/dist/r/guest-chat.json +166 -0
- package/dist/r/hetzner-storage.json +13 -1
- package/dist/r/ibm-cos-storage.json +13 -1
- package/dist/r/idrive-e2-storage.json +13 -1
- package/dist/r/image-viewer.json +49 -0
- package/dist/r/just-bash-sandbox.json +32 -0
- package/dist/r/litellm-gateway.json +5 -8
- package/dist/r/mcp.json +128 -121
- package/dist/r/memory-storage.json +5 -3
- package/dist/r/minio-storage.json +13 -1
- package/dist/r/model-preferences.json +41 -55
- package/dist/r/neon-storage.json +8 -1
- package/dist/r/netlify-blobs-storage.json +10 -2
- package/dist/r/onedrive-storage.json +2 -1
- package/dist/r/openai-compatible-gateway.json +5 -8
- package/dist/r/openai-gateway.json +5 -8
- package/dist/r/openrouter-gateway.json +4 -8
- package/dist/r/oracle-cloud-storage.json +18 -1
- package/dist/r/ovhcloud-storage.json +13 -1
- package/dist/r/pocketbase-storage.json +2 -1
- package/dist/r/projects.json +107 -108
- package/dist/r/r2-storage.json +9 -1
- package/dist/r/radix/ai-titles.json +14 -17
- package/dist/r/radix/akamai-storage.json +13 -1
- package/dist/r/radix/alibaba-storage.json +13 -1
- package/dist/r/radix/appwrite-storage.json +8 -1
- package/dist/r/radix/archil-storage.json +8 -1
- package/dist/r/radix/attach-workspace-file.json +82 -0
- package/dist/r/radix/attachment-uploads.json +24 -35
- package/dist/r/radix/azure-storage.json +8 -1
- package/dist/r/radix/backblaze-b2-storage.json +13 -1
- package/dist/r/radix/bunny-storage-storage.json +2 -1
- package/dist/r/radix/cloudinary-storage.json +2 -1
- package/dist/r/radix/credits.json +24 -46
- package/dist/r/radix/deep-research.json +55 -141
- package/dist/r/radix/default-sandbox.json +35 -0
- package/dist/r/radix/desktop.json +129 -0
- package/dist/r/radix/digitalocean-spaces-storage.json +13 -1
- package/dist/r/radix/docker-sandbox.json +35 -0
- package/dist/r/radix/dropbox-storage.json +2 -1
- package/dist/r/radix/exoscale-storage.json +13 -1
- package/dist/r/radix/feedback.json +31 -53
- package/dist/r/radix/filebase-storage.json +8 -1
- package/dist/r/radix/firebase-storage-storage.json +2 -1
- package/dist/r/radix/followup-suggestions.json +44 -66
- package/dist/r/radix/ftp-storage.json +18 -1
- package/dist/r/radix/gcs-storage.json +8 -1
- package/dist/r/radix/generate-image.json +22 -16
- package/dist/r/radix/generate-video.json +16 -10
- package/dist/r/radix/google-drive-storage.json +2 -1
- package/dist/r/radix/guest-chat.json +166 -0
- package/dist/r/radix/hetzner-storage.json +13 -1
- package/dist/r/radix/ibm-cos-storage.json +13 -1
- package/dist/r/radix/idrive-e2-storage.json +13 -1
- package/dist/r/radix/image-viewer.json +49 -0
- package/dist/r/radix/just-bash-sandbox.json +32 -0
- package/dist/r/radix/litellm-gateway.json +5 -8
- package/dist/r/radix/mcp.json +128 -121
- package/dist/r/radix/memory-storage.json +5 -3
- package/dist/r/radix/minio-storage.json +13 -1
- package/dist/r/radix/model-preferences.json +41 -55
- package/dist/r/radix/neon-storage.json +8 -1
- package/dist/r/radix/netlify-blobs-storage.json +10 -2
- package/dist/r/radix/onedrive-storage.json +2 -1
- package/dist/r/radix/openai-compatible-gateway.json +5 -8
- package/dist/r/radix/openai-gateway.json +5 -8
- package/dist/r/radix/openrouter-gateway.json +4 -8
- package/dist/r/radix/oracle-cloud-storage.json +18 -1
- package/dist/r/radix/ovhcloud-storage.json +13 -1
- package/dist/r/radix/pocketbase-storage.json +2 -1
- package/dist/r/radix/projects.json +107 -108
- package/dist/r/radix/r2-storage.json +9 -1
- package/dist/r/radix/registry.json +2339 -2554
- package/dist/r/radix/s3-storage.json +15 -1
- package/dist/r/radix/scaleway-storage.json +13 -1
- package/dist/r/radix/search.json +74 -66
- package/dist/r/radix/sftp-storage.json +18 -1
- package/dist/r/radix/sharepoint-storage.json +2 -1
- package/dist/r/radix/sharing.json +58 -64
- package/dist/r/radix/spreadsheet-grid.json +20 -0
- package/dist/r/radix/spreadsheet-viewer.json +62 -0
- package/dist/r/radix/storj-storage.json +8 -1
- package/dist/r/radix/streamdown-math.json +35 -0
- package/dist/r/radix/streamdown-mermaid.json +34 -0
- package/dist/r/radix/supabase-storage.json +8 -1
- package/dist/r/radix/tencent-storage.json +13 -1
- package/dist/r/radix/tigris-storage.json +8 -1
- package/dist/r/radix/uploadthing-storage.json +2 -1
- package/dist/r/radix/vercel-blob-storage.json +3 -1
- package/dist/r/radix/vercel-gateway.json +7 -9
- package/dist/r/radix/vercel-sandbox.json +8 -26
- package/dist/r/radix/video-viewer.json +42 -0
- package/dist/r/radix/vultr-storage.json +13 -1
- package/dist/r/radix/wasabi-storage.json +13 -1
- package/dist/r/radix/webdav-storage.json +13 -1
- package/dist/r/radix/yandex-storage.json +8 -1
- package/dist/r/registry.json +2340 -2555
- package/dist/r/s3-storage.json +15 -1
- package/dist/r/scaleway-storage.json +13 -1
- package/dist/r/search.json +74 -66
- package/dist/r/sftp-storage.json +18 -1
- package/dist/r/sharepoint-storage.json +2 -1
- package/dist/r/sharing.json +58 -64
- package/dist/r/spreadsheet-grid.json +20 -0
- package/dist/r/spreadsheet-viewer.json +62 -0
- package/dist/r/storj-storage.json +8 -1
- package/dist/r/streamdown-math.json +35 -0
- package/dist/r/streamdown-mermaid.json +34 -0
- package/dist/r/supabase-storage.json +8 -1
- package/dist/r/tencent-storage.json +13 -1
- package/dist/r/tigris-storage.json +8 -1
- package/dist/r/uploadthing-storage.json +2 -1
- package/dist/r/vercel-blob-storage.json +3 -1
- package/dist/r/vercel-gateway.json +7 -9
- package/dist/r/vercel-sandbox.json +8 -26
- package/dist/r/video-viewer.json +42 -0
- package/dist/r/vultr-storage.json +13 -1
- package/dist/r/wasabi-storage.json +13 -1
- package/dist/r/webdav-storage.json +13 -1
- package/dist/r/yandex-storage.json +8 -1
- package/package.json +19 -40
- package/dist/r/base/code-documents.json +0 -96
- package/dist/r/base/code-execution-runtime.json +0 -25
- package/dist/r/base/code-execution-ui.json +0 -32
- package/dist/r/base/code-execution.json +0 -69
- package/dist/r/base/daytona-sandbox.json +0 -55
- package/dist/r/base/delete-document.json +0 -58
- package/dist/r/base/firecrawl-search.json +0 -72
- package/dist/r/base/get-weather.json +0 -52
- package/dist/r/base/langfuse.json +0 -63
- package/dist/r/base/read-document.json +0 -34
- package/dist/r/base/retrieve-url.json +0 -69
- package/dist/r/base/saved-code-execution.json +0 -84
- package/dist/r/base/sheet-documents.json +0 -94
- package/dist/r/base/tavily-search.json +0 -72
- package/dist/r/base/text-documents.json +0 -117
- package/dist/r/base/vercel-analytics.json +0 -46
- package/dist/r/base/vercel-speed-insights.json +0 -46
- package/dist/r/base/word-count.json +0 -51
- package/dist/r/code-documents.json +0 -96
- package/dist/r/code-execution-runtime.json +0 -25
- package/dist/r/code-execution-ui.json +0 -32
- package/dist/r/code-execution.json +0 -69
- package/dist/r/daytona-sandbox.json +0 -55
- package/dist/r/delete-document.json +0 -58
- package/dist/r/firecrawl-search.json +0 -72
- package/dist/r/get-weather.json +0 -52
- package/dist/r/langfuse.json +0 -63
- package/dist/r/radix/code-documents.json +0 -96
- package/dist/r/radix/code-execution-runtime.json +0 -25
- package/dist/r/radix/code-execution-ui.json +0 -32
- package/dist/r/radix/code-execution.json +0 -69
- package/dist/r/radix/daytona-sandbox.json +0 -55
- package/dist/r/radix/delete-document.json +0 -58
- package/dist/r/radix/firecrawl-search.json +0 -72
- package/dist/r/radix/get-weather.json +0 -52
- package/dist/r/radix/langfuse.json +0 -63
- package/dist/r/radix/read-document.json +0 -34
- package/dist/r/radix/retrieve-url.json +0 -69
- package/dist/r/radix/saved-code-execution.json +0 -84
- package/dist/r/radix/sheet-documents.json +0 -94
- package/dist/r/radix/tavily-search.json +0 -72
- package/dist/r/radix/text-documents.json +0 -117
- package/dist/r/radix/vercel-analytics.json +0 -46
- package/dist/r/radix/vercel-speed-insights.json +0 -46
- package/dist/r/radix/word-count.json +0 -51
- package/dist/r/read-document.json +0 -34
- package/dist/r/retrieve-url.json +0 -69
- package/dist/r/saved-code-execution.json +0 -84
- package/dist/r/sheet-documents.json +0 -94
- package/dist/r/tavily-search.json +0 -72
- package/dist/r/text-documents.json +0 -117
- package/dist/r/vercel-analytics.json +0 -46
- package/dist/r/vercel-speed-insights.json +0 -46
- package/dist/r/word-count.json +0 -51
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "desktop",
|
|
4
|
+
"description": "Electron authentication, browser handoff and renderer integration",
|
|
5
|
+
"dependencies": [
|
|
6
|
+
"@better-auth/electron@1.6.2",
|
|
7
|
+
"better-auth@1.6.2",
|
|
8
|
+
"lucide-react@0.553.0",
|
|
9
|
+
"sonner@^2.0.7"
|
|
10
|
+
],
|
|
11
|
+
"files": [
|
|
12
|
+
{
|
|
13
|
+
"path": "src/plugins/desktop/src/desktop-auth-client.ts",
|
|
14
|
+
"content": "import {\n ELECTRON_AUTH_CALLBACK_PATH,\n ELECTRON_AUTH_CLIENT_ID,\n ELECTRON_AUTH_COOKIE_PREFIX,\n} from \"./protocol\";\nimport { ELECTRON_APP_SCHEME } from \"./electron-auth\";\nimport { createAuthClient } from \"better-auth/react\";\nimport { electronProxyClient } from \"@better-auth/electron/proxy\";\nimport { lastLoginMethodClient } from \"better-auth/client/plugins\";\n\nconst electronAuthPlugin = electronProxyClient({\n callbackPath: ELECTRON_AUTH_CALLBACK_PATH,\n clientID: ELECTRON_AUTH_CLIENT_ID,\n cookiePrefix: ELECTRON_AUTH_COOKIE_PREFIX,\n protocol: {\n scheme: ELECTRON_APP_SCHEME,\n },\n});\n\n// Better Auth auto-detects the base URL from window.location.origin on client\n// and uses relative URLs for SSR, so we don't need to specify baseURL\nconst authClient = createAuthClient({\n plugins: [lastLoginMethodClient(), electronAuthPlugin],\n});\n\nexport default authClient;\n",
|
|
15
|
+
"type": "registry:file",
|
|
16
|
+
"target": "~/chatjs/plugins/desktop/desktop-auth-client.ts"
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
"path": "src/plugins/desktop/src/auth-form.tsx",
|
|
20
|
+
"content": "\"use client\";\nimport { isElectronRenderer } from \"./bridge\";\nimport { useSyncExternalStore } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { useSearchParams } from \"next/navigation\";\nimport { AuthCardSkeleton } from \"@/components/auth-card-skeleton\";\nimport { AuthFormView } from \"@/components/auth-form-view\";\nimport { SocialAuthProviders } from \"@/components/auth-providers\";\nimport authClient from \"@/lib/auth-client\";\nimport {\n buildSocialAuthRequest,\n isElectronTransferQuery,\n} from \"./electron-auth\";\nimport { ElectronBrowserSignIn, ElectronTransferUser } from \"./auth-ui\";\n\n// Preload capabilities are fixed for the lifetime of the renderer.\nconst subscribe = () => () => {\n /* No subscription to release. */\n};\nconst BrowserTransfer = ({\n mode,\n query,\n}: {\n readonly mode: \"login\" | \"register\";\n readonly query: Readonly<Record<string, string>>;\n}) => {\n const { data: session, isPending } = authClient.useSession();\n if (isPending) {\n return (\n <AuthCardSkeleton\n title=\"Connecting…\"\n description=\"Connecting your desktop app\"\n />\n );\n }\n if (session?.user) {\n return <ElectronTransferUser query={query} session={session} />;\n }\n const request = buildSocialAuthRequest(query, globalThis.location?.origin);\n return (\n <AuthFormView mode={mode} query={query}>\n <SocialAuthProviders {...request} query={query} />\n </AuthFormView>\n );\n};\n\nconst DesktopAuthForm = ({\n mode,\n children,\n}: {\n readonly mode: \"login\" | \"register\";\n readonly children: ReactNode;\n}): ReactNode => {\n const query = Object.fromEntries(useSearchParams().entries());\n const native = useSyncExternalStore(\n subscribe,\n isElectronRenderer,\n () => false\n );\n if (native) {\n return (\n <AuthFormView\n mode={mode}\n query={query}\n title=\"Continue in browser\"\n description=\"Use your browser to sign in or create an account.\"\n footer={\n <div className=\"text-muted-foreground text-center text-sm\">\n New and existing accounts both continue through the browser flow.\n </div>\n }\n >\n <ElectronBrowserSignIn buttonLabel=\"Continue in browser\" />\n </AuthFormView>\n );\n }\n if (isElectronTransferQuery(query)) {\n return <BrowserTransfer mode={mode} query={query} />;\n }\n return children;\n};\n\nexport default DesktopAuthForm;\n",
|
|
21
|
+
"type": "registry:file",
|
|
22
|
+
"target": "~/chatjs/plugins/desktop/auth-form.tsx"
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
"path": "src/plugins/desktop/src/auth-handler.tsx",
|
|
26
|
+
"content": "\"use client\";\nimport type {\n ElectronAuthErrorContext,\n ElectronRendererAuthState,\n} from \"./bridge\";\n\nimport { nonEmptyText } from \"@/components/text-value\";\n\nimport { AlertCircle, LoaderCircle } from \"lucide-react\";\nimport React, { useEffect, useState } from \"react\";\n\nimport type { JSX as ReactJSX } from \"react\";\n\nimport { toast } from \"sonner\";\nimport { Button } from \"@/components/ui/button\";\n\nimport authClient from \"@/chatjs/plugins/desktop/desktop-auth-client\";\n\nimport { useRouter } from \"next/navigation\";\n\nconst ElectronAuthOverlay = ({\n state,\n}: {\n readonly state: Readonly<ElectronRendererAuthState>;\n}): ReactJSX.Element | null => {\n const [, startEventAction] = React.useTransition();\n const [isDismissed, setIsDismissed] = useState(false);\n\n if (state.status === \"idle\" || !state.message) {\n return null;\n }\n\n const isLoading =\n state.status === \"awaiting-browser\" || state.status === \"finishing\";\n const canCancel = state.status === \"awaiting-browser\";\n let detailMessage: string;\n\n if (state.status === \"awaiting-browser\") {\n detailMessage = \"Complete sign-in in your browser, then come back here.\";\n } else if (state.status === \"finishing\") {\n detailMessage =\n \"Your browser has returned to ChatJS. We're finalizing the session now.\";\n } else {\n const { detail } = state;\n detailMessage =\n typeof detail === \"string\" && detail !== \"\"\n ? detail\n : \"If nothing changes, try the browser flow again.\";\n }\n\n if (!isLoading && isDismissed) {\n return null;\n }\n\n return (\n <div className=\"bg-background/90 pointer-events-auto fixed inset-0 z-[999999] flex items-center justify-center px-4 backdrop-blur-sm\">\n <div className=\"bg-background w-full max-w-sm rounded-2xl border p-6 shadow-2xl\">\n <div className=\"flex items-start gap-3\">\n <div className=\"text-muted-foreground mt-0.5\">\n {isLoading ? (\n <LoaderCircle className=\"size-5 animate-spin\" />\n ) : (\n <AlertCircle className=\"size-5 text-amber-600\" />\n )}\n </div>\n <div className=\"space-y-2\">\n <p className=\"font-medium\">{state.message}</p>\n <p className=\"text-muted-foreground text-sm\">{detailMessage}</p>\n {canCancel ? (\n <Button\n className=\"mt-2\"\n\n onClick={() => {\n startEventAction(async () => {\n try {\n await window.electronAPI?.cancelAuthFlow?.();\n } catch (error) {\n console.error(\n \"Failed to cancel Electron auth flow\",\n error\n );\n }\n });\n }}\n size=\"sm\"\n type=\"button\"\n variant=\"outline\"\n >\n Go back\n </Button>\n ) : null}\n {isLoading ? null : (\n <Button\n className=\"mt-2\"\n onClick={() => {\n setIsDismissed(true);\n }}\n size=\"sm\"\n type=\"button\"\n variant=\"outline\"\n >\n Dismiss\n </Button>\n )}\n </div>\n </div>\n </div>\n </div>\n );\n};\n\n/**\n * Handles the electron auth redirect after OAuth completes in the browser.\n * When the user finishes OAuth, `ensureElectronRedirect` detects the\n * electron redirect cookie and sends the user back to the Electron app\n * via deep link.\n *\n * Mount this in the root layout so it runs on every page.\n *\n * @returns {ReactJSX.Element | null} The current overlay, or null outside the enabled desktop flow.\n */\nexport const ElectronAuthHandler = (): ReactJSX.Element | null => {\n const router = useRouter();\n const [authState, setAuthState] = useState<ElectronRendererAuthState>({\n message: null,\n status: \"idle\",\n });\n\n useEffect((): (() => void) | undefined => {\n const id = authClient.ensureElectronRedirect();\n\n return (): void => {\n clearInterval(id);\n };\n }, []);\n\n useEffect((): (() => void) | undefined => {\n if (typeof window.requestAuth !== \"function\") {\n return undefined;\n }\n\n if (\n typeof window.onAuthenticated !== \"function\" ||\n typeof window.onUserUpdated !== \"function\" ||\n typeof window.onAuthError !== \"function\" ||\n typeof window.electronAPI?.onAuthStateChanged !== \"function\"\n ) {\n return undefined;\n }\n\n const loadAuthState = async (): Promise<void> => {\n try {\n const state = await window.electronAPI?.getAuthState?.();\n if (state) {\n setAuthState(state);\n }\n } catch (error) {\n console.error(\"Failed to read Electron auth state\", error);\n }\n };\n void loadAuthState();\n\n const syncAndRefresh = async (): Promise<void> => {\n await window.electronAPI?.syncAuthSession?.();\n router.refresh();\n };\n const syncAuthenticatedSession = async (): Promise<void> => {\n try {\n await syncAndRefresh();\n } catch (error) {\n console.error(\n \"Failed to sync auth session after authentication\",\n error\n );\n }\n };\n const unsubscribeAuthenticated = window.onAuthenticated(() => {\n void syncAuthenticatedSession();\n });\n const syncUpdatedUser = async (): Promise<void> => {\n try {\n await syncAndRefresh();\n } catch (error) {\n console.error(\"Failed to sync auth session after user update\", error);\n }\n };\n const unsubscribeUserUpdated = window.onUserUpdated(() => {\n void syncUpdatedUser();\n });\n const unsubscribeAuthError = window.onAuthError(\n (ctx: Readonly<ElectronAuthErrorContext>) => {\n toast.error(nonEmptyText(ctx.message) ?? \"Authentication failed\");\n }\n );\n const unsubscribeAuthState = window.electronAPI.onAuthStateChanged(\n (state: Readonly<ElectronRendererAuthState>) => {\n setAuthState(state);\n }\n );\n\n return (): void => {\n unsubscribeAuthenticated();\n unsubscribeUserUpdated();\n unsubscribeAuthError();\n unsubscribeAuthState();\n };\n }, [router]);\n\n const overlayKey = `${authState.status}:${authState.message ?? \"\"}:${\n authState.status === \"idle\" ? \"\" : (authState.detail ?? \"\")\n }`;\n\n return <ElectronAuthOverlay key={overlayKey} state={authState} />;\n};\n",
|
|
27
|
+
"type": "registry:file",
|
|
28
|
+
"target": "~/chatjs/plugins/desktop/auth-handler.tsx"
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
"path": "src/plugins/desktop/src/auth-server.ts",
|
|
32
|
+
"content": "import type { AuthenticationIntegration } from \"@/chatjs/core/authentication/contracts\";\nimport {\n ELECTRON_AUTH_CLIENT_ID,\n ELECTRON_AUTH_COOKIE_PREFIX,\n} from \"./protocol\";\nimport { ELECTRON_APP_SCHEME } from \"./electron-auth\";\nimport type { AuthContext } from \"better-auth\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { electron } from \"@better-auth/electron\";\n\nconst plugin = electron({\n clientID: ELECTRON_AUTH_CLIENT_ID,\n cookiePrefix: ELECTRON_AUTH_COOKIE_PREFIX,\n});\n\n// Better Auth matches custom trusted origins by prefix. Electron sends one\n// exact synthetic origin; validate it before the plugin promotes the header.\nconst electronAuthPlugin = {\n ...plugin,\n\n async onRequest(\n request: ReadonlyNativeSurface<Request>,\n\n context: AuthContext\n ): Promise<{ response: Response } | { request: Request } | undefined> {\n const origin = request.headers.get(\"origin\");\n const electronOrigin = request.headers.get(\"electron-origin\");\n const expectedOrigin = `${ELECTRON_APP_SCHEME}:/`;\n if (\n (electronOrigin !== null && electronOrigin !== expectedOrigin) ||\n ((origin ?? \"\").startsWith(`${ELECTRON_APP_SCHEME}:`) &&\n origin !== expectedOrigin)\n ) {\n return {\n response: new Response(\"Invalid Electron origin\", { status: 403 }),\n };\n }\n return await plugin.onRequest(request, context);\n },\n};\n\nconst desktopAuth = {\n plugins: [electronAuthPlugin],\n trustedOrigins: [`${ELECTRON_APP_SCHEME}:/`],\n isAuthRoute: (url) =>\n url.pathname === \"/device-login\" ||\n ((url.pathname === \"/login\" || url.pathname === \"/register\") &&\n url.searchParams.get(\"client_id\") === ELECTRON_AUTH_CLIENT_ID),\n} satisfies AuthenticationIntegration;\nexport { electronAuthPlugin };\n\nexport default desktopAuth;\n",
|
|
33
|
+
"type": "registry:file",
|
|
34
|
+
"target": "~/chatjs/plugins/desktop/auth-server.ts"
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
"path": "src/plugins/desktop/src/auth-ui.tsx",
|
|
38
|
+
"content": "\"use client\";\n\nimport { ExternalLink, LoaderCircle } from \"lucide-react\";\nimport React, {\n useEffect,\n useMemo,\n useRef,\n useState,\n useTransition,\n} from \"react\";\n\nimport type { JSX as ReactJSX } from \"react\";\n\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\n\nimport type { Session } from \"@/lib/auth\";\n\nimport config from \"@/chat.config\";\n\nimport authClient from \"@/chatjs/plugins/desktop/desktop-auth-client\";\n\nimport { Button, buttonVariants } from \"@/components/ui/button\";\n\nimport { useRouter } from \"next/navigation\";\n\nconst AUTH_FEEDBACK_DELAY_MS = 300;\n\nconst ElectronBrowserSignIn = ({\n buttonLabel = \"Continue with browser\",\n}: {\n readonly buttonLabel?: string;\n}): ReactJSX.Element => {\n const [opened, setOpened] = useState(false);\n\n return (\n <div className=\"space-y-3\">\n <p className=\"text-muted-foreground text-center text-sm\">\n Sign-in opens in your browser. On macOS, {config.appName} may ask to use\n Keychain so it can store your session securely.\n </p>\n <Button\n className=\"w-full\"\n onClick={() => {\n const { requestAuth } = window;\n if (typeof requestAuth !== \"function\") {\n return;\n }\n const launchBrowserSignIn = async (): Promise<void> => {\n try {\n await Promise.resolve();\n await requestAuth();\n } catch (error) {\n console.error(\"Failed to launch browser sign-in\", error);\n }\n };\n void launchBrowserSignIn();\n globalThis.setTimeout(() => {\n setOpened(true);\n }, AUTH_FEEDBACK_DELAY_MS);\n }}\n type=\"button\"\n variant=\"outline\"\n >\n <ExternalLink className=\"mr-2 size-4\" />\n {buttonLabel}\n </Button>\n\n {opened ? (\n <p className=\"text-muted-foreground text-center text-sm\">\n Finish signing in through your browser. If macOS asks about Keychain\n access, allow it to keep your session saved securely.\n </p>\n ) : null}\n </div>\n );\n};\n\nconst ElectronTransferUser = ({\n query,\n session,\n}: {\n readonly query: Readonly<Record<string, string>>;\n readonly session: ReadonlyNativeSurface<Session>;\n}): ReactJSX.Element => {\n const [isPending, startTransition] = useTransition();\n const router = useRouter();\n const hasStartedTransferRef = useRef(false);\n const useAnotherAccountHref = useMemo(() => {\n const params = new URLSearchParams(query);\n params.delete(\"client_id\");\n params.delete(\"state\");\n params.delete(\"code_challenge\");\n params.delete(\"code_challenge_method\");\n\n const nextQuery = params.toString();\n if (nextQuery) {\n return `/login?${nextQuery}`;\n }\n return \"/login\";\n }, [query]);\n\n useEffect(() => {\n if (hasStartedTransferRef.current) {\n return;\n }\n hasStartedTransferRef.current = true;\n\n startTransition(async () => {\n await authClient.electron.transferUser({ fetchOptions: { query } });\n router.refresh();\n });\n }, [query, router]);\n\n return (\n <div className=\"space-y-4\">\n <div className=\"rounded-lg border px-4 py-3 text-sm\">\n <p className=\"font-medium\">{session.user.name || session.user.email}</p>\n <p className=\"text-muted-foreground\">{session.user.email}</p>\n </div>\n\n <Button\n className=\"w-full\"\n disabled={isPending}\n onClick={() => {\n startTransition(async () => {\n await authClient.electron.transferUser({ fetchOptions: { query } });\n router.refresh();\n });\n }}\n type=\"button\"\n >\n {isPending ? (\n <>\n <LoaderCircle className=\"mr-2 size-4 animate-spin\" />\n Connecting…\n </>\n ) : (\n \"Continue to desktop app\"\n )}\n </Button>\n\n <a\n className={buttonVariants({ className: \"w-full\", variant: \"ghost\" })}\n href={useAnotherAccountHref}\n >\n Use another account\n </a>\n </div>\n );\n};\nexport { ElectronBrowserSignIn, ElectronTransferUser };\n",
|
|
39
|
+
"type": "registry:file",
|
|
40
|
+
"target": "~/chatjs/plugins/desktop/auth-ui.tsx"
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
"path": "src/plugins/desktop/src/bridge.ts",
|
|
44
|
+
"content": "// Types exposed by the Electron companion preload bridge.\nexport interface ElectronAuthErrorContext {\n message?: string;\n path?: string;\n status?: number;\n statusText?: string;\n}\n\nexport type ElectronRendererAuthState =\n | {\n status: \"idle\";\n message: null;\n }\n | {\n status: \"awaiting-browser\" | \"finishing\" | \"timed-out\" | \"error\";\n message: string;\n detail?: string | null;\n };\n\ndeclare global {\n interface Window {\n electronAPI?: {\n cancelAuthFlow?: () => Promise<void>;\n getAuthState?: () => Promise<ElectronRendererAuthState>;\n isElectron: boolean;\n onAuthStateChanged?: (\n callback: (state: Readonly<ElectronRendererAuthState>) => void\n ) => () => void;\n platform: string;\n syncAuthSession?: () => Promise<void>;\n };\n onAuthError?: (\n callback: (context: Readonly<ElectronAuthErrorContext>) => void\n ) => () => void;\n onAuthenticated?: (callback: (user: unknown) => void) => () => void;\n onUserUpdated?: (callback: (user: unknown) => void) => () => void;\n requestAuth?: (options?: {\n readonly provider?: string;\n }) => Promise<void> | void;\n signOut?: () => Promise<void>;\n }\n}\n\nexport const isElectronRenderer = (): boolean =>\n typeof window !== \"undefined\" && typeof window.requestAuth === \"function\";\n",
|
|
45
|
+
"type": "registry:file",
|
|
46
|
+
"target": "~/chatjs/plugins/desktop/bridge.ts"
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
"path": "src/plugins/desktop/src/layout-ui.ts",
|
|
50
|
+
"content": "\"use client\";\nimport { definePlugin, slot } from \"@/chatjs/core/ui/slots\";\nimport { LayoutEffects } from \"@/components/layout-slots\";\nimport { ElectronAuthHandler } from \"./auth-handler\";\n\nexport const layoutUi = definePlugin({\n id: \"desktop\",\n slots: [slot(LayoutEffects, ElectronAuthHandler)],\n});\n",
|
|
51
|
+
"type": "registry:file",
|
|
52
|
+
"target": "~/chatjs/plugins/desktop/layout-ui.ts"
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
"path": "src/plugins/desktop/src/navigation.ts",
|
|
56
|
+
"content": "import { isElectronRenderer } from \"./bridge\";\n\nconst desktopNavigation = (): boolean => isElectronRenderer();\n\nexport default desktopNavigation;\n",
|
|
57
|
+
"type": "registry:file",
|
|
58
|
+
"target": "~/chatjs/plugins/desktop/navigation.ts"
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
"path": "src/plugins/desktop/src/protocol.ts",
|
|
62
|
+
"content": "export const ELECTRON_AUTH_CLIENT_ID = \"electron\";\n\nexport const ELECTRON_AUTH_COOKIE_PREFIX = \"better-auth\";\n\nexport const ELECTRON_AUTH_CALLBACK_PATH = \"/auth/callback\";\n",
|
|
63
|
+
"type": "registry:file",
|
|
64
|
+
"target": "~/chatjs/plugins/desktop/protocol.ts"
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
"path": "src/plugins/desktop/src/device-login-page.tsx",
|
|
68
|
+
"content": "\"use client\";\n\nimport { CheckCircle2, LoaderCircle } from \"lucide-react\";\nimport React, { useEffect, useMemo, useRef, useState } from \"react\";\n\nimport { usePathname, useSearchParams } from \"next/navigation\";\n\nimport Link from \"next/link\";\n\nimport { Button, buttonVariants } from \"@/components/ui/button\";\n\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"@/components/ui/card\";\n\nimport type { JSX as ReactJSX } from \"react\";\n\nimport authClient from \"@/chatjs/plugins/desktop/desktop-auth-client\";\nimport { config } from \"@/lib/config\";\nimport { isElectronTransferQuery } from \"@/chatjs/plugins/desktop/electron-auth\";\n\ntype DeviceLoginState = \"checking-session\" | \"transferring\" | \"waiting-for-app\";\n\nconst DEVICE_LOGIN_COMPLETED_PARAM = \"done\";\n\nconst DeviceAuthScreen = ({\n state,\n onRetry,\n}: {\n readonly state: \"checking-session\" | \"transferring\" | \"waiting-for-app\";\n readonly onRetry: () => void;\n}): React.JSX.Element => {\n const isLoading = state === \"checking-session\" || state === \"transferring\";\n let title = \"You're signed in\";\n\n if (isLoading) {\n title =\n state === \"checking-session\"\n ? \"Checking your session...\"\n : \"Opening the desktop app...\";\n }\n\n return (\n <div className=\"bg-background flex min-h-dvh w-screen items-center justify-center\">\n <div className=\"w-full max-w-sm px-6\">\n <Card>\n <CardHeader className=\"text-center\">\n <div className=\"mb-2 flex justify-center\">\n {isLoading ? (\n <LoaderCircle className=\"text-muted-foreground size-8 animate-spin\" />\n ) : (\n <div className=\"bg-foreground text-background inline-flex h-14 w-14 items-center justify-center rounded-2xl\">\n <CheckCircle2 className=\"size-7\" />\n </div>\n )}\n </div>\n <CardTitle className=\"text-xl\">{title}</CardTitle>\n {!isLoading && (\n <CardDescription>\n You can close this tab and return to {config.appName}.\n </CardDescription>\n )}\n </CardHeader>\n {!isLoading && (\n <CardContent className=\"text-center\">\n <div className=\"mb-4\">\n <Link\n className={buttonVariants({\n className: \"w-full\",\n variant: \"outline\",\n })}\n href=\"/\"\n >\n Continue on web\n </Link>\n </div>\n <p className=\"text-muted-foreground/60 text-xs\">\n Didn't open?{\" \"}\n <Button\n className=\"text-muted-foreground/60 hover:text-muted-foreground h-auto p-0 text-xs underline underline-offset-2 hover:no-underline\"\n onClick={onRetry}\n type=\"button\"\n variant=\"link\"\n >\n Try again\n </Button>\n </p>\n </CardContent>\n )}\n </Card>\n </div>\n </div>\n );\n};\n\nexport const DeviceLoginPage = (): ReactJSX.Element => {\n const pathname = usePathname();\n const searchParams = useSearchParams();\n const [state, setState] = useState<DeviceLoginState>(\"checking-session\");\n const transferStartedRef = useRef(false);\n\n const query = useMemo(\n () => Object.fromEntries(searchParams.entries()),\n [searchParams]\n );\n const isCompletedView =\n searchParams.get(DEVICE_LOGIN_COMPLETED_PARAM) === \"1\";\n const shouldWaitForApp = isCompletedView || !isElectronTransferQuery(query);\n const displayState =\n shouldWaitForApp && state === \"checking-session\"\n ? \"waiting-for-app\"\n : state;\n\n useEffect((): (() => void) | undefined => {\n if (shouldWaitForApp) {\n return undefined;\n }\n\n let cancelled = false;\n\n const checkSession = async (): Promise<void> => {\n const { data: session } = await authClient.getSession();\n\n if (cancelled || transferStartedRef.current) {\n return;\n }\n\n if (!session?.user) {\n setState(\"waiting-for-app\");\n return;\n }\n\n transferStartedRef.current = true;\n setState(\"transferring\");\n\n await authClient.electron.transferUser({\n fetchOptions: {\n onError: () => {\n transferStartedRef.current = false;\n setState(\"waiting-for-app\");\n },\n onSuccess: () => {\n globalThis.history.replaceState(\n {},\n \"\",\n `${pathname}?${DEVICE_LOGIN_COMPLETED_PARAM}=1`\n );\n setState(\"waiting-for-app\");\n },\n query,\n },\n });\n };\n const sessionCheck = checkSession();\n void (async (): Promise<void> => {\n try {\n await sessionCheck;\n } catch {\n if (cancelled) {\n return;\n }\n\n transferStartedRef.current = false;\n setState(\"waiting-for-app\");\n }\n })();\n\n return (): void => {\n cancelled = true;\n };\n }, [pathname, query, shouldWaitForApp]);\n\n return (\n <DeviceAuthScreen\n onRetry={() => {\n transferStartedRef.current = false;\n setState(\"transferring\");\n const transfer = authClient.electron.transferUser({\n fetchOptions: {\n onError: () => {\n transferStartedRef.current = false;\n setState(\"waiting-for-app\");\n },\n onSuccess: () => {\n globalThis.history.replaceState(\n {},\n \"\",\n `${pathname}?${DEVICE_LOGIN_COMPLETED_PARAM}=1`\n );\n setState(\"waiting-for-app\");\n },\n query,\n },\n });\n void (async (): Promise<void> => {\n try {\n await transfer;\n } catch {\n transferStartedRef.current = false;\n setState(\"waiting-for-app\");\n }\n })();\n }}\n state={displayState}\n />\n );\n};\n",
|
|
69
|
+
"type": "registry:file",
|
|
70
|
+
"target": "~/chatjs/plugins/desktop/device-login-page.tsx"
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
"path": "src/plugins/desktop/src/device-login-route.tsx",
|
|
74
|
+
"content": "import type { Metadata } from \"next\";\nimport { headers } from \"next/headers\";\nimport { redirect } from \"next/navigation\";\nimport React, { Suspense } from \"react\";\n\nimport { AuthCardSkeleton } from \"@/components/auth-card-skeleton\";\nimport { DeviceLoginPage } from \"@/chatjs/plugins/desktop/device-login-page\";\nimport { auth } from \"@/lib/auth\";\nimport { toSearchParamRecord } from \"@/chatjs/plugins/desktop/electron-auth\";\n\nconst metadata: Metadata = {\n description: \"Sign in for the desktop app\",\n title: \"Device Login\",\n};\n\nconst DeviceLoginFallback = (): React.JSX.Element => (\n <div className=\"container mx-auto flex h-dvh w-screen items-center justify-center px-4\">\n <AuthCardSkeleton\n cardClassName=\"w-full max-w-md\"\n description=\"Connecting your desktop app\"\n title=\"Device login\"\n variant=\"device\"\n />\n </div>\n);\n\nconst DeviceLoginContent = async ({\n searchParams,\n}: {\n readonly searchParams: Readonly<\n Promise<Readonly<Record<string, string | readonly string[] | undefined>>>\n >;\n}): Promise<React.JSX.Element> => {\n const resolvedSearchParams = await searchParams;\n const query = toSearchParamRecord(resolvedSearchParams);\n const isCompletedView = query.done === \"1\";\n const queryString = new URLSearchParams(query).toString();\n const currentHref = queryString\n ? `/device-login?${queryString}`\n : \"/device-login\";\n const session = await auth.api.getSession({ headers: await headers() });\n\n if (!(session?.user || isCompletedView)) {\n redirect(`/login?returnTo=${encodeURIComponent(currentHref)}`);\n }\n\n return (\n <Suspense fallback={<DeviceLoginFallback />}>\n <DeviceLoginPage />\n </Suspense>\n );\n};\n\nconst DeviceLoginRoute = ({\n searchParams,\n}: {\n readonly searchParams: Readonly<\n Promise<Readonly<Record<string, string | readonly string[] | undefined>>>\n >;\n}): React.JSX.Element => (\n <Suspense fallback={<DeviceLoginFallback />}>\n <DeviceLoginContent searchParams={searchParams} />\n </Suspense>\n);\n\nexport { metadata };\nexport default DeviceLoginRoute;\n",
|
|
75
|
+
"type": "registry:file",
|
|
76
|
+
"target": "~/chatjs/plugins/desktop/device-login-route.tsx"
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
"path": "src/plugins/desktop/src/electron-auth.ts",
|
|
80
|
+
"content": "import type { SocialAuthSignInOptions } from \"@/lib/social-auth\";\nimport { config } from \"@/lib/config\";\n\nimport { ELECTRON_AUTH_CLIENT_ID } from \"./protocol\";\n\nconst ELECTRON_APP_SCHEME = config.appPrefix;\n\n// @better-auth/electron sends this synthetic Origin for the current protocol.\nconst ELECTRON_TRUSTED_ORIGINS = [`${ELECTRON_APP_SCHEME}:/`] as const;\n\ntype SearchParamValue = string | readonly string[] | undefined;\n\nconst toSearchParamRecord = (\n searchParams: Readonly<Record<string, SearchParamValue>>\n): Record<string, string> => {\n const query: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(searchParams)) {\n if (typeof value === \"string\") {\n query[key] = value;\n } else if (typeof value === \"object\") {\n const [firstValue] = value;\n if (typeof firstValue === \"string\" && firstValue !== \"\") {\n query[key] = firstValue;\n }\n }\n }\n\n return query;\n};\n\nconst isElectronTransferQuery = (\n query: Readonly<Record<string, string>>\n): boolean => query.client_id === ELECTRON_AUTH_CLIENT_ID;\n\nconst buildSocialAuthRequest = (\n query: Readonly<Record<string, string>>,\n origin?: string\n): {\n callbackURL?: string;\n onRedirectToUrl?: (url: string) => void;\n signInOptions?: SocialAuthSignInOptions;\n} => {\n const isElectronTransfer = isElectronTransferQuery(query);\n const deviceLoginCallbackURL =\n typeof origin === \"string\" && origin !== \"\"\n ? new URL(\"/device-login\", origin).toString()\n : \"/device-login\";\n\n if (isElectronTransfer) {\n return {\n callbackURL: deviceLoginCallbackURL,\n onRedirectToUrl: (url: string): void => {\n const { location } = globalThis;\n if (typeof location === \"object\" && location !== null) {\n location.assign(url);\n }\n },\n signInOptions: {\n disableRedirect: true,\n errorCallbackURL: deviceLoginCallbackURL,\n newUserCallbackURL: deviceLoginCallbackURL,\n },\n };\n }\n\n return {\n callbackURL: query.returnTo,\n };\n};\n\nexport {\n ELECTRON_APP_SCHEME,\n ELECTRON_TRUSTED_ORIGINS,\n toSearchParamRecord,\n isElectronTransferQuery,\n buildSocialAuthRequest,\n};\n",
|
|
81
|
+
"type": "registry:file",
|
|
82
|
+
"target": "~/chatjs/plugins/desktop/electron-auth.ts"
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
"path": "src/plugins/desktop/src/sign-out.ts",
|
|
86
|
+
"content": "import { isElectronRenderer } from \"./bridge\";\n\nconst signOutDesktop = async (): Promise<boolean> => {\n if (!isElectronRenderer()) {\n return false;\n }\n if (typeof window.signOut !== \"function\") {\n throw new TypeError(\"Desktop sign-out is unavailable.\");\n }\n await window.signOut();\n try {\n await window.electronAPI?.syncAuthSession?.();\n } catch (error) {\n // A refresh failure cannot undo a completed native sign-out.\n console.error(\"Failed to refresh the signed-out desktop session\", error);\n }\n return true;\n};\n\nexport default signOutDesktop;\n",
|
|
87
|
+
"type": "registry:file",
|
|
88
|
+
"target": "~/chatjs/plugins/desktop/sign-out.ts"
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
"path": "src/plugins/desktop/adapters/app/(auth)/device-login/page.tsx",
|
|
92
|
+
"content": "// ChatJS source: desktop. Ownership: chatjs/plugins/desktop/plugin.json.\nexport { default, metadata } from \"@/chatjs/plugins/desktop/device-login-route\";\n",
|
|
93
|
+
"type": "registry:file",
|
|
94
|
+
"target": "~/app/(auth)/device-login/page.tsx"
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
"path": "dist/source/desktop.json",
|
|
98
|
+
"content": "{\n \"contractVersion\": 3,\n \"uiBase\": \"base\",\n \"id\": \"desktop\",\n \"kind\": \"plugin\",\n \"files\": [\n \"chatjs/plugins/desktop/desktop-auth-client.ts\",\n \"chatjs/plugins/desktop/auth-form.tsx\",\n \"chatjs/plugins/desktop/auth-handler.tsx\",\n \"chatjs/plugins/desktop/auth-server.ts\",\n \"chatjs/plugins/desktop/auth-ui.tsx\",\n \"chatjs/plugins/desktop/bridge.ts\",\n \"chatjs/plugins/desktop/layout-ui.ts\",\n \"chatjs/plugins/desktop/navigation.ts\",\n \"chatjs/plugins/desktop/protocol.ts\",\n \"chatjs/plugins/desktop/device-login-page.tsx\",\n \"chatjs/plugins/desktop/device-login-route.tsx\",\n \"chatjs/plugins/desktop/electron-auth.ts\",\n \"chatjs/plugins/desktop/sign-out.ts\",\n \"app/(auth)/device-login/page.tsx\"\n ]\n}\n",
|
|
99
|
+
"type": "registry:file",
|
|
100
|
+
"target": "~/chatjs/plugins/desktop/plugin.json"
|
|
101
|
+
}
|
|
102
|
+
],
|
|
103
|
+
"meta": {
|
|
104
|
+
"icon": "setup/electron",
|
|
105
|
+
"chatjs": {
|
|
106
|
+
"contractVersion": 3,
|
|
107
|
+
"uiBase": "base",
|
|
108
|
+
"id": "desktop",
|
|
109
|
+
"kind": "plugin",
|
|
110
|
+
"files": [
|
|
111
|
+
"chatjs/plugins/desktop/desktop-auth-client.ts",
|
|
112
|
+
"chatjs/plugins/desktop/auth-form.tsx",
|
|
113
|
+
"chatjs/plugins/desktop/auth-handler.tsx",
|
|
114
|
+
"chatjs/plugins/desktop/auth-server.ts",
|
|
115
|
+
"chatjs/plugins/desktop/auth-ui.tsx",
|
|
116
|
+
"chatjs/plugins/desktop/bridge.ts",
|
|
117
|
+
"chatjs/plugins/desktop/layout-ui.ts",
|
|
118
|
+
"chatjs/plugins/desktop/navigation.ts",
|
|
119
|
+
"chatjs/plugins/desktop/protocol.ts",
|
|
120
|
+
"chatjs/plugins/desktop/device-login-page.tsx",
|
|
121
|
+
"chatjs/plugins/desktop/device-login-route.tsx",
|
|
122
|
+
"chatjs/plugins/desktop/electron-auth.ts",
|
|
123
|
+
"chatjs/plugins/desktop/sign-out.ts",
|
|
124
|
+
"app/(auth)/device-login/page.tsx"
|
|
125
|
+
]
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
"type": "registry:item"
|
|
129
|
+
}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"path": "src/storage/digitalocean-spaces/storage-provider.ts",
|
|
15
15
|
"content": "export { digitaloceanSpaces as createStorageAdapter } from \"files-sdk/digitalocean-spaces\";\n",
|
|
16
16
|
"type": "registry:file",
|
|
17
|
-
"target": "~/
|
|
17
|
+
"target": "~/chatjs/providers/storage.ts"
|
|
18
18
|
}
|
|
19
19
|
],
|
|
20
20
|
"meta": {
|
|
@@ -23,6 +23,18 @@
|
|
|
23
23
|
"bucket",
|
|
24
24
|
"region"
|
|
25
25
|
],
|
|
26
|
+
"configFields": [
|
|
27
|
+
{
|
|
28
|
+
"key": "bucket",
|
|
29
|
+
"label": "bucket",
|
|
30
|
+
"type": "text"
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
"key": "region",
|
|
34
|
+
"label": "region",
|
|
35
|
+
"type": "text"
|
|
36
|
+
}
|
|
37
|
+
],
|
|
26
38
|
"contractVersion": 1,
|
|
27
39
|
"envRequirements": [
|
|
28
40
|
{
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "docker-sandbox",
|
|
4
|
+
"title": "Docker",
|
|
5
|
+
"description": "Containers on a reachable Docker host, with native Python and Node processes.",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"eve@npm:@chat-js/eve@1.1.1-chatjs.0"
|
|
8
|
+
],
|
|
9
|
+
"files": [
|
|
10
|
+
{
|
|
11
|
+
"path": "src/sandboxes/docker/sandbox.ts",
|
|
12
|
+
"content": "import { defineSandbox } from \"eve/sandbox\";\nimport { DockerSandbox } from \"eve/sandbox/docker\";\n\nexport const environment = DockerSandbox.environment();\nexport default defineSandbox(async () => await environment.open());\n",
|
|
13
|
+
"type": "registry:file",
|
|
14
|
+
"target": "~/agent/sandbox.ts"
|
|
15
|
+
}
|
|
16
|
+
],
|
|
17
|
+
"meta": {
|
|
18
|
+
"chatjs": {
|
|
19
|
+
"contractVersion": 1,
|
|
20
|
+
"kind": "sandbox",
|
|
21
|
+
"id": "docker",
|
|
22
|
+
"capabilities": {
|
|
23
|
+
"persistent": true,
|
|
24
|
+
"runtimes": [
|
|
25
|
+
"python",
|
|
26
|
+
"javascript"
|
|
27
|
+
],
|
|
28
|
+
"cleanup": "eve-session",
|
|
29
|
+
"cancellation": "eve"
|
|
30
|
+
},
|
|
31
|
+
"envRequirements": []
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"type": "registry:item"
|
|
35
|
+
}
|
|
@@ -12,12 +12,13 @@
|
|
|
12
12
|
"path": "src/storage/dropbox/storage-provider.ts",
|
|
13
13
|
"content": "export { dropbox as createStorageAdapter } from \"files-sdk/dropbox\";\n",
|
|
14
14
|
"type": "registry:file",
|
|
15
|
-
"target": "~/
|
|
15
|
+
"target": "~/chatjs/providers/storage.ts"
|
|
16
16
|
}
|
|
17
17
|
],
|
|
18
18
|
"meta": {
|
|
19
19
|
"chatjs": {
|
|
20
20
|
"configKeys": [],
|
|
21
|
+
"configFields": [],
|
|
21
22
|
"contractVersion": 1,
|
|
22
23
|
"envRequirements": [
|
|
23
24
|
{
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "deep-research",
|
|
3
|
+
"description": "Research with installed EVE capabilities; produces a sandbox report. ChatJS adds optional progress UI.",
|
|
4
|
+
"dependencies": [
|
|
5
|
+
"eve@npm:@chat-js/eve@1.1.1-chatjs.0",
|
|
6
|
+
"zod@4.5.4"
|
|
7
|
+
],
|
|
8
|
+
"files": [
|
|
9
|
+
{
|
|
10
|
+
"path": "src/tools/deep-research/agent/tools/deep-research.ts",
|
|
11
|
+
"content": "// ChatJS source: deep-research. Ownership: chatjs/tools/deep-research/chatjs.json.\nimport { defineWorkflowTool, toolOutput } from \"eve/tools\";\nimport {\n clarifyWithUserInstructions,\n compressResearchSimpleHumanMessage,\n compressResearchSystemPrompt,\n finalReportGenerationPrompt,\n leadResearcherPrompt,\n researchSystemPrompt,\n transformMessagesIntoResearchTopicPrompt,\n} from \"../lib/research/prompts\";\nimport { prepareResearch, researchCompletedAt } from \"../lib/research/steps\";\nimport {\n researchBrief,\n researchInput,\n researchClarification,\n researchDecision,\n researchFindings,\n researchReport,\n researchResult,\n} from \"../lib/research/schemas\";\nimport type { ResearchUpdate } from \"../lib/research/schemas\";\nimport type { AgentSession, WorkflowToolContext } from \"eve/tools\";\nimport { z } from \"zod\";\n\nimport {\n readResearchFiles,\n writeResearchFile,\n} from \"../lib/research/workspace\";\n\ntype ResearchResult = ReturnType<typeof researchResult>;\n\ntype ResearchWorkflowContext = Readonly<\n Omit<WorkflowToolContext, \"abortSignal\"> & {\n abortSignal: Readonly<AbortSignal>;\n }\n>;\n\nconst structuredMessage = (message: string): string =>\n `${message}\\n\\nDeliver the requested fields through the eve__reply tool. Put any Markdown inside its string fields; do not return prose or JSON text instead of calling the tool.`;\n\nconst outputSchema = (schema: z.ZodType): Record<string, z.JSONType> =>\n z.record(z.string(), z.json()).parse(z.toJSONSchema(schema));\n\nconst researchReply = async (\n agent: Readonly<AgentSession>,\n options: Readonly<{\n message: string;\n outputSchema: Record<string, z.JSONType>;\n signal: AbortSignal;\n }>\n): Promise<unknown> => {\n options.signal.throwIfAborted();\n const response = await agent.send(options.message, {\n outputSchema: options.outputSchema,\n signal: options.signal,\n });\n const result = await response.result();\n options.signal.throwIfAborted();\n if (result.status === \"failed\") {\n throw new Error(result.error?.message ?? \"Research agent failed\");\n }\n if (result.data === undefined) {\n throw new Error(\"Research agent ended without structured output\");\n }\n return result.data;\n};\n\nconst INITIAL_RESEARCH_ROUND = 0;\nconst RESEARCH_ROUND_INCREMENT = 1;\nconst BRIEF_UPDATE_INDEX = 1;\nconst EMPTY_TOPIC_COUNT = 0;\n\nexport default defineWorkflowTool({\n availableInSubagents: false,\n description:\n \"Conduct deep research using installed EVE capabilities and sandbox files. Supply the full task and relevant conversation context in request. Use only for explicit deep research requests, once per turn. Returns a Markdown report path in the shared sandbox. After completion, deliver the file using attach_workspace_file when installed or your channel's native file delivery. If no delivery mechanism exists, explain where the file is and do not invent a download URL. If clarification is needed, ask the returned questions. If research fails, report the error instead of starting duplicate research.\",\n async *execute(\n input: Readonly<z.infer<typeof researchInput>>,\n context: ResearchWorkflowContext\n ): AsyncGenerator<ResearchResult, void> {\n \"use workflow\";\n const { config, date, messages, timestamp } = await prepareResearch(\n input.request\n );\n const updates: ResearchUpdate[] = [];\n const progress = (): ResearchResult =>\n researchResult({ format: \"progress\" }, updates);\n if (config.allow_clarification) {\n const clarification = researchClarification.parse(\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n clarifyWithUserInstructions({ date, messages })\n ),\n outputSchema: outputSchema(researchClarification),\n })\n );\n if (clarification.need_clarification) {\n yield researchResult({\n answer: clarification.question,\n format: \"clarifying_questions\",\n });\n return;\n }\n }\n updates.push(\n {\n timestamp,\n title: \"Starting research\",\n toolCallId: context.callId,\n type: \"started\",\n },\n {\n status: \"running\",\n title: \"Writing research brief\",\n toolCallId: context.callId,\n type: \"writing\",\n }\n );\n yield progress();\n const brief = researchBrief.parse(\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n transformMessagesIntoResearchTopicPrompt({ date, messages })\n ),\n outputSchema: outputSchema(researchBrief),\n })\n );\n await writeResearchFile(context, \"brief.md\", brief.research_brief);\n updates[BRIEF_UPDATE_INDEX] = {\n message: brief.research_brief,\n status: \"completed\",\n title: \"Writing research brief\",\n toolCallId: context.callId,\n type: \"writing\",\n };\n yield progress();\n\n const noteFiles: string[] = [];\n const decisionSchema = researchDecision.extend({\n topics: researchDecision.shape.topics.max(\n config.max_concurrent_research_units\n ),\n });\n // Preserve the SDK's max_researcher_iterations + 1 decision steps, including\n // its allowance for research on the final step if the supervisor has not finished.\n for (\n let round = INITIAL_RESEARCH_ROUND;\n round <= config.max_researcher_iterations;\n round += RESEARCH_ROUND_INCREMENT\n ) {\n context.abortSignal.throwIfAborted();\n // oxlint-disable-next-line no-await-in-loop -- Each decision reads the notes completed by preceding research rounds.\n const findings = await readResearchFiles(context, [\n \"brief.md\",\n ...noteFiles,\n ]);\n const decision = decisionSchema.parse(\n // oxlint-disable-next-line no-await-in-loop -- Each decision consumes the findings added by the preceding round.\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n `${leadResearcherPrompt({ date, max_concurrent_research_units: config.max_concurrent_research_units })}\\n\\nResearch brief: ${findings[0]}\\n\\nFindings so far:\\n${findings.slice(1).join(\"\\n\\n\")}\\n\\nDecision round ${round + RESEARCH_ROUND_INCREMENT} of ${config.max_researcher_iterations + RESEARCH_ROUND_INCREMENT}. Return your next decision.`\n ),\n outputSchema: outputSchema(decisionSchema),\n })\n );\n if (decision.complete) {\n break;\n }\n if (decision.topics.length === EMPTY_TOPIC_COUNT) {\n throw new Error(\n \"The research supervisor must select topics or finish.\"\n );\n }\n for (const topic of decision.topics) {\n context.abortSignal.throwIfAborted();\n const updateIndex = updates.length;\n updates.push({\n message: topic,\n status: \"running\",\n title: \"Researching topic\",\n toolCallId: context.callId,\n type: \"thoughts\",\n });\n yield progress();\n const raw = researchFindings.parse(\n // oxlint-disable-next-line no-await-in-loop -- Complete the topic before moving to the next research stage.\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n `${researchSystemPrompt({ date, max_search_queries: config.search_api_max_queries, mcp_prompt: \"Use eve__search to discover installed search/retrieval connections and eve__tool to call them. Use native read_file or bash for relevant sandbox files. Do not call deepResearch recursively. If current external evidence is needed but no search capability is installed, say so explicitly; never fabricate sources.\" })}\\n\\nResearch brief:\\n${findings[0]}\\n\\nTopic:\\n${topic}\\n\\nReturn comprehensive raw findings with source URLs, citations, uncertainties, and conflicting evidence.`\n ),\n outputSchema: outputSchema(researchFindings),\n })\n );\n const topicNumber = noteFiles.length + 1;\n const sourceFile = `topic-${topicNumber}-sources.md`;\n // oxlint-disable-next-line no-await-in-loop -- Preserve cited source findings before compression.\n await writeResearchFile(\n context,\n sourceFile,\n `# ${topic}\\n\\n${raw.findings}`\n );\n // oxlint-disable-next-line no-await-in-loop -- Compression consumes the saved source file.\n const [sources] = await readResearchFiles(context, [sourceFile]);\n const compressed = researchFindings.parse(\n // oxlint-disable-next-line no-await-in-loop -- Commit this topic's compressed notes before the next topic and supervisor decision.\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n `${compressResearchSystemPrompt({ date })}\\n\\n${sources}\\n\\n${compressResearchSimpleHumanMessage}`\n ),\n outputSchema: outputSchema(researchFindings),\n })\n );\n const noteFile = `topic-${topicNumber}-notes.md`;\n // oxlint-disable-next-line no-await-in-loop -- Commit notes before advancing the supervisor.\n await writeResearchFile(\n context,\n noteFile,\n `# ${topic}\\n\\n${compressed.findings}`\n );\n noteFiles.push(noteFile);\n updates[updateIndex] = {\n message: topic,\n status: \"completed\",\n title: \"Research topic completed\",\n toolCallId: context.callId,\n type: \"thoughts\",\n };\n yield progress();\n }\n }\n const reportUpdateIndex = updates.length;\n updates.push({\n status: \"running\",\n title: \"Writing final report\",\n toolCallId: context.callId,\n type: \"writing\",\n });\n yield progress();\n const [savedBrief, ...savedNotes] = await readResearchFiles(context, [\n \"brief.md\",\n ...noteFiles,\n ]);\n const report = researchReport.parse(\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n `${finalReportGenerationPrompt({ date, findings: savedNotes.join(\"\\n\"), research_brief: savedBrief })}\\n\\nWrite the complete Markdown report with title ${JSON.stringify(brief.title)}. Return title and content; the workflow will publish the report as a Markdown file.`\n ),\n outputSchema: outputSchema(researchReport),\n })\n );\n context.abortSignal.throwIfAborted();\n const reportPath = await writeResearchFile(\n context,\n \"report.md\",\n report.content\n );\n const completedAt = await researchCompletedAt();\n updates[reportUpdateIndex] = {\n status: \"completed\",\n title: \"Writing final report\",\n toolCallId: context.callId,\n type: \"writing\",\n };\n updates.push({\n timestamp: completedAt,\n title: \"Research complete\",\n toolCallId: context.callId,\n type: \"completed\",\n });\n yield researchResult(\n { path: reportPath, title: report.title, format: \"report\" },\n updates\n );\n },\n inputSchema: researchInput,\n toModelOutput: (result) => toolOutput.json(result.output),\n});\n",
|
|
12
|
+
"type": "registry:file",
|
|
13
|
+
"target": "~/agent/tools/deepResearch.ts"
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
"path": "src/tools/deep-research/agent/lib/research/configuration.ts",
|
|
17
|
+
"content": "/** Workflow-specific bounds. Model, reasoning, approvals, connections, and sandbox belong to agent/agent.ts and native EVE files. */\nexport const researchOptions = {\n allow_clarification: true,\n max_concurrent_research_units: 2,\n max_researcher_iterations: 1,\n search_api_max_queries: 2,\n};\n",
|
|
18
|
+
"type": "registry:file",
|
|
19
|
+
"target": "~/agent/lib/research/configuration.ts"
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
"path": "src/tools/deep-research/agent/lib/research/prompts.ts",
|
|
23
|
+
"content": "const clarifyWithUserInstructions = ({\n messages,\n date,\n}: Readonly<{\n messages: string;\n date: string;\n}>): string =>\n `These are the messages that have been exchanged so far from the user asking for the report:\n<Messages>\n${messages}\n</Messages>\n\nToday's date is ${date}.\n\nAssess whether you need to ask a clarifying question, or if the user has already provided enough information for you to start research.\nIMPORTANT: If you can see in the messages history that you have already asked a clarifying question, you almost always do not need to ask another one. Only ask another question if ABSOLUTELY NECESSARY.\n\nIf there are acronyms, abbreviations, or unknown terms, ask the user to clarify.\nIf you need to ask a question, follow these guidelines:\n- Be concise while gathering all necessary information\n- Make sure to gather all the information needed to carry out the research task in a concise, well-structured manner.\n- Use bullet points or numbered lists if appropriate for clarity. Make sure that this uses markdown formatting and will be rendered correctly if the string output is passed to a markdown renderer.\n- Don't ask for unnecessary information, or information that the user has already provided. If you can see that the user has already provided the information, do not ask for it again.\n\nRespond in valid JSON format with these exact keys:\n\"need_clarification\": boolean,\n\"question\": \"<question to ask the user to clarify the report scope>\",\n\"verification\": \"<verification message that we will start research>\"\n\nIf you need to ask a clarifying question, return:\n\"need_clarification\": true,\n\"question\": \"<your clarifying question>\",\n\"verification\": \"\"\n\nIf you do not need to ask a clarifying question, return:\n\"need_clarification\": false,\n\"question\": \"\",\n\"verification\": \"<acknowledgement message that you will now start research based on the provided information>\"\n\nFor the verification message when no clarification is needed:\n- Acknowledge that you have sufficient information to proceed\n- Briefly summarize the key aspects of what you understand from their request\n- Confirm that you will now begin the research process\n- Keep the message concise and professional`;\n\nconst transformMessagesIntoResearchTopicPrompt = ({\n messages,\n date,\n}: Readonly<{\n messages: string;\n date: string;\n}>): string =>\n `You will be given a set of messages that have been exchanged so far between yourself and the user.\nYour job is to translate these messages into a more detailed and concrete research question that will be used to guide the research.\n\nThe messages that have been exchanged so far between yourself and the user are:\n<Messages>\n${messages}\n</Messages>\n\nToday's date is ${date}.\n\nYou will return a single research question that will be used to guide the research.\n\nGuidelines:\n1. Maximize Specificity and Detail\n- Include all known user preferences and explicitly list key attributes or dimensions to consider.\n- It is important that all details from the user are included in the instructions.\n\n2. Fill in Unstated But Necessary Dimensions as Open-Ended\n- If certain attributes are essential for a meaningful output but the user has not provided them, explicitly state that they are open-ended or default to no specific constraint.\n\n3. Avoid Unwarranted Assumptions\n- If the user has not provided a particular detail, do not invent one.\n- Instead, state the lack of specification and guide the researcher to treat it as flexible or accept all possible options.\n\n4. Use the First Person\n- Phrase the request from the perspective of the user.\n\n5. Sources\n- If specific sources should be prioritized, specify them in the research question.\n- For product and travel research, prefer linking directly to official or primary websites (e.g., official brand sites, manufacturer pages, or reputable e-commerce platforms like Amazon for user reviews) rather than aggregator sites or SEO-heavy blogs.\n- For academic or scientific queries, prefer linking directly to the original paper or official journal publication rather than survey papers or secondary summaries.\n- For people, try linking directly to their LinkedIn profile, or their personal website if they have one.\n- If the query is in a specific language, prioritize sources published in that language.`;\n\nconst leadResearcherPrompt = ({\n date,\n max_concurrent_research_units,\n}: Readonly<{\n date: string;\n max_concurrent_research_units: number;\n}>): string =>\n `You are a research supervisor. Today's date is ${date}.\nYou receive a research brief and findings from all completed topics. Decide whether the evidence is sufficient for a comprehensive report or identify specific gaps requiring follow-up research.\n\nReturn JSON with complete (boolean) and topics (array of strings).\n- To research, set complete to false and provide up to ${max_concurrent_research_units} detailed, self-contained topics. The workflow will run them sequentially and return their findings before your next decision.\n- To finish, set complete to true and topics to []. A separate writer synthesizes the report.\n- Start by researching the brief. On later rounds, request only net new information that is necessary to answer it. Do not ask researchers to synthesize existing findings.\n- Each topic must include all necessary context, explain acronyms, and state the desired depth of effort. Researchers do not see your other topics or findings.\n- Split independent questions when that improves coverage. Resolve dependencies first. More topics increase cost; prefer fewer comprehensive investigations over redundant subtopics.\n- Judge evidence coverage and reliability, not formatting. Findings may be raw or messy.\n- Match depth to the user's request. Detailed or comprehensive requests warrant more follow-up than broad overviews.\n- As research accumulates, require a stronger reason to request additional work. Finish when the findings adequately answer the brief. Do not repeat topics with minor rephrasing.`;\n\nconst researchSystemPrompt = ({\n date,\n mcp_prompt,\n max_search_queries,\n}: Readonly<{\n date: string;\n mcp_prompt: string;\n max_search_queries: number;\n}>): string =>\n `You are a research assistant conducting deep research on the user's input topic. Use the tools and search methods provided to research the user's input topic. For context, today's date is ${date}.\n\n<Task>\nYour job is to use tools and search methods to find information that can answer the question that a user asks.\nYou can use any of the tools provided to you to find resources that can help answer the research question. You can call these tools in series or in parallel, your research is conducted in a tool-calling loop.\n</Task>\n\n<Tool Calling Guidelines>\n- Make sure you review all of the tools you have available to you, match the tools to the user's request, and select the tool that is most likely to be the best fit.\n- In each iteration, select the BEST tool for the job, this may or may not be general websearch.\n- When selecting the next tool to call, make sure that you are calling tools with arguments that you have not already tried.\n- Tool calling is costly, so be sure to be very intentional about what you look up. Some of the tools may have implicit limitations. As you call tools, feel out what these limitations are, and adjust your tool calls accordingly.\n- You have a maximum of ${max_search_queries} web search queries available, so use them strategically and efficiently.\n- This could mean that you need to call a different tool or stop searching, e.g. it's okay to recognize that a tool has limitations and cannot do what you need it to.\n- Don't mention any tool limitations in your output, but adjust your tool calls accordingly.\n- ${mcp_prompt}\n<Tool Calling Guidelines>\n\n<Criteria for Finishing Research>\n- The user will give you a sense of how much effort you should put into the research. This does not translate ~directly~ to the number of tool calls you should make, but it does give you a sense of the depth of the research you should conduct.\n- Once you have enough evidence, stop searching and call eve__reply with your findings, including source URLs, citations, uncertainties, and conflicting evidence.\n- One case where you should stop is if your previous tool calls have stopped yielding useful information.\n</Criteria for Finishing Research>\n\n<Helpful Tips>\n1. If you haven't conducted any searches yet, start with broad searches to get necessary context and background information. Once you have some background, you can start to narrow down your searches to get more specific information.\n2. Different topics require different levels of research depth. If the question is broad, your research can be more shallow, and you may not need to iterate and call tools as many times.\n3. If the question is detailed, you may need to be more stingy about the depth of your findings, and you may need to iterate and call tools more times to get a fully detailed answer.\n</Helpful Tips>\n\n<Critical Reminders>\n- You MUST conduct research using web search or a different tool before finishing! You cannot finish without conducting research first!\n- The caller needs your findings, not just your search activity. Always finish by calling eve__reply with the collected evidence; a separate agent will compress it and write the user-facing report.\n</Critical Reminders>`;\n\nconst compressResearchSystemPrompt = ({\n date,\n}: Readonly<{ date: string }>): string =>\n `You are a research assistant that has conducted research on a topic by calling several tools and web searches. Your job is now to clean up the findings, but preserve all of the relevant statements and information that the researcher has gathered. For context, today's date is ${date}.\n\n<Task>\nYou need to clean up information gathered from tool calls and web searches in the existing messages.\nAll relevant information should be repeated and rewritten verbatim, but in a cleaner format.\nThe purpose of this step is just to remove any obviously irrelevant or duplicative information.\nFor example, if three sources all say \"X\", you could say \"These three sources all stated X\".\nOnly these fully comprehensive cleaned findings are going to be returned to the user, so it's crucial that you don't lose any information from the raw messages.\n</Task>\n\n<Guidelines>\n1. Your output findings should be fully comprehensive and include ALL of the information and sources that the researcher has gathered from tool calls and web searches. It is expected that you repeat key information verbatim.\n2. This report can be as long as necessary to return ALL of the information that the researcher has gathered.\n3. In your report, you should return inline citations for each source that the researcher found.\n4. You should include a \"Sources\" section at the end of the report that lists all of the sources the researcher found with corresponding citations, cited against statements in the report.\n5. Make sure to include ALL of the sources that the researcher gathered in the report, and how they were used to answer the question!\n6. It's really important not to lose any sources. A later LLM will be used to merge this report with others, so having all of the sources is critical.\n</Guidelines>\n\n<Output Format>\nThe report should be structured like this:\n**List of Queries and Tool Calls Made**\n**Fully Comprehensive Findings**\n**List of All Relevant Sources (with citations in the report)**\n</Output Format>\n\n<Citation Rules>\n- Assign each unique URL a single citation number in your text\n- End with ### Sources that lists each source with corresponding numbers\n- IMPORTANT: Number sources sequentially without gaps (1,2,3,4...) in the final list regardless of which sources you choose\n- Example format:\n [1] Source Title: URL\n [2] Source Title: URL\n</Citation Rules>\n\nCritical Reminder: It is extremely important that any information that is even remotely relevant to the user's research topic is preserved verbatim (e.g. don't rewrite it, don't summarize it, don't paraphrase it).`;\n\nconst compressResearchSimpleHumanMessage = `All above messages are about research conducted by an AI Researcher. Please clean up these findings.\n\nDO NOT summarize the information. I want the raw information returned, just in a cleaner format. Make sure all relevant information is preserved - you can rewrite findings verbatim.`;\n\nconst FINAL_REPORT_INSTRUCTIONS = `\n\nPlease create a detailed answer to the overall research brief that:\n1. Is well-organized with proper headings (# for title, ## for sections, ### for subsections)\n2. Includes specific facts and insights from the research\n3. References relevant sources using [Title](URL) format\n4. Provides a balanced, thorough analysis. Be as comprehensive as possible, and include all information that is relevant to the overall research question. People are using you for deep research and will expect detailed, comprehensive answers.\n5. Includes a \"Sources\" section at the end with all referenced links\n\nYou can structure your report in a number of different ways. Here are some examples:\n\nTo answer a question that asks you to compare two things, you might structure your report like this:\n1/ intro\n2/ overview of topic A\n3/ overview of topic B\n4/ comparison between A and B\n5/ conclusion\n\nTo answer a question that asks you to return a list of things, you might only need a single section which is the entire list.\n1/ list of things or table of things\nOr, you could choose to make each item in the list a separate section in the report. When asked for lists, you don't need an introduction or conclusion.\n1/ item 1\n2/ item 2\n3/ item 3\n\nTo answer a question that asks you to summarize a topic, give a report, or give an overview, you might structure your report like this:\n1/ overview of topic\n2/ concept 1\n3/ concept 2\n4/ concept 3\n5/ conclusion\n\nIf you think you can answer the question with a single section, you can do that too!\n1/ answer\n\nREMEMBER: Section is a VERY fluid and loose concept. You can structure your report however you think is best, including in ways that are not listed above!\nMake sure that your sections are cohesive, and make sense for the reader.\n\nFor each section of the report, do the following:\n- Use simple, clear language\n- Use ## for section title (Markdown format) for each section of the report\n- Do NOT ever refer to yourself as the writer of the report. This should be a professional report without any self-referential language.\n- Do not say what you are doing in the report. Just write the report without any commentary from yourself.\n\nFormat the report in clear markdown with proper structure and include source references where appropriate.\n\n<Citation Rules>\n- Assign each unique URL a single citation number in your text\n- End with ### Sources that lists each source with corresponding numbers\n- IMPORTANT: Number sources sequentially without gaps (1,2,3,4...) in the final list regardless of which sources you choose\n- Each source should be a separate line item in a list, so that in markdown it is rendered as a list.\n- Example format:\n [1] Source Title: URL\n [2] Source Title: URL\n- Citations are extremely important. Make sure to include these, and pay a lot of attention to getting these right. Users will often use these citations to look into more information.\n</Citation Rules>`;\n\nconst finalReportGenerationPrompt = ({\n research_brief,\n date,\n findings,\n}: Readonly<{\n research_brief: string;\n date: string;\n findings: string;\n}>): string =>\n `Based on all the research conducted, create a comprehensive, well-structured answer to the overall research brief:\n<Research Brief>\n${research_brief}\n</Research Brief>\n\nToday's date is ${date}.\n\nHere are the findings from the research that you conducted:\n<Findings>\n${findings}\n</Findings>${FINAL_REPORT_INSTRUCTIONS}`;\nexport {\n clarifyWithUserInstructions,\n compressResearchSimpleHumanMessage,\n compressResearchSystemPrompt,\n finalReportGenerationPrompt,\n leadResearcherPrompt,\n researchSystemPrompt,\n transformMessagesIntoResearchTopicPrompt,\n};\n",
|
|
24
|
+
"type": "registry:file",
|
|
25
|
+
"target": "~/agent/lib/research/prompts.ts"
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"path": "src/tools/deep-research/agent/lib/research/schemas.ts",
|
|
29
|
+
"content": "import { z } from \"zod\";\n\nconst MINIMUM_RESEARCH_TEXT_LENGTH = 1;\n\nconst researchOutput = z.union([\n z.object({ format: z.literal(\"progress\") }),\n z.object({ answer: z.string(), format: z.literal(\"clarifying_questions\") }),\n z.object({\n format: z.literal(\"report\"),\n path: z.string(),\n title: z.string(),\n }),\n]);\n\nconst researchInput = z.object({\n request: z\n .string()\n .min(1)\n .describe(\n \"The full research task, relevant conversation context, scope, and any input sandbox file paths.\"\n ),\n});\n\nconst researchClarification = z.object({\n need_clarification: z.boolean(),\n question: z.string(),\n verification: z.string(),\n});\n\nconst researchBrief = z.object({\n research_brief: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n title: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n});\n\nconst researchDecision = z.object({\n complete: z.boolean(),\n topics: z.array(z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH)),\n});\n\nconst researchFindings = z.object({\n findings: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n});\n\nconst researchReport = z.object({\n content: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n title: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n});\nexport {\n researchBrief,\n researchClarification,\n researchDecision,\n researchFindings,\n researchInput,\n researchOutput,\n researchReport,\n};\n\nexport interface ResearchUpdate {\n type: \"started\" | \"writing\" | \"thoughts\" | \"completed\";\n title: string;\n toolCallId: string;\n timestamp?: number;\n message?: string;\n status?: \"running\" | \"completed\";\n}\n\n// Optional presentation metadata; plain JSON that any EVE channel can consume.\nexport const researchResult = (\n output: z.input<typeof researchOutput>,\n updates: readonly ResearchUpdate[] = []\n) => ({\n kind: \"chatjs.tool-result\" as const,\n version: 1 as const,\n status: \"success\" as const,\n output: researchOutput.parse(output),\n updates: updates.map((update) => ({ ...update })),\n usage: { costUsd: 0 },\n});\n",
|
|
30
|
+
"type": "registry:file",
|
|
31
|
+
"target": "~/agent/lib/research/schemas.ts"
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
"path": "src/tools/deep-research/agent/lib/research/steps.ts",
|
|
35
|
+
"content": "import { researchOptions } from \"./configuration\";\n\n// oxlint-disable-next-line eslint/func-style, eslint/require-await -- EVE requires async step declarations. Record the clock and authored options once for workflow replay.\nexport async function prepareResearch(request: string) {\n \"use step\";\n return {\n config: researchOptions,\n date: new Date().toLocaleDateString(\"en-US\", {\n day: \"numeric\",\n month: \"short\",\n weekday: \"short\",\n year: \"numeric\",\n }),\n messages: request,\n timestamp: Date.now(),\n };\n}\n\n// oxlint-disable-next-line eslint/func-style, eslint/require-await -- EVE requires async step declarations. Completion time is a durable workflow step.\nexport async function researchCompletedAt() {\n \"use step\";\n return Date.now();\n}\n",
|
|
36
|
+
"type": "registry:file",
|
|
37
|
+
"target": "~/agent/lib/research/steps.ts"
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
"path": "src/tools/deep-research/agent/lib/research/workspace.ts",
|
|
41
|
+
"content": "import type { WorkflowStepToolContext } from \"eve/tools\";\nimport type { SandboxSession } from \"eve/sandbox\";\n\ntype Context = Readonly<\n Pick<WorkflowStepToolContext, \"callId\" | \"abortSignal\"> & {\n getSandbox: () => PromiseLike<\n Pick<SandboxSession, \"resolvePath\" | \"readTextFile\" | \"writeTextFile\">\n >;\n }\n>;\n\n// Per-call paths keep follow-up research from overwriting an earlier report.\nconst researchPath = (callId: string, name: string): string => {\n if (!/^[a-z0-9-]+\\.md$/u.test(name)) {\n throw new Error(\"Invalid research workspace filename.\");\n }\n return `research/run-${encodeURIComponent(callId)}/${name}`;\n};\n\n// oxlint-disable-next-line eslint/func-style -- EVE durable steps require function declarations. Whole-file writes are safe to retry.\nexport async function writeResearchFile(\n context: Context,\n name: string,\n content: string\n): Promise<string> {\n \"use step\";\n context.abortSignal.throwIfAborted();\n const sandbox = await context.getSandbox();\n const path = sandbox.resolvePath(researchPath(context.callId, name));\n await sandbox.writeTextFile({ path, content, signal: context.abortSignal });\n return path;\n}\n\n// oxlint-disable-next-line eslint/func-style -- Read the current workspace in a durable step, not during workflow replay.\nexport async function readResearchFiles(\n context: Context,\n names: readonly string[]\n): Promise<string[]> {\n \"use step\";\n context.abortSignal.throwIfAborted();\n const sandbox = await context.getSandbox();\n return await Promise.all(\n names.map(async (name) => {\n const path = sandbox.resolvePath(researchPath(context.callId, name));\n const content = await sandbox.readTextFile({\n path,\n signal: context.abortSignal,\n });\n if (content === null) {\n throw new Error(\n `Research workspace file is no longer available: ${path}`\n );\n }\n return content;\n })\n );\n}\n",
|
|
42
|
+
"type": "registry:file",
|
|
43
|
+
"target": "~/agent/lib/research/workspace.ts"
|
|
44
|
+
}
|
|
45
|
+
],
|
|
46
|
+
"type": "registry:item"
|
|
47
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "chatjs",
|
|
3
|
+
"homepage": "https://chatjs.dev",
|
|
4
|
+
"items": [
|
|
5
|
+
{
|
|
6
|
+
"name": "deep-research",
|
|
7
|
+
"description": "Research with installed EVE capabilities; produces a sandbox report. ChatJS adds optional progress UI.",
|
|
8
|
+
"dependencies": [
|
|
9
|
+
"eve@npm:@chat-js/eve@1.1.1-chatjs.0",
|
|
10
|
+
"zod@4.5.4"
|
|
11
|
+
],
|
|
12
|
+
"files": [
|
|
13
|
+
{
|
|
14
|
+
"path": "src/tools/deep-research/agent/tools/deep-research.ts",
|
|
15
|
+
"content": "// ChatJS source: deep-research. Ownership: chatjs/tools/deep-research/chatjs.json.\nimport { defineWorkflowTool, toolOutput } from \"eve/tools\";\nimport {\n clarifyWithUserInstructions,\n compressResearchSimpleHumanMessage,\n compressResearchSystemPrompt,\n finalReportGenerationPrompt,\n leadResearcherPrompt,\n researchSystemPrompt,\n transformMessagesIntoResearchTopicPrompt,\n} from \"../lib/research/prompts\";\nimport { prepareResearch, researchCompletedAt } from \"../lib/research/steps\";\nimport {\n researchBrief,\n researchInput,\n researchClarification,\n researchDecision,\n researchFindings,\n researchReport,\n researchResult,\n} from \"../lib/research/schemas\";\nimport type { ResearchUpdate } from \"../lib/research/schemas\";\nimport type { AgentSession, WorkflowToolContext } from \"eve/tools\";\nimport { z } from \"zod\";\n\nimport {\n readResearchFiles,\n writeResearchFile,\n} from \"../lib/research/workspace\";\n\ntype ResearchResult = ReturnType<typeof researchResult>;\n\ntype ResearchWorkflowContext = Readonly<\n Omit<WorkflowToolContext, \"abortSignal\"> & {\n abortSignal: Readonly<AbortSignal>;\n }\n>;\n\nconst structuredMessage = (message: string): string =>\n `${message}\\n\\nDeliver the requested fields through the eve__reply tool. Put any Markdown inside its string fields; do not return prose or JSON text instead of calling the tool.`;\n\nconst outputSchema = (schema: z.ZodType): Record<string, z.JSONType> =>\n z.record(z.string(), z.json()).parse(z.toJSONSchema(schema));\n\nconst researchReply = async (\n agent: Readonly<AgentSession>,\n options: Readonly<{\n message: string;\n outputSchema: Record<string, z.JSONType>;\n signal: AbortSignal;\n }>\n): Promise<unknown> => {\n options.signal.throwIfAborted();\n const response = await agent.send(options.message, {\n outputSchema: options.outputSchema,\n signal: options.signal,\n });\n const result = await response.result();\n options.signal.throwIfAborted();\n if (result.status === \"failed\") {\n throw new Error(result.error?.message ?? \"Research agent failed\");\n }\n if (result.data === undefined) {\n throw new Error(\"Research agent ended without structured output\");\n }\n return result.data;\n};\n\nconst INITIAL_RESEARCH_ROUND = 0;\nconst RESEARCH_ROUND_INCREMENT = 1;\nconst BRIEF_UPDATE_INDEX = 1;\nconst EMPTY_TOPIC_COUNT = 0;\n\nexport default defineWorkflowTool({\n availableInSubagents: false,\n description:\n \"Conduct deep research using installed EVE capabilities and sandbox files. Supply the full task and relevant conversation context in request. Use only for explicit deep research requests, once per turn. Returns a Markdown report path in the shared sandbox. After completion, deliver the file using attach_workspace_file when installed or your channel's native file delivery. If no delivery mechanism exists, explain where the file is and do not invent a download URL. If clarification is needed, ask the returned questions. If research fails, report the error instead of starting duplicate research.\",\n async *execute(\n input: Readonly<z.infer<typeof researchInput>>,\n context: ResearchWorkflowContext\n ): AsyncGenerator<ResearchResult, void> {\n \"use workflow\";\n const { config, date, messages, timestamp } = await prepareResearch(\n input.request\n );\n const updates: ResearchUpdate[] = [];\n const progress = (): ResearchResult =>\n researchResult({ format: \"progress\" }, updates);\n if (config.allow_clarification) {\n const clarification = researchClarification.parse(\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n clarifyWithUserInstructions({ date, messages })\n ),\n outputSchema: outputSchema(researchClarification),\n })\n );\n if (clarification.need_clarification) {\n yield researchResult({\n answer: clarification.question,\n format: \"clarifying_questions\",\n });\n return;\n }\n }\n updates.push(\n {\n timestamp,\n title: \"Starting research\",\n toolCallId: context.callId,\n type: \"started\",\n },\n {\n status: \"running\",\n title: \"Writing research brief\",\n toolCallId: context.callId,\n type: \"writing\",\n }\n );\n yield progress();\n const brief = researchBrief.parse(\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n transformMessagesIntoResearchTopicPrompt({ date, messages })\n ),\n outputSchema: outputSchema(researchBrief),\n })\n );\n await writeResearchFile(context, \"brief.md\", brief.research_brief);\n updates[BRIEF_UPDATE_INDEX] = {\n message: brief.research_brief,\n status: \"completed\",\n title: \"Writing research brief\",\n toolCallId: context.callId,\n type: \"writing\",\n };\n yield progress();\n\n const noteFiles: string[] = [];\n const decisionSchema = researchDecision.extend({\n topics: researchDecision.shape.topics.max(\n config.max_concurrent_research_units\n ),\n });\n // Preserve the SDK's max_researcher_iterations + 1 decision steps, including\n // its allowance for research on the final step if the supervisor has not finished.\n for (\n let round = INITIAL_RESEARCH_ROUND;\n round <= config.max_researcher_iterations;\n round += RESEARCH_ROUND_INCREMENT\n ) {\n context.abortSignal.throwIfAborted();\n // oxlint-disable-next-line no-await-in-loop -- Each decision reads the notes completed by preceding research rounds.\n const findings = await readResearchFiles(context, [\n \"brief.md\",\n ...noteFiles,\n ]);\n const decision = decisionSchema.parse(\n // oxlint-disable-next-line no-await-in-loop -- Each decision consumes the findings added by the preceding round.\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n `${leadResearcherPrompt({ date, max_concurrent_research_units: config.max_concurrent_research_units })}\\n\\nResearch brief: ${findings[0]}\\n\\nFindings so far:\\n${findings.slice(1).join(\"\\n\\n\")}\\n\\nDecision round ${round + RESEARCH_ROUND_INCREMENT} of ${config.max_researcher_iterations + RESEARCH_ROUND_INCREMENT}. Return your next decision.`\n ),\n outputSchema: outputSchema(decisionSchema),\n })\n );\n if (decision.complete) {\n break;\n }\n if (decision.topics.length === EMPTY_TOPIC_COUNT) {\n throw new Error(\n \"The research supervisor must select topics or finish.\"\n );\n }\n for (const topic of decision.topics) {\n context.abortSignal.throwIfAborted();\n const updateIndex = updates.length;\n updates.push({\n message: topic,\n status: \"running\",\n title: \"Researching topic\",\n toolCallId: context.callId,\n type: \"thoughts\",\n });\n yield progress();\n const raw = researchFindings.parse(\n // oxlint-disable-next-line no-await-in-loop -- Complete the topic before moving to the next research stage.\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n `${researchSystemPrompt({ date, max_search_queries: config.search_api_max_queries, mcp_prompt: \"Use eve__search to discover installed search/retrieval connections and eve__tool to call them. Use native read_file or bash for relevant sandbox files. Do not call deepResearch recursively. If current external evidence is needed but no search capability is installed, say so explicitly; never fabricate sources.\" })}\\n\\nResearch brief:\\n${findings[0]}\\n\\nTopic:\\n${topic}\\n\\nReturn comprehensive raw findings with source URLs, citations, uncertainties, and conflicting evidence.`\n ),\n outputSchema: outputSchema(researchFindings),\n })\n );\n const topicNumber = noteFiles.length + 1;\n const sourceFile = `topic-${topicNumber}-sources.md`;\n // oxlint-disable-next-line no-await-in-loop -- Preserve cited source findings before compression.\n await writeResearchFile(\n context,\n sourceFile,\n `# ${topic}\\n\\n${raw.findings}`\n );\n // oxlint-disable-next-line no-await-in-loop -- Compression consumes the saved source file.\n const [sources] = await readResearchFiles(context, [sourceFile]);\n const compressed = researchFindings.parse(\n // oxlint-disable-next-line no-await-in-loop -- Commit this topic's compressed notes before the next topic and supervisor decision.\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n `${compressResearchSystemPrompt({ date })}\\n\\n${sources}\\n\\n${compressResearchSimpleHumanMessage}`\n ),\n outputSchema: outputSchema(researchFindings),\n })\n );\n const noteFile = `topic-${topicNumber}-notes.md`;\n // oxlint-disable-next-line no-await-in-loop -- Commit notes before advancing the supervisor.\n await writeResearchFile(\n context,\n noteFile,\n `# ${topic}\\n\\n${compressed.findings}`\n );\n noteFiles.push(noteFile);\n updates[updateIndex] = {\n message: topic,\n status: \"completed\",\n title: \"Research topic completed\",\n toolCallId: context.callId,\n type: \"thoughts\",\n };\n yield progress();\n }\n }\n const reportUpdateIndex = updates.length;\n updates.push({\n status: \"running\",\n title: \"Writing final report\",\n toolCallId: context.callId,\n type: \"writing\",\n });\n yield progress();\n const [savedBrief, ...savedNotes] = await readResearchFiles(context, [\n \"brief.md\",\n ...noteFiles,\n ]);\n const report = researchReport.parse(\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n `${finalReportGenerationPrompt({ date, findings: savedNotes.join(\"\\n\"), research_brief: savedBrief })}\\n\\nWrite the complete Markdown report with title ${JSON.stringify(brief.title)}. Return title and content; the workflow will publish the report as a Markdown file.`\n ),\n outputSchema: outputSchema(researchReport),\n })\n );\n context.abortSignal.throwIfAborted();\n const reportPath = await writeResearchFile(\n context,\n \"report.md\",\n report.content\n );\n const completedAt = await researchCompletedAt();\n updates[reportUpdateIndex] = {\n status: \"completed\",\n title: \"Writing final report\",\n toolCallId: context.callId,\n type: \"writing\",\n };\n updates.push({\n timestamp: completedAt,\n title: \"Research complete\",\n toolCallId: context.callId,\n type: \"completed\",\n });\n yield researchResult(\n { path: reportPath, title: report.title, format: \"report\" },\n updates\n );\n },\n inputSchema: researchInput,\n toModelOutput: (result) => toolOutput.json(result.output),\n});\n",
|
|
16
|
+
"type": "registry:file",
|
|
17
|
+
"target": "~/agent/tools/deepResearch.ts"
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
"path": "src/tools/deep-research/agent/lib/research/configuration.ts",
|
|
21
|
+
"content": "/** Workflow-specific bounds. Model, reasoning, approvals, connections, and sandbox belong to agent/agent.ts and native EVE files. */\nexport const researchOptions = {\n allow_clarification: true,\n max_concurrent_research_units: 2,\n max_researcher_iterations: 1,\n search_api_max_queries: 2,\n};\n",
|
|
22
|
+
"type": "registry:file",
|
|
23
|
+
"target": "~/agent/lib/research/configuration.ts"
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
"path": "src/tools/deep-research/agent/lib/research/prompts.ts",
|
|
27
|
+
"content": "const clarifyWithUserInstructions = ({\n messages,\n date,\n}: Readonly<{\n messages: string;\n date: string;\n}>): string =>\n `These are the messages that have been exchanged so far from the user asking for the report:\n<Messages>\n${messages}\n</Messages>\n\nToday's date is ${date}.\n\nAssess whether you need to ask a clarifying question, or if the user has already provided enough information for you to start research.\nIMPORTANT: If you can see in the messages history that you have already asked a clarifying question, you almost always do not need to ask another one. Only ask another question if ABSOLUTELY NECESSARY.\n\nIf there are acronyms, abbreviations, or unknown terms, ask the user to clarify.\nIf you need to ask a question, follow these guidelines:\n- Be concise while gathering all necessary information\n- Make sure to gather all the information needed to carry out the research task in a concise, well-structured manner.\n- Use bullet points or numbered lists if appropriate for clarity. Make sure that this uses markdown formatting and will be rendered correctly if the string output is passed to a markdown renderer.\n- Don't ask for unnecessary information, or information that the user has already provided. If you can see that the user has already provided the information, do not ask for it again.\n\nRespond in valid JSON format with these exact keys:\n\"need_clarification\": boolean,\n\"question\": \"<question to ask the user to clarify the report scope>\",\n\"verification\": \"<verification message that we will start research>\"\n\nIf you need to ask a clarifying question, return:\n\"need_clarification\": true,\n\"question\": \"<your clarifying question>\",\n\"verification\": \"\"\n\nIf you do not need to ask a clarifying question, return:\n\"need_clarification\": false,\n\"question\": \"\",\n\"verification\": \"<acknowledgement message that you will now start research based on the provided information>\"\n\nFor the verification message when no clarification is needed:\n- Acknowledge that you have sufficient information to proceed\n- Briefly summarize the key aspects of what you understand from their request\n- Confirm that you will now begin the research process\n- Keep the message concise and professional`;\n\nconst transformMessagesIntoResearchTopicPrompt = ({\n messages,\n date,\n}: Readonly<{\n messages: string;\n date: string;\n}>): string =>\n `You will be given a set of messages that have been exchanged so far between yourself and the user.\nYour job is to translate these messages into a more detailed and concrete research question that will be used to guide the research.\n\nThe messages that have been exchanged so far between yourself and the user are:\n<Messages>\n${messages}\n</Messages>\n\nToday's date is ${date}.\n\nYou will return a single research question that will be used to guide the research.\n\nGuidelines:\n1. Maximize Specificity and Detail\n- Include all known user preferences and explicitly list key attributes or dimensions to consider.\n- It is important that all details from the user are included in the instructions.\n\n2. Fill in Unstated But Necessary Dimensions as Open-Ended\n- If certain attributes are essential for a meaningful output but the user has not provided them, explicitly state that they are open-ended or default to no specific constraint.\n\n3. Avoid Unwarranted Assumptions\n- If the user has not provided a particular detail, do not invent one.\n- Instead, state the lack of specification and guide the researcher to treat it as flexible or accept all possible options.\n\n4. Use the First Person\n- Phrase the request from the perspective of the user.\n\n5. Sources\n- If specific sources should be prioritized, specify them in the research question.\n- For product and travel research, prefer linking directly to official or primary websites (e.g., official brand sites, manufacturer pages, or reputable e-commerce platforms like Amazon for user reviews) rather than aggregator sites or SEO-heavy blogs.\n- For academic or scientific queries, prefer linking directly to the original paper or official journal publication rather than survey papers or secondary summaries.\n- For people, try linking directly to their LinkedIn profile, or their personal website if they have one.\n- If the query is in a specific language, prioritize sources published in that language.`;\n\nconst leadResearcherPrompt = ({\n date,\n max_concurrent_research_units,\n}: Readonly<{\n date: string;\n max_concurrent_research_units: number;\n}>): string =>\n `You are a research supervisor. Today's date is ${date}.\nYou receive a research brief and findings from all completed topics. Decide whether the evidence is sufficient for a comprehensive report or identify specific gaps requiring follow-up research.\n\nReturn JSON with complete (boolean) and topics (array of strings).\n- To research, set complete to false and provide up to ${max_concurrent_research_units} detailed, self-contained topics. The workflow will run them sequentially and return their findings before your next decision.\n- To finish, set complete to true and topics to []. A separate writer synthesizes the report.\n- Start by researching the brief. On later rounds, request only net new information that is necessary to answer it. Do not ask researchers to synthesize existing findings.\n- Each topic must include all necessary context, explain acronyms, and state the desired depth of effort. Researchers do not see your other topics or findings.\n- Split independent questions when that improves coverage. Resolve dependencies first. More topics increase cost; prefer fewer comprehensive investigations over redundant subtopics.\n- Judge evidence coverage and reliability, not formatting. Findings may be raw or messy.\n- Match depth to the user's request. Detailed or comprehensive requests warrant more follow-up than broad overviews.\n- As research accumulates, require a stronger reason to request additional work. Finish when the findings adequately answer the brief. Do not repeat topics with minor rephrasing.`;\n\nconst researchSystemPrompt = ({\n date,\n mcp_prompt,\n max_search_queries,\n}: Readonly<{\n date: string;\n mcp_prompt: string;\n max_search_queries: number;\n}>): string =>\n `You are a research assistant conducting deep research on the user's input topic. Use the tools and search methods provided to research the user's input topic. For context, today's date is ${date}.\n\n<Task>\nYour job is to use tools and search methods to find information that can answer the question that a user asks.\nYou can use any of the tools provided to you to find resources that can help answer the research question. You can call these tools in series or in parallel, your research is conducted in a tool-calling loop.\n</Task>\n\n<Tool Calling Guidelines>\n- Make sure you review all of the tools you have available to you, match the tools to the user's request, and select the tool that is most likely to be the best fit.\n- In each iteration, select the BEST tool for the job, this may or may not be general websearch.\n- When selecting the next tool to call, make sure that you are calling tools with arguments that you have not already tried.\n- Tool calling is costly, so be sure to be very intentional about what you look up. Some of the tools may have implicit limitations. As you call tools, feel out what these limitations are, and adjust your tool calls accordingly.\n- You have a maximum of ${max_search_queries} web search queries available, so use them strategically and efficiently.\n- This could mean that you need to call a different tool or stop searching, e.g. it's okay to recognize that a tool has limitations and cannot do what you need it to.\n- Don't mention any tool limitations in your output, but adjust your tool calls accordingly.\n- ${mcp_prompt}\n<Tool Calling Guidelines>\n\n<Criteria for Finishing Research>\n- The user will give you a sense of how much effort you should put into the research. This does not translate ~directly~ to the number of tool calls you should make, but it does give you a sense of the depth of the research you should conduct.\n- Once you have enough evidence, stop searching and call eve__reply with your findings, including source URLs, citations, uncertainties, and conflicting evidence.\n- One case where you should stop is if your previous tool calls have stopped yielding useful information.\n</Criteria for Finishing Research>\n\n<Helpful Tips>\n1. If you haven't conducted any searches yet, start with broad searches to get necessary context and background information. Once you have some background, you can start to narrow down your searches to get more specific information.\n2. Different topics require different levels of research depth. If the question is broad, your research can be more shallow, and you may not need to iterate and call tools as many times.\n3. If the question is detailed, you may need to be more stingy about the depth of your findings, and you may need to iterate and call tools more times to get a fully detailed answer.\n</Helpful Tips>\n\n<Critical Reminders>\n- You MUST conduct research using web search or a different tool before finishing! You cannot finish without conducting research first!\n- The caller needs your findings, not just your search activity. Always finish by calling eve__reply with the collected evidence; a separate agent will compress it and write the user-facing report.\n</Critical Reminders>`;\n\nconst compressResearchSystemPrompt = ({\n date,\n}: Readonly<{ date: string }>): string =>\n `You are a research assistant that has conducted research on a topic by calling several tools and web searches. Your job is now to clean up the findings, but preserve all of the relevant statements and information that the researcher has gathered. For context, today's date is ${date}.\n\n<Task>\nYou need to clean up information gathered from tool calls and web searches in the existing messages.\nAll relevant information should be repeated and rewritten verbatim, but in a cleaner format.\nThe purpose of this step is just to remove any obviously irrelevant or duplicative information.\nFor example, if three sources all say \"X\", you could say \"These three sources all stated X\".\nOnly these fully comprehensive cleaned findings are going to be returned to the user, so it's crucial that you don't lose any information from the raw messages.\n</Task>\n\n<Guidelines>\n1. Your output findings should be fully comprehensive and include ALL of the information and sources that the researcher has gathered from tool calls and web searches. It is expected that you repeat key information verbatim.\n2. This report can be as long as necessary to return ALL of the information that the researcher has gathered.\n3. In your report, you should return inline citations for each source that the researcher found.\n4. You should include a \"Sources\" section at the end of the report that lists all of the sources the researcher found with corresponding citations, cited against statements in the report.\n5. Make sure to include ALL of the sources that the researcher gathered in the report, and how they were used to answer the question!\n6. It's really important not to lose any sources. A later LLM will be used to merge this report with others, so having all of the sources is critical.\n</Guidelines>\n\n<Output Format>\nThe report should be structured like this:\n**List of Queries and Tool Calls Made**\n**Fully Comprehensive Findings**\n**List of All Relevant Sources (with citations in the report)**\n</Output Format>\n\n<Citation Rules>\n- Assign each unique URL a single citation number in your text\n- End with ### Sources that lists each source with corresponding numbers\n- IMPORTANT: Number sources sequentially without gaps (1,2,3,4...) in the final list regardless of which sources you choose\n- Example format:\n [1] Source Title: URL\n [2] Source Title: URL\n</Citation Rules>\n\nCritical Reminder: It is extremely important that any information that is even remotely relevant to the user's research topic is preserved verbatim (e.g. don't rewrite it, don't summarize it, don't paraphrase it).`;\n\nconst compressResearchSimpleHumanMessage = `All above messages are about research conducted by an AI Researcher. Please clean up these findings.\n\nDO NOT summarize the information. I want the raw information returned, just in a cleaner format. Make sure all relevant information is preserved - you can rewrite findings verbatim.`;\n\nconst FINAL_REPORT_INSTRUCTIONS = `\n\nPlease create a detailed answer to the overall research brief that:\n1. Is well-organized with proper headings (# for title, ## for sections, ### for subsections)\n2. Includes specific facts and insights from the research\n3. References relevant sources using [Title](URL) format\n4. Provides a balanced, thorough analysis. Be as comprehensive as possible, and include all information that is relevant to the overall research question. People are using you for deep research and will expect detailed, comprehensive answers.\n5. Includes a \"Sources\" section at the end with all referenced links\n\nYou can structure your report in a number of different ways. Here are some examples:\n\nTo answer a question that asks you to compare two things, you might structure your report like this:\n1/ intro\n2/ overview of topic A\n3/ overview of topic B\n4/ comparison between A and B\n5/ conclusion\n\nTo answer a question that asks you to return a list of things, you might only need a single section which is the entire list.\n1/ list of things or table of things\nOr, you could choose to make each item in the list a separate section in the report. When asked for lists, you don't need an introduction or conclusion.\n1/ item 1\n2/ item 2\n3/ item 3\n\nTo answer a question that asks you to summarize a topic, give a report, or give an overview, you might structure your report like this:\n1/ overview of topic\n2/ concept 1\n3/ concept 2\n4/ concept 3\n5/ conclusion\n\nIf you think you can answer the question with a single section, you can do that too!\n1/ answer\n\nREMEMBER: Section is a VERY fluid and loose concept. You can structure your report however you think is best, including in ways that are not listed above!\nMake sure that your sections are cohesive, and make sense for the reader.\n\nFor each section of the report, do the following:\n- Use simple, clear language\n- Use ## for section title (Markdown format) for each section of the report\n- Do NOT ever refer to yourself as the writer of the report. This should be a professional report without any self-referential language.\n- Do not say what you are doing in the report. Just write the report without any commentary from yourself.\n\nFormat the report in clear markdown with proper structure and include source references where appropriate.\n\n<Citation Rules>\n- Assign each unique URL a single citation number in your text\n- End with ### Sources that lists each source with corresponding numbers\n- IMPORTANT: Number sources sequentially without gaps (1,2,3,4...) in the final list regardless of which sources you choose\n- Each source should be a separate line item in a list, so that in markdown it is rendered as a list.\n- Example format:\n [1] Source Title: URL\n [2] Source Title: URL\n- Citations are extremely important. Make sure to include these, and pay a lot of attention to getting these right. Users will often use these citations to look into more information.\n</Citation Rules>`;\n\nconst finalReportGenerationPrompt = ({\n research_brief,\n date,\n findings,\n}: Readonly<{\n research_brief: string;\n date: string;\n findings: string;\n}>): string =>\n `Based on all the research conducted, create a comprehensive, well-structured answer to the overall research brief:\n<Research Brief>\n${research_brief}\n</Research Brief>\n\nToday's date is ${date}.\n\nHere are the findings from the research that you conducted:\n<Findings>\n${findings}\n</Findings>${FINAL_REPORT_INSTRUCTIONS}`;\nexport {\n clarifyWithUserInstructions,\n compressResearchSimpleHumanMessage,\n compressResearchSystemPrompt,\n finalReportGenerationPrompt,\n leadResearcherPrompt,\n researchSystemPrompt,\n transformMessagesIntoResearchTopicPrompt,\n};\n",
|
|
28
|
+
"type": "registry:file",
|
|
29
|
+
"target": "~/agent/lib/research/prompts.ts"
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
"path": "src/tools/deep-research/agent/lib/research/schemas.ts",
|
|
33
|
+
"content": "import { z } from \"zod\";\n\nconst MINIMUM_RESEARCH_TEXT_LENGTH = 1;\n\nconst researchOutput = z.union([\n z.object({ format: z.literal(\"progress\") }),\n z.object({ answer: z.string(), format: z.literal(\"clarifying_questions\") }),\n z.object({\n format: z.literal(\"report\"),\n path: z.string(),\n title: z.string(),\n }),\n]);\n\nconst researchInput = z.object({\n request: z\n .string()\n .min(1)\n .describe(\n \"The full research task, relevant conversation context, scope, and any input sandbox file paths.\"\n ),\n});\n\nconst researchClarification = z.object({\n need_clarification: z.boolean(),\n question: z.string(),\n verification: z.string(),\n});\n\nconst researchBrief = z.object({\n research_brief: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n title: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n});\n\nconst researchDecision = z.object({\n complete: z.boolean(),\n topics: z.array(z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH)),\n});\n\nconst researchFindings = z.object({\n findings: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n});\n\nconst researchReport = z.object({\n content: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n title: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n});\nexport {\n researchBrief,\n researchClarification,\n researchDecision,\n researchFindings,\n researchInput,\n researchOutput,\n researchReport,\n};\n\nexport interface ResearchUpdate {\n type: \"started\" | \"writing\" | \"thoughts\" | \"completed\";\n title: string;\n toolCallId: string;\n timestamp?: number;\n message?: string;\n status?: \"running\" | \"completed\";\n}\n\n// Optional presentation metadata; plain JSON that any EVE channel can consume.\nexport const researchResult = (\n output: z.input<typeof researchOutput>,\n updates: readonly ResearchUpdate[] = []\n) => ({\n kind: \"chatjs.tool-result\" as const,\n version: 1 as const,\n status: \"success\" as const,\n output: researchOutput.parse(output),\n updates: updates.map((update) => ({ ...update })),\n usage: { costUsd: 0 },\n});\n",
|
|
34
|
+
"type": "registry:file",
|
|
35
|
+
"target": "~/agent/lib/research/schemas.ts"
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
"path": "src/tools/deep-research/agent/lib/research/steps.ts",
|
|
39
|
+
"content": "import { researchOptions } from \"./configuration\";\n\n// oxlint-disable-next-line eslint/func-style, eslint/require-await -- EVE requires async step declarations. Record the clock and authored options once for workflow replay.\nexport async function prepareResearch(request: string) {\n \"use step\";\n return {\n config: researchOptions,\n date: new Date().toLocaleDateString(\"en-US\", {\n day: \"numeric\",\n month: \"short\",\n weekday: \"short\",\n year: \"numeric\",\n }),\n messages: request,\n timestamp: Date.now(),\n };\n}\n\n// oxlint-disable-next-line eslint/func-style, eslint/require-await -- EVE requires async step declarations. Completion time is a durable workflow step.\nexport async function researchCompletedAt() {\n \"use step\";\n return Date.now();\n}\n",
|
|
40
|
+
"type": "registry:file",
|
|
41
|
+
"target": "~/agent/lib/research/steps.ts"
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
"path": "src/tools/deep-research/agent/lib/research/workspace.ts",
|
|
45
|
+
"content": "import type { WorkflowStepToolContext } from \"eve/tools\";\nimport type { SandboxSession } from \"eve/sandbox\";\n\ntype Context = Readonly<\n Pick<WorkflowStepToolContext, \"callId\" | \"abortSignal\"> & {\n getSandbox: () => PromiseLike<\n Pick<SandboxSession, \"resolvePath\" | \"readTextFile\" | \"writeTextFile\">\n >;\n }\n>;\n\n// Per-call paths keep follow-up research from overwriting an earlier report.\nconst researchPath = (callId: string, name: string): string => {\n if (!/^[a-z0-9-]+\\.md$/u.test(name)) {\n throw new Error(\"Invalid research workspace filename.\");\n }\n return `research/run-${encodeURIComponent(callId)}/${name}`;\n};\n\n// oxlint-disable-next-line eslint/func-style -- EVE durable steps require function declarations. Whole-file writes are safe to retry.\nexport async function writeResearchFile(\n context: Context,\n name: string,\n content: string\n): Promise<string> {\n \"use step\";\n context.abortSignal.throwIfAborted();\n const sandbox = await context.getSandbox();\n const path = sandbox.resolvePath(researchPath(context.callId, name));\n await sandbox.writeTextFile({ path, content, signal: context.abortSignal });\n return path;\n}\n\n// oxlint-disable-next-line eslint/func-style -- Read the current workspace in a durable step, not during workflow replay.\nexport async function readResearchFiles(\n context: Context,\n names: readonly string[]\n): Promise<string[]> {\n \"use step\";\n context.abortSignal.throwIfAborted();\n const sandbox = await context.getSandbox();\n return await Promise.all(\n names.map(async (name) => {\n const path = sandbox.resolvePath(researchPath(context.callId, name));\n const content = await sandbox.readTextFile({\n path,\n signal: context.abortSignal,\n });\n if (content === null) {\n throw new Error(\n `Research workspace file is no longer available: ${path}`\n );\n }\n return content;\n })\n );\n}\n",
|
|
46
|
+
"type": "registry:file",
|
|
47
|
+
"target": "~/agent/lib/research/workspace.ts"
|
|
48
|
+
}
|
|
49
|
+
],
|
|
50
|
+
"type": "registry:item"
|
|
51
|
+
}
|
|
52
|
+
]
|
|
53
|
+
}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"path": "src/storage/exoscale/storage-provider.ts",
|
|
15
15
|
"content": "export { exoscale as createStorageAdapter } from \"files-sdk/exoscale\";\n",
|
|
16
16
|
"type": "registry:file",
|
|
17
|
-
"target": "~/
|
|
17
|
+
"target": "~/chatjs/providers/storage.ts"
|
|
18
18
|
}
|
|
19
19
|
],
|
|
20
20
|
"meta": {
|
|
@@ -23,6 +23,18 @@
|
|
|
23
23
|
"bucket",
|
|
24
24
|
"region"
|
|
25
25
|
],
|
|
26
|
+
"configFields": [
|
|
27
|
+
{
|
|
28
|
+
"key": "bucket",
|
|
29
|
+
"label": "bucket",
|
|
30
|
+
"type": "text"
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
"key": "region",
|
|
34
|
+
"label": "region",
|
|
35
|
+
"type": "text"
|
|
36
|
+
}
|
|
37
|
+
],
|
|
26
38
|
"contractVersion": 1,
|
|
27
39
|
"envRequirements": [
|
|
28
40
|
{
|