@chat-js/registry 0.2.0-beta.0 → 0.2.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/r/ai-titles.json +3 -0
- package/dist/r/attachment-uploads.json +6 -3
- package/dist/r/base/ai-titles.json +50 -0
- package/dist/r/base/akamai-storage.json +44 -0
- package/dist/r/base/alibaba-storage.json +44 -0
- package/dist/r/base/appwrite-storage.json +50 -0
- package/dist/r/base/archil-storage.json +52 -0
- package/dist/r/base/attachment-uploads.json +90 -0
- package/dist/r/base/azure-storage.json +51 -0
- package/dist/r/base/backblaze-b2-storage.json +44 -0
- package/dist/r/base/bunny-storage-storage.json +48 -0
- package/dist/r/base/cloudinary-storage.json +43 -0
- package/dist/r/base/code-documents.json +96 -0
- package/dist/r/base/code-execution-runtime.json +25 -0
- package/dist/r/base/code-execution-ui.json +32 -0
- package/dist/r/base/code-execution.json +69 -0
- package/dist/r/base/credits.json +103 -0
- package/dist/r/base/daytona-sandbox.json +55 -0
- package/dist/r/base/deep-research.json +224 -0
- package/dist/r/base/delete-document.json +58 -0
- package/dist/r/base/digitalocean-spaces-storage.json +44 -0
- package/dist/r/base/dropbox-storage.json +43 -0
- package/dist/r/base/exoscale-storage.json +44 -0
- package/dist/r/base/feedback.json +112 -0
- package/dist/r/base/filebase-storage.json +43 -0
- package/dist/r/base/firebase-storage-storage.json +52 -0
- package/dist/r/base/firecrawl-search.json +72 -0
- package/dist/r/base/followup-suggestions.json +152 -0
- package/dist/r/base/ftp-storage.json +54 -0
- package/dist/r/base/gcs-storage.json +33 -0
- package/dist/r/base/generate-image.json +101 -0
- package/dist/r/base/generate-video.json +70 -0
- package/dist/r/base/get-weather.json +52 -0
- package/dist/r/base/google-drive-storage.json +47 -0
- package/dist/r/base/hetzner-storage.json +44 -0
- package/dist/r/base/ibm-cos-storage.json +44 -0
- package/dist/r/base/idrive-e2-storage.json +44 -0
- package/dist/r/base/langfuse.json +63 -0
- package/dist/r/base/litellm-gateway.json +67 -0
- package/dist/r/base/mcp.json +320 -0
- package/dist/r/base/memory-storage.json +28 -0
- package/dist/r/base/minio-storage.json +44 -0
- package/dist/r/base/model-preferences.json +131 -0
- package/dist/r/base/neon-storage.json +44 -0
- package/dist/r/base/netlify-blobs-storage.json +31 -0
- package/dist/r/base/onedrive-storage.json +48 -0
- package/dist/r/base/openai-compatible-gateway.json +69 -0
- package/dist/r/base/openai-gateway.json +67 -0
- package/dist/r/base/openrouter-gateway.json +75 -0
- package/dist/r/base/oracle-cloud-storage.json +45 -0
- package/dist/r/base/ovhcloud-storage.json +44 -0
- package/dist/r/base/pocketbase-storage.json +50 -0
- package/dist/r/base/projects.json +275 -0
- package/dist/r/base/r2-storage.json +44 -0
- package/dist/r/base/read-document.json +34 -0
- package/dist/r/base/registry.json +4949 -0
- package/dist/r/base/retrieve-url.json +69 -0
- package/dist/r/base/s3-storage.json +44 -0
- package/dist/r/base/saved-code-execution.json +84 -0
- package/dist/r/base/scaleway-storage.json +44 -0
- package/dist/r/base/search.json +146 -0
- package/dist/r/base/sftp-storage.json +58 -0
- package/dist/r/base/sharepoint-storage.json +50 -0
- package/dist/r/base/sharing.json +144 -0
- package/dist/r/base/sheet-documents.json +94 -0
- package/dist/r/base/storj-storage.json +43 -0
- package/dist/r/base/supabase-storage.json +48 -0
- package/dist/r/base/tavily-search.json +72 -0
- package/dist/r/base/tencent-storage.json +44 -0
- package/dist/r/base/text-documents.json +117 -0
- package/dist/r/base/tigris-storage.json +43 -0
- package/dist/r/base/uploadthing-storage.json +38 -0
- package/dist/r/base/vercel-analytics.json +46 -0
- package/dist/r/base/vercel-blob-storage.json +42 -0
- package/dist/r/base/vercel-gateway.json +77 -0
- package/dist/r/base/vercel-sandbox.json +67 -0
- package/dist/r/base/vercel-speed-insights.json +46 -0
- package/dist/r/base/vultr-storage.json +44 -0
- package/dist/r/base/wasabi-storage.json +44 -0
- package/dist/r/base/webdav-storage.json +52 -0
- package/dist/r/base/word-count.json +51 -0
- package/dist/r/base/yandex-storage.json +43 -0
- package/dist/r/code-execution-ui.json +4 -3
- package/dist/r/code-execution.json +2 -2
- package/dist/r/credits.json +5 -0
- package/dist/r/deep-research.json +4 -0
- package/dist/r/feedback.json +7 -0
- package/dist/r/firecrawl-search.json +2 -2
- package/dist/r/followup-suggestions.json +5 -0
- package/dist/r/generate-image.json +3 -3
- package/dist/r/generate-video.json +2 -2
- package/dist/r/get-weather.json +3 -3
- package/dist/r/mcp.json +17 -1
- package/dist/r/model-preferences.json +7 -1
- package/dist/r/openai-compatible-gateway.json +1 -1
- package/dist/r/openai-gateway.json +1 -1
- package/dist/r/openrouter-gateway.json +1 -1
- package/dist/r/projects.json +9 -0
- package/dist/r/radix/ai-titles.json +50 -0
- package/dist/r/radix/akamai-storage.json +44 -0
- package/dist/r/radix/alibaba-storage.json +44 -0
- package/dist/r/radix/appwrite-storage.json +50 -0
- package/dist/r/radix/archil-storage.json +52 -0
- package/dist/r/radix/attachment-uploads.json +90 -0
- package/dist/r/radix/azure-storage.json +51 -0
- package/dist/r/radix/backblaze-b2-storage.json +44 -0
- package/dist/r/radix/bunny-storage-storage.json +48 -0
- package/dist/r/radix/cloudinary-storage.json +43 -0
- package/dist/r/radix/code-documents.json +96 -0
- package/dist/r/radix/code-execution-runtime.json +25 -0
- package/dist/r/radix/code-execution-ui.json +32 -0
- package/dist/r/radix/code-execution.json +69 -0
- package/dist/r/radix/credits.json +103 -0
- package/dist/r/radix/daytona-sandbox.json +55 -0
- package/dist/r/radix/deep-research.json +224 -0
- package/dist/r/radix/delete-document.json +58 -0
- package/dist/r/radix/digitalocean-spaces-storage.json +44 -0
- package/dist/r/radix/dropbox-storage.json +43 -0
- package/dist/r/radix/exoscale-storage.json +44 -0
- package/dist/r/radix/feedback.json +112 -0
- package/dist/r/radix/filebase-storage.json +43 -0
- package/dist/r/radix/firebase-storage-storage.json +52 -0
- package/dist/r/radix/firecrawl-search.json +72 -0
- package/dist/r/radix/followup-suggestions.json +152 -0
- package/dist/r/radix/ftp-storage.json +54 -0
- package/dist/r/radix/gcs-storage.json +33 -0
- package/dist/r/radix/generate-image.json +101 -0
- package/dist/r/radix/generate-video.json +70 -0
- package/dist/r/radix/get-weather.json +52 -0
- package/dist/r/radix/google-drive-storage.json +47 -0
- package/dist/r/radix/hetzner-storage.json +44 -0
- package/dist/r/radix/ibm-cos-storage.json +44 -0
- package/dist/r/radix/idrive-e2-storage.json +44 -0
- package/dist/r/radix/langfuse.json +63 -0
- package/dist/r/radix/litellm-gateway.json +67 -0
- package/dist/r/radix/mcp.json +320 -0
- package/dist/r/radix/memory-storage.json +28 -0
- package/dist/r/radix/minio-storage.json +44 -0
- package/dist/r/radix/model-preferences.json +131 -0
- package/dist/r/radix/neon-storage.json +44 -0
- package/dist/r/radix/netlify-blobs-storage.json +31 -0
- package/dist/r/radix/onedrive-storage.json +48 -0
- package/dist/r/radix/openai-compatible-gateway.json +69 -0
- package/dist/r/radix/openai-gateway.json +67 -0
- package/dist/r/radix/openrouter-gateway.json +75 -0
- package/dist/r/radix/oracle-cloud-storage.json +45 -0
- package/dist/r/radix/ovhcloud-storage.json +44 -0
- package/dist/r/radix/pocketbase-storage.json +50 -0
- package/dist/r/radix/projects.json +275 -0
- package/dist/r/radix/r2-storage.json +44 -0
- package/dist/r/radix/read-document.json +34 -0
- package/dist/r/radix/registry.json +4949 -0
- package/dist/r/radix/retrieve-url.json +69 -0
- package/dist/r/radix/s3-storage.json +44 -0
- package/dist/r/radix/saved-code-execution.json +84 -0
- package/dist/r/radix/scaleway-storage.json +44 -0
- package/dist/r/radix/search.json +146 -0
- package/dist/r/radix/sftp-storage.json +58 -0
- package/dist/r/radix/sharepoint-storage.json +50 -0
- package/dist/r/radix/sharing.json +144 -0
- package/dist/r/radix/sheet-documents.json +94 -0
- package/dist/r/radix/storj-storage.json +43 -0
- package/dist/r/radix/supabase-storage.json +48 -0
- package/dist/r/radix/tavily-search.json +72 -0
- package/dist/r/radix/tencent-storage.json +44 -0
- package/dist/r/radix/text-documents.json +117 -0
- package/dist/r/radix/tigris-storage.json +43 -0
- package/dist/r/radix/uploadthing-storage.json +38 -0
- package/dist/r/radix/vercel-analytics.json +46 -0
- package/dist/r/radix/vercel-blob-storage.json +42 -0
- package/dist/r/radix/vercel-gateway.json +77 -0
- package/dist/r/radix/vercel-sandbox.json +67 -0
- package/dist/r/radix/vercel-speed-insights.json +46 -0
- package/dist/r/radix/vultr-storage.json +44 -0
- package/dist/r/radix/wasabi-storage.json +44 -0
- package/dist/r/radix/webdav-storage.json +52 -0
- package/dist/r/radix/word-count.json +51 -0
- package/dist/r/radix/yandex-storage.json +43 -0
- package/dist/r/registry.json +108 -29
- package/dist/r/retrieve-url.json +5 -3
- package/dist/r/saved-code-execution.json +3 -0
- package/dist/r/search.json +7 -1
- package/dist/r/sharing.json +7 -0
- package/dist/r/sheet-documents.json +2 -1
- package/dist/r/tavily-search.json +2 -2
- package/dist/r/text-documents.json +2 -1
- package/dist/r/word-count.json +2 -2
- package/package.json +4 -1
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "retrieve-url",
|
|
4
|
+
"description": "Fetch structured information from a single URL",
|
|
5
|
+
"dependencies": [
|
|
6
|
+
"ai@7.0.137",
|
|
7
|
+
"zod@4.5.4",
|
|
8
|
+
"@mendable/firecrawl-js@1.29.1",
|
|
9
|
+
"lucide-react@0.553.0",
|
|
10
|
+
"react-markdown@^10.1.0"
|
|
11
|
+
],
|
|
12
|
+
"files": [
|
|
13
|
+
{
|
|
14
|
+
"path": "src/tools/retrieve-url/retrieve-url-env.ts",
|
|
15
|
+
"content": "import { z } from \"zod\";\n\nconst environmentSchema = z.object({\n FIRECRAWL_API_KEY: z.string().optional(),\n});\n\nconst readToolEnvironment = (\n environment: Readonly<NodeJS.ProcessEnv> = process.env\n) => environmentSchema.parse(environment);\n\nexport { readToolEnvironment };\n",
|
|
16
|
+
"type": "registry:file",
|
|
17
|
+
"target": "~/tools/chatjs/retrieve-url/retrieve-url-env.ts"
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
"path": "src/tools/retrieve-url/tool.ts",
|
|
21
|
+
"content": "import FirecrawlApp from \"@mendable/firecrawl-js\";\nimport { defineTool } from \"eve/tools\";\nimport { readToolEnvironment } from \"./retrieve-url-env\";\nimport { createModuleLogger } from \"@/lib/logger\";\nimport { executeWithToolUsage } from \"@/lib/eve/tool-usage\";\nimport { retrievedInput } from \"./schemas\";\nimport { toolResultToModelOutput } from \"@/lib/eve/tool-model-output\";\nimport { z } from \"zod\";\n\ntype RetrieveUrlInput = Readonly<z.infer<typeof retrievedInput>>;\ntype RetrieveUrlContext = Readonly<{\n abortSignal: Readonly<AbortSignal>;\n}>;\ntype RetrieveUrlUsage = Readonly<{\n addCostUsd: (cost: number) => void;\n markUnknown: () => void;\n}>;\n\nconst hasNonEmptyValue = (value: string | null | undefined): value is string =>\n typeof value === \"string\" && value !== \"\";\n\nconst UNBILLED_TOOL_COST_USD = 0;\nconst log = createModuleLogger(\"tools/retrieve-url\");\n\nconst createClient = (): FirecrawlApp | null => {\n const env = readToolEnvironment();\n return hasNonEmptyValue(env.FIRECRAWL_API_KEY)\n ? new FirecrawlApp({ apiKey: env.FIRECRAWL_API_KEY })\n : null;\n};\n\nconst parseUrl = (url: string): URL | null => {\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return null;\n }\n return parsed;\n } catch {\n return null;\n }\n};\n\nconst redactUrl = (url: Readonly<Pick<URL, \"origin\" | \"pathname\">>): string =>\n `${url.origin}${url.pathname}`;\n\nexport const retrieveUrl = defineTool({\n description: `Fetch structured information from a single URL via Firecrawl.\n\nUse for:\n- Extract content from a specific URL supplied by the user\n\nAvoid:\n- General-purpose web searches`,\n execute: async ({ url }: RetrieveUrlInput, context: RetrieveUrlContext) =>\n await executeWithToolUsage(context, async (usage: RetrieveUrlUsage) => {\n usage.addCostUsd(UNBILLED_TOOL_COST_USD);\n try {\n const app = createClient();\n if (!app) {\n return {\n error:\n \"Firecrawl is not configured. Set FIRECRAWL_API_KEY to enable retrieval.\",\n };\n }\n const parsedUrl = parseUrl(url);\n if (!parsedUrl) {\n return {\n error: \"Please provide a valid http:// or https:// URL.\",\n };\n }\n\n const redactedUrl = redactUrl(parsedUrl);\n const normalizedUrl = parsedUrl.toString();\n // Firecrawl does not return a monetary receipt for scrape/extract.\n usage.markUnknown();\n const content = await app.scrapeUrl(normalizedUrl);\n if (!(content.success && content.metadata)) {\n return {\n results: [\n {\n error: content.error,\n },\n ],\n };\n }\n\n const schema = z.object({\n content: z.string(),\n description: z.string(),\n title: z.string(),\n });\n\n const { metadata } = content;\n let { description, title } = metadata;\n let extractedContent = content.markdown;\n\n if (\n !(\n hasNonEmptyValue(title) &&\n hasNonEmptyValue(description) &&\n hasNonEmptyValue(extractedContent)\n )\n ) {\n const extractResult = await app.extract([normalizedUrl], {\n prompt:\n \"Extract the page title, main content, and a brief description.\",\n schema,\n });\n\n if (\n extractResult.success &&\n extractResult.data !== undefined &&\n extractResult.data !== null\n ) {\n const extracted = schema\n .extend({\n content: schema.shape.content.catch(\"\"),\n description: schema.shape.description.catch(\"\"),\n title: schema.shape.title.catch(\"\"),\n })\n .safeParse(extractResult.data);\n if (extracted.success) {\n title = hasNonEmptyValue(title) ? title : extracted.data.title;\n description = hasNonEmptyValue(description)\n ? description\n : extracted.data.description;\n extractedContent = hasNonEmptyValue(extractedContent)\n ? extractedContent\n : extracted.data.content;\n }\n }\n }\n\n return {\n results: [\n {\n content: extractedContent ?? \"\",\n description: description ?? \"\",\n language: metadata.language,\n title: hasNonEmptyValue(title) ? title : \"Untitled\",\n url: redactedUrl,\n },\n ],\n };\n } catch (error) {\n const parsedUrl = parseUrl(url);\n log.error(\n {\n err: error,\n url: parsedUrl ? redactUrl(parsedUrl) : \"<invalid-url>\",\n },\n \"Firecrawl API error in retrieveUrl tool\"\n );\n return { error: \"Failed to retrieve content\" };\n }\n }),\n inputSchema: retrievedInput,\n toModelOutput: toolResultToModelOutput,\n});\n",
|
|
22
|
+
"type": "registry:file",
|
|
23
|
+
"target": "~/tools/chatjs/retrieve-url/tool.ts"
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
"path": "src/tools/retrieve-url/renderer.tsx",
|
|
27
|
+
"content": "\"use client\";\nimport { ChevronDown, ExternalLink, Globe, TextIcon } from \"lucide-react\";\nimport { retrievedInput, retrievedResult } from \"./schemas\";\nimport React from \"react\";\nimport ReactMarkdown from \"react-markdown\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport type { ToolRendererProps } from \"@/lib/ai/define-tool-renderer\";\nimport { defineToolRenderer } from \"@/lib/ai/define-tool-renderer\";\n\ntype RetrieveUrlRendererTool = ToolRendererProps<\n typeof retrievedInput,\n typeof retrievedResult\n>[\"tool\"];\n\nconst LoadingState = (): React.JSX.Element => (\n <div className=\"border-border bg-card my-4 rounded-xl border p-4\">\n <div className=\"flex items-center gap-4\">\n <div className=\"relative h-10 w-10\">\n <div className=\"bg-primary/10 absolute inset-0 animate-pulse rounded-full\" />\n <Globe className=\"text-primary/70 absolute inset-0 m-auto h-5 w-5\" />\n </div>\n <div className=\"flex-1 space-y-2\">\n <div className=\"bg-muted-foreground/20 h-4 w-36 animate-pulse rounded-md\" />\n <div className=\"space-y-1.5\">\n <div className=\"bg-muted-foreground/15 h-3 w-full animate-pulse rounded-md\" />\n <div className=\"bg-muted-foreground/15 h-3 w-2/3 animate-pulse rounded-md\" />\n </div>\n </div>\n </div>\n </div>\n);\n\nconst ErrorState = ({\n errorMessage,\n}: Readonly<{ errorMessage: string | undefined }>): React.JSX.Element => (\n <div className=\"my-4 rounded-xl border border-red-200 bg-red-50 p-4 dark:border-red-500 dark:bg-red-950/50\">\n <div className=\"flex items-center gap-3\">\n <div className=\"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-red-100 dark:bg-red-900/50\">\n <Globe className=\"h-4 w-4 text-red-600 dark:text-red-300\" />\n </div>\n <div>\n <div className=\"text-sm font-medium text-red-700 dark:text-red-300\">\n Error retrieving content\n </div>\n <div className=\"mt-1 text-xs text-red-600/80 dark:text-red-400/80\">\n {errorMessage}\n </div>\n </div>\n </div>\n </div>\n);\n\nconst getItemProperty = (\n item: unknown,\n property: string,\n defaultValue: string\n): string => {\n if (item !== null && typeof item === \"object\" && property in item) {\n const value: unknown = Reflect.get(item, property);\n return typeof value === \"string\" ? value : defaultValue;\n }\n return defaultValue;\n};\n\nconst RetrievedContentHeader = ({\n firstItem,\n}: Readonly<{ firstItem: unknown }>): React.JSX.Element => {\n const url = getItemProperty(firstItem, \"url\", \"\");\n const title = getItemProperty(firstItem, \"title\", \"Retrieved Content\");\n const description = getItemProperty(\n firstItem,\n \"description\",\n \"No description available\"\n );\n const language = getItemProperty(firstItem, \"language\", \"Unknown\");\n\n return (\n <div className=\"p-4\">\n <div className=\"flex items-start gap-4\">\n <div className=\"relative h-10 w-10 shrink-0\">\n <div className=\"from-primary/10 absolute inset-0 rounded-lg bg-linear-to-br to-transparent\" />\n <Globe className=\"text-primary/70 absolute inset-0 m-auto h-5 w-5\" />\n </div>\n <div className=\"min-w-0 flex-1 space-y-2\">\n <h2 className=\"text-foreground truncate text-lg font-semibold tracking-tight\">\n {title}\n </h2>\n <p className=\"text-muted-foreground line-clamp-2 text-sm\">\n {description}\n </p>\n <div className=\"flex items-center gap-3\">\n <span className=\"bg-primary/10 text-primary rounded-full px-2.5 py-0.5 text-xs font-medium\">\n {language}\n </span>\n <a\n className=\"text-muted-foreground hover:text-primary inline-flex items-center gap-1.5 text-xs transition-colors\"\n href={url || \"#\"}\n rel=\"noopener noreferrer\"\n target=\"_blank\"\n >\n <ExternalLink className=\"h-3 w-3\" />\n View source\n </a>\n </div>\n </div>\n </div>\n </div>\n );\n};\n\nconst RetrievedContentDetails = ({\n firstItem,\n}: Readonly<{ firstItem: unknown }>): React.JSX.Element => {\n const content = getItemProperty(firstItem, \"content\", \"No content available\");\n\n return (\n <div className=\"border-border border-t\">\n <details className=\"group\">\n <summary className=\"text-muted-foreground hover:bg-muted flex w-full cursor-pointer items-center justify-between px-4 py-2 text-sm transition-colors\">\n <div className=\"flex items-center gap-2\">\n <TextIcon className=\"text-muted-foreground h-4 w-4\" />\n <span>View content</span>\n </div>\n <ChevronDown className=\"h-4 w-4 transition-transform duration-200 group-open:rotate-180\" />\n </summary>\n <div className=\"bg-muted/50 max-h-[50vh] overflow-y-auto p-4\">\n <div className=\"prose prose-neutral dark:prose-invert prose-sm max-w-none\">\n <ReactMarkdown>{content}</ReactMarkdown>\n </div>\n </div>\n </details>\n </div>\n );\n};\n\nconst getFirstItem = (result: unknown): unknown => {\n if (\n result !== null &&\n typeof result === \"object\" &&\n \"results\" in result &&\n Array.isArray(result.results)\n ) {\n return result.results[0];\n }\n return undefined;\n};\n\nconst getErrorMessage = (\n result: unknown,\n firstItem: unknown\n): string | null => {\n const topLevelError =\n result !== null &&\n typeof result === \"object\" &&\n \"error\" in result &&\n typeof result.error === \"string\"\n ? result.error\n : undefined;\n const firstItemError =\n firstItem !== null &&\n typeof firstItem === \"object\" &&\n \"error\" in firstItem &&\n typeof firstItem.error === \"string\"\n ? firstItem.error\n : undefined;\n\n return topLevelError ?? firstItemError ?? null;\n};\n\nconst RetrieveUrlView = ({\n tool,\n}: ReadonlyNativeSurface<{\n tool: RetrieveUrlRendererTool;\n messageId: string;\n isReadonly: boolean;\n}>): React.JSX.Element | null => {\n if (tool.state === \"input-available\" || tool.state === \"input-streaming\") {\n return <LoadingState />;\n }\n\n if (tool.state !== \"output-available\") {\n return null;\n }\n\n if (tool.output === undefined) {\n return null;\n }\n\n const { output: result } = tool;\n const firstItem = getFirstItem(result);\n const errorMessage = getErrorMessage(result, firstItem);\n\n if (typeof errorMessage === \"string\" && errorMessage !== \"\") {\n return <ErrorState errorMessage={errorMessage} />;\n }\n\n return (\n <div className=\"border-border bg-card my-4 overflow-hidden rounded-xl border\">\n <RetrievedContentHeader firstItem={firstItem} />\n <RetrievedContentDetails firstItem={firstItem} />\n </div>\n );\n};\n\nexport const RetrieveUrlRenderer = defineToolRenderer({\n inputSchema: retrievedInput,\n outputSchema: retrievedResult,\n render: RetrieveUrlView,\n});\n",
|
|
28
|
+
"type": "registry:file",
|
|
29
|
+
"target": "~/tools/chatjs/retrieve-url/renderer.tsx"
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
"path": "src/tools/retrieve-url/schemas.ts",
|
|
33
|
+
"content": "import { z } from \"zod\";\n\nconst retrievedInput = z.object({\n url: z.string().describe(\"The URL to retrieve the information from.\"),\n});\n\nconst retrievedContent = z\n .object({\n content: z.string(),\n description: z.string(),\n language: z.string().optional(),\n title: z.string(),\n url: z.string(),\n })\n .transform((item) => ({ ...item, language: item.language }));\nconst retrievalFailure = z\n .object({ error: z.string().optional() })\n .transform((item) => ({ error: item.error }));\nconst retrievedResult = z.union([\n z.object({ error: z.string() }),\n z.object({ results: z.array(retrievedContent) }),\n z.object({ results: z.array(retrievalFailure) }),\n]);\nexport { retrievedInput, retrievedResult };\n",
|
|
34
|
+
"type": "registry:file",
|
|
35
|
+
"target": "~/tools/chatjs/retrieve-url/schemas.ts"
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
"path": "dist/source/retrieve-url.json",
|
|
39
|
+
"content": "{\n \"envRequirements\": [{ \"options\": [[\"FIRECRAWL_API_KEY\"]] }],\n \"id\": \"retrieve-url\",\n \"kind\": \"tool\",\n \"requiresTools\": [],\n \"slot\": \"retrieveUrl\",\n \"tools\": [\n { \"rendererExport\": \"RetrieveUrlRenderer\", \"toolExport\": \"retrieveUrl\" }\n ],\n \"contractVersion\": 1\n}\n",
|
|
40
|
+
"type": "registry:file",
|
|
41
|
+
"target": "~/tools/chatjs/retrieve-url/chatjs.json"
|
|
42
|
+
}
|
|
43
|
+
],
|
|
44
|
+
"meta": {
|
|
45
|
+
"chatjs": {
|
|
46
|
+
"envRequirements": [
|
|
47
|
+
{
|
|
48
|
+
"options": [
|
|
49
|
+
[
|
|
50
|
+
"FIRECRAWL_API_KEY"
|
|
51
|
+
]
|
|
52
|
+
]
|
|
53
|
+
}
|
|
54
|
+
],
|
|
55
|
+
"id": "retrieve-url",
|
|
56
|
+
"kind": "tool",
|
|
57
|
+
"requiresTools": [],
|
|
58
|
+
"slot": "retrieveUrl",
|
|
59
|
+
"tools": [
|
|
60
|
+
{
|
|
61
|
+
"rendererExport": "RetrieveUrlRenderer",
|
|
62
|
+
"toolExport": "retrieveUrl"
|
|
63
|
+
}
|
|
64
|
+
],
|
|
65
|
+
"contractVersion": 1
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
"type": "registry:item"
|
|
69
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "s3-storage",
|
|
4
|
+
"title": "S3",
|
|
5
|
+
"description": "AWS S3 (and any S3-compatible bucket). Uses the standard AWS credential chain - environment, IAM role, shared profile.",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"files-sdk@2.5.0",
|
|
8
|
+
"@aws-sdk/client-s3@^3.1079.0",
|
|
9
|
+
"@aws-sdk/s3-presigned-post@^3.700.0",
|
|
10
|
+
"@aws-sdk/s3-request-presigner@^3.700.0"
|
|
11
|
+
],
|
|
12
|
+
"files": [
|
|
13
|
+
{
|
|
14
|
+
"path": "src/storage/s3/storage-provider.ts",
|
|
15
|
+
"content": "export { s3 as createStorageAdapter } from \"files-sdk/s3\";\n",
|
|
16
|
+
"type": "registry:file",
|
|
17
|
+
"target": "~/lib/storage-provider.ts"
|
|
18
|
+
}
|
|
19
|
+
],
|
|
20
|
+
"meta": {
|
|
21
|
+
"chatjs": {
|
|
22
|
+
"configKeys": [
|
|
23
|
+
"bucket"
|
|
24
|
+
],
|
|
25
|
+
"contractVersion": 1,
|
|
26
|
+
"envRequirements": [
|
|
27
|
+
{
|
|
28
|
+
"description": "S3 configuration",
|
|
29
|
+
"options": [
|
|
30
|
+
[
|
|
31
|
+
"AWS_REGION"
|
|
32
|
+
]
|
|
33
|
+
]
|
|
34
|
+
}
|
|
35
|
+
],
|
|
36
|
+
"id": "s3",
|
|
37
|
+
"kind": "storage",
|
|
38
|
+
"optionalEnv": [
|
|
39
|
+
"AWS_SESSION_TOKEN"
|
|
40
|
+
]
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
"type": "registry:item"
|
|
44
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "saved-code-execution",
|
|
4
|
+
"description": "Run saved code revisions with a compatible installed executor",
|
|
5
|
+
"dependencies": [
|
|
6
|
+
"lucide-react@0.553.0"
|
|
7
|
+
],
|
|
8
|
+
"registryDependencies": [
|
|
9
|
+
"@chatjs/code-documents",
|
|
10
|
+
"@chatjs/code-execution-ui"
|
|
11
|
+
],
|
|
12
|
+
"files": [
|
|
13
|
+
{
|
|
14
|
+
"path": "src/tools/saved-code-execution/tool.ts",
|
|
15
|
+
"content": "import { defineTool } from \"eve/tools\";\nimport { documentExecutionInput } from \"./schemas\";\nimport { executeEveCodeDocument } from \"./execute\";\nimport { toolResultToModelOutput } from \"@/lib/eve/tool-model-output\";\n\nexport const runCodeDocument = defineTool({\n description:\n \"Run the exact saved Python or JavaScript code document revision in this conversation. Supply its document and revision IDs. Do not copy, rewrite, or substitute its source code.\",\n execute: executeEveCodeDocument,\n inputSchema: documentExecutionInput,\n toModelOutput: toolResultToModelOutput,\n});\n",
|
|
16
|
+
"type": "registry:file",
|
|
17
|
+
"target": "~/tools/chatjs/saved-code-execution/tool.ts"
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
"path": "src/tools/saved-code-execution/execute.ts",
|
|
21
|
+
"content": "import {\n documentExecutionInput,\n documentExecutionLanguage,\n eveCodeExecutionResult,\n} from \"./schemas\";\nimport {\n installedDocumentKinds,\n installedToolNames,\n} from \"@/composition/generated/installed-tools\";\nimport type { ToolContext } from \"eve/tools\";\nimport { getEveDocumentRevision } from \"@/lib/db/eve-documents\";\nimport { resolveEveConversationScope } from \"@/lib/eve/conversation-scope\";\nimport { eveToolAllowed } from \"@/lib/eve/turn-tools\";\nimport { codeExecutor } from \"@/composition/generated/code-executor\";\n\ntype ReadonlyCodeExecutionContext = Readonly<\n Pick<ToolContext, \"callId\" | \"session\"> & {\n abortSignal: Readonly<AbortSignal>;\n }\n>;\ntype CodeResult = Awaited<ReturnType<NonNullable<typeof codeExecutor>>>;\ntype SuccessfulCodeResult = Extract<CodeResult, { status: \"success\" }>;\ntype DocumentExecutionSource = Readonly<{\n code: string;\n language: \"python\" | \"javascript\";\n title: string;\n}>;\ntype DocumentExecutionResult = {\n -readonly [\n Key in keyof Omit<SuccessfulCodeResult, \"output\">\n ]: SuccessfulCodeResult[Key];\n} & {\n output: ReturnType<typeof eveCodeExecutionResult.parse> & {\n code: string;\n language: \"python\" | \"javascript\";\n title: string;\n documentId: string;\n revisionId: string;\n };\n};\n\ntype DocumentExecutionStream = AsyncGenerator<\n Extract<CodeResult, { status: \"error\" }> | DocumentExecutionResult,\n void,\n unknown\n>;\n\nconst documentResult = (\n result: Readonly<\n Omit<SuccessfulCodeResult, \"output\"> & {\n output: Readonly<SuccessfulCodeResult[\"output\"]>;\n }\n >,\n source: DocumentExecutionSource,\n revision: Readonly<{ documentId: string; id: string }>\n): DocumentExecutionResult => {\n const output = eveCodeExecutionResult.safeParse(result.output);\n return {\n ...result,\n output: {\n ...(output.success\n ? output.data\n : {\n chart: \"\",\n message:\n \"Execution finished, but its output has an unsupported format.\",\n }),\n ...source,\n documentId: revision.documentId,\n revisionId: revision.id,\n },\n };\n};\n\n/**\n * Execute saved source, never model-supplied replacement code.\n * @param {unknown} value Untrusted tool input validated against the shared execution schema.\n * @param {ToolContext} context Native tool context supplying session scope, call metadata, and cancellation.\n * @yields {unknown} Native EVE platform result snapshots with document identity.\n */\nexport const executeEveCodeDocument = async function* executeEveCodeDocument(\n value: unknown,\n context: ReadonlyCodeExecutionContext\n): DocumentExecutionStream {\n if (\n !(\n installedDocumentKinds.has(\"code\") &&\n installedToolNames.has(\"runCodeDocument\")\n )\n ) {\n throw new Error(\"Document execution is disabled.\");\n }\n const input = documentExecutionInput.parse(value);\n const scope = await resolveEveConversationScope(\n (context.session.auth.initiator ?? {}).principalId,\n context.session.id,\n context.abortSignal\n );\n const revision = await getEveDocumentRevision(\n scope.ownerId,\n scope.conversationId,\n input.documentId,\n input.revisionId\n );\n if (!revision || revision.kind !== \"code\") {\n throw new Error(\"Code document not found.\");\n }\n const language = documentExecutionLanguage(revision.title);\n if (!language) {\n throw new Error(\"Only Python and JavaScript documents can be run.\");\n }\n context.abortSignal.throwIfAborted();\n const source = { code: revision.content, language, title: revision.title };\n if (!codeExecutor || !eveToolAllowed(\"codeExecution\")) {\n throw new Error(\"Installed code executor is unavailable.\");\n }\n const result = await codeExecutor(source, {\n abortSignal: context.abortSignal,\n callId: context.callId,\n session: context.session,\n });\n if (result.status === \"error\") {\n yield result;\n return;\n }\n yield documentResult(result, source, revision);\n};\n",
|
|
22
|
+
"type": "registry:file",
|
|
23
|
+
"target": "~/tools/chatjs/saved-code-execution/execute.ts"
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
"path": "src/tools/saved-code-execution/schemas.ts",
|
|
27
|
+
"content": "import { z } from \"zod\";\n\nconst documentExecutionInput = z.object({\n documentId: z.uuid(),\n revisionId: z.uuid(),\n});\n\nconst chartLabels = {\n title: z.string(),\n x_label: z.string().optional(),\n y_label: z.string().optional(),\n};\nconst point = z.tuple([z.union([z.number(), z.string()]), z.number()]);\nconst series = z.object({\n label: z.string(),\n points: z.array(point),\n});\nconst barElement = z.object({\n group: z.string(),\n label: z.string(),\n value: z.number(),\n});\nconst lineChart = z.object({\n ...chartLabels,\n elements: z.array(series),\n type: z.literal(\"line\"),\n x_scale: z.literal(\"datetime\").nullish(),\n});\nconst scatterChart = z.object({\n ...chartLabels,\n elements: z.array(series),\n type: z.literal(\"scatter\"),\n x_scale: z.literal(\"datetime\").nullish(),\n});\nconst barChart = z.object({\n ...chartLabels,\n elements: z.array(barElement),\n type: z.literal(\"bar\"),\n});\nconst chart = z.discriminatedUnion(\"type\", [lineChart, scatterChart, barChart]);\nconst encodedChart = z.object({ base64: z.string(), format: z.string() });\n\n/** The saved-code runner owns its output contract independently of installed renderers. */\nconst eveCodeExecutionResult = z.object({\n chart: z.union([z.string(), encodedChart, chart]),\n message: z.string(),\n});\n\nconst LAST_EXTENSION_INDEX = -1;\nconst executionLanguageByExtension: ReadonlyMap<\n string,\n \"python\" | \"javascript\"\n> = new Map([\n [\"py\", \"python\"],\n [\"js\", \"javascript\"],\n [\"mjs\", \"javascript\"],\n [\"cjs\", \"javascript\"],\n]);\nconst documentExecutionLanguage = (\n title: string\n): \"python\" | \"javascript\" | undefined => {\n if (!title.includes(\".\")) {\n return \"python\";\n }\n const extension = (\n title.split(\".\").at(LAST_EXTENSION_INDEX) ?? \"\"\n ).toLowerCase();\n if (!(typeof extension === \"string\" && extension !== \"\")) {\n return \"python\";\n }\n return executionLanguageByExtension.get(extension);\n};\nexport {\n documentExecutionInput,\n documentExecutionLanguage,\n eveCodeExecutionResult,\n};\n",
|
|
28
|
+
"type": "registry:file",
|
|
29
|
+
"target": "~/tools/chatjs/saved-code-execution/schemas.ts"
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
"path": "src/tools/saved-code-execution/document.tsx",
|
|
33
|
+
"content": "\"use client\";\nimport {\n Tooltip,\n TooltipContent,\n TooltipTrigger,\n} from \"@/components/ui/tooltip\";\nimport {\n installedDocumentKinds,\n installedToolNames,\n} from \"@/composition/generated/installed-tools\";\nimport { Button } from \"@/components/ui/button\";\nimport type { DocumentRunProps } from \"@/lib/eve/document-ui\";\nimport { EveDocumentRunResult } from \"./result\";\nimport { Play } from \"lucide-react\";\nimport React from \"react\";\nimport { config } from \"@/lib/config\";\nimport { documentExecutionLanguage } from \"./schemas\";\nimport { latestDocumentRun } from \"./document-runs\";\n\nexport const EveDocumentRun = ({\n documentId,\n revisionId,\n title,\n kind,\n messages,\n disabled,\n onAction,\n buttonOnly = false,\n resultOnly = false,\n}: DocumentRunProps): React.JSX.Element | null => {\n const [, startEventAction] = React.useTransition();\n const run = latestDocumentRun(messages, documentId, revisionId);\n const canRun =\n onAction !== undefined &&\n installedDocumentKinds.has(\"code\") &&\n installedToolNames.has(\"runCodeDocument\") &&\n documentExecutionLanguage(title) !== undefined;\n if (\n kind !== \"code\" ||\n !(canRun || run) ||\n (resultOnly && !run) ||\n (buttonOnly && !canRun)\n ) {\n return null;\n }\n return (\n <div\n className={buttonOnly ? \"shrink-0\" : \"shrink-0 space-y-2 border-t p-2\"}\n >\n {canRun && !resultOnly && (\n <Tooltip>\n <TooltipTrigger\n render={\n <Button\n className=\"hover:bg-accent h-fit px-2 py-1.5 [&_svg]:size-[18px]\"\n disabled={disabled}\n\n onClick={() => {\n startEventAction(async () => {\n await onAction({\n message: `Run the saved code using runCodeDocument with documentId \"${documentId}\" and revisionId \"${revisionId}\". Execute exactly this revision once. Do not edit the document or substitute codeExecution. Report the result briefly.`,\n modelId: config.ai.tools.code.edits,\n });\n });\n }}\n size=\"sm\"\n variant=\"outline\"\n >\n <Play size={18} /> Run\n </Button>\n }\n />\n <TooltipContent>Execute code</TooltipContent>\n </Tooltip>\n )}\n {run && !buttonOnly && (\n <details key={run.part.toolCallId} open>\n <summary className=\"cursor-pointer text-sm\">Execution result</summary>\n <div\n className=\"max-h-64 overflow-auto pt-2\"\n data-testid=\"document-run-result\"\n >\n <EveDocumentRunResult part={run.part} />\n </div>\n </details>\n )}\n </div>\n );\n};\n",
|
|
34
|
+
"type": "registry:file",
|
|
35
|
+
"target": "~/tools/chatjs/saved-code-execution/document.tsx"
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
"path": "src/tools/saved-code-execution/document-runs.ts",
|
|
39
|
+
"content": "import type { EveDynamicToolPart, EveMessage } from \"eve/client\";\n\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\n\nimport { documentExecutionInput } from \"./schemas\";\n\n/** Project the latest execution of this revision from the native transcript.\n * @param {readonly ReadonlyNativeSurface<Pick<EveMessage, \"id\" | \"parts\">>[]} messages Transcript identifiers and parts read newest-first without changing the matched part reference.\n * @param {string} documentId Document identity accepted by the execution tool.\n * @param {string} revisionId Revision identity required to match that run.\n * @returns {{ messageId: string; part: EveDynamicToolPart } | undefined} The newest matching tool part by original reference, or no result when that revision has not run.\n */\nexport const latestDocumentRun = (\n messages: readonly ReadonlyNativeSurface<Pick<EveMessage, \"id\" | \"parts\">>[],\n documentId: string,\n revisionId: string\n): { messageId: string; part: EveDynamicToolPart } | undefined => {\n for (const message of messages.toReversed()) {\n for (const part of message.parts.toReversed()) {\n if (part.type === \"dynamic-tool\" && part.toolName === \"runCodeDocument\") {\n const input = documentExecutionInput.safeParse(part.input);\n if (\n input.success &&\n input.data.documentId === documentId &&\n input.data.revisionId === revisionId\n ) {\n return { messageId: message.id, part };\n }\n }\n }\n }\n return undefined;\n};\n",
|
|
40
|
+
"type": "registry:file",
|
|
41
|
+
"target": "~/tools/chatjs/saved-code-execution/document-runs.ts"
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
"path": "src/tools/saved-code-execution/renderer.tsx",
|
|
45
|
+
"content": "\"use client\";\nimport { documentExecutionInput, eveCodeExecutionResult } from \"./schemas\";\nimport { CodeExecutionChart } from \"@/tools/chatjs/_shared/code-execution/code-execution-chart\";\nimport React from \"react\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport type { z as Zod } from \"zod\";\nimport { defineToolRenderer } from \"@/lib/ai/define-tool-renderer\";\n\ntype SavedCodeInput = Zod.output<typeof documentExecutionInput>;\ntype SavedCodeOutput = Zod.output<typeof eveCodeExecutionResult> &\n SavedCodeInput;\ntype SavedCodeTool = { toolCallId: string } & (\n | {\n state: \"input-streaming\";\n input?: Partial<SavedCodeInput>;\n output?: never;\n }\n | { state: \"input-available\"; input: SavedCodeInput; output?: never }\n | {\n state: \"output-available\";\n input: SavedCodeInput;\n output: SavedCodeOutput;\n }\n);\ntype SavedCodeRenderProps = ReadonlyNativeSurface<{\n isReadonly: boolean;\n messageId: string;\n tool: SavedCodeTool;\n}>;\n\nexport const SavedCodeRenderer = defineToolRenderer({\n inputSchema: documentExecutionInput,\n outputSchema: eveCodeExecutionResult.extend(documentExecutionInput.shape),\n render: ({ tool }: SavedCodeRenderProps) => {\n if (tool.state === \"output-available\") {\n return (\n <div className=\"space-y-3\">\n <p>{tool.output.message}</p>\n <CodeExecutionChart value={tool.output.chart} />\n </div>\n );\n }\n return <output>Running saved code…</output>;\n },\n});\n",
|
|
46
|
+
"type": "registry:file",
|
|
47
|
+
"target": "~/tools/chatjs/saved-code-execution/renderer.tsx"
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
"path": "src/tools/saved-code-execution/result.tsx",
|
|
51
|
+
"content": "\"use client\";\nimport type { EveMessagePart } from \"eve/client\";\nimport React from \"react\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { eveCodeExecutionResult } from \"./schemas\";\nimport { toolOutputSchema } from \"@/lib/eve/tool-result\";\nimport { CodeExecutionChart } from \"@/tools/chatjs/_shared/code-execution/code-execution-chart\";\n\nexport const EveDocumentRunResult = ({\n part,\n}: ReadonlyNativeSurface<{\n part: Extract<EveMessagePart, { type: \"dynamic-tool\" }>;\n}>): React.JSX.Element => {\n if (part.state === \"output-error\") {\n return <p role=\"alert\">{part.errorText}</p>;\n }\n if (part.state === \"output-denied\") {\n return <p>Document execution declined.</p>;\n }\n if (part.state !== \"output-available\") {\n return <output>Running saved code…</output>;\n }\n const result = toolOutputSchema.safeParse(part.output);\n if (!result.success) {\n return <p role=\"alert\">This tool result could not be displayed.</p>;\n }\n if (result.data.status === \"error\") {\n return <p role=\"alert\">{result.data.error}</p>;\n }\n const output = eveCodeExecutionResult.safeParse(result.data.output);\n if (output.success) {\n return (\n <div className=\"space-y-3\">\n <p>{output.data.message}</p>\n <CodeExecutionChart value={output.data.chart} />\n </div>\n );\n }\n return <p role=\"alert\">This saved-code result could not be displayed.</p>;\n};\n",
|
|
52
|
+
"type": "registry:file",
|
|
53
|
+
"target": "~/tools/chatjs/saved-code-execution/result.tsx"
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
"path": "dist/source/saved-code-execution.json",
|
|
57
|
+
"content": "{\n \"documentRunExport\": \"EveDocumentRun\",\n \"envRequirements\": [],\n \"id\": \"saved-code-execution\",\n \"kind\": \"tool\",\n \"requiresTools\": [\"createCodeDocument\", \"readDocument\", \"codeExecution\"],\n \"tools\": [\n { \"rendererExport\": \"SavedCodeRenderer\", \"toolExport\": \"runCodeDocument\" }\n ],\n \"contractVersion\": 2,\n \"uiBase\": \"base\"\n}\n",
|
|
58
|
+
"type": "registry:file",
|
|
59
|
+
"target": "~/tools/chatjs/saved-code-execution/chatjs.json"
|
|
60
|
+
}
|
|
61
|
+
],
|
|
62
|
+
"meta": {
|
|
63
|
+
"chatjs": {
|
|
64
|
+
"documentRunExport": "EveDocumentRun",
|
|
65
|
+
"envRequirements": [],
|
|
66
|
+
"id": "saved-code-execution",
|
|
67
|
+
"kind": "tool",
|
|
68
|
+
"requiresTools": [
|
|
69
|
+
"createCodeDocument",
|
|
70
|
+
"readDocument",
|
|
71
|
+
"codeExecution"
|
|
72
|
+
],
|
|
73
|
+
"tools": [
|
|
74
|
+
{
|
|
75
|
+
"rendererExport": "SavedCodeRenderer",
|
|
76
|
+
"toolExport": "runCodeDocument"
|
|
77
|
+
}
|
|
78
|
+
],
|
|
79
|
+
"contractVersion": 2,
|
|
80
|
+
"uiBase": "base"
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
"type": "registry:item"
|
|
84
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "scaleway-storage",
|
|
4
|
+
"title": "Scaleway Object Storage",
|
|
5
|
+
"description": "Scaleway Object Storage via the S3-compatible API. Endpoint derived from the region code (fr-par, nl-ams, pl-waw).",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"files-sdk@2.5.0",
|
|
8
|
+
"@aws-sdk/client-s3@^3.1079.0",
|
|
9
|
+
"@aws-sdk/s3-presigned-post@^3.700.0",
|
|
10
|
+
"@aws-sdk/s3-request-presigner@^3.700.0"
|
|
11
|
+
],
|
|
12
|
+
"files": [
|
|
13
|
+
{
|
|
14
|
+
"path": "src/storage/scaleway/storage-provider.ts",
|
|
15
|
+
"content": "export { scaleway as createStorageAdapter } from \"files-sdk/scaleway\";\n",
|
|
16
|
+
"type": "registry:file",
|
|
17
|
+
"target": "~/lib/storage-provider.ts"
|
|
18
|
+
}
|
|
19
|
+
],
|
|
20
|
+
"meta": {
|
|
21
|
+
"chatjs": {
|
|
22
|
+
"configKeys": [
|
|
23
|
+
"bucket",
|
|
24
|
+
"region"
|
|
25
|
+
],
|
|
26
|
+
"contractVersion": 1,
|
|
27
|
+
"envRequirements": [
|
|
28
|
+
{
|
|
29
|
+
"description": "Scaleway Object Storage credentials",
|
|
30
|
+
"options": [
|
|
31
|
+
[
|
|
32
|
+
"SCW_ACCESS_KEY",
|
|
33
|
+
"SCW_SECRET_KEY"
|
|
34
|
+
]
|
|
35
|
+
]
|
|
36
|
+
}
|
|
37
|
+
],
|
|
38
|
+
"id": "scaleway",
|
|
39
|
+
"kind": "storage",
|
|
40
|
+
"optionalEnv": []
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
"type": "registry:item"
|
|
44
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "search",
|
|
4
|
+
"description": "Search chat titles and conversation text",
|
|
5
|
+
"dependencies": [
|
|
6
|
+
"@tanstack/react-query@^5.104.1",
|
|
7
|
+
"@trpc/server@^11.1.2",
|
|
8
|
+
"drizzle-orm@^0.45.1",
|
|
9
|
+
"lucide-react@0.553.0"
|
|
10
|
+
],
|
|
11
|
+
"files": [
|
|
12
|
+
{
|
|
13
|
+
"path": "src/plugins/search/src/backfill.ts",
|
|
14
|
+
"content": "import { and, asc, eq, gt } from \"drizzle-orm\";\n\nimport { assertEveConfigured } from \"@/lib/eve/server\";\nimport { backfillEveSearchConversation } from \"@/plugins/search/search-backfill\";\nimport { db } from \"@/lib/db/client\";\nimport { eveConversation } from \"@/lib/db/schema\";\n\nconst DATABASE_SHUTDOWN_TIMEOUT_SECONDS = 5;\nconst MILLISECONDS_PER_SECOND = 1000;\nconst DATABASE_SHUTDOWN_TIMEOUT_MILLISECONDS =\n DATABASE_SHUTDOWN_TIMEOUT_SECONDS * MILLISECONDS_PER_SECOND;\nconst SHUTDOWN_TERMINATION_GRACE_MILLISECONDS = 250;\nconst SHUTDOWN_OUTPUT_FLUSH_TIMEOUT_MILLISECONDS = 250;\nconst BACKFILL_BATCH_SIZE = 50;\nconst FAILURE_EXIT_STATUS = 1;\nconst SUCCESS_EXIT_STATUS = 0;\nconst INITIAL_PROGRESS_COUNT = 0;\nconst BACKFILL_COUNT_INCREMENT = 1;\nconst LAST_BATCH_INDEX = -1;\nconst INITIAL_BACKFILL_CURSOR = \"\";\n\ntype DatabaseShutdownOutcome =\n | { kind: \"complete\" }\n | { error: unknown; kind: \"failure\" };\n\nconst createDelay = (\n milliseconds: number\n): { cancel: () => void; promise: Promise<boolean> } => {\n const delaySignal = Promise.withResolvers<boolean>();\n const timer = setTimeout(() => {\n delaySignal.resolve(true);\n }, milliseconds);\n return {\n cancel: () => {\n clearTimeout(timer);\n delaySignal.resolve(false);\n },\n promise: delaySignal.promise,\n };\n};\n\nconst endDatabaseClient = async (): Promise<DatabaseShutdownOutcome> => {\n try {\n await db.$client.end({ timeout: DATABASE_SHUTDOWN_TIMEOUT_SECONDS });\n return { kind: \"complete\" };\n } catch (error) {\n return { error, kind: \"failure\" };\n }\n};\n\ntype BackfillConversation = Pick<\n typeof eveConversation.$inferSelect,\n \"id\" | \"ownerId\" | \"sessionId\"\n>;\n\nconst selectNextBatch = async (\n cursor: string | undefined\n): Promise<BackfillConversation[]> => {\n const query = db\n .select({\n id: eveConversation.id,\n ownerId: eveConversation.ownerId,\n sessionId: eveConversation.sessionId,\n })\n .from(eveConversation);\n if (typeof cursor === \"string\" && cursor !== \"\") {\n return await query\n .where(\n and(eq(eveConversation.state, \"bound\"), gt(eveConversation.id, cursor))\n )\n .orderBy(asc(eveConversation.id))\n .limit(BACKFILL_BATCH_SIZE);\n }\n return await query\n .where(eq(eveConversation.state, \"bound\"))\n .orderBy(asc(eveConversation.id))\n .limit(BACKFILL_BATCH_SIZE);\n};\n\nconst main = async (): Promise<number> => {\n assertEveConfigured();\n let cursor = INITIAL_BACKFILL_CURSOR;\n let indexed = INITIAL_PROGRESS_COUNT;\n let failed = INITIAL_PROGRESS_COUNT;\n while (true) {\n // oxlint-disable-next-line no-await-in-loop -- The next query uses the cursor advanced only after the previous batch has finished indexing.\n const batch = await selectNextBatch(cursor);\n if (batch.length === INITIAL_PROGRESS_COUNT) {\n break;\n }\n for (const conversation of batch) {\n if (conversation.sessionId !== null && conversation.sessionId !== \"\") {\n try {\n // oxlint-disable-next-line no-await-in-loop -- Load and index one conversation snapshot at a time to bound memory and database work.\n await backfillEveSearchConversation(\n conversation.ownerId,\n conversation.id,\n conversation.sessionId\n );\n indexed += BACKFILL_COUNT_INCREMENT;\n } catch (error) {\n failed += BACKFILL_COUNT_INCREMENT;\n console.error(\n `Search backfill failed for conversation ${conversation.id}; rerun to retry.`,\n error\n );\n }\n }\n }\n cursor = batch[batch.length + LAST_BATCH_INDEX].id;\n console.info(`Search backfill: ${indexed} indexed, ${failed} failed.`);\n }\n if (failed > INITIAL_PROGRESS_COUNT) {\n return FAILURE_EXIT_STATUS;\n }\n return SUCCESS_EXIT_STATUS;\n};\n\nconst flushOutputBeforeForcedExit = async (): Promise<void> => {\n const stdoutFlushed = Promise.withResolvers<boolean>();\n const stderrFlushed = Promise.withResolvers<boolean>();\n process.stdout.write(\"\", () => {\n stdoutFlushed.resolve(true);\n });\n process.stderr.write(\"\", () => {\n stderrFlushed.resolve(true);\n });\n const flushDeadline = createDelay(SHUTDOWN_OUTPUT_FLUSH_TIMEOUT_MILLISECONDS);\n await Promise.race([\n Promise.all([stdoutFlushed.promise, stderrFlushed.promise]),\n flushDeadline.promise,\n ]);\n flushDeadline.cancel();\n};\n\nconst shutdownDatabase = async (exitStatus: number): Promise<number> => {\n const deadline = createDelay(DATABASE_SHUTDOWN_TIMEOUT_MILLISECONDS);\n const shutdown = endDatabaseClient();\n const firstOutcome = await Promise.race([shutdown, deadline.promise]);\n if (typeof firstOutcome === \"boolean\") {\n const terminationGrace = createDelay(\n SHUTDOWN_TERMINATION_GRACE_MILLISECONDS\n );\n const finalShutdownOutcome = await Promise.race([\n shutdown,\n terminationGrace.promise,\n ]);\n if (\n typeof finalShutdownOutcome === \"object\" &&\n finalShutdownOutcome.kind === \"failure\"\n ) {\n console.error(\n \"Search backfill database shutdown failed.\",\n finalShutdownOutcome.error\n );\n }\n console.error(\n \"Search backfill database shutdown timed out; forcing process exit.\"\n );\n await flushOutputBeforeForcedExit();\n process.exit(FAILURE_EXIT_STATUS);\n }\n deadline.cancel();\n if (firstOutcome.kind === \"failure\") {\n console.error(\n \"Search backfill database shutdown failed.\",\n firstOutcome.error\n );\n return FAILURE_EXIT_STATUS;\n }\n return exitStatus;\n};\nvoid (async (): Promise<void> => {\n let exitStatus = SUCCESS_EXIT_STATUS;\n try {\n exitStatus = await main();\n } catch (error) {\n console.error(\n \"Search backfill could not start. Check the database and EVE configuration.\",\n error\n );\n exitStatus = FAILURE_EXIT_STATUS;\n } finally {\n exitStatus = await shutdownDatabase(exitStatus);\n }\n process.exitCode = exitStatus;\n})();\n",
|
|
15
|
+
"type": "registry:file",
|
|
16
|
+
"target": "~/plugins/search/backfill.ts"
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
"path": "src/plugins/search/src/chat.ts",
|
|
20
|
+
"content": "import { inArray } from \"drizzle-orm\";\nimport type { ChatServerIntegration } from \"@/lib/chat-plugin-contracts\";\nimport { eveSearchText } from \"./search-schema\";\n\nexport const searchChat = {\n onDeleteConversations: async (tx, { conversationIds }) => {\n if (conversationIds.length === 0) {\n return;\n }\n await tx\n .delete(eveSearchText)\n .where(inArray(eveSearchText.conversationId, [...conversationIds]));\n },\n} satisfies ChatServerIntegration;\n",
|
|
21
|
+
"type": "registry:file",
|
|
22
|
+
"target": "~/plugins/search/chat.ts"
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
"path": "src/plugins/search/src/client-plugin.ts",
|
|
26
|
+
"content": "import type { ChatClientPlugin } from \"@/lib/plugin-contracts\";\nimport { EveSearchChats } from \"./search-chats\";\n\nexport const searchClient = () =>\n ({\n id: \"search\",\n chat: { SidebarHeader: EveSearchChats },\n }) satisfies ChatClientPlugin;\n",
|
|
27
|
+
"type": "registry:file",
|
|
28
|
+
"target": "~/plugins/search/client-plugin.ts"
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
"path": "src/plugins/search/src/router.ts",
|
|
32
|
+
"content": "import { TRPCError } from \"@trpc/server\";\nimport { z } from \"zod\";\nimport { eveOwnedProcedure } from \"@/trpc/eve-owned-procedure\";\nimport { createTRPCRouter } from \"@/trpc/init\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { MAX_SEARCH_QUERY_LENGTH } from \"./search-text\";\nimport { searchEveConversations } from \"./search-queries\";\n\nconst MAX_OWNER_SCOPE_LENGTH = 128;\nexport const searchRouter = createTRPCRouter({\n query: eveOwnedProcedure\n .input(\n z.object({\n cursor: z\n .object({\n id: z.uuid(),\n rank: z.number().nonnegative(),\n updatedAt: z.iso.datetime(),\n })\n .nullish(),\n ownerScope: z.string().nonempty().max(MAX_OWNER_SCOPE_LENGTH),\n search: z.string().trim().nonempty().max(MAX_SEARCH_QUERY_LENGTH),\n })\n )\n .query(\n async ({\n ctx,\n input,\n }: {\n readonly ctx: { readonly eveOwnerId: string };\n readonly input: ReadonlyNativeSurface<{\n ownerScope: string;\n search: string;\n cursor?:\n | { id: string; rank: number; updatedAt: string }\n | null\n | undefined;\n }>;\n }) => {\n if (input.ownerScope !== ctx.eveOwnerId) {\n throw new TRPCError({ code: \"FORBIDDEN\" });\n }\n return await searchEveConversations(ctx.eveOwnerId, input);\n }\n ),\n});\n",
|
|
33
|
+
"type": "registry:file",
|
|
34
|
+
"target": "~/plugins/search/router.ts"
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
"path": "src/plugins/search/src/search-backfill.ts",
|
|
38
|
+
"content": "import { Client } from \"eve/client\";\n\nimport { indexEveSearchText } from \"@/plugins/search/search-queries\";\n\nimport { getEveConnectionOptions } from \"@/lib/eve/connection-options\";\nimport type { EveSearchText } from \"./search-text\";\nimport { eveEventSearchText } from \"./search-text\";\n\nconst SEARCH_SNAPSHOT_TIMEOUT_MS = 30_000;\nconst SEARCH_INDEX_BATCH_SIZE = 100;\n\n/**\n * Recover from durable events, including text omitted from the bounded live retry buffer.\n * @param {string} ownerId Owner whose EVE credentials and search index receive the recovered text.\n * @param {string} conversationId Conversation receiving idempotent event and seed search entries.\n * @param {string} sessionId Durable EVE session whose snapshot supplies the history.\n * @returns {Promise<void>} Resolves after every batch is indexed; snapshot and index failures reject for a later retry.\n */\nexport const backfillEveSearchConversation = async (\n ownerId: string,\n conversationId: string,\n sessionId: string\n): Promise<void> => {\n const client = new Client(getEveConnectionOptions(ownerId));\n const snapshot = await client.sessions\n .attach(sessionId)\n .snapshot({ signal: AbortSignal.timeout(SEARCH_SNAPSHOT_TIMEOUT_MS) });\n let batch: EveSearchText[] = [];\n for (const event of snapshot.events) {\n for (const entry of eveEventSearchText(event)) {\n batch.push(entry);\n if (batch.length === SEARCH_INDEX_BATCH_SIZE) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- Flush SEARCH_INDEX_BATCH_SIZE text entries before continuing the snapshot so a failed batch stops later writes and buffered indexing work stays bounded.\n await indexEveSearchText(ownerId, conversationId, batch);\n batch = [];\n }\n }\n }\n await indexEveSearchText(ownerId, conversationId, batch);\n};\n",
|
|
39
|
+
"type": "registry:file",
|
|
40
|
+
"target": "~/plugins/search/search-backfill.ts"
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
"path": "src/plugins/search/src/search-chats.tsx",
|
|
44
|
+
"content": "\"use client\";\n\nimport { hasText } from \"@/components/text-value\";\n\nimport { useInfiniteQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { SearchIcon } from \"lucide-react\";\nimport { createPortal } from \"react-dom\";\nimport { useRouter } from \"next/navigation\";\nimport React, { useEffect, useState, useSyncExternalStore } from \"react\";\nimport type { JSX as ReactJSX } from \"react\";\n\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogOverlay,\n DialogTitle,\n DialogTrigger,\n} from \"@/components/ui/dialog\";\nimport { SidebarMenuButton, useSidebar } from \"@/components/ui/sidebar\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { useTRPC } from \"@/trpc/react\";\n\nimport { EveSearchResultsView } from \"./search-results-view\";\nimport { useDebouncedSearch } from \"./use-debounced-search\";\n\nconst SearchResults = ({\n onSelect,\n onClose,\n ownerId,\n}: {\n readonly onSelect: (id: string) => void;\n readonly onClose: () => void;\n readonly ownerId: string;\n}): ReactJSX.Element => {\n const trpc = useTRPC();\n const queryClient = useQueryClient();\n const [query, setQuery] = useState(\"\");\n const search = useDebouncedSearch(query);\n const history = useInfiniteQuery(\n trpc.eve.list.infiniteQueryOptions(\n { ownerScope: ownerId },\n {\n enabled: !query.trim(),\n getNextPageParam: (page: {\n readonly nextCursor: {\n readonly isPinned: boolean;\n readonly updatedAt: string;\n readonly id: string;\n } | null;\n }) => page.nextCursor,\n refetchOnWindowFocus: false,\n staleTime: 0,\n }\n )\n );\n const results = useInfiniteQuery(\n trpc.search.query.infiniteQueryOptions(\n { ownerScope: ownerId, search },\n {\n enabled: Boolean(search) && search === query.trim(),\n getNextPageParam: (page: {\n readonly nextCursor: {\n readonly rank: number;\n readonly updatedAt: string;\n readonly id: string;\n } | null;\n }) => page.nextCursor,\n refetchOnWindowFocus: false,\n staleTime: 0,\n trpc: { abortOnUnmount: true },\n }\n )\n );\n const isSearch = Boolean(query.trim());\n const active = isSearch ? results : history;\n const changingQuery = query.trim() !== search;\n const waiting =\n changingQuery ||\n active.isPending ||\n (active.isFetching && !active.isFetchingNextPage);\n const failed = !changingQuery && active.isError;\n const recentItems =\n history.data?.pages\n .flatMap(\n (\n page: ReadonlyNativeSurface<\n NonNullable<typeof history.data>[\"pages\"][number]\n >\n ) => page.items\n )\n .filter(\n (item: {\n readonly state: \"creating\" | \"bound\" | \"uncertain\" | \"deleting\";\n }) => item.state === \"bound\"\n )\n .map(\n (\n item: ReadonlyNativeSurface<\n NonNullable<typeof history.data>[\"pages\"][number][\"items\"][number]\n >\n ) => ({\n ...item,\n conversationId: item.conversationId ?? item.id,\n excerpt: \"\",\n })\n ) ?? [];\n const matchedItems =\n results.data?.pages.flatMap(\n (\n page: ReadonlyNativeSurface<\n NonNullable<typeof results.data>[\"pages\"][number]\n >\n ) => page.items\n ) ?? [];\n const currentItems = isSearch ? matchedItems : recentItems;\n const items = waiting || failed ? [] : currentItems;\n const seen = new Set<string>();\n const distinct = items.filter((item: { readonly id: string }) => {\n if (seen.has(item.id)) {\n return false;\n }\n seen.add(item.id);\n return true;\n });\n return (\n <EveSearchResultsView\n onClose={onClose}\n query={query}\n onQueryChange={(value) => {\n if (value.trim() !== query.trim()) {\n // Cancel immediately, not after the debounce: an old response must\n // never publish while the user is already typing a different query.\n void queryClient.cancelQueries({\n exact: true,\n queryKey: trpc.search.query.infiniteQueryKey({\n ownerScope: ownerId,\n search,\n }),\n });\n }\n setQuery(value);\n }}\n searching={waiting}\n pending={waiting && !failed}\n error={failed}\n items={distinct}\n isSearch={isSearch}\n onSelect={onSelect}\n\n onRetry={() => {\n void active.refetch();\n }}\n hasMore={!waiting && !failed && active.hasNextPage}\n loadingMore={active.isFetchingNextPage}\n\n onLoadMore={() => {\n void active.fetchNextPage();\n }}\n disableLoadMore={active.isFetching || changingQuery}\n />\n );\n};\n\nconst searchShortcut = () => {\n if (navigator.platform.toUpperCase().includes(\"MAC\")) {\n return \"Cmd+K\";\n }\n return \"Ctrl+K\";\n};\n\nconst unsubscribePlatform = (): null => null;\nconst subscribePlatform = () => unsubscribePlatform;\n\nconst serverShortcut = (): string => \"Ctrl+K\";\n\nexport const EveSearchChats = ({\n ownerId,\n}: {\n readonly ownerId?: string;\n}): ReactJSX.Element => {\n const shortcut = useSyncExternalStore(\n subscribePlatform,\n searchShortcut,\n serverShortcut\n );\n const [open, setOpen] = useState(false);\n const router = useRouter();\n const { isMobile, openMobile, setOpenMobile } = useSidebar();\n useEffect(() => {\n const down = (\n event: Readonly<\n Pick<KeyboardEvent, \"key\" | \"metaKey\" | \"ctrlKey\" | \"preventDefault\">\n >\n ): void => {\n if (event.key.toLowerCase() === \"k\" && (event.metaKey || event.ctrlKey)) {\n event.preventDefault();\n setOpen((value) => !value);\n }\n };\n document.addEventListener(\"keydown\", down);\n return (): void => {\n document.removeEventListener(\"keydown\", down);\n };\n }, []);\n return (\n <Dialog open={open} onOpenChange={setOpen}>\n <DialogTrigger render={<SidebarMenuButton tooltip=\"Search chats\" />}>\n <SearchIcon className=\"size-4\" />\n <span>Search chats</span>\n <span className=\"text-muted-foreground ml-auto text-xs\">\n {shortcut}\n </span>\n </DialogTrigger>\n {/* Base UI omits nested backdrops. Search must also cover its parent sheet. */}\n {open &&\n isMobile &&\n openMobile &&\n createPortal(<DialogOverlay forceRender />, document.body)}\n <DialogContent\n className=\"overflow-hidden p-0 max-md:z-[51]\"\n showCloseButton={!hasText(ownerId)}\n >\n <DialogHeader className=\"sr-only\">\n <DialogTitle>Search chats</DialogTitle>\n <DialogDescription>\n Search your conversation history.\n </DialogDescription>\n </DialogHeader>\n {open && !hasText(ownerId) && (\n <p className=\"text-muted-foreground p-4 text-sm\">\n Start a chat to see your conversation history.\n </p>\n )}\n {open && hasText(ownerId) && (\n <SearchResults\n key={ownerId}\n ownerId={ownerId}\n onClose={() => {\n setOpen(false);\n }}\n onSelect={(id) => {\n setOpen(false);\n setOpenMobile(false);\n router.push(`/chat/${id}`);\n }}\n />\n )}\n </DialogContent>\n </Dialog>\n );\n};\n",
|
|
45
|
+
"type": "registry:file",
|
|
46
|
+
"target": "~/plugins/search/search-chats.tsx"
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
"path": "src/plugins/search/src/search-hook.ts",
|
|
50
|
+
"content": "import { isGuestSession } from \"@/lib/eve/session-identity\";\nimport type { EveSearchText } from \"./search-text\";\nimport type { HookContext } from \"eve/hooks\";\nimport { defineHook } from \"eve/hooks\";\nimport { defineState } from \"eve/context\";\n\nimport { indexEveSearchText } from \"./search-queries\";\nimport { resolveEveConversationScope } from \"@/lib/eve/conversation-scope\";\nimport { backfillEveSearchConversation } from \"./search-backfill\";\nimport { eveEventSearchText } from \"./search-text\";\n\nconst maxPendingEntries = 256;\nconst maxPendingCharacters = 256_000;\n\nconst needsRecovery = defineState(\"chatjs.search-recovery\", () => false);\nconst pending = defineState<EveSearchText[]>(\"chatjs.search-prefix\", () => []);\n\nexport default defineHook({\n events: {\n \"*\": async (\n event: Parameters<typeof eveEventSearchText>[0],\n context: Readonly<{\n session: Readonly<\n Pick<HookContext[\"session\"], \"id\" | \"auth\" | \"parent\">\n >;\n }>\n ) => {\n if (isGuestSession(context.session)) {\n return;\n }\n if (context.session.parent) {\n return;\n }\n const entries = eveEventSearchText(event);\n const restoring = event.type === \"history.seeded\";\n if (!restoring && event.type !== \"turn.started\" && entries.length === 0) {\n return;\n }\n let omitted = 0;\n pending.update((current: readonly EveSearchText[]) => {\n const retained: EveSearchText[] = [];\n const keys = new Set<string>();\n let characters = 0;\n for (const batch of [current, entries]) {\n for (const entry of batch) {\n if (keys.has(entry.key)) {\n continue;\n }\n if (\n retained.length >= maxPendingEntries ||\n characters + entry.text.length > maxPendingCharacters\n ) {\n omitted += 1;\n continue;\n }\n keys.add(entry.key);\n retained.push(entry);\n characters += entry.text.length;\n }\n }\n return retained;\n });\n if (omitted) {\n needsRecovery.update(() => true);\n // Recover from durable EVE events after binding; manual backfill is a fallback.\n console.error(\n \"Search retry buffer overflow; automatic snapshot recovery queued. Run plugins/search/backfill.ts if retries keep failing.\",\n {\n omitted,\n sessionId: context.session.id,\n }\n );\n }\n // History can arrive before the native creation receipt binds the session.\n if (restoring) {\n return;\n }\n if (pending.get().length === 0 && !needsRecovery.get()) {\n return;\n }\n try {\n const scope = await resolveEveConversationScope(\n context.session.auth.initiator?.principalId,\n context.session.id,\n AbortSignal.timeout(10_000),\n context.session.auth.initiator?.attributes.chatjsReservationId\n );\n if (needsRecovery.get()) {\n // Hook events are already durable, so the snapshot includes the current\n // message as well as any restored history omitted from the retry buffer.\n await backfillEveSearchConversation(\n scope.ownerId,\n scope.conversationId,\n context.session.id\n );\n needsRecovery.update(() => false);\n } else {\n await indexEveSearchText(\n scope.ownerId,\n scope.conversationId,\n pending.get()\n );\n }\n pending.update(() => []);\n } catch (error) {\n // Projection failures must not turn a successful chat into turn.failed.\n // Keep the pending text for the next message or turn; backfill also repairs it.\n console.error(\n \"Search indexing failed; will retry on the next chat event.\",\n {\n name: error instanceof Error ? error.name : \"UnknownError\",\n stack:\n error instanceof Error\n ? error.stack?.split(\"\\n\").slice(1).join(\"\\n\")\n : undefined,\n }\n );\n }\n },\n },\n});\n",
|
|
51
|
+
"type": "registry:file",
|
|
52
|
+
"target": "~/plugins/search/search-hook.ts"
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
"path": "src/plugins/search/src/search-queries.ts",
|
|
56
|
+
"content": "import { isNonEmptyString } from \"@/lib/is-non-empty-string\";\n\nimport { and, eq, sql } from \"drizzle-orm\";\nimport { z } from \"zod\";\n\nimport type { EveSearchText } from \"@/plugins/search/search-text\";\nimport { MAX_SEARCH_QUERY_LENGTH } from \"@/plugins/search/search-text\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\n\nimport { db } from \"@/lib/db/client\";\nimport { eveConversation } from \"@/lib/db/schema\";\nimport { eveSearchText } from \"./search-schema\";\n\nconst SEARCH_CHUNK_LENGTH = 8000;\nconst SEARCH_WRITE_BATCH_SIZE = 100;\nconst SEARCH_PAGE_SIZE = 20;\nconst QUOTE_PAIR_SIZE = 2;\nconst UNQUOTED_SEGMENT_REMAINDER = 1;\nconst FIRST_INDEX = 0;\nconst LAST_ITEM_OFFSET = -1;\nconst EMPTY_RESULT_COUNT = 0;\n\ntype SearchTransaction = Readonly<Pick<typeof db, \"select\" | \"insert\">>;\nconst splitSearchChunks = (\n entries: readonly EveSearchText[]\n): EveSearchText[] =>\n entries.flatMap((entry: EveSearchText) => {\n const result: EveSearchText[] = [];\n for (\n let offset = FIRST_INDEX;\n offset < entry.text.length;\n offset += SEARCH_CHUNK_LENGTH\n ) {\n result.push({\n key: `${entry.key}:${offset}`,\n text: entry.text.slice(\n offset,\n offset + SEARCH_CHUNK_LENGTH + MAX_SEARCH_QUERY_LENGTH\n ),\n });\n }\n return result;\n });\n\n/**\n * Writes search chunks only while the owner’s conversation binding is active.\n * The binding lock serializes the write with deletion, and existing keys are\n * updated when their indexed text changes.\n * @param {SearchTransaction} tx Transaction shared with the caller’s conversation update.\n * @param {string} ownerId Owner whose active conversation is being indexed.\n * @param {string} conversationId Bound conversation that owns the chunks.\n * @param {readonly EveSearchText[]} entries Search keys and text chunks to persist.\n */\nconst writeEveSearchText = async (\n tx: SearchTransaction,\n ownerId: string,\n conversationId: string,\n entries: readonly EveSearchText[]\n): Promise<void> => {\n const [conversation] = await tx\n .select({ id: eveConversation.id })\n .from(eveConversation)\n .where(\n and(\n eq(eveConversation.id, conversationId),\n eq(eveConversation.ownerId, ownerId),\n eq(eveConversation.state, \"bound\")\n )\n )\n .for(\"update\");\n const hasConversation = Boolean(conversation);\n if (!hasConversation) {\n return;\n }\n // Bound vectors and insert batches even for unusually large pasted messages.\n const chunks = splitSearchChunks(entries);\n for (\n let index = FIRST_INDEX;\n index < chunks.length;\n index += SEARCH_WRITE_BATCH_SIZE\n ) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- Insert at most SEARCH_WRITE_BATCH_SIZE rows per query on the locked transaction; search-backfill awaits each committed batch before advancing.\n await tx\n .insert(eveSearchText)\n .values(\n chunks\n .slice(index, index + SEARCH_WRITE_BATCH_SIZE)\n .map((entry: EveSearchText) => ({\n ...entry,\n conversationId,\n ownerId,\n }))\n )\n .onConflictDoUpdate({\n set: { text: sql`excluded.text` },\n setWhere: sql`${eveSearchText.text} is distinct from excluded.text`,\n target: [eveSearchText.conversationId, eveSearchText.key],\n });\n }\n};\n\nconst indexEveSearchText = async (\n ownerId: string,\n conversationId: string,\n entries: readonly EveSearchText[]\n): Promise<void> => {\n if (entries.length > EMPTY_RESULT_COUNT) {\n await db.transaction(async (tx: SearchTransaction) => {\n await writeEveSearchText(tx, ownerId, conversationId, entries);\n });\n }\n};\n\nconst eveSearchResult = z.object({\n id: z.string(),\n conversationId: z.string(),\n title: z.string(),\n excerpt: z.string(),\n updatedAt: z.string(),\n rank: z.number(),\n highlightQuery: z.string(),\n highlightWords: z.record(z.string(), z.string()),\n});\ntype EveSearchResult = z.infer<typeof eveSearchResult>;\n\n// Modify only PostgreSQL's normalized final positive operand, never raw query syntax.\n// The leading boundary excludes !'negated' terms; closing groups remain intact.\nconst finalSearchOperand = \"(^|[ (|&])('[^']*(?:''[^']*)*')([)]*)$\";\nconst finalUnquotedWord = /[\\p{L}\\p{N}]$/u;\n\n// Read PostgreSQL's normalized operands so highlighting shares its tokenization,\n// quoting and prefix rules instead of interpreting the user's query again.\nconst queryToken = /!|[()]|'(?<term>(?:[^'\\\\]|\\\\.|'')*)'(?<prefix>:\\*)?/gu;\nconst escapedQueryCharacter = /\\\\(?<character>.)/gu;\nconst markedWord = /⟦(?<word>[^⟧]*)⟧/gu;\n\nconst highlightSearchExcerpt = (\n excerpt: string,\n query: string,\n words: Readonly<Record<string, string>>\n): string => {\n const terms: { prefix: boolean; text: string }[] = [];\n const groups = [false];\n let negateNext = false;\n for (const token of query.matchAll(queryToken)) {\n const negated = (groups.at(LAST_ITEM_OFFSET) ?? false) !== negateNext;\n if (token[FIRST_INDEX] === \"!\") {\n negateNext = !negateNext;\n continue;\n }\n if (token[FIRST_INDEX] === \"(\") {\n groups.push(negated);\n } else if (token[FIRST_INDEX] === \")\") {\n groups.pop();\n } else if (!negated && isNonEmptyString(token.groups?.term)) {\n terms.push({\n prefix: Boolean(token.groups.prefix),\n text: token.groups.term\n .replace(escapedQueryCharacter, \"$1\")\n .replaceAll(\"''\", \"'\"),\n });\n }\n negateNext = false;\n }\n return excerpt.replace(markedWord, (marked, word: string) => {\n const normalized = words[word] ?? word;\n const lengths = terms\n .filter(\n ({ prefix, text }: Readonly<{ prefix: boolean; text: string }>) => {\n if (prefix) {\n return normalized.startsWith(text);\n }\n return normalized === text;\n }\n )\n .map(\n ({ text }: Readonly<{ prefix: boolean; text: string }>) => text.length\n );\n const length = Math.max(EMPTY_RESULT_COUNT, ...lengths);\n\n if (length) {\n return `⟦${word.slice(FIRST_INDEX, length)}⟧${word.slice(length)}`;\n }\n return marked;\n });\n};\n\n/**\n * Searches an owner’s bound conversations and returns one ranked result per chat.\n * The cursor continues after a result using rank, update time, and chat ID.\n * @param {string} ownerId Owner whose private conversation and search text rows are queried.\n * @param {{ search: string; cursor?: { rank: number; updatedAt: string; id: string } | null }} input Search text and optional continuation cursor.\n * @returns {Promise<{ items: Array<Omit<EveSearchResult, \"highlightQuery\" | \"highlightWords\">>; nextCursor: { id: string; rank: number; updatedAt: string } | null }>} A page of highlighted chat results and a cursor when more results exist.\n */\nconst searchEveConversations = async (\n ownerId: string,\n input: {\n readonly search: string;\n readonly cursor?: {\n readonly rank: number;\n readonly updatedAt: string;\n readonly id: string;\n } | null;\n }\n): Promise<{\n items: Omit<EveSearchResult, \"highlightQuery\" | \"highlightWords\">[];\n nextCursor: { id: string; rank: number; updatedAt: string } | null;\n}> => {\n const { cursor } = input;\n const query = input.search.trim();\n const prefixLastWord =\n finalUnquotedWord.test(query) &&\n query.split('\"').length % QUOTE_PAIR_SIZE === UNQUOTED_SEGMENT_REMAINDER;\n const rows = await db.execute(sql`\n with parsed as (select websearch_to_tsquery('simple', ${query}) as terms),\n query as (\n select case when ${prefixLastWord}\n then to_tsquery('simple', regexp_replace(terms::text, ${finalSearchOperand}, ${String.raw`\\1\\2:*\\3`}))\n else terms end as terms\n from parsed\n ),\n matches as (\n select chat.id, branch.id as \"conversationId\", chat.title, chat.\"updatedAt\",\n 2 + ts_rank_cd(to_tsvector('simple', chat.title), query.terms) as rank,\n ''::text as body\n from \"EveChat\" chat cross join query\n join lateral (\n select id from \"EveConversation\"\n where \"chatId\" = chat.id and \"ownerId\" = ${ownerId} and state = 'bound'\n order by (id = chat.\"activeConversationId\") desc, \"createdAt\", id limit 1\n ) branch on true\n where chat.\"ownerId\" = ${ownerId} and to_tsvector('simple', chat.title) @@ query.terms\n union all\n select chat.id, branch.id, chat.title, chat.\"updatedAt\",\n ts_rank_cd(to_tsvector('simple', content.text), query.terms) as rank,\n content.text as body\n from \"EveSearchText\" content cross join query\n join \"EveConversation\" branch on branch.id = content.\"conversationId\" and branch.\"ownerId\" = ${ownerId} and branch.state = 'bound'\n join \"EveChat\" chat on chat.id = branch.\"chatId\" and chat.\"ownerId\" = ${ownerId}\n where content.\"ownerId\" = ${ownerId} and to_tsvector('simple', content.text) @@ query.terms\n ), best as (\n select distinct on (id) *, max(rank) over (partition by id) as \"chatRank\"\n from matches\n order by id, (body <> '') desc, rank desc, \"conversationId\", body\n ), headlines as (\n select id, \"conversationId\", title, query.terms::text as \"highlightQuery\",\n to_char(\"updatedAt\", 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') as \"updatedAt\",\n \"chatRank\"::double precision as rank,\n case when body = '' then '' else ts_headline('simple', body, query.terms,\n 'StartSel=⟦, StopSel=⟧, MaxWords=32, MinWords=12, MaxFragments=1') end as excerpt\n from best cross join query\n where ${\n cursor\n ? sql`\n \"chatRank\" < ${cursor.rank}::double precision\n or (\"chatRank\" = ${cursor.rank}::double precision and \"updatedAt\" < ${cursor.updatedAt}::timestamp)\n or (\"chatRank\" = ${cursor.rank}::double precision and \"updatedAt\" = ${cursor.updatedAt}::timestamp and id > ${cursor.id})\n `\n : sql`true`\n }\n order by \"chatRank\" desc, best.\"updatedAt\" desc, id\n limit 21\n )\n -- Use the same dictionary as the search vector, including its locale rules.\n select headlines.*, (\n select coalesce(jsonb_object_agg(word[1], (ts_lexize('simple', word[1]))[1]), '{}'::jsonb)\n from regexp_matches(excerpt, '⟦([^⟧]*)⟧', 'g') as word\n ) as \"highlightWords\"\n from headlines\n order by rank desc, \"updatedAt\" desc, id\n `);\n const items = z.array(eveSearchResult).parse(rows);\n const page = items\n .slice(FIRST_INDEX, SEARCH_PAGE_SIZE)\n .map(\n ({\n highlightQuery,\n highlightWords,\n ...item\n }: ReadonlyNativeSurface<EveSearchResult>) => ({\n ...item,\n excerpt: highlightSearchExcerpt(\n item.excerpt,\n highlightQuery,\n highlightWords\n ),\n })\n );\n const last = page.at(LAST_ITEM_OFFSET);\n return {\n items: page,\n nextCursor:\n items.length > SEARCH_PAGE_SIZE && last\n ? { id: last.id, rank: last.rank, updatedAt: last.updatedAt }\n : null,\n };\n};\nexport { indexEveSearchText, searchEveConversations, writeEveSearchText };\n",
|
|
57
|
+
"type": "registry:file",
|
|
58
|
+
"target": "~/plugins/search/search-queries.ts"
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
"path": "src/plugins/search/src/search-results-view.tsx",
|
|
62
|
+
"content": "\"use client\";\n\nimport { LoaderCircle, MessageSquare, X } from \"lucide-react\";\nimport React, { useRef } from \"react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport {\n Command,\n CommandGroup,\n CommandInput,\n CommandItem,\n CommandList,\n} from \"@/components/ui/command\";\nimport { Skeleton } from \"@/components/ui/skeleton\";\n\nconst highlightedExcerpt = (\n excerpt: string\n): (React.JSX.Element | string)[] => {\n let previousEnd = 0;\n const parts = [...excerpt.matchAll(/⟦[^⟧]*⟧/gu)].flatMap(\n (match: readonly string[] & Readonly<{ index: number }>) => {\n const start = match.index;\n const before = excerpt.slice(previousEnd, start);\n previousEnd = start + match[0].length;\n const mark = (\n <mark\n className=\"text-foreground bg-transparent font-medium\"\n key={start}\n >\n {match[0].slice(1, -1)}\n </mark>\n );\n if (before.length > 0) {\n return [before, mark];\n }\n return [mark];\n }\n );\n if (previousEnd < excerpt.length) {\n parts.push(excerpt.slice(previousEnd));\n }\n return parts;\n};\n\nexport const EveSearchResultsView = ({\n query,\n onQueryChange,\n onClose,\n searching,\n pending,\n error,\n items,\n isSearch,\n onSelect,\n onRetry,\n hasMore,\n loadingMore,\n onLoadMore,\n disableLoadMore,\n}: {\n readonly query: string;\n readonly onQueryChange: (query: string) => void;\n readonly onClose: () => void;\n readonly searching: boolean;\n readonly pending: boolean;\n readonly error: boolean;\n readonly items: readonly {\n readonly id: string;\n readonly conversationId: string;\n readonly title: string;\n readonly excerpt: string;\n }[];\n readonly isSearch: boolean;\n readonly onSelect: (id: string) => void;\n readonly onRetry: () => void;\n readonly hasMore: boolean;\n readonly loadingMore: boolean;\n readonly onLoadMore: () => void;\n readonly disableLoadMore: boolean;\n}): React.JSX.Element => {\n const inputRef = useRef<HTMLInputElement>(null);\n return (\n <Command\n shouldFilter={false}\n className=\"**:data-[slot=command-input-wrapper]:h-12\"\n >\n <div className=\"flex items-center pr-2\">\n <CommandInput\n ref={inputRef}\n aria-label=\"Search conversations\"\n className=\"min-w-0\"\n placeholder=\"Search titles and messages…\"\n value={query}\n onValueChange={onQueryChange}\n maxLength={255}\n />\n <div className=\"text-muted-foreground flex shrink-0 items-center gap-1\">\n {searching && (\n <LoaderCircle\n aria-hidden=\"true\"\n className=\"pointer-events-none mx-1 size-4 animate-spin\"\n />\n )}\n {query.length > 0 && (\n <>\n <Button\n variant=\"ghost\"\n size=\"sm\"\n onClick={() => {\n onQueryChange(\"\");\n inputRef.current?.focus();\n }}\n >\n Clear\n </Button>\n <span aria-hidden=\"true\" className=\"bg-border mx-1 h-5 w-px\" />\n </>\n )}\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Close search\"\n onClick={onClose}\n >\n <X />\n </Button>\n </div>\n </div>\n <output className=\"sr-only\" aria-live=\"polite\">\n {searching ? \"Searching…\" : \"\"}\n </output>\n <CommandList\n className=\"h-[300px] max-h-[50dvh]\"\n aria-busy={searching || pending}\n >\n {pending && (\n <output aria-label=\"Loading chats\" className=\"block p-1\">\n <div aria-hidden=\"true\">\n <div className=\"flex h-8 items-center px-2\">\n <Skeleton className=\"bg-foreground/10 h-3 w-20\" />\n </div>\n {[\"w-40\", \"w-56\", \"w-32\", \"w-48\", \"w-36\", \"w-44\"].map(\n (width): React.JSX.Element => (\n <div\n className=\"flex h-11 items-center gap-3 px-2\"\n key={width}\n >\n <Skeleton className=\"bg-foreground/10 size-4 shrink-0\" />\n <Skeleton\n className={`bg-foreground/10 h-4 max-w-[75%] ${width}`}\n />\n </div>\n )\n )}\n </div>\n </output>\n )}\n {error && (\n <div className=\"p-4 text-sm\" role=\"alert\">\n Could not search chats.{\" \"}\n <Button variant=\"ghost\" onClick={onRetry}>\n Retry\n </Button>\n </div>\n )}\n {!pending && !error && !searching && items.length === 0 && (\n <p className=\"text-muted-foreground p-4 text-sm\">\n {isSearch\n ? \"No chats found. Try different words.\"\n : \"Your recent chats will appear here.\"}\n </p>\n )}\n {items.length > 0 && (\n <CommandGroup heading={isSearch ? \"Best matches\" : \"Recent chats\"}>\n {items.map((item): React.JSX.Element => (\n <CommandItem\n className=\"cursor-pointer items-start gap-3 px-2 py-3\"\n key={item.id}\n value={item.id}\n onSelect={() => {\n onSelect(item.conversationId);\n }}\n >\n <MessageSquare className=\"text-muted-foreground mt-0.5 size-4 shrink-0\" />\n <div className=\"flex min-w-0 flex-1 flex-col gap-1\">\n <span className=\"truncate font-medium\">{item.title}</span>\n {item.excerpt && (\n <span className=\"text-muted-foreground line-clamp-2 text-xs leading-relaxed\">\n {highlightedExcerpt(item.excerpt)}\n </span>\n )}\n </div>\n </CommandItem>\n ))}\n </CommandGroup>\n )}\n {hasMore && (\n <Button\n variant=\"ghost\"\n disabled={disableLoadMore}\n onClick={onLoadMore}\n >\n {loadingMore ? \"Loading…\" : \"Load more chats\"}\n </Button>\n )}\n </CommandList>\n </Command>\n );\n};\n",
|
|
63
|
+
"type": "registry:file",
|
|
64
|
+
"target": "~/plugins/search/search-results-view.tsx"
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
"path": "src/plugins/search/src/search-schema.ts",
|
|
68
|
+
"content": "import { sql } from \"drizzle-orm\";\nimport {\n foreignKey,\n index,\n pgTable,\n primaryKey,\n text,\n uuid,\n} from \"drizzle-orm/pg-core\";\nimport { eveConversation } from \"@/lib/db/schema\";\n\n/** Rebuildable display-text projection; EVE remains the transcript source of truth. */\nexport const eveSearchText = pgTable(\n \"EveSearchText\",\n {\n conversationId: uuid(\"conversationId\").notNull(),\n key: text(\"key\").notNull(),\n ownerId: text(\"ownerId\").notNull(),\n text: text(\"text\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.conversationId, table.key] }),\n foreignKey({\n columns: [table.conversationId, table.ownerId],\n foreignColumns: [eveConversation.id, eveConversation.ownerId],\n }).onDelete(\"cascade\"),\n index(\"EveSearchText_owner\").on(table.ownerId),\n index(\"EveSearchText_content\").using(\n \"gin\",\n sql`to_tsvector('simple', ${table.text})`\n ),\n ]\n);\n",
|
|
69
|
+
"type": "registry:file",
|
|
70
|
+
"target": "~/plugins/search/search-schema.ts"
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
"path": "src/plugins/search/src/search-text.ts",
|
|
74
|
+
"content": "import type { MessageStreamEvent } from \"eve/client\";\nimport type { EveCopySeed } from \"@/lib/eve/copy-seed\";\n\n/** SDK fields this reader does not inspect remain optional and opaque. */\ntype IgnoredSdkFields<Value> = Value extends object\n ? { readonly [Key in keyof Value]?: unknown }\n : unknown;\n\n// Accepted copy plans are indexed before native session binding.\ntype SeedMessage = EveCopySeed[\"messages\"][number];\ntype IncomingMessage = Extract<\n MessageStreamEvent,\n { type: \"message.received\" }\n>;\n\ntype SearchTextEvent = IgnoredSdkFields<MessageStreamEvent> &\n (\n | {\n readonly type: \"history.seeded\";\n readonly data: {\n readonly messages: Parameters<typeof eveSeedSearchText>[0];\n } & IgnoredSdkFields<\n Extract<MessageStreamEvent, { type: \"history.seeded\" }>[\"data\"]\n >;\n }\n | {\n readonly type: \"message.received\";\n readonly data: Parameters<typeof incomingMessageSearchText>[0][\"data\"];\n readonly meta: { readonly id: string } & IgnoredSdkFields<\n MessageStreamEvent[\"meta\"]\n >;\n }\n | {\n readonly type: \"message.completed\";\n readonly data: { readonly message: string | null } & IgnoredSdkFields<\n Extract<MessageStreamEvent, { type: \"message.completed\" }>[\"data\"]\n >;\n readonly meta: { readonly id: string } & IgnoredSdkFields<\n MessageStreamEvent[\"meta\"]\n >;\n }\n | {\n readonly type: Exclude<\n MessageStreamEvent[\"type\"],\n \"history.seeded\" | \"message.received\" | \"message.completed\"\n >;\n }\n );\n\nconst MAX_SEARCH_QUERY_LENGTH = 255;\n\ninterface EveSearchText {\n readonly key: string;\n readonly text: string;\n}\n\n/**\n * Index display text only: never reasoning, tool payloads, files, or auth metadata.\n * @param {readonly { readonly role: string; readonly parts: readonly { readonly type: string; readonly text?: string; }[]; }[]} messages Seeded message parts and roles whose visible text may enter the search index.\n * @returns {EveSearchText[]} Nonempty user/assistant text indexed by its original seed position.\n */\nconst eveSeedSearchText = (\n messages: readonly ({\n readonly role: string;\n readonly parts: readonly ({\n readonly type: string;\n readonly text?: string;\n } & IgnoredSdkFields<SeedMessage[\"parts\"][number]>)[];\n } & IgnoredSdkFields<SeedMessage> & { readonly id?: string })[]\n): EveSearchText[] =>\n messages.flatMap((message, index) => {\n const text = message.parts\n .filter((part) => part.type === \"text\")\n .map((part) => part.text ?? \"\")\n .join(\"\\n\")\n .trim();\n if (text && [\"user\", \"assistant\"].includes(message.role)) {\n return [{ key: `seed:${index}`, text }];\n }\n return [];\n });\n\n/** Read the display text of an incoming event without trimming its stored value.\n * @param {{ readonly data: { readonly message: string; readonly parts?: readonly { readonly type: string; readonly text?: string }[]; }; readonly meta: { readonly id: string; }; }} event Incoming message fields needed to extract visible text and preserve its event identity.\n * @returns {EveSearchText[]} The nonempty display text item, or an empty array.\n */\nconst incomingMessageSearchText = (event: {\n readonly data: {\n readonly message: string;\n readonly parts?: readonly ({\n readonly type: string;\n readonly text?: string;\n } & IgnoredSdkFields<\n NonNullable<IncomingMessage[\"data\"][\"parts\"]>[number]\n >)[];\n } & IgnoredSdkFields<IncomingMessage[\"data\"]>;\n readonly meta: { readonly id: string } & IgnoredSdkFields<\n MessageStreamEvent[\"meta\"]\n >;\n}): EveSearchText[] => {\n const text = event.data.parts\n ? event.data.parts\n .filter((part) => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\\n\")\n : event.data.message;\n if (text.trim()) {\n return [{ key: `event:${event.meta.id}`, text }];\n }\n return [];\n};\n\n/**\n * Immutable event identities make live delivery, seeded prefixes and backfills idempotent.\n * @param {MessageStreamEvent} event Native history or live event that may contain visible user/assistant text.\n * @returns {EveSearchText[]} Display text with stable event/seed keys, including seeded history and excluding empty content.\n */\nconst eveEventSearchText = (event: SearchTextEvent): EveSearchText[] => {\n if (event.type === \"history.seeded\") {\n return eveSeedSearchText(event.data.messages);\n }\n if (event.type === \"message.received\") {\n return incomingMessageSearchText(event);\n }\n if (\n event.type === \"message.completed\" &&\n typeof event.data.message === \"string\" &&\n event.data.message.trim() !== \"\"\n ) {\n return [{ key: `event:${event.meta.id}`, text: event.data.message }];\n }\n return [];\n};\n\nexport { eveEventSearchText, eveSeedSearchText, MAX_SEARCH_QUERY_LENGTH };\nexport type { EveSearchText };\n",
|
|
75
|
+
"type": "registry:file",
|
|
76
|
+
"target": "~/plugins/search/search-text.ts"
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
"path": "src/plugins/search/src/server-plugin.ts",
|
|
80
|
+
"content": "import type { ChatPlugin } from \"@/lib/plugin-contracts\";\nimport { searchRouter } from \"./router\";\n\nexport const search = () =>\n ({ id: \"search\", routers: { search: searchRouter } }) satisfies ChatPlugin;\n",
|
|
81
|
+
"type": "registry:file",
|
|
82
|
+
"target": "~/plugins/search/server-plugin.ts"
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
"path": "src/plugins/search/src/use-debounced-search.ts",
|
|
86
|
+
"content": "\"use client\";\n\nimport { useEffect, useState } from \"react\";\n// Typing coalesces requests; clearing remains a cancellable asynchronous update.\nconst typingDebounceDelayMs = 250;\nconst clearedSearchDelayMs = 0;\n\nexport const useDebouncedSearch = (value: string): string => {\n const normalized = value.trim();\n const [search, setSearch] = useState(normalized);\n useEffect(() => {\n const timeout = setTimeout(\n () => {\n setSearch(normalized);\n },\n normalized ? typingDebounceDelayMs : clearedSearchDelayMs\n );\n return (): void => {\n clearTimeout(timeout);\n };\n }, [normalized]);\n return search;\n};\n",
|
|
87
|
+
"type": "registry:file",
|
|
88
|
+
"target": "~/plugins/search/use-debounced-search.ts"
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
"path": "src/plugins/search/adapters/agent/hooks/search.ts",
|
|
92
|
+
"content": "export { default } from \"@/plugins/search/search-hook\";\n",
|
|
93
|
+
"type": "registry:file",
|
|
94
|
+
"target": "~/agent/hooks/search.ts"
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
"path": "dist/source/search.json",
|
|
98
|
+
"content": "{\n \"id\": \"search\",\n \"kind\": \"plugin\",\n \"files\": [\n \"plugins/search/backfill.ts\",\n \"plugins/search/chat.ts\",\n \"plugins/search/client-plugin.ts\",\n \"plugins/search/router.ts\",\n \"plugins/search/search-backfill.ts\",\n \"plugins/search/search-chats.tsx\",\n \"plugins/search/search-hook.ts\",\n \"plugins/search/search-queries.ts\",\n \"plugins/search/search-results-view.tsx\",\n \"plugins/search/search-schema.ts\",\n \"plugins/search/search-text.ts\",\n \"plugins/search/server-plugin.ts\",\n \"plugins/search/use-debounced-search.ts\",\n \"agent/hooks/search.ts\"\n ],\n \"databaseSchemas\": [\"plugins/search/search-schema.ts\"],\n \"chat\": { \"export\": \"searchChat\" },\n \"server\": { \"export\": \"search\", \"routers\": [\"search\"] },\n \"client\": {\n \"export\": \"searchClient\",\n \"composerControls\": [],\n \"settingsItems\": [],\n \"chat\": true\n },\n \"contractVersion\": 2,\n \"uiBase\": \"base\"\n}\n",
|
|
99
|
+
"type": "registry:file",
|
|
100
|
+
"target": "~/plugins/search/chatjs.json"
|
|
101
|
+
}
|
|
102
|
+
],
|
|
103
|
+
"meta": {
|
|
104
|
+
"chatjs": {
|
|
105
|
+
"id": "search",
|
|
106
|
+
"kind": "plugin",
|
|
107
|
+
"files": [
|
|
108
|
+
"plugins/search/backfill.ts",
|
|
109
|
+
"plugins/search/chat.ts",
|
|
110
|
+
"plugins/search/client-plugin.ts",
|
|
111
|
+
"plugins/search/router.ts",
|
|
112
|
+
"plugins/search/search-backfill.ts",
|
|
113
|
+
"plugins/search/search-chats.tsx",
|
|
114
|
+
"plugins/search/search-hook.ts",
|
|
115
|
+
"plugins/search/search-queries.ts",
|
|
116
|
+
"plugins/search/search-results-view.tsx",
|
|
117
|
+
"plugins/search/search-schema.ts",
|
|
118
|
+
"plugins/search/search-text.ts",
|
|
119
|
+
"plugins/search/server-plugin.ts",
|
|
120
|
+
"plugins/search/use-debounced-search.ts",
|
|
121
|
+
"agent/hooks/search.ts"
|
|
122
|
+
],
|
|
123
|
+
"databaseSchemas": [
|
|
124
|
+
"plugins/search/search-schema.ts"
|
|
125
|
+
],
|
|
126
|
+
"chat": {
|
|
127
|
+
"export": "searchChat"
|
|
128
|
+
},
|
|
129
|
+
"server": {
|
|
130
|
+
"export": "search",
|
|
131
|
+
"routers": [
|
|
132
|
+
"search"
|
|
133
|
+
]
|
|
134
|
+
},
|
|
135
|
+
"client": {
|
|
136
|
+
"export": "searchClient",
|
|
137
|
+
"composerControls": [],
|
|
138
|
+
"settingsItems": [],
|
|
139
|
+
"chat": true
|
|
140
|
+
},
|
|
141
|
+
"contractVersion": 2,
|
|
142
|
+
"uiBase": "base"
|
|
143
|
+
}
|
|
144
|
+
},
|
|
145
|
+
"type": "registry:item"
|
|
146
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "sftp-storage",
|
|
4
|
+
"title": "SFTP",
|
|
5
|
+
"description": "SFTP (SSH File Transfer Protocol) via ssh2-sftp-client. Node-only. Connect-per-operation with an injectable client for batch work; url() needs an HTTP front (publicBaseUrl).",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"files-sdk@2.5.0",
|
|
8
|
+
"ssh2-sftp-client@^12.1.1"
|
|
9
|
+
],
|
|
10
|
+
"files": [
|
|
11
|
+
{
|
|
12
|
+
"path": "src/storage/sftp/storage-provider.ts",
|
|
13
|
+
"content": "export { sftp as createStorageAdapter } from \"files-sdk/sftp\";\n",
|
|
14
|
+
"type": "registry:file",
|
|
15
|
+
"target": "~/lib/storage-provider.ts"
|
|
16
|
+
}
|
|
17
|
+
],
|
|
18
|
+
"meta": {
|
|
19
|
+
"chatjs": {
|
|
20
|
+
"configKeys": [
|
|
21
|
+
"host",
|
|
22
|
+
"port",
|
|
23
|
+
"root"
|
|
24
|
+
],
|
|
25
|
+
"contractVersion": 1,
|
|
26
|
+
"envRequirements": [
|
|
27
|
+
{
|
|
28
|
+
"description": "SFTP configuration",
|
|
29
|
+
"options": [
|
|
30
|
+
[
|
|
31
|
+
"SFTP_HOST"
|
|
32
|
+
]
|
|
33
|
+
]
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
"description": "SFTP credentials",
|
|
37
|
+
"options": [
|
|
38
|
+
[
|
|
39
|
+
"SFTP_USERNAME",
|
|
40
|
+
"SFTP_PASSWORD"
|
|
41
|
+
],
|
|
42
|
+
[
|
|
43
|
+
"SFTP_USERNAME",
|
|
44
|
+
"SFTP_PRIVATE_KEY"
|
|
45
|
+
]
|
|
46
|
+
]
|
|
47
|
+
}
|
|
48
|
+
],
|
|
49
|
+
"id": "sftp",
|
|
50
|
+
"kind": "storage",
|
|
51
|
+
"optionalEnv": [
|
|
52
|
+
"SFTP_PASSPHRASE",
|
|
53
|
+
"SFTP_PORT"
|
|
54
|
+
]
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
"type": "registry:item"
|
|
58
|
+
}
|