@chat-js/registry 0.2.0-beta.2 → 0.2.0-beta.4
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 +15 -11
- package/dist/r/ai-titles.json +10 -10
- package/dist/r/akamai-storage.json +1 -1
- package/dist/r/alibaba-storage.json +1 -1
- package/dist/r/appwrite-storage.json +1 -1
- package/dist/r/archil-storage.json +1 -1
- package/dist/r/attach-workspace-file.json +82 -0
- package/dist/r/attachment-uploads.json +19 -21
- package/dist/r/azure-storage.json +1 -1
- package/dist/r/backblaze-b2-storage.json +1 -1
- package/dist/r/base/ai-titles.json +10 -10
- package/dist/r/base/akamai-storage.json +1 -1
- package/dist/r/base/alibaba-storage.json +1 -1
- package/dist/r/base/appwrite-storage.json +1 -1
- package/dist/r/base/archil-storage.json +1 -1
- package/dist/r/base/attach-workspace-file.json +82 -0
- package/dist/r/base/attachment-uploads.json +19 -21
- package/dist/r/base/azure-storage.json +1 -1
- package/dist/r/base/backblaze-b2-storage.json +1 -1
- package/dist/r/base/bunny-storage-storage.json +1 -1
- package/dist/r/base/cloudinary-storage.json +1 -1
- package/dist/r/base/credits.json +22 -22
- package/dist/r/base/deep-research.json +57 -139
- package/dist/r/base/default-sandbox.json +35 -0
- package/dist/r/base/desktop.json +144 -0
- package/dist/r/base/digitalocean-spaces-storage.json +1 -1
- package/dist/r/base/docker-sandbox.json +35 -0
- package/dist/r/base/dropbox-storage.json +1 -1
- package/dist/r/base/exoscale-storage.json +1 -1
- package/dist/r/base/feedback.json +25 -25
- package/dist/r/base/filebase-storage.json +1 -1
- package/dist/r/base/firebase-storage-storage.json +1 -1
- package/dist/r/base/followup-suggestions.json +40 -40
- package/dist/r/base/ftp-storage.json +1 -1
- package/dist/r/base/gcs-storage.json +1 -1
- package/dist/r/base/generate-image.json +21 -15
- package/dist/r/base/generate-video.json +15 -9
- package/dist/r/base/google-drive-storage.json +1 -1
- package/dist/r/base/guest-chat.json +181 -0
- package/dist/r/base/hetzner-storage.json +1 -1
- package/dist/r/base/ibm-cos-storage.json +1 -1
- package/dist/r/base/idrive-e2-storage.json +1 -1
- package/dist/r/base/image-viewer.json +55 -0
- package/dist/r/base/just-bash-sandbox.json +32 -0
- package/dist/r/base/litellm-gateway.json +2 -5
- package/dist/r/base/mcp.json +123 -93
- package/dist/r/base/memory-storage.json +1 -1
- package/dist/r/base/minio-storage.json +1 -1
- package/dist/r/base/model-preferences.json +35 -28
- package/dist/r/base/neon-storage.json +1 -1
- package/dist/r/base/netlify-blobs-storage.json +1 -1
- package/dist/r/base/onedrive-storage.json +1 -1
- package/dist/r/base/openai-compatible-gateway.json +2 -5
- package/dist/r/base/openai-gateway.json +2 -5
- package/dist/r/base/openrouter-gateway.json +2 -6
- package/dist/r/base/oracle-cloud-storage.json +1 -1
- package/dist/r/base/ovhcloud-storage.json +1 -1
- package/dist/r/base/pocketbase-storage.json +1 -1
- package/dist/r/base/projects.json +104 -83
- package/dist/r/base/r2-storage.json +1 -1
- package/dist/r/base/registry.json +1725 -2117
- package/dist/r/base/s3-storage.json +1 -1
- package/dist/r/base/scaleway-storage.json +1 -1
- package/dist/r/base/search.json +70 -40
- package/dist/r/base/sftp-storage.json +1 -1
- package/dist/r/base/sharepoint-storage.json +1 -1
- package/dist/r/base/sharing.json +55 -39
- package/dist/r/base/spreadsheet-grid.json +20 -0
- package/dist/r/base/spreadsheet-viewer.json +68 -0
- package/dist/r/base/storj-storage.json +1 -1
- package/dist/r/base/supabase-storage.json +1 -1
- package/dist/r/base/tencent-storage.json +1 -1
- package/dist/r/base/tigris-storage.json +1 -1
- package/dist/r/base/uploadthing-storage.json +1 -1
- package/dist/r/base/vercel-blob-storage.json +1 -1
- package/dist/r/base/vercel-gateway.json +2 -6
- package/dist/r/base/vercel-sandbox.json +8 -26
- package/dist/r/base/video-viewer.json +48 -0
- package/dist/r/base/vultr-storage.json +1 -1
- package/dist/r/base/wasabi-storage.json +1 -1
- package/dist/r/base/webdav-storage.json +1 -1
- package/dist/r/base/yandex-storage.json +1 -1
- package/dist/r/bunny-storage-storage.json +1 -1
- package/dist/r/cloudinary-storage.json +1 -1
- package/dist/r/credits.json +22 -22
- package/dist/r/deep-research.json +57 -139
- package/dist/r/default-sandbox.json +35 -0
- package/dist/r/desktop.json +144 -0
- package/dist/r/digitalocean-spaces-storage.json +1 -1
- package/dist/r/docker-sandbox.json +35 -0
- package/dist/r/dropbox-storage.json +1 -1
- package/dist/r/eve/deep-research.json +47 -0
- package/dist/r/eve/registry.json +53 -0
- package/dist/r/exoscale-storage.json +1 -1
- package/dist/r/feedback.json +25 -25
- package/dist/r/filebase-storage.json +1 -1
- package/dist/r/firebase-storage-storage.json +1 -1
- package/dist/r/followup-suggestions.json +40 -40
- package/dist/r/ftp-storage.json +1 -1
- package/dist/r/gcs-storage.json +1 -1
- package/dist/r/generate-image.json +21 -15
- package/dist/r/generate-video.json +15 -9
- package/dist/r/google-drive-storage.json +1 -1
- package/dist/r/guest-chat.json +181 -0
- package/dist/r/hetzner-storage.json +1 -1
- package/dist/r/ibm-cos-storage.json +1 -1
- package/dist/r/idrive-e2-storage.json +1 -1
- package/dist/r/image-viewer.json +55 -0
- package/dist/r/just-bash-sandbox.json +32 -0
- package/dist/r/litellm-gateway.json +2 -5
- package/dist/r/mcp.json +123 -93
- package/dist/r/memory-storage.json +1 -1
- package/dist/r/minio-storage.json +1 -1
- package/dist/r/model-preferences.json +35 -28
- package/dist/r/neon-storage.json +1 -1
- package/dist/r/netlify-blobs-storage.json +1 -1
- package/dist/r/onedrive-storage.json +1 -1
- package/dist/r/openai-compatible-gateway.json +2 -5
- package/dist/r/openai-gateway.json +2 -5
- package/dist/r/openrouter-gateway.json +2 -6
- package/dist/r/oracle-cloud-storage.json +1 -1
- package/dist/r/ovhcloud-storage.json +1 -1
- package/dist/r/pocketbase-storage.json +1 -1
- package/dist/r/projects.json +104 -83
- package/dist/r/r2-storage.json +1 -1
- package/dist/r/radix/ai-titles.json +10 -10
- package/dist/r/radix/akamai-storage.json +1 -1
- package/dist/r/radix/alibaba-storage.json +1 -1
- package/dist/r/radix/appwrite-storage.json +1 -1
- package/dist/r/radix/archil-storage.json +1 -1
- package/dist/r/radix/attach-workspace-file.json +82 -0
- package/dist/r/radix/attachment-uploads.json +19 -21
- package/dist/r/radix/azure-storage.json +1 -1
- package/dist/r/radix/backblaze-b2-storage.json +1 -1
- package/dist/r/radix/bunny-storage-storage.json +1 -1
- package/dist/r/radix/cloudinary-storage.json +1 -1
- package/dist/r/radix/credits.json +22 -22
- package/dist/r/radix/deep-research.json +57 -139
- package/dist/r/radix/default-sandbox.json +35 -0
- package/dist/r/radix/desktop.json +144 -0
- package/dist/r/radix/digitalocean-spaces-storage.json +1 -1
- package/dist/r/radix/docker-sandbox.json +35 -0
- package/dist/r/radix/dropbox-storage.json +1 -1
- package/dist/r/radix/exoscale-storage.json +1 -1
- package/dist/r/radix/feedback.json +25 -25
- package/dist/r/radix/filebase-storage.json +1 -1
- package/dist/r/radix/firebase-storage-storage.json +1 -1
- package/dist/r/radix/followup-suggestions.json +40 -40
- package/dist/r/radix/ftp-storage.json +1 -1
- package/dist/r/radix/gcs-storage.json +1 -1
- package/dist/r/radix/generate-image.json +21 -15
- package/dist/r/radix/generate-video.json +15 -9
- package/dist/r/radix/google-drive-storage.json +1 -1
- package/dist/r/radix/guest-chat.json +181 -0
- package/dist/r/radix/hetzner-storage.json +1 -1
- package/dist/r/radix/ibm-cos-storage.json +1 -1
- package/dist/r/radix/idrive-e2-storage.json +1 -1
- package/dist/r/radix/image-viewer.json +55 -0
- package/dist/r/radix/just-bash-sandbox.json +32 -0
- package/dist/r/radix/litellm-gateway.json +2 -5
- package/dist/r/radix/mcp.json +123 -93
- package/dist/r/radix/memory-storage.json +1 -1
- package/dist/r/radix/minio-storage.json +1 -1
- package/dist/r/radix/model-preferences.json +35 -28
- package/dist/r/radix/neon-storage.json +1 -1
- package/dist/r/radix/netlify-blobs-storage.json +1 -1
- package/dist/r/radix/onedrive-storage.json +1 -1
- package/dist/r/radix/openai-compatible-gateway.json +2 -5
- package/dist/r/radix/openai-gateway.json +2 -5
- package/dist/r/radix/openrouter-gateway.json +2 -6
- package/dist/r/radix/oracle-cloud-storage.json +1 -1
- package/dist/r/radix/ovhcloud-storage.json +1 -1
- package/dist/r/radix/pocketbase-storage.json +1 -1
- package/dist/r/radix/projects.json +104 -83
- package/dist/r/radix/r2-storage.json +1 -1
- package/dist/r/radix/registry.json +1728 -2120
- package/dist/r/radix/s3-storage.json +1 -1
- package/dist/r/radix/scaleway-storage.json +1 -1
- package/dist/r/radix/search.json +70 -40
- package/dist/r/radix/sftp-storage.json +1 -1
- package/dist/r/radix/sharepoint-storage.json +1 -1
- package/dist/r/radix/sharing.json +55 -39
- package/dist/r/radix/spreadsheet-grid.json +20 -0
- package/dist/r/radix/spreadsheet-viewer.json +68 -0
- package/dist/r/radix/storj-storage.json +1 -1
- package/dist/r/radix/supabase-storage.json +1 -1
- package/dist/r/radix/tencent-storage.json +1 -1
- package/dist/r/radix/tigris-storage.json +1 -1
- package/dist/r/radix/uploadthing-storage.json +1 -1
- package/dist/r/radix/vercel-blob-storage.json +1 -1
- package/dist/r/radix/vercel-gateway.json +2 -6
- package/dist/r/radix/vercel-sandbox.json +8 -26
- package/dist/r/radix/video-viewer.json +48 -0
- package/dist/r/radix/vultr-storage.json +1 -1
- package/dist/r/radix/wasabi-storage.json +1 -1
- package/dist/r/radix/webdav-storage.json +1 -1
- package/dist/r/radix/yandex-storage.json +1 -1
- package/dist/r/registry.json +1725 -2117
- package/dist/r/s3-storage.json +1 -1
- package/dist/r/scaleway-storage.json +1 -1
- package/dist/r/search.json +70 -40
- package/dist/r/sftp-storage.json +1 -1
- package/dist/r/sharepoint-storage.json +1 -1
- package/dist/r/sharing.json +55 -39
- package/dist/r/spreadsheet-grid.json +20 -0
- package/dist/r/spreadsheet-viewer.json +68 -0
- package/dist/r/storj-storage.json +1 -1
- package/dist/r/supabase-storage.json +1 -1
- package/dist/r/tencent-storage.json +1 -1
- package/dist/r/tigris-storage.json +1 -1
- package/dist/r/uploadthing-storage.json +1 -1
- package/dist/r/vercel-blob-storage.json +1 -1
- package/dist/r/vercel-gateway.json +2 -6
- package/dist/r/vercel-sandbox.json +8 -26
- package/dist/r/video-viewer.json +48 -0
- package/dist/r/vultr-storage.json +1 -1
- package/dist/r/wasabi-storage.json +1 -1
- package/dist/r/webdav-storage.json +1 -1
- package/dist/r/yandex-storage.json +1 -1
- package/package.json +9 -30
- package/dist/r/base/code-documents.json +0 -96
- package/dist/r/base/code-execution-runtime.json +0 -25
- package/dist/r/base/code-execution-ui.json +0 -32
- package/dist/r/base/code-execution.json +0 -69
- package/dist/r/base/daytona-sandbox.json +0 -55
- package/dist/r/base/delete-document.json +0 -58
- package/dist/r/base/firecrawl-search.json +0 -72
- package/dist/r/base/get-weather.json +0 -52
- package/dist/r/base/langfuse.json +0 -63
- package/dist/r/base/read-document.json +0 -34
- package/dist/r/base/retrieve-url.json +0 -69
- package/dist/r/base/saved-code-execution.json +0 -84
- package/dist/r/base/sheet-documents.json +0 -94
- package/dist/r/base/tavily-search.json +0 -72
- package/dist/r/base/text-documents.json +0 -117
- package/dist/r/base/vercel-analytics.json +0 -46
- package/dist/r/base/vercel-speed-insights.json +0 -46
- package/dist/r/base/word-count.json +0 -51
- package/dist/r/code-documents.json +0 -96
- package/dist/r/code-execution-runtime.json +0 -25
- package/dist/r/code-execution-ui.json +0 -32
- package/dist/r/code-execution.json +0 -69
- package/dist/r/daytona-sandbox.json +0 -55
- package/dist/r/delete-document.json +0 -58
- package/dist/r/firecrawl-search.json +0 -72
- package/dist/r/get-weather.json +0 -52
- package/dist/r/langfuse.json +0 -63
- package/dist/r/radix/code-documents.json +0 -96
- package/dist/r/radix/code-execution-runtime.json +0 -25
- package/dist/r/radix/code-execution-ui.json +0 -32
- package/dist/r/radix/code-execution.json +0 -69
- package/dist/r/radix/daytona-sandbox.json +0 -55
- package/dist/r/radix/delete-document.json +0 -58
- package/dist/r/radix/firecrawl-search.json +0 -72
- package/dist/r/radix/get-weather.json +0 -52
- package/dist/r/radix/langfuse.json +0 -63
- package/dist/r/radix/read-document.json +0 -34
- package/dist/r/radix/retrieve-url.json +0 -69
- package/dist/r/radix/saved-code-execution.json +0 -84
- package/dist/r/radix/sheet-documents.json +0 -94
- package/dist/r/radix/tavily-search.json +0 -72
- package/dist/r/radix/text-documents.json +0 -117
- package/dist/r/radix/vercel-analytics.json +0 -46
- package/dist/r/radix/vercel-speed-insights.json +0 -46
- package/dist/r/radix/word-count.json +0 -51
- package/dist/r/read-document.json +0 -34
- package/dist/r/retrieve-url.json +0 -69
- package/dist/r/saved-code-execution.json +0 -84
- package/dist/r/sheet-documents.json +0 -94
- package/dist/r/tavily-search.json +0 -72
- package/dist/r/text-documents.json +0 -117
- package/dist/r/vercel-analytics.json +0 -46
- package/dist/r/vercel-speed-insights.json +0 -46
- package/dist/r/word-count.json +0 -51
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "guest-chat",
|
|
4
|
+
"description": "Disposable text chat for visitors with isolated sessions and bounded cleanup",
|
|
5
|
+
"dependencies": [
|
|
6
|
+
"ai@7.0.137",
|
|
7
|
+
"drizzle-orm@^0.45.1",
|
|
8
|
+
"zod@4.5.4"
|
|
9
|
+
],
|
|
10
|
+
"files": [
|
|
11
|
+
{
|
|
12
|
+
"path": "src/plugins/guest-chat/src/cleanup.ts",
|
|
13
|
+
"content": "import type { CleanupTask } from \"@/lib/cleanup/contracts\";\nimport { cleanupGuestRuntimeSessions } from \"./guest-cleanup\";\n\nexport const guestCleanup = {\n id: \"guest-chat\",\n run: cleanupGuestRuntimeSessions,\n} satisfies CleanupTask;\n",
|
|
14
|
+
"type": "registry:file",
|
|
15
|
+
"target": "~/chatjs/plugins/guest-chat/cleanup.ts"
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
"path": "src/plugins/guest-chat/src/guest-auth.ts",
|
|
19
|
+
"content": "import type { SessionAuthentication } from \"@/chatjs/core/session/contracts\";\nimport { readGuestBody } from \"@/chatjs/plugins/guest-chat/guest-body\";\nimport { GUEST_POLICY } from \"@/chatjs/plugins/guest-chat/guest-policy\";\nimport {\n readGuestRuntimePolicy,\n reserveGuestRuntimeMessage,\n} from \"@/chatjs/plugins/guest-chat/guest-queries\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { readGuestCredential } from \"@/chatjs/plugins/guest-chat/guest-credential\";\nimport { safeStreamQuery } from \"@/lib/eve/request-policy\";\nimport { z } from \"zod\";\n\nconst MIN_FIELD_LENGTH = 1;\nconst MAX_MESSAGE_LENGTH = GUEST_POLICY.maxMessageCharacters;\nconst MAX_TURN_ID_LENGTH = 200;\nconst BEARER_PREFIX = \"Bearer \";\n\nconst message = z\n .object({\n message: z.string().trim().min(MIN_FIELD_LENGTH).max(MAX_MESSAGE_LENGTH),\n })\n .strict();\n\nconst cancel = z\n .object({\n turnId: z.string().min(MIN_FIELD_LENGTH).max(MAX_TURN_ID_LENGTH).optional(),\n })\n .strict();\n\ntype Claims = NonNullable<ReturnType<typeof readGuestCredential>>;\n\nconst guestOperation = (\n claims: Claims,\n url: URL,\n method: string\n): { body?: z.ZodType; send?: boolean } | null => {\n if (claims.sessionId === undefined) {\n return method === \"POST\" && url.pathname === \"/eve/v1/session\"\n ? { body: z.object({ operationId: z.literal(claims.policyId) }).strict() }\n : null;\n }\n const path = `/eve/v1/session/${claims.sessionId}`;\n if (\n method === \"GET\" &&\n url.pathname === `${path}/stream` &&\n safeStreamQuery(url.searchParams)\n ) {\n return {};\n }\n if (method !== \"POST\") {\n return null;\n }\n if (url.pathname === `${path}/end`) {\n return {\n body:\n claims.purpose === \"cleanup\"\n ? z\n .object({\n reason: z.literal(\"Guest retention expired\").optional(),\n })\n .strict()\n : z.object({}).strict(),\n };\n }\n if (claims.purpose === \"cleanup\") {\n return null;\n }\n if (url.pathname === path) {\n return { body: message, send: true };\n }\n if (url.pathname === `${path}/cancel`) {\n return { body: cancel };\n }\n return null;\n};\n\nconst policyMatches = (\n claims: Claims,\n policy: NonNullable<Awaited<ReturnType<typeof readGuestRuntimePolicy>>>\n): boolean => {\n if (\n policy.modelId !== claims.modelId ||\n String(policy.policyVersion) !== GUEST_POLICY.version\n ) {\n return false;\n }\n if (policy.sessionId !== (claims.sessionId ?? null)) {\n return false;\n }\n if (claims.purpose === \"cleanup\") {\n return policy.state === \"deleting\";\n }\n return (\n policy.state === \"active\" &&\n policy.credentialExpiresAt.getTime() > Date.now() &&\n policy.expiresAt.getTime() > Date.now()\n );\n};\n\n/** Authenticate every guest command against both signed credentials and durable policy. */\nexport const authenticateDisposableGuest = async (\n request: ReadonlyNativeSurface<Request>\n): Promise<SessionAuthentication | null> => {\n const authorization = request.headers.get(\"authorization\") ?? \"\";\n const claims = readGuestCredential(\n authorization.startsWith(BEARER_PREFIX)\n ? authorization.slice(BEARER_PREFIX.length)\n : null\n );\n if (\n !claims ||\n (claims.purpose !== \"cleanup\" && claims.modelId !== GUEST_POLICY.modelId)\n ) {\n return null;\n }\n const policy = await readGuestRuntimePolicy(claims.policyId, claims.ownerId);\n if (policy === null || !policyMatches(claims, policy)) {\n return null;\n }\n const operation = guestOperation(\n claims,\n new URL(request.url),\n request.method\n );\n if (operation === null) {\n return null;\n }\n const command = operation.body ? await readGuestBody(request) : undefined;\n if (operation.body && !operation.body.safeParse(command).success) {\n return null;\n }\n if (operation.send === true) {\n const admission = await reserveGuestRuntimeMessage({\n sessionId: claims.sessionId ?? \"\",\n ownerId: claims.ownerId,\n requestsPerMinute: GUEST_POLICY.requestsPerMinute,\n inputCharacters: message.parse(command).message.length,\n maxInputCharacters: GUEST_POLICY.maxInputCharacters,\n });\n if (admission !== \"ready\") {\n return null;\n }\n }\n return {\n attributes: {\n modelId: claims.modelId,\n chatjsSessionKind: \"guest\",\n chatjsPolicyVersion: GUEST_POLICY.version,\n chatjsPolicyId: policy.id,\n },\n authenticator: \"chatjs-disposable-guest\",\n issuer: \"chatjs\",\n principalId: claims.ownerId,\n principalType: \"guest\",\n subject: claims.ownerId,\n };\n};\n",
|
|
20
|
+
"type": "registry:file",
|
|
21
|
+
"target": "~/chatjs/plugins/guest-chat/guest-auth.ts"
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"path": "src/plugins/guest-chat/src/guest-body.ts",
|
|
25
|
+
"content": "import type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\n\n/** Read a small guest command without buffering an unbounded HTTP request. */\nexport const readGuestBody = async (\n request: ReadonlyNativeSurface<Request>\n): Promise<unknown> => {\n const reader = request.clone().body?.getReader();\n if (!reader) {\n return null;\n }\n const decoder = new TextDecoder();\n let bytes = 0;\n let text = \"\";\n try {\n for (;;) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- Read and bound each sequential stream chunk before requesting the next.\n const part = await reader.read();\n if (part.done) {\n break;\n }\n bytes += part.value.byteLength;\n if (bytes > 24_000) {\n void reader.cancel();\n return null;\n }\n text += decoder.decode(part.value, { stream: true });\n }\n return JSON.parse(text + decoder.decode());\n } catch {\n return null;\n } finally {\n reader.releaseLock();\n }\n};\n",
|
|
26
|
+
"type": "registry:file",
|
|
27
|
+
"target": "~/chatjs/plugins/guest-chat/guest-body.ts"
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
"path": "src/plugins/guest-chat/src/guest-cleanup-auth.ts",
|
|
31
|
+
"content": "import { getEveConnectionOptions } from \"@/lib/eve/connection-options\";\nimport { issueGuestCredential } from \"@/chatjs/plugins/guest-chat/guest-credential\";\n\n/** Server-only cleanup authorization is valid only for a deletion-pending policy. */\nexport const getGuestCleanupConnectionOptions = (input: {\n readonly policyId: string;\n readonly modelId: string;\n readonly ownerId: string;\n readonly sessionId?: string;\n}): ReturnType<typeof getEveConnectionOptions> => ({\n ...getEveConnectionOptions(input.ownerId),\n auth: {\n bearer: issueGuestCredential({\n ...input,\n expiresAt: Date.now() + 300_000,\n purpose: \"cleanup\",\n }),\n },\n});\n",
|
|
32
|
+
"type": "registry:file",
|
|
33
|
+
"target": "~/chatjs/plugins/guest-chat/guest-cleanup-auth.ts"
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
"path": "src/plugins/guest-chat/src/guest-cleanup.ts",
|
|
37
|
+
"content": "import { z } from \"zod\";\nimport { Client, ClientError } from \"eve/client\";\n\nimport {\n bindGuestRuntimeCleanupSession,\n claimExpiredGuestRuntimeSession,\n completeGuestRuntimeDeletion,\n countPendingGuestRuntimeDeletions,\n pruneGuestRuntimeRates,\n} from \"@/chatjs/plugins/guest-chat/guest-queries\";\nimport { getGuestCleanupConnectionOptions } from \"@/chatjs/plugins/guest-chat/guest-cleanup-auth\";\n\nconst MAX_CLEANUP_BATCH = 5;\nconst RETIRE_TIMEOUT_MS = 30_000;\n\nconst resolveCleanupSession = async (\n guest: {\n readonly id: string;\n readonly modelId: string;\n readonly ownerId: string;\n readonly sessionId: string | null;\n },\n signal: AbortSignal\n): Promise<string> => {\n if (guest.sessionId !== null) {\n return guest.sessionId;\n }\n // Replay the original operation before deletion. EVE returns its existing\n // session or creates one empty session, which this sweep immediately retires.\n const connection = getGuestCleanupConnectionOptions({\n ownerId: guest.ownerId,\n modelId: guest.modelId,\n policyId: guest.id,\n });\n const response = await fetch(`${connection.baseUrl}/v1/session`, {\n method: \"POST\",\n redirect: \"error\",\n headers: {\n ...connection.headers,\n authorization: `Bearer ${connection.auth.bearer}`,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({ operationId: guest.id }),\n signal,\n });\n if (!response.ok) {\n throw new Error(\"Guest creation reconciliation remains unresolved.\");\n }\n const { sessionId } = z\n .object({ sessionId: z.string().min(1) })\n .parse(await response.json());\n if (\n !(await bindGuestRuntimeCleanupSession(guest.id, guest.ownerId, sessionId))\n ) {\n throw new Error(\"Guest cleanup binding changed.\");\n }\n return sessionId;\n};\n\nexport const cleanupGuestRuntimeSessions = async ({\n deadline = Number.POSITIVE_INFINITY,\n}: { readonly deadline?: number } = {}): Promise<{\n deletedCount: number;\n retiredCount: number;\n pendingCount: number;\n skipped: boolean;\n}> => {\n const initialPendingCount = await countPendingGuestRuntimeDeletions();\n if (initialPendingCount === 0) {\n await pruneGuestRuntimeRates();\n return {\n deletedCount: 0,\n retiredCount: 0,\n pendingCount: 0,\n skipped: false,\n };\n }\n let retiredCount = 0;\n let pendingCount = 0;\n for (\n let attempt = 0;\n attempt < MAX_CLEANUP_BATCH && Date.now() < deadline;\n attempt += 1\n ) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- Claim and retire one session at a time to bound provider connections and work.\n const guest = await claimExpiredGuestRuntimeSession();\n if (!guest) {\n break;\n }\n let phase = \"reconcile-session\";\n try {\n const signal = AbortSignal.timeout(\n Math.max(1, Math.min(RETIRE_TIMEOUT_MS, deadline - Date.now()))\n );\n // oxlint-disable-next-line eslint/no-await-in-loop -- Reconcile only the current claimed guest before retirement.\n const sessionId = await resolveCleanupSession(guest, signal);\n phase = \"retire\";\n const retire = async (): Promise<void> => {\n const client = new Client(\n getGuestCleanupConnectionOptions({\n ownerId: guest.ownerId,\n modelId: guest.modelId,\n policyId: guest.id,\n sessionId,\n })\n );\n const session = client.sessions.attach(sessionId);\n const current = await session.snapshot({\n signal,\n });\n if (current.events.some((event) => event.type === \"session.ended\")) {\n return;\n }\n const retirement = await session.end({\n reason: \"Guest retention expired\",\n signal,\n });\n for await (const event of retirement.stream({\n signal,\n })) {\n if (event.type === \"session.ended\") {\n return;\n }\n }\n const snapshot = await session.snapshot({\n signal,\n });\n if (!snapshot.events.some((event) => event.type === \"session.ended\")) {\n throw new Error(\"Guest retirement is not terminal. Retry cleanup.\");\n }\n };\n try {\n // oxlint-disable-next-line eslint/no-await-in-loop -- Finish this session before completing its policy; payloads follow native World retention.\n await retire();\n } catch (error) {\n // EVE can expire history as soon as end completes. Only its explicit\n // expiry response is terminal evidence; 404, auth and transport failures retry.\n if (\n !ClientError.is(error) ||\n error.status !== 410 ||\n error.code !== \"session_expired\"\n ) {\n throw error;\n }\n }\n phase = \"complete-policy\";\n // oxlint-disable-next-line eslint/no-await-in-loop -- Complete local policy after verified ending or expiry.\n if (!(await completeGuestRuntimeDeletion(guest.id, sessionId))) {\n throw new Error(\"Guest deletion binding changed.\");\n }\n retiredCount += 1;\n } catch {\n pendingCount += 1;\n console.error(\"Guest runtime cleanup requires retry\", {\n policyId: guest.id,\n phase,\n });\n }\n }\n if (Date.now() >= deadline) {\n // No new bookkeeping after the deadline; a later sweep establishes completion.\n return {\n deletedCount: 0,\n retiredCount,\n pendingCount: Math.max(\n pendingCount,\n initialPendingCount - retiredCount,\n 1\n ),\n skipped: false,\n };\n }\n await pruneGuestRuntimeRates();\n pendingCount = Math.max(\n pendingCount,\n await countPendingGuestRuntimeDeletions()\n );\n return { deletedCount: 0, retiredCount, pendingCount, skipped: false };\n};\n",
|
|
38
|
+
"type": "registry:file",
|
|
39
|
+
"target": "~/chatjs/plugins/guest-chat/guest-cleanup.ts"
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
"path": "src/plugins/guest-chat/src/guest-credential.ts",
|
|
43
|
+
"content": "import { createHmac, randomUUID, timingSafeEqual } from \"node:crypto\";\nimport { env } from \"@/lib/env\";\nimport { z } from \"zod\";\n\nimport { GUEST_POLICY } from \"@/chatjs/plugins/guest-chat/guest-policy\";\n\nconst MINIMUM_IDENTIFIER_LENGTH = 1;\nconst MAXIMUM_CREDENTIAL_CHARACTERS = 2048;\nconst SIGNED_CREDENTIAL_PART_COUNT = 2;\nconst GUEST_SESSION_DURATION_MS = GUEST_POLICY.credentialDurationMs;\n\nconst claimsSchema = z\n .object({\n expiresAt: z.number().int().positive(),\n policyId: z.uuid(),\n purpose: z.enum([\"chat\", \"cleanup\"]).default(\"chat\"),\n modelId: z.string().min(MINIMUM_IDENTIFIER_LENGTH),\n ownerId: z.uuid(),\n sessionId: z.string().min(MINIMUM_IDENTIFIER_LENGTH).optional(),\n })\n .strict();\n\nconst signature = (payload: string): Buffer =>\n createHmac(\"sha256\", env.EVE_GATEWAY_SECRET)\n .update(`chatjs:disposable-guest:v2:${payload}`)\n .digest();\n\nconst issueGuestCredential = (claims: z.infer<typeof claimsSchema>): string => {\n const payload = Buffer.from(\n JSON.stringify(claimsSchema.parse(claims))\n ).toString(\"base64url\");\n return `${payload}.${signature(payload).toString(\"base64url\")}`;\n};\n\nconst newGuestClaims = (\n modelId: string\n): {\n expiresAt: number;\n policyId: string;\n purpose: \"chat\";\n modelId: string;\n ownerId: ReturnType<typeof randomUUID>;\n} => ({\n expiresAt: Date.now() + GUEST_SESSION_DURATION_MS,\n policyId: randomUUID(),\n purpose: \"chat\",\n modelId,\n ownerId: randomUUID(),\n});\n\nconst readGuestCredential = (\n token: string | null\n): z.infer<typeof claimsSchema> | null => {\n if (\n token === null ||\n token === \"\" ||\n token.length > MAXIMUM_CREDENTIAL_CHARACTERS\n ) {\n return null;\n }\n const parts = token.split(\".\");\n if (parts.length !== SIGNED_CREDENTIAL_PART_COUNT) {\n return null;\n }\n const [payload, supplied] = parts;\n const actual = Buffer.from(supplied, \"base64url\");\n const expected = signature(payload);\n if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {\n return null;\n }\n try {\n const claims = claimsSchema.parse(\n JSON.parse(Buffer.from(payload, \"base64url\").toString())\n );\n\n if (claims.expiresAt > Date.now()) {\n return claims;\n }\n return null;\n } catch {\n return null;\n }\n};\nexport {\n GUEST_SESSION_DURATION_MS,\n issueGuestCredential,\n newGuestClaims,\n readGuestCredential,\n};\n",
|
|
44
|
+
"type": "registry:file",
|
|
45
|
+
"target": "~/chatjs/plugins/guest-chat/guest-credential.ts"
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
"path": "src/plugins/guest-chat/src/guest-ip.ts",
|
|
49
|
+
"content": "import { createHmac } from \"node:crypto\";\nimport { isIP } from \"node:net\";\nimport { env } from \"@/lib/env\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\n\nconst eveGuestIpHash = (address: string, secret: string): string => {\n if (!(address && secret)) {\n throw new Error(\"A trusted client address and server secret are required.\");\n }\n return createHmac(\"sha256\", secret)\n .update(`eve-guest-ip:${address}`)\n .digest(\"hex\");\n};\n\nconst IPV6_VERSION = 6;\nconst INVALID_IP_VERSION = 0;\nconst LEADING_BRACKET_LENGTH = 1;\nconst TRAILING_BRACKET_INDEX = -1;\nconst IPV4_OCTET_RANGE = 256;\nconst MAPPED_HIGH_WORD_GROUP = 1;\nconst MAPPED_LOW_WORD_GROUP = 2;\n\nconst MAPPED_IP = /^::ffff:(?<high>[0-9a-f]{1,4}):(?<low>[0-9a-f]{1,4})$/u;\n\n/**\n * Hashes a trusted canonical client address; development uses the local address.\n * @param {ReadonlyNativeSurface<Request>} request Request whose configured proxy header supplies the client address outside development.\n * @returns {string} The keyed guest IP hash after mapped IPv6 normalization; unavailable or invalid addresses throw.\n */\nconst guestRequestIpHash = (\n request: ReadonlyNativeSurface<Request>\n): string => {\n if (env.NODE_ENV === \"development\") {\n return eveGuestIpHash(\"127.0.0.1\", env.AUTH_SECRET);\n }\n // https://vercel.com/docs/headers/request-headers#x-vercel-forwarded-for\n const header =\n typeof env.VERCEL_URL === \"string\" && env.VERCEL_URL !== \"\"\n ? \"x-vercel-forwarded-for\"\n : process.env.TRUSTED_CLIENT_IP_HEADER;\n const address =\n typeof header === \"string\" && header !== \"\"\n ? (request.headers.get(header) ?? \"\").trim()\n : \"\";\n if (\n address === \"\" ||\n isIP(address) === INVALID_IP_VERSION ||\n address.includes(\"%\")\n ) {\n throw new Error(\"Trusted client address is unavailable.\");\n }\n const canonical =\n isIP(address) === IPV6_VERSION\n ? new URL(`http://[${address}]`).hostname.slice(\n LEADING_BRACKET_LENGTH,\n TRAILING_BRACKET_INDEX\n )\n : address;\n const mapped = MAPPED_IP.exec(canonical);\n const normalized =\n mapped === null\n ? canonical\n : [\n Math.floor(\n Number.parseInt(mapped[MAPPED_HIGH_WORD_GROUP], 16) /\n IPV4_OCTET_RANGE\n ),\n Number.parseInt(mapped[MAPPED_HIGH_WORD_GROUP], 16) %\n IPV4_OCTET_RANGE,\n Math.floor(\n Number.parseInt(mapped[MAPPED_LOW_WORD_GROUP], 16) /\n IPV4_OCTET_RANGE\n ),\n Number.parseInt(mapped[MAPPED_LOW_WORD_GROUP], 16) % IPV4_OCTET_RANGE,\n ].join(\".\");\n return eveGuestIpHash(normalized, env.AUTH_SECRET);\n};\n\nexport { guestRequestIpHash };\n",
|
|
50
|
+
"type": "registry:file",
|
|
51
|
+
"target": "~/chatjs/plugins/guest-chat/guest-ip.ts"
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"path": "src/plugins/guest-chat/src/guest-model.ts",
|
|
55
|
+
"content": "import type { SessionModel } from \"@/chatjs/core/session/contracts\";\nimport type { LanguageModelMiddleware } from \"ai\";\nimport { wrapLanguageModel } from \"ai\";\nimport { GUEST_POLICY } from \"@/chatjs/plugins/guest-chat/guest-policy\";\nimport { resolveEveModel } from \"@/lib/eve/model-selection\";\n\nconst MAX_OUTPUT_CHARACTERS = GUEST_POLICY.maxOutputTokens * 16;\n\n/** Enforce bounds at the provider call, including accumulated conversation history. */\nexport const guestModelMiddleware: LanguageModelMiddleware = {\n specificationVersion: \"v4\",\n // AI SDK requires a promise-returning middleware; validation itself is synchronous.\n // oxlint-disable-next-line eslint/require-await\n transformParams: async ({ params }) => {\n if (\n JSON.stringify(params.prompt).length > GUEST_POLICY.maxInputCharacters ||\n params.prompt.some(\n (message) =>\n message.role === \"tool\" ||\n (typeof message.content !== \"string\" &&\n message.content.some(\n (part) =>\n part.type !== \"text\" &&\n !(message.role === \"assistant\" && part.type === \"reasoning\")\n ))\n )\n ) {\n throw new Error(\"Guest input limit reached. Start a new chat.\");\n }\n return {\n ...params,\n // Reserve the small guest output budget for the visible answer.\n providerOptions: {\n ...params.providerOptions,\n openai: {\n ...params.providerOptions?.openai,\n reasoningEffort: \"minimal\",\n },\n },\n tools: [],\n toolChoice: { type: \"none\" },\n maxOutputTokens: GUEST_POLICY.maxOutputTokens,\n abortSignal: params.abortSignal\n ? AbortSignal.any([params.abortSignal, AbortSignal.timeout(60_000)])\n : AbortSignal.timeout(60_000),\n };\n },\n wrapGenerate: async ({ doGenerate }) => {\n const result = await doGenerate();\n if (result.content.some((part) => part.type === \"tool-call\")) {\n throw new Error(\"Guest models cannot invoke tools.\");\n }\n const characters = result.content.reduce(\n (total, part) =>\n total +\n (part.type === \"text\" || part.type === \"reasoning\"\n ? part.text.length\n : 0),\n 0\n );\n if (characters > MAX_OUTPUT_CHARACTERS) {\n throw new Error(\"Guest output limit reached.\");\n }\n return result;\n },\n wrapStream: async ({ doStream }) => {\n const result = await doStream();\n let characters = 0;\n return {\n ...result,\n stream: result.stream.pipeThrough(\n new TransformStream({\n transform(part, controller) {\n if (\n part.type === \"tool-call\" ||\n part.type === \"tool-input-start\" ||\n part.type === \"tool-input-delta\" ||\n part.type === \"tool-input-end\"\n ) {\n throw new Error(\"Guest models cannot invoke tools.\");\n }\n if (part.type === \"text-delta\" || part.type === \"reasoning-delta\") {\n characters += part.delta.length;\n if (characters > MAX_OUTPUT_CHARACTERS) {\n throw new Error(\"Guest output limit reached.\");\n }\n }\n controller.enqueue(part);\n },\n })\n ),\n };\n },\n};\n\nexport const resolveGuestModel = async (): Promise<SessionModel> => {\n const resolved = await resolveEveModel(GUEST_POLICY.modelId);\n return {\n ...resolved,\n modelContextWindowTokens: Math.min(resolved.modelContextWindowTokens, 8192),\n model: wrapLanguageModel({\n model: resolved.model,\n middleware: guestModelMiddleware,\n }),\n };\n};\n",
|
|
56
|
+
"type": "registry:file",
|
|
57
|
+
"target": "~/chatjs/plugins/guest-chat/guest-model.ts"
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
"path": "src/plugins/guest-chat/src/guest-policy.ts",
|
|
61
|
+
"content": "import { config } from \"@/lib/config\";\n\nexport const guestModelIdForGateway = (gateway: string): string =>\n gateway === \"openai\" ? \"gpt-5-nano\" : \"openai/gpt-5-nano\";\n\n/** Server-owned guest policy. Public constants describe limits, never authorize them. */\nexport const GUEST_POLICY = {\n version: \"1\",\n modelId: guestModelIdForGateway(config.ai.gateway),\n requestsPerMinute: 5,\n sessionsPerHour: 5,\n credentialDurationMs: 3_600_000,\n retentionMs: 86_400_000,\n maxMessageCharacters: 4000,\n maxInputCharacters: 24_000,\n maxOutputTokens: 512,\n} as const;\n\nexport const GUEST_INSTRUCTIONS =\n \"You are a helpful assistant. This is a temporary text conversation. You have no tools, files, saved user history, or ability to perform external actions.\";\n",
|
|
62
|
+
"type": "registry:file",
|
|
63
|
+
"target": "~/chatjs/plugins/guest-chat/guest-policy.ts"
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
"path": "src/plugins/guest-chat/src/guest-retention.ts",
|
|
67
|
+
"content": "import type { TraceCapturePolicy } from \"eve/instrumentation/otel\";\n\n// EVE derives retention 0 from omitted input/output capture. Preserve EVE's\n// default policy for every other principal, including registered users.\nexport const guestTracePolicy: TraceCapturePolicy = ({ principalType }) =>\n principalType === \"guest\"\n ? { emit: true, recordInputs: false, recordOutputs: false }\n : true;\n",
|
|
68
|
+
"type": "registry:file",
|
|
69
|
+
"target": "~/chatjs/plugins/guest-chat/guest-retention.ts"
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
"path": "src/plugins/guest-chat/src/guest-queries.ts",
|
|
73
|
+
"content": "import { and, eq, inArray, isNull, lte, or, sql } from \"drizzle-orm\";\nimport { z } from \"zod\";\n\nimport { db } from \"@/lib/db/client\";\nimport { guestRuntimeRate, guestRuntimeSession } from \"./guest-schema\";\n\ntype GuestTransaction = Parameters<Parameters<typeof db.transaction>[0]>[0];\nconst hash = z.string().regex(/^[0-9a-f]{64}$/u);\nconst positiveLimit = z.number().int().positive();\n\nconst rateBucket = async (\n tx: GuestTransaction,\n ipHash: string,\n kind: \"session\" | \"message\"\n) => {\n await tx.execute(\n sql`select pg_advisory_xact_lock(hashtext(${`guest-runtime:${kind}:${ipHash}`}))`\n );\n const [clock] = await tx\n .select({\n startsAt:\n sql<Date>`date_trunc(${kind === \"session\" ? \"hour\" : \"minute\"}, now())`.mapWith(\n guestRuntimeRate.startsAt\n ),\n })\n .from(sql`(select 1) as clock`);\n if (typeof clock !== \"object\") {\n throw new TypeError(\"Database clock unavailable.\");\n }\n const key = { ipHash, kind, startsAt: clock.startsAt };\n const [row] = await tx\n .select()\n .from(guestRuntimeRate)\n .where(\n and(\n eq(guestRuntimeRate.ipHash, ipHash),\n eq(guestRuntimeRate.kind, kind),\n eq(guestRuntimeRate.startsAt, key.startsAt)\n )\n );\n return { key, requests: row?.requests ?? 0 };\n};\n\nconst incrementRate = async (\n tx: GuestTransaction,\n key: typeof guestRuntimeRate.$inferInsert\n): Promise<void> => {\n await tx\n .insert(guestRuntimeRate)\n .values({ ...key, requests: 1 })\n .onConflictDoUpdate({\n target: [\n guestRuntimeRate.ipHash,\n guestRuntimeRate.kind,\n guestRuntimeRate.startsAt,\n ],\n set: { requests: sql`${guestRuntimeRate.requests} + 1` },\n });\n};\n\nexport const createGuestRuntimeSession = async (input: {\n ownerId: string;\n modelId: string;\n ipHash: string;\n credentialExpiresAt: Date;\n requestsPerMinute: number;\n sessionsPerHour: number;\n}) => {\n hash.parse(input.ipHash);\n positiveLimit.parse(input.requestsPerMinute);\n positiveLimit.parse(input.sessionsPerHour);\n z.string().min(1).parse(input.ownerId);\n z.string().min(1).parse(input.modelId);\n if (\n !Number.isFinite(input.credentialExpiresAt.getTime()) ||\n input.credentialExpiresAt <= new Date()\n ) {\n throw new Error(\"Guest credential expiry must be in the future.\");\n }\n return await db.transaction(async (tx) => {\n const bucket = await rateBucket(tx, input.ipHash, \"session\");\n if (bucket.requests >= input.sessionsPerHour) {\n return { status: \"rate-limited\" } as const;\n }\n const [guest] = await tx\n .insert(guestRuntimeSession)\n .values({\n ownerId: input.ownerId,\n modelId: input.modelId,\n ipHash: input.ipHash,\n credentialExpiresAt: input.credentialExpiresAt,\n })\n .returning();\n if (typeof guest !== \"object\") {\n throw new TypeError(\"Guest policy creation failed.\");\n }\n await incrementRate(tx, bucket.key);\n return { status: \"ready\", guest } as const;\n });\n};\n\nexport const bindGuestRuntimeSession = async (\n id: string,\n ownerId: string,\n sessionId: string\n): Promise<boolean> => {\n z.string().min(1).parse(sessionId);\n const rows = await db\n .update(guestRuntimeSession)\n .set({ sessionId })\n .where(\n and(\n eq(guestRuntimeSession.id, id),\n eq(guestRuntimeSession.ownerId, ownerId),\n eq(guestRuntimeSession.state, \"active\"),\n sql`${guestRuntimeSession.credentialExpiresAt} > now()`,\n or(\n isNull(guestRuntimeSession.sessionId),\n eq(guestRuntimeSession.sessionId, sessionId)\n )\n )\n )\n .returning({ id: guestRuntimeSession.id });\n return rows.length === 1;\n};\n\nexport const readGuestRuntimePolicy = async (\n id: string,\n ownerId: string\n): Promise<typeof guestRuntimeSession.$inferSelect | null> => {\n const [guest] = await db\n .select()\n .from(guestRuntimeSession)\n .where(\n and(\n eq(guestRuntimeSession.id, id),\n eq(guestRuntimeSession.ownerId, ownerId)\n )\n );\n return guest ?? null;\n};\n\nexport const readGuestRuntimeSession = async (\n sessionId: string\n): Promise<typeof guestRuntimeSession.$inferSelect | null> => {\n const [guest] = await db\n .select()\n .from(guestRuntimeSession)\n .where(eq(guestRuntimeSession.sessionId, sessionId));\n return guest ?? null;\n};\n\n// Admission is charged before dispatch. Ambiguous network failures do not refund\n// capacity: retrying cannot exceed the budget by claiming a send was lost.\nexport const reserveGuestRuntimeMessage = async (input: {\n sessionId: string;\n ownerId: string;\n requestsPerMinute: number;\n inputCharacters: number;\n maxInputCharacters: number;\n}): Promise<\"ready\" | \"unavailable\" | \"input-limit\" | \"rate-limited\"> => {\n positiveLimit.parse(input.requestsPerMinute);\n positiveLimit.parse(input.inputCharacters);\n positiveLimit.parse(input.maxInputCharacters);\n return await db.transaction(async (tx) => {\n const [guest] = await tx\n .select()\n .from(guestRuntimeSession)\n .where(\n and(\n eq(guestRuntimeSession.sessionId, input.sessionId),\n eq(guestRuntimeSession.ownerId, input.ownerId),\n eq(guestRuntimeSession.state, \"active\"),\n sql`${guestRuntimeSession.credentialExpiresAt} > now()`,\n sql`${guestRuntimeSession.expiresAt} > now()`\n )\n )\n .for(\"update\");\n if (typeof guest !== \"object\") {\n return \"unavailable\";\n }\n if (\n guest.inputCharactersUsed + input.inputCharacters >\n input.maxInputCharacters\n ) {\n return \"input-limit\";\n }\n const bucket = await rateBucket(tx, guest.ipHash, \"message\");\n if (bucket.requests >= input.requestsPerMinute) {\n return \"rate-limited\";\n }\n await incrementRate(tx, bucket.key);\n await tx\n .update(guestRuntimeSession)\n .set({\n inputCharactersUsed: sql`${guestRuntimeSession.inputCharactersUsed} + ${input.inputCharacters}`,\n })\n .where(eq(guestRuntimeSession.id, guest.id));\n return \"ready\";\n });\n};\n\n// A five-minute cooldown bounds repeated failures. Completion is idempotent\n// for the exact policy/session binding when retries overlap.\nexport const claimExpiredGuestRuntimeSession = async () =>\n await db.transaction(async (tx) => {\n const [guest] = await tx\n .select()\n .from(guestRuntimeSession)\n .where(\n and(\n inArray(guestRuntimeSession.state, [\"active\", \"deleting\"]),\n lte(guestRuntimeSession.expiresAt, sql`now()`),\n or(\n isNull(guestRuntimeSession.cleanupAttemptedAt),\n lte(\n guestRuntimeSession.cleanupAttemptedAt,\n sql`now() - interval '5 minutes'`\n )\n )\n )\n )\n .orderBy(\n sql`${guestRuntimeSession.cleanupAttemptedAt} asc nulls first`,\n guestRuntimeSession.createdAt\n )\n .limit(1)\n .for(\"update\", { skipLocked: true });\n if (typeof guest !== \"object\") {\n return null;\n }\n await tx\n .update(guestRuntimeSession)\n .set({ state: \"deleting\", cleanupAttemptedAt: sql`now()` })\n .where(eq(guestRuntimeSession.id, guest.id));\n return { ...guest, state: \"deleting\" };\n });\n\n// Completes local credential-policy cleanup; this is not a claim of provider payload erasure.\nexport const completeGuestRuntimeDeletion = async (\n id: string,\n sessionId: string\n): Promise<boolean> => {\n const rows = await db\n .update(guestRuntimeSession)\n .set({\n state: \"deleted\",\n deletedAt: sql`coalesce(${guestRuntimeSession.deletedAt}, now())`,\n })\n .where(\n and(\n eq(guestRuntimeSession.id, id),\n eq(guestRuntimeSession.sessionId, sessionId),\n inArray(guestRuntimeSession.state, [\"deleting\", \"deleted\"])\n )\n )\n .returning({ id: guestRuntimeSession.id });\n return rows.length === 1;\n};\n\nexport const pruneGuestRuntimeRates = async (): Promise<void> => {\n await db.execute(\n sql`delete from ${guestRuntimeRate} where ${guestRuntimeRate.startsAt} <= now() - interval '2 days'`\n );\n};\n\n// Only the cleanup worker may bind a replayed creation after public access expires.\nexport const bindGuestRuntimeCleanupSession = async (\n id: string,\n ownerId: string,\n sessionId: string\n): Promise<boolean> => {\n z.string().min(1).parse(sessionId);\n const rows = await db\n .update(guestRuntimeSession)\n .set({ sessionId })\n .where(\n and(\n eq(guestRuntimeSession.id, id),\n eq(guestRuntimeSession.ownerId, ownerId),\n eq(guestRuntimeSession.state, \"deleting\"),\n or(\n isNull(guestRuntimeSession.sessionId),\n eq(guestRuntimeSession.sessionId, sessionId)\n )\n )\n )\n .returning({ id: guestRuntimeSession.id });\n return rows.length === 1;\n};\n\n/** Includes unclaimed expired guests and attempts hidden by cooldowns or another worker. */\nexport const countPendingGuestRuntimeDeletions = async (): Promise<number> => {\n const [row] = await db\n .select({ count: sql<number>`count(*)`.mapWith(Number) })\n .from(guestRuntimeSession)\n .where(\n and(\n inArray(guestRuntimeSession.state, [\"active\", \"deleting\"]),\n lte(guestRuntimeSession.expiresAt, sql`now()`)\n )\n );\n if (typeof row !== \"object\") {\n throw new TypeError(\"Guest deletion inventory unavailable.\");\n }\n return row.count;\n};\n",
|
|
74
|
+
"type": "registry:file",
|
|
75
|
+
"target": "~/chatjs/plugins/guest-chat/guest-queries.ts"
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
"path": "src/plugins/guest-chat/src/guest-scheduler.ts",
|
|
79
|
+
"content": "import { env } from \"@/lib/env\";\n\nimport { localDeletionAvailable } from \"@/lib/eve/local-deletion-available\";\n\nconst CLEANUP_INTERVAL_MS = 60_000;\n\ninterface CleanupScheduler {\n stop: () => void;\n start: () => void;\n run: () => Promise<void>;\n}\n\nconst schedulerGlobal: typeof globalThis & {\n chatjsEveGuestCleanup?: CleanupScheduler;\n} = globalThis;\n\nconst enabled = (): boolean => {\n if (\n env.NODE_ENV !== \"development\" ||\n !env.EVE_GATEWAY_SECRET ||\n !localDeletionAvailable()\n ) {\n return false;\n }\n try {\n const database = new URL(env.DATABASE_URL);\n return (\n [\"postgres:\", \"postgresql:\"].includes(database.protocol) &&\n [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(database.hostname)\n );\n } catch {\n return false;\n }\n};\n\n/**\n * Start or refresh the development-only guest cleanup scheduler.\n * Never load database clients for a remote or disabled runtime.\n * @returns {(() => void) | undefined} The scheduler stop callback, or undefined when local cleanup is disabled.\n */\nexport const startLocalEveGuestCleanup = (): (() => void) | undefined => {\n if (!enabled()) {\n schedulerGlobal.chatjsEveGuestCleanup?.stop();\n return undefined;\n }\n const run = async (): Promise<void> => {\n if (!enabled()) {\n return;\n }\n const { cleanupGuestRuntimeSessions } = await import(\"./guest-cleanup\");\n const results = await Promise.allSettled([cleanupGuestRuntimeSessions()]);\n for (const result of results) {\n if (\n result.status === \"fulfilled\" &&\n (result.value.skipped ||\n result.value.retiredCount ||\n Boolean(result.value.pendingCount))\n ) {\n console.info(\"Local EVE guest cleanup\", result.value);\n }\n }\n if (results.some((result) => result.status === \"rejected\")) {\n throw new Error(\"Guest cleanup incomplete; the next sweep will retry.\");\n }\n };\n if (schedulerGlobal.chatjsEveGuestCleanup) {\n // Instrumentation can be reloaded during development. Refresh the callback\n // without adding another timer or overlapping an in-flight sweep.\n schedulerGlobal.chatjsEveGuestCleanup.run = run;\n schedulerGlobal.chatjsEveGuestCleanup.start();\n return schedulerGlobal.chatjsEveGuestCleanup.stop;\n }\n let stopped = true;\n let running = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const scheduler = {\n run,\n schedule(): void {\n if (stopped || running || timer) {\n return;\n }\n timer = setTimeout(() => {\n void scheduler.tick();\n }, CLEANUP_INTERVAL_MS);\n timer.unref();\n },\n start(): void {\n stopped = false;\n scheduler.schedule();\n },\n stop: (): void => {\n stopped = true;\n clearTimeout(timer);\n timer = undefined;\n },\n async tick(): Promise<void> {\n timer = undefined;\n running = true;\n try {\n await scheduler.run();\n } catch {\n console.error(\n \"Local EVE guest cleanup failed; the next sweep will retry.\"\n );\n } finally {\n running = false;\n scheduler.schedule();\n }\n },\n };\n schedulerGlobal.chatjsEveGuestCleanup = scheduler;\n scheduler.start();\n return scheduler.stop;\n};\n",
|
|
80
|
+
"type": "registry:file",
|
|
81
|
+
"target": "~/chatjs/plugins/guest-chat/guest-scheduler.ts"
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
"path": "src/plugins/guest-chat/src/guest-schema.ts",
|
|
85
|
+
"content": "import { sql } from \"drizzle-orm\";\nimport {\n pgTable,\n uuid,\n text,\n integer,\n timestamp,\n check,\n index,\n primaryKey,\n} from \"drizzle-orm/pg-core\";\n\nconst guestRuntimeSession = pgTable(\n \"GuestRuntimeSession\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n ownerId: text(\"ownerId\").notNull().unique(),\n sessionId: text(\"sessionId\").unique(),\n modelId: text(\"modelId\").notNull(),\n ipHash: text(\"ipHash\").notNull(),\n policyVersion: integer(\"policyVersion\").notNull().default(1),\n state: text(\"state\").notNull().default(\"active\"),\n createdAt: timestamp(\"createdAt\", { withTimezone: true })\n .notNull()\n .defaultNow(),\n expiresAt: timestamp(\"expiresAt\", { withTimezone: true })\n .notNull()\n .default(sql`now() + interval '24 hours'`),\n credentialExpiresAt: timestamp(\"credentialExpiresAt\", {\n withTimezone: true,\n }).notNull(),\n inputCharactersUsed: integer(\"inputCharactersUsed\").notNull().default(0),\n cleanupAttemptedAt: timestamp(\"cleanupAttemptedAt\", { withTimezone: true }),\n deletedAt: timestamp(\"deletedAt\", { withTimezone: true }),\n },\n (columns) => [\n check(\n \"GuestRuntimeSession_state\",\n sql`${columns.state} in ('active', 'deleting', 'deleted')`\n ),\n check(\n \"GuestRuntimeSession_ip_hash\",\n sql`${columns.ipHash} ~ '^[0-9a-f]{64}$'`\n ),\n check(\n \"GuestRuntimeSession_expiry\",\n sql`${columns.expiresAt} = ${columns.createdAt} + interval '24 hours'`\n ),\n index(\"GuestRuntimeSession_cleanup_idx\").on(\n columns.state,\n columns.expiresAt\n ),\n ]\n);\n\nconst guestRuntimeRate = pgTable(\n \"GuestRuntimeRate\",\n {\n ipHash: text(\"ipHash\").notNull(),\n kind: text(\"kind\").notNull(),\n startsAt: timestamp(\"startsAt\", { withTimezone: true }).notNull(),\n requests: integer(\"requests\").notNull().default(0),\n },\n (columns) => [\n primaryKey({ columns: [columns.ipHash, columns.kind, columns.startsAt] }),\n check(\"GuestRuntimeRate_requests\", sql`${columns.requests} >= 0`),\n check(\n \"GuestRuntimeRate_kind\",\n sql`${columns.kind} in ('session', 'message')`\n ),\n ]\n);\n\nexport { guestRuntimeSession, guestRuntimeRate };\n",
|
|
86
|
+
"type": "registry:file",
|
|
87
|
+
"target": "~/chatjs/plugins/guest-chat/guest-schema.ts"
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
"path": "src/plugins/guest-chat/src/routes/create-session.ts",
|
|
91
|
+
"content": "import { readGuestBody } from \"@/chatjs/plugins/guest-chat/guest-body\";\nimport {\n createGuestRuntimeSession,\n bindGuestRuntimeSession,\n} from \"@/chatjs/plugins/guest-chat/guest-queries\";\nimport { guestRequestIpHash } from \"@/chatjs/plugins/guest-chat/guest-ip\";\nimport { GUEST_POLICY } from \"@/chatjs/plugins/guest-chat/guest-policy\";\nimport {\n issueGuestCredential,\n newGuestClaims,\n} from \"@/chatjs/plugins/guest-chat/guest-credential\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { env } from \"@/lib/env\";\nimport { getEveConnectionOptions } from \"@/lib/eve/connection-options\";\nimport { loadEveModelDefinition } from \"@/lib/eve/model-selection\";\nimport { sameOrigin } from \"@/lib/eve/request-policy\";\nimport { z } from \"zod\";\n\nconst MINIMUM_MODEL_ID_LENGTH = 1;\nconst GUEST_CREATION_TIMEOUT_MS = 60_000;\n\nconst hasConfiguredHost = (value: typeof env.APP_URL): value is string =>\n Boolean(value);\n\nconst input = z\n .object({ modelId: z.string().min(MINIMUM_MODEL_ID_LENGTH) })\n .strict();\n\nconst createdSession = z.object({\n sessionId: z.string().regex(/^[A-Za-z0-9_-]+$/u),\n});\n\n/**\n * Starts a guest Eve session and returns a browser-safe, session-scoped credential.\n * The creation credential remains server-side; the client keeps the guest credential in memory.\n * @param {Request} request Same-origin request containing the selected guest model.\n * @returns {Promise<Response>} JSON with the guest session details, or an error response.\n */\nexport const POST = async (\n request: ReadonlyNativeSurface<Request>\n): Promise<Response> => {\n if (!sameOrigin(request, new URL(env.APP_URL ?? request.url).origin)) {\n return new Response(null, { status: 403 });\n }\n const value = input.safeParse(await readGuestBody(request));\n if (!value.success || value.data.modelId !== GUEST_POLICY.modelId) {\n return Response.json(\n { error: \"Choose an available guest model.\" },\n { status: 400 }\n );\n }\n const hasVercelHost = Boolean(env.VERCEL_URL);\n const host = hasVercelHost ? `https://${env.VERCEL_URL}` : env.APP_URL;\n if (!hasConfiguredHost(host)) {\n return Response.json(\n { error: \"Configure APP_URL before starting guest chats.\" },\n { status: 503 }\n );\n }\n await loadEveModelDefinition(value.data.modelId);\n let ipHash: string;\n try {\n ipHash = guestRequestIpHash(request);\n } catch {\n return Response.json(\n { error: \"Guest admission is unavailable.\" },\n { status: 503 }\n );\n }\n const claims = newGuestClaims(GUEST_POLICY.modelId);\n const admission = await createGuestRuntimeSession({\n ownerId: claims.ownerId,\n modelId: GUEST_POLICY.modelId,\n ipHash,\n credentialExpiresAt: new Date(claims.expiresAt),\n requestsPerMinute: GUEST_POLICY.requestsPerMinute,\n sessionsPerHour: GUEST_POLICY.sessionsPerHour,\n });\n if (admission.status !== \"ready\") {\n return Response.json(\n { error: \"Guest limit reached. Please try again later or sign in.\" },\n { status: 429 }\n );\n }\n claims.policyId = admission.guest.id;\n const connection = getEveConnectionOptions(\n claims.ownerId,\n new URL(host).origin\n );\n const response = await fetch(\n new URL(\"/eve/chat/v1/session\", connection.baseUrl),\n {\n body: JSON.stringify({ operationId: claims.policyId }),\n cache: \"no-store\",\n headers: {\n ...connection.headers,\n authorization: `Bearer ${issueGuestCredential(claims)}`,\n \"content-type\": \"application/json\",\n },\n method: \"POST\",\n redirect: \"error\",\n signal: AbortSignal.timeout(GUEST_CREATION_TIMEOUT_MS),\n }\n );\n if (!response.ok) {\n return Response.json(\n { error: \"Could not start chat. Please try again.\" },\n { status: 502 }\n );\n }\n const { sessionId } = createdSession.parse(await response.json());\n if (\n !(await bindGuestRuntimeSession(claims.policyId, claims.ownerId, sessionId))\n ) {\n return Response.json(\n { error: \"Could not bind guest session. Please try again.\" },\n { status: 502 }\n );\n }\n return Response.json(\n {\n credential: issueGuestCredential({ ...claims, sessionId }),\n expiresAt: claims.expiresAt,\n sessionId,\n },\n { headers: { \"cache-control\": \"no-store\" } }\n );\n};\n",
|
|
92
|
+
"type": "registry:file",
|
|
93
|
+
"target": "~/chatjs/plugins/guest-chat/routes/create-session.ts"
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
"path": "src/plugins/guest-chat/src/server-plugin.ts",
|
|
97
|
+
"content": "import type { ChatPlugin } from \"@/chatjs/core/installation/plugin\";\n\nexport const guestChat = () =>\n ({\n id: \"guest-chat\",\n instrumentation: async () => {\n if (process.env.NEXT_RUNTIME === \"nodejs\") {\n const { startLocalEveGuestCleanup } = await import(\"./guest-scheduler\");\n startLocalEveGuestCleanup();\n }\n },\n }) satisfies ChatPlugin;\n",
|
|
98
|
+
"type": "registry:file",
|
|
99
|
+
"target": "~/chatjs/plugins/guest-chat/server-plugin.ts"
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
"path": "src/plugins/guest-chat/src/session-profile.ts",
|
|
103
|
+
"content": "import type { SessionProfile } from \"@/chatjs/core/session/contracts\";\nimport { authenticateDisposableGuest } from \"./guest-auth\";\nimport { resolveGuestModel } from \"./guest-model\";\nimport { GUEST_INSTRUCTIONS } from \"./guest-policy\";\n\nexport const guestSessionProfile = {\n authenticator: \"chatjs-disposable-guest\",\n authenticate: authenticateDisposableGuest,\n toolNames: new Set<string>(),\n specialists: false,\n resolveModel: resolveGuestModel,\n instructions: GUEST_INSTRUCTIONS,\n} satisfies SessionProfile;\n",
|
|
104
|
+
"type": "registry:file",
|
|
105
|
+
"target": "~/chatjs/plugins/guest-chat/session-profile.ts"
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
"path": "src/plugins/guest-chat/src/signed-out.tsx",
|
|
109
|
+
"content": "\"use client\";\n\nimport { hasText, nonEmptyText } from \"@/components/text-value\";\n\nimport { useEveAgent } from \"eve/react\";\nimport React, { useEffect, useRef, useState } from \"react\";\nimport type { JSX as ReactJSX, ReactNode } from \"react\";\nimport { z } from \"zod\";\n\nimport {\n MessageScroller,\n MessageScrollerProvider,\n MessageScrollerViewport,\n MessageScrollerContent,\n MessageScrollerButton,\n} from \"@/components/ui/message-scroller\";\nimport { ChatHeaderView } from \"@/components/chat-header-view\";\nimport { ChatConversation } from \"@/components/chat/chat-conversation\";\nimport { ChatWelcomeView } from \"@/components/chat/chat-welcome-view\";\nimport { Button } from \"@/components/ui/button\";\nimport type { ReadonlyEveMessage } from \"@/lib/eve/readonly-message-types\";\nimport { GUEST_POLICY } from \"./guest-policy\";\n\nimport { EveModelPicker } from \"@/components/eve/eve-model-picker\";\nimport { EveComposer } from \"@/components/eve/eve-composer\";\nimport { ChatTranscript } from \"@/components/chat/chat-transcript\";\n\nconst bindingSchema = z.object({\n credential: z.string(),\n expiresAt: z.number(),\n sessionId: z.string(),\n});\ntype Binding = Readonly<z.infer<typeof bindingSchema>> & {\n readonly firstMessage: string;\n readonly modelId: string;\n};\n\nconst retireGuest = async (\n binding: Readonly<Pick<Binding, \"sessionId\" | \"credential\">>\n): Promise<void> => {\n try {\n await fetch(`/eve/chat/v1/session/${binding.sessionId}/end`, {\n body: \"{}\",\n headers: {\n authorization: `Bearer ${binding.credential}`,\n \"content-type\": \"application/json\",\n },\n keepalive: true,\n method: \"POST\",\n });\n } catch {\n // Unload delivery is best effort. Scheduled cleanup handles abandoned sessions.\n }\n};\n\nconst createGuestSession = async (modelId: string) => {\n const response = await fetch(\"/api/eve-guest\", {\n body: JSON.stringify({ modelId }),\n headers: { \"content-type\": \"application/json\" },\n method: \"POST\",\n });\n if (!response.ok) {\n throw new Error(\"Could not start chat. Please try again.\");\n }\n return bindingSchema.parse(await response.json());\n};\n\n/** Shared guest presentation, also exercised with deterministic visual fixtures. */\nconst GuestConversationView = ({\n messages,\n modelId,\n busy,\n failure,\n expired,\n draft,\n onDraftChange,\n onSend,\n onStop,\n}: {\n readonly messages: readonly ReadonlyEveMessage[];\n readonly modelId: string;\n readonly busy: boolean;\n readonly failure?: string;\n readonly expired: boolean;\n readonly draft: string;\n readonly onDraftChange: (draft: string) => void;\n readonly onSend: (text: string) => void;\n readonly onStop: () => void;\n}): ReactJSX.Element => (\n <>\n <MessageScrollerProvider autoScroll>\n <MessageScroller className=\"min-h-0 flex-1\">\n <MessageScrollerViewport>\n <MessageScrollerContent className=\"mx-auto w-full max-w-3xl p-4\">\n <ChatTranscript\n messages={messages}\n isReadonly={false}\n disabled={busy}\n respond={() => {\n // Guest sessions do not expose tool input requests.\n }}\n modelForMessage={() => modelId}\n />\n {busy && (\n <output className=\"text-muted-foreground text-sm\">\n Responding…\n </output>\n )}\n </MessageScrollerContent>\n </MessageScrollerViewport>\n <MessageScrollerButton />\n </MessageScroller>\n </MessageScrollerProvider>\n <div className=\"mx-auto w-full max-w-3xl p-4\">\n {hasText(failure) && (\n <p role=\"alert\" className=\"text-destructive mb-3 text-sm\">\n {failure}\n </p>\n )}\n {expired && (\n <output className=\"text-muted-foreground mb-3 text-sm\">\n This chat has expired. Start a new chat to continue.\n <Button\n variant=\"link\"\n onClick={() => {\n globalThis.dispatchEvent(new Event(\"chatjs:new-chat\"));\n }}\n >\n New chat\n </Button>\n </output>\n )}\n <EveComposer\n autoFocus\n\n modelPicker={<EveModelPicker disabled modelId={modelId} />}\n status={busy ? \"streaming\" : \"ready\"}\n disabled={busy || expired}\n draft={draft}\n onDraftChange={onDraftChange}\n onSubmit={() => {\n onSend(draft.trim());\n }}\n onStop={\n busy && !expired\n ? (): void => {\n onStop();\n }\n : undefined\n }\n />\n </div>\n </>\n);\n\nconst GuestConversation = ({\n binding,\n}: {\n readonly binding: Binding;\n}): ReactJSX.Element => {\n const agent = useEveAgent({\n agent: \"chat\",\n auth: { bearer: binding.credential },\n initialSession: { sessionId: binding.sessionId, streamIndex: 0 },\n });\n const [draft, setDraft] = useState(\"\");\n\n const [commandError, setCommandError] = useState(\"\");\n const [expired, setExpired] = useState(false);\n const started = useRef(false);\n const pending = useRef(false);\n const busy = agent.status === \"busy\" || agent.status === \"resuming\";\n const send = async (text: string): Promise<void> => {\n if (pending.current) {\n return;\n }\n if (Date.now() >= binding.expiresAt) {\n setExpired(true);\n return;\n }\n pending.current = true;\n setCommandError(\"\");\n setDraft(\"\");\n try {\n await agent.send(text);\n } catch (error) {\n setCommandError(\n error instanceof Error ? error.message : \"Message could not be sent.\"\n );\n setDraft(text);\n }\n pending.current = false;\n };\n useEffect(() => {\n // EVE attaches its observer on the next task. Defer the initial send too,\n // so React Strict Mode's probe cleanup cannot abort the first message.\n const timer = setTimeout(() => {\n if (!started.current) {\n started.current = true;\n void send(binding.firstMessage);\n }\n }, 0);\n return (): void => {\n clearTimeout(timer);\n };\n });\n useEffect(() => {\n const timer = setTimeout(\n () => {\n setExpired(true);\n },\n Math.max(0, binding.expiresAt - Date.now())\n );\n return (): void => {\n clearTimeout(timer);\n };\n }, [binding.expiresAt]);\n useEffect(() => {\n const retire = (): void => {\n void retireGuest(binding);\n };\n window.addEventListener(\"pagehide\", retire);\n return (): void => {\n window.removeEventListener(\"pagehide\", retire);\n };\n }, [binding]);\n const stop = async (): Promise<void> => {\n try {\n await agent.cancel();\n } catch {\n setCommandError(\"Could not stop the response.\");\n }\n };\n const latestTurn = agent.events.findLast(\n (event) => event.type === \"turn.started\" || event.type === \"turn.settled\"\n );\n const failure =\n nonEmptyText(commandError) ??\n nonEmptyText(agent.error?.message) ??\n (latestTurn?.type === \"turn.settled\"\n ? latestTurn.data.error?.message\n : undefined);\n return (\n <GuestConversationView\n messages={agent.messages}\n modelId={binding.modelId}\n busy={busy}\n failure={failure}\n expired={expired}\n draft={draft}\n onDraftChange={setDraft}\n onSend={(text) => {\n void send(text);\n }}\n onStop={() => {\n void stop();\n }}\n />\n );\n};\n\nconst GuestChatLayout = ({\n children,\n}: {\n readonly children: ReactNode;\n}): ReactJSX.Element => (\n <ChatConversation className=\"bg-background @container h-dvh max-h-dvh w-full min-w-0\">\n <ChatHeaderView breadcrumb={null} className=\"h-(--header-height)\" />\n {children}\n </ChatConversation>\n);\n\nconst GuestWelcomeView = ({\n modelId,\n busy,\n error,\n draft,\n onDraftChange,\n onSend,\n}: {\n readonly modelId: string;\n readonly busy: boolean;\n readonly error?: string;\n readonly draft: string;\n readonly onDraftChange: (draft: string) => void;\n readonly onSend: () => void;\n}): ReactJSX.Element => (\n <ChatWelcomeView>\n {hasText(error) && (\n <p role=\"alert\" className=\"text-destructive mb-3 text-sm\">\n {error}\n </p>\n )}\n <EveComposer\n autoFocus\n modelPicker={<EveModelPicker disabled modelId={modelId} />}\n status={busy ? \"submitted\" : \"ready\"}\n disabled={busy || !modelId}\n draft={draft}\n onDraftChange={onDraftChange}\n onSubmit={onSend}\n />\n </ChatWelcomeView>\n);\n\n/** No URL, cookie, storage, or persisted application identity owns this chat. */\nconst GuestChatScreen = (): ReactJSX.Element => {\n const [binding, setBinding] = useState<Binding>();\n const [draft, setDraft] = useState(\"\");\n const { modelId } = GUEST_POLICY;\n const [busy, setBusy] = useState(false);\n const [commandError, setCommandError] = useState(\"\");\n const pending = useRef(false);\n const generation = useRef(0);\n const submit = async (): Promise<void> => {\n if (pending.current || !draft.trim()) {\n return;\n }\n const currentGeneration = generation.current;\n pending.current = true;\n setBusy(true);\n setCommandError(\"\");\n try {\n const created = {\n ...(await createGuestSession(modelId)),\n firstMessage: draft.trim(),\n modelId,\n };\n if (generation.current !== currentGeneration) {\n void retireGuest(created);\n return;\n }\n setBinding(created);\n setDraft(\"\");\n } catch (error) {\n if (generation.current !== currentGeneration) {\n return;\n }\n setCommandError(\n error instanceof Error ? error.message : \"Could not start chat.\"\n );\n }\n if (generation.current === currentGeneration) {\n pending.current = false;\n setBusy(false);\n }\n };\n useEffect(() => {\n const reset = (): void => {\n generation.current += 1;\n pending.current = false;\n setBusy(false);\n if (binding) {\n void retireGuest(binding);\n }\n setBinding(undefined);\n setDraft(\"\");\n setCommandError(\"\");\n };\n const restore = (\n event: Readonly<Pick<PageTransitionEvent, \"persisted\">>\n ): void => {\n if (event.persisted) {\n reset();\n }\n };\n globalThis.addEventListener(\"chatjs:new-chat\", reset);\n window.addEventListener(\"pageshow\", restore);\n return (): void => {\n globalThis.removeEventListener(\"chatjs:new-chat\", reset);\n window.removeEventListener(\"pageshow\", restore);\n };\n }, [binding]);\n return (\n <GuestChatLayout>\n {binding ? (\n <GuestConversation binding={binding} key={binding.sessionId} />\n ) : (\n <GuestWelcomeView\n modelId={modelId}\n busy={busy}\n error={commandError}\n draft={draft}\n onDraftChange={setDraft}\n onSend={() => {\n void submit();\n }}\n />\n )}\n </GuestChatLayout>\n );\n};\n\nexport {\n GuestChatScreen,\n GuestChatLayout,\n GuestWelcomeView,\n GuestConversationView,\n};\n",
|
|
110
|
+
"type": "registry:file",
|
|
111
|
+
"target": "~/chatjs/plugins/guest-chat/signed-out.tsx"
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
"path": "src/plugins/guest-chat/adapters/agent/instrumentation/guest-retention.ts",
|
|
115
|
+
"content": "import { otel } from \"eve/instrumentation/otel\";\nimport { guestTracePolicy } from \"@/chatjs/plugins/guest-chat/guest-retention\";\n\nexport default otel({ tracePolicy: guestTracePolicy });\n",
|
|
116
|
+
"type": "registry:file",
|
|
117
|
+
"target": "~/agent/instrumentation/guest-retention.ts"
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
"path": "src/plugins/guest-chat/adapters/app/api/eve-guest/route.ts",
|
|
121
|
+
"content": "// ChatJS source: guest-chat. Ownership: chatjs/plugins/guest-chat/chatjs.json.\nexport { POST } from \"@/chatjs/plugins/guest-chat/routes/create-session\";\n",
|
|
122
|
+
"type": "registry:file",
|
|
123
|
+
"target": "~/app/api/eve-guest/route.ts"
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
"path": "dist/source/guest-chat.json",
|
|
127
|
+
"content": "{\n \"id\": \"guest-chat\",\n \"kind\": \"plugin\",\n \"files\": [\n \"chatjs/plugins/guest-chat/cleanup.ts\",\n \"chatjs/plugins/guest-chat/guest-auth.ts\",\n \"chatjs/plugins/guest-chat/guest-body.ts\",\n \"chatjs/plugins/guest-chat/guest-cleanup-auth.ts\",\n \"chatjs/plugins/guest-chat/guest-cleanup.ts\",\n \"chatjs/plugins/guest-chat/guest-credential.ts\",\n \"chatjs/plugins/guest-chat/guest-ip.ts\",\n \"chatjs/plugins/guest-chat/guest-model.ts\",\n \"chatjs/plugins/guest-chat/guest-policy.ts\",\n \"chatjs/plugins/guest-chat/guest-retention.ts\",\n \"chatjs/plugins/guest-chat/guest-queries.ts\",\n \"chatjs/plugins/guest-chat/guest-scheduler.ts\",\n \"chatjs/plugins/guest-chat/guest-schema.ts\",\n \"chatjs/plugins/guest-chat/routes/create-session.ts\",\n \"chatjs/plugins/guest-chat/server-plugin.ts\",\n \"chatjs/plugins/guest-chat/session-profile.ts\",\n \"chatjs/plugins/guest-chat/signed-out.tsx\",\n \"app/api/eve-guest/route.ts\",\n \"agent/instrumentation/guest-retention.ts\"\n ],\n \"databaseSchemas\": [\n \"chatjs/plugins/guest-chat/guest-schema.ts\"\n ],\n \"signedOut\": {\n \"export\": \"GuestChatScreen\"\n },\n \"sessionProfile\": {\n \"export\": \"guestSessionProfile\",\n \"authenticator\": \"chatjs-disposable-guest\"\n },\n \"cleanup\": {\n \"export\": \"guestCleanup\",\n \"id\": \"guest-chat\"\n },\n \"server\": {\n \"export\": \"guestChat\",\n \"routers\": [],\n \"instrumentation\": true\n },\n \"contractVersion\": 2,\n \"uiBase\": \"radix\"\n}\n",
|
|
128
|
+
"type": "registry:file",
|
|
129
|
+
"target": "~/chatjs/plugins/guest-chat/chatjs.json"
|
|
130
|
+
}
|
|
131
|
+
],
|
|
132
|
+
"meta": {
|
|
133
|
+
"chatjs": {
|
|
134
|
+
"id": "guest-chat",
|
|
135
|
+
"kind": "plugin",
|
|
136
|
+
"files": [
|
|
137
|
+
"chatjs/plugins/guest-chat/cleanup.ts",
|
|
138
|
+
"chatjs/plugins/guest-chat/guest-auth.ts",
|
|
139
|
+
"chatjs/plugins/guest-chat/guest-body.ts",
|
|
140
|
+
"chatjs/plugins/guest-chat/guest-cleanup-auth.ts",
|
|
141
|
+
"chatjs/plugins/guest-chat/guest-cleanup.ts",
|
|
142
|
+
"chatjs/plugins/guest-chat/guest-credential.ts",
|
|
143
|
+
"chatjs/plugins/guest-chat/guest-ip.ts",
|
|
144
|
+
"chatjs/plugins/guest-chat/guest-model.ts",
|
|
145
|
+
"chatjs/plugins/guest-chat/guest-policy.ts",
|
|
146
|
+
"chatjs/plugins/guest-chat/guest-retention.ts",
|
|
147
|
+
"chatjs/plugins/guest-chat/guest-queries.ts",
|
|
148
|
+
"chatjs/plugins/guest-chat/guest-scheduler.ts",
|
|
149
|
+
"chatjs/plugins/guest-chat/guest-schema.ts",
|
|
150
|
+
"chatjs/plugins/guest-chat/routes/create-session.ts",
|
|
151
|
+
"chatjs/plugins/guest-chat/server-plugin.ts",
|
|
152
|
+
"chatjs/plugins/guest-chat/session-profile.ts",
|
|
153
|
+
"chatjs/plugins/guest-chat/signed-out.tsx",
|
|
154
|
+
"app/api/eve-guest/route.ts",
|
|
155
|
+
"agent/instrumentation/guest-retention.ts"
|
|
156
|
+
],
|
|
157
|
+
"databaseSchemas": [
|
|
158
|
+
"chatjs/plugins/guest-chat/guest-schema.ts"
|
|
159
|
+
],
|
|
160
|
+
"signedOut": {
|
|
161
|
+
"export": "GuestChatScreen"
|
|
162
|
+
},
|
|
163
|
+
"sessionProfile": {
|
|
164
|
+
"export": "guestSessionProfile",
|
|
165
|
+
"authenticator": "chatjs-disposable-guest"
|
|
166
|
+
},
|
|
167
|
+
"cleanup": {
|
|
168
|
+
"export": "guestCleanup",
|
|
169
|
+
"id": "guest-chat"
|
|
170
|
+
},
|
|
171
|
+
"server": {
|
|
172
|
+
"export": "guestChat",
|
|
173
|
+
"routers": [],
|
|
174
|
+
"instrumentation": true
|
|
175
|
+
},
|
|
176
|
+
"contractVersion": 2,
|
|
177
|
+
"uiBase": "radix"
|
|
178
|
+
}
|
|
179
|
+
},
|
|
180
|
+
"type": "registry:item"
|
|
181
|
+
}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"path": "src/storage/hetzner/storage-provider.ts",
|
|
15
15
|
"content": "export { hetzner as createStorageAdapter } from \"files-sdk/hetzner\";\n",
|
|
16
16
|
"type": "registry:file",
|
|
17
|
-
"target": "~/
|
|
17
|
+
"target": "~/chatjs/providers/storage.ts"
|
|
18
18
|
}
|
|
19
19
|
],
|
|
20
20
|
"meta": {
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"path": "src/storage/ibm-cos/storage-provider.ts",
|
|
15
15
|
"content": "export { ibmCos as createStorageAdapter } from \"files-sdk/ibm-cos\";\n",
|
|
16
16
|
"type": "registry:file",
|
|
17
|
-
"target": "~/
|
|
17
|
+
"target": "~/chatjs/providers/storage.ts"
|
|
18
18
|
}
|
|
19
19
|
],
|
|
20
20
|
"meta": {
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"path": "src/storage/idrive-e2/storage-provider.ts",
|
|
15
15
|
"content": "export { idriveE2 as createStorageAdapter } from \"files-sdk/idrive-e2\";\n",
|
|
16
16
|
"type": "registry:file",
|
|
17
|
-
"target": "~/
|
|
17
|
+
"target": "~/chatjs/providers/storage.ts"
|
|
18
18
|
}
|
|
19
19
|
],
|
|
20
20
|
"meta": {
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "image-viewer",
|
|
4
|
+
"title": "Image viewer",
|
|
5
|
+
"description": "Open image artifacts in a full-screen viewer. Optional for image generation.",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"lucide-react@0.553.0"
|
|
8
|
+
],
|
|
9
|
+
"files": [
|
|
10
|
+
{
|
|
11
|
+
"path": "src/plugins/image-viewer/src/client-plugin.ts",
|
|
12
|
+
"content": "\"use client\";\nimport { definePlugin, slot } from \"@/chatjs/core/ui/slots\";\nimport { ArtifactViewerActions } from \"@/components/artifact-actions\";\nimport { ImageViewerAction } from \"./viewer-action\";\n\nexport const imageViewerClient = definePlugin({\n id: \"image-viewer\",\n slots: [slot(ArtifactViewerActions, ImageViewerAction)],\n});\n",
|
|
13
|
+
"type": "registry:file",
|
|
14
|
+
"target": "~/chatjs/plugins/image-viewer/client-plugin.ts"
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
"path": "src/plugins/image-viewer/src/viewer-action.tsx",
|
|
18
|
+
"content": "\"use client\";\n\nimport { ExpandIcon } from \"lucide-react\";\nimport { useState } from \"react\";\nimport type { ArtifactReference } from \"@/components/artifact-actions\";\nimport { Button } from \"@/components/ui/button\";\nimport { ImageModal } from \"./image-modal\";\n\nexport const ImageViewerAction = ({\n artifact,\n onOpen,\n}: {\n readonly artifact: ArtifactReference;\n readonly onOpen?: () => void;\n}) => {\n const [open, setOpen] = useState(false);\n if (!artifact.mediaType.startsWith(\"image/\")) {\n return null;\n }\n return (\n <>\n <Button\n aria-label=\"Open image\"\n title=\"Open image\"\n size=\"icon-sm\"\n variant=\"ghost\"\n className=\"bg-black/50 text-white hover:bg-black/70 hover:text-white\"\n onClick={() => {\n onOpen?.();\n setOpen(true);\n }}\n >\n <ExpandIcon size={16} />\n </Button>\n {open && (\n <ImageModal\n imageName={artifact.name}\n imageUrl={artifact.url}\n isOpen\n onClose={() => {\n setOpen(false);\n }}\n />\n )}\n </>\n );\n};\n",
|
|
19
|
+
"type": "registry:file",
|
|
20
|
+
"target": "~/chatjs/plugins/image-viewer/viewer-action.tsx"
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
"path": "src/plugins/image-viewer/src/image-modal.tsx",
|
|
24
|
+
"content": "\"use client\";\n\nimport { ImageOffIcon, XIcon } from \"lucide-react\";\nimport Image from \"next/image\";\nimport React from \"react\";\nimport type { JSX as ReactJSX } from \"react\";\n\nimport { ImageActions } from \"@/components/image-actions\";\n\nimport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogTitle,\n} from \"@/components/ui/dialog\";\n\nimport { useImageLoadError } from \"@/hooks/use-image-load-error\";\n\ninterface ImageModalProps {\n readonly imageName?: string;\n readonly imageUrl: string;\n readonly isOpen: boolean;\n readonly onClose: () => void;\n readonly showActions?: boolean;\n}\n\nconst ImageModal = ({\n isOpen,\n onClose,\n imageUrl,\n imageName,\n showActions = true,\n}: ImageModalProps): ReactJSX.Element => {\n const { handleImageError, imageUnavailable } = useImageLoadError(imageUrl);\n\n return (\n <Dialog onOpenChange={onClose} open={isOpen}>\n <DialogContent\n className=\"bg-background/50 h-screen w-screen max-w-none rounded-none border-none p-0 backdrop-blur-sm sm:max-w-none\"\n showCloseButton={false}\n >\n <DialogTitle className=\"sr-only\">\n {imageName ?? \"Image Preview\"}\n </DialogTitle>\n <DialogDescription className=\"sr-only\">\n {imageName ?? \"Image preview\"}\n </DialogDescription>\n <DialogClose className=\"absolute top-4 left-4 z-10 rounded-lg bg-white/10 p-2 text-white hover:bg-white/20\">\n <XIcon size={20} />\n <span className=\"sr-only\">Close</span>\n </DialogClose>\n <button\n className=\"group flex h-full w-full cursor-pointer items-center justify-center\"\n onClick={(event: {\n readonly target: object;\n readonly currentTarget: object;\n }) => {\n if (event.target === event.currentTarget) {\n onClose();\n }\n }}\n type=\"button\"\n >\n {imageUnavailable ? (\n <output className=\"flex flex-col items-center gap-3 text-white\">\n <ImageOffIcon className=\"size-10\" />\n <span>Image unavailable</span>\n </output>\n ) : (\n imageUrl !== \"\" && (\n <Image\n alt={imageName ?? \"Expanded image\"}\n loading=\"eager\"\n unoptimized\n className=\"h-auto max-h-[90vh] w-auto max-w-[90vw] object-contain\"\n // Auto CSS sizing keeps unknown attachment dimensions intrinsic; zero hints reserve no artificial aspect ratio.\n height={0}\n width={0}\n onError={handleImageError}\n src={imageUrl}\n />\n )\n )}\n </button>\n {showActions && !imageUnavailable && (\n <ImageActions\n className=\"absolute top-4 right-4\"\n imageUrl={imageUrl}\n />\n )}\n </DialogContent>\n </Dialog>\n );\n};\nexport { ImageModal };\n",
|
|
25
|
+
"type": "registry:file",
|
|
26
|
+
"target": "~/chatjs/plugins/image-viewer/image-modal.tsx"
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
"path": "dist/source/image-viewer.json",
|
|
30
|
+
"content": "{\n \"id\": \"image-viewer\",\n \"kind\": \"plugin\",\n \"files\": [\n \"chatjs/plugins/image-viewer/client-plugin.ts\",\n \"chatjs/plugins/image-viewer/viewer-action.tsx\",\n \"chatjs/plugins/image-viewer/image-modal.tsx\"\n ],\n \"client\": {\n \"export\": \"imageViewerClient\",\n \"composerControls\": [],\n \"settingsItems\": [],\n \"chat\": true\n },\n \"contractVersion\": 2,\n \"uiBase\": \"radix\"\n}\n",
|
|
31
|
+
"type": "registry:file",
|
|
32
|
+
"target": "~/chatjs/plugins/image-viewer/chatjs.json"
|
|
33
|
+
}
|
|
34
|
+
],
|
|
35
|
+
"meta": {
|
|
36
|
+
"chatjs": {
|
|
37
|
+
"id": "image-viewer",
|
|
38
|
+
"kind": "plugin",
|
|
39
|
+
"files": [
|
|
40
|
+
"chatjs/plugins/image-viewer/client-plugin.ts",
|
|
41
|
+
"chatjs/plugins/image-viewer/viewer-action.tsx",
|
|
42
|
+
"chatjs/plugins/image-viewer/image-modal.tsx"
|
|
43
|
+
],
|
|
44
|
+
"client": {
|
|
45
|
+
"export": "imageViewerClient",
|
|
46
|
+
"composerControls": [],
|
|
47
|
+
"settingsItems": [],
|
|
48
|
+
"chat": true
|
|
49
|
+
},
|
|
50
|
+
"contractVersion": 2,
|
|
51
|
+
"uiBase": "radix"
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
"type": "registry:item"
|
|
55
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "just-bash-sandbox",
|
|
4
|
+
"title": "just-bash",
|
|
5
|
+
"description": "Simulated shell and filesystem. Cannot run native Python or Node processes.",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"eve@npm:@chat-js/eve@1.0.0-rc.6-chatjs.1"
|
|
8
|
+
],
|
|
9
|
+
"files": [
|
|
10
|
+
{
|
|
11
|
+
"path": "src/sandboxes/just-bash/sandbox.ts",
|
|
12
|
+
"content": "import { defineSandbox } from \"eve/sandbox\";\nimport { JustBashSandbox } from \"eve/sandbox/just-bash\";\n\nexport const environment = JustBashSandbox.environment();\nexport default defineSandbox(async () => await environment.open());\n",
|
|
13
|
+
"type": "registry:file",
|
|
14
|
+
"target": "~/agent/sandbox.ts"
|
|
15
|
+
}
|
|
16
|
+
],
|
|
17
|
+
"meta": {
|
|
18
|
+
"chatjs": {
|
|
19
|
+
"contractVersion": 1,
|
|
20
|
+
"kind": "sandbox",
|
|
21
|
+
"id": "just-bash",
|
|
22
|
+
"capabilities": {
|
|
23
|
+
"persistent": true,
|
|
24
|
+
"runtimes": [],
|
|
25
|
+
"cleanup": "eve-session",
|
|
26
|
+
"cancellation": "eve"
|
|
27
|
+
},
|
|
28
|
+
"envRequirements": []
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"type": "registry:item"
|
|
32
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
3
|
"name": "litellm-gateway",
|
|
4
|
-
"title": "
|
|
4
|
+
"title": "LiteLLM",
|
|
5
5
|
"dependencies": [
|
|
6
6
|
"@chat-js/gateways@0.2.0",
|
|
7
7
|
"@ai-sdk/openai-compatible@3.0.44"
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"path": "src/gateways/litellm/gateway.ts",
|
|
12
12
|
"content": "import type { LanguageModelV4 } from \"@ai-sdk/provider\";\n\nimport type { AiGatewayModel } from \"@chat-js/gateways/models\";\n\nimport type { GatewayProvider } from \"@chat-js/gateways/gateway-provider\";\n\nimport { GatewayRuntime } from \"@chat-js/gateways/runtime\";\n\nimport type { ImageModel } from \"ai\";\nimport { createOpenAICompatible } from \"@ai-sdk/openai-compatible\";\nimport { z } from \"zod\";\n\nconst MODEL_DISCOVERY_TIMEOUT_MS = 10_000;\nconst TRAILING_SLASHES_REGEX = /\\/+$/u;\n\nconst litellmModelSchema = z.object({\n created: z.number().optional(),\n id: z.string(),\n object: z.string().optional(),\n owned_by: z.string().optional(),\n});\nconst litellmModelsResponseSchema = z.object({\n data: z.array(litellmModelSchema),\n});\n\ntype LiteLLMModelResponse = z.infer<\n typeof litellmModelsResponseSchema\n>[\"data\"][number];\n\nconst getModelsUrl = (baseURL: string): string => {\n const normalizedBaseURL = baseURL.replace(TRAILING_SLASHES_REGEX, \"\");\n if (normalizedBaseURL.endsWith(\"/v1\")) {\n return `${normalizedBaseURL}/models`;\n }\n return `${normalizedBaseURL}/v1/models`;\n};\n\nconst UNKNOWN_MODEL_LIMIT = 0;\nconst toAiGatewayModel = (model: LiteLLMModelResponse): AiGatewayModel => ({\n context_window: UNKNOWN_MODEL_LIMIT,\n created: model.created ?? UNKNOWN_MODEL_LIMIT,\n description: \"\",\n id: model.id,\n max_tokens: UNKNOWN_MODEL_LIMIT,\n name: model.id,\n object: \"model\",\n owned_by: model.owned_by ?? \"litellm\",\n pricing: {},\n type: \"language\",\n});\n\nclass LiteLLMGateway\n extends GatewayRuntime\n implements GatewayProvider<\"litellm\">\n{\n public readonly type = \"litellm\" as const;\n\n private getProvider(): ReturnType<typeof createOpenAICompatible> {\n const apiKey = this.getApiKey();\n const baseURL = this.getBaseURL();\n if (!(typeof baseURL === \"string\" && baseURL !== \"\")) {\n throw new Error(\"LITELLM_BASE_URL is not configured\");\n }\n return createOpenAICompatible({\n apiKey,\n baseURL,\n name: \"litellm\",\n });\n }\n\n public createLanguageModel(modelId: string): LanguageModelV4 {\n const provider = this.getProvider();\n return provider(modelId);\n }\n\n public createImageModel(modelId: string): ImageModel {\n const provider = this.getProvider();\n return provider.imageModel(modelId);\n }\n\n public readonly createVideoModel = null;\n\n private getApiKey(): string | undefined {\n return this.env.LITELLM_API_KEY;\n }\n\n private getBaseURL(): string | undefined {\n const baseURL = this.env.LITELLM_BASE_URL;\n if (baseURL === undefined || baseURL === \"\") {\n return undefined;\n }\n return z.url().parse(baseURL);\n }\n\n public async fetchModels(): Promise<AiGatewayModel[]> {\n const apiKey = this.getApiKey();\n const baseURL = this.getBaseURL();\n\n if (!(typeof baseURL === \"string\" && baseURL !== \"\")) {\n this.log.warn(\"No LITELLM_BASE_URL found, using fallback models\");\n return [...this.getFallbackModels(this.type)];\n }\n\n const url = getModelsUrl(baseURL);\n this.log.debug({ url }, \"Fetching models from LiteLLM proxy\");\n\n try {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (typeof apiKey === \"string\" && apiKey !== \"\") {\n headers.Authorization = `Bearer ${apiKey}`;\n }\n\n const response = await this.fetch(url, {\n headers,\n signal: AbortSignal.timeout(MODEL_DISCOVERY_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n this.log.error(\n { status: response.status, statusText: response.statusText, url },\n \"LiteLLM proxy returned non-OK response\"\n );\n throw new Error(`Failed to fetch models: ${response.statusText}`);\n }\n\n const body = litellmModelsResponseSchema.parse(await response.json());\n const models = body.data;\n const result = models.map((model) => toAiGatewayModel(model));\n\n this.log.info(\n { modelCount: result.length },\n \"Successfully fetched models from LiteLLM proxy\"\n );\n return result;\n } catch (error) {\n this.log.error(\n { err: error, url },\n \"Error fetching models from LiteLLM proxy, falling back to generated models\"\n );\n return [...this.getFallbackModels(this.type)];\n }\n }\n}\nexport { LiteLLMGateway as Gateway, LiteLLMGateway };\n",
|
|
13
13
|
"type": "registry:file",
|
|
14
|
-
"target": "~/
|
|
14
|
+
"target": "~/chatjs/providers/gateway.ts"
|
|
15
15
|
}
|
|
16
16
|
],
|
|
17
17
|
"meta": {
|
|
@@ -22,9 +22,6 @@
|
|
|
22
22
|
},
|
|
23
23
|
"contractVersion": 1,
|
|
24
24
|
"defaults": {
|
|
25
|
-
"anonymousModels": [
|
|
26
|
-
"openai/gpt-4o-mini"
|
|
27
|
-
],
|
|
28
25
|
"curatedDefaults": [
|
|
29
26
|
"openai/gpt-4o-mini",
|
|
30
27
|
"openai/gpt-4o",
|