@chat-js/registry 0.2.0-beta.3 → 0.2.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +1 -1
  2. package/dist/r/ai-titles.json +1 -1
  3. package/dist/r/attach-workspace-file.json +82 -0
  4. package/dist/r/attachment-uploads.json +1 -2
  5. package/dist/r/base/ai-titles.json +1 -1
  6. package/dist/r/base/attach-workspace-file.json +82 -0
  7. package/dist/r/base/attachment-uploads.json +1 -2
  8. package/dist/r/base/deep-research.json +46 -123
  9. package/dist/r/base/default-sandbox.json +35 -0
  10. package/dist/r/base/docker-sandbox.json +35 -0
  11. package/dist/r/base/generate-image.json +10 -4
  12. package/dist/r/base/generate-video.json +9 -3
  13. package/dist/r/base/guest-chat.json +2 -2
  14. package/dist/r/base/image-viewer.json +55 -0
  15. package/dist/r/base/just-bash-sandbox.json +32 -0
  16. package/dist/r/base/litellm-gateway.json +2 -2
  17. package/dist/r/base/mcp.json +1 -1
  18. package/dist/r/base/openai-compatible-gateway.json +2 -2
  19. package/dist/r/base/openai-gateway.json +2 -2
  20. package/dist/r/base/openrouter-gateway.json +2 -2
  21. package/dist/r/base/projects.json +3 -3
  22. package/dist/r/base/registry.json +970 -1751
  23. package/dist/r/base/search.json +6 -6
  24. package/dist/r/base/sharing.json +3 -3
  25. package/dist/r/base/spreadsheet-grid.json +20 -0
  26. package/dist/r/base/spreadsheet-viewer.json +68 -0
  27. package/dist/r/base/vercel-gateway.json +2 -2
  28. package/dist/r/base/vercel-sandbox.json +8 -26
  29. package/dist/r/base/video-viewer.json +48 -0
  30. package/dist/r/deep-research.json +46 -123
  31. package/dist/r/default-sandbox.json +35 -0
  32. package/dist/r/docker-sandbox.json +35 -0
  33. package/dist/r/eve/deep-research.json +47 -0
  34. package/dist/r/eve/registry.json +53 -0
  35. package/dist/r/generate-image.json +10 -4
  36. package/dist/r/generate-video.json +9 -3
  37. package/dist/r/guest-chat.json +2 -2
  38. package/dist/r/image-viewer.json +55 -0
  39. package/dist/r/just-bash-sandbox.json +32 -0
  40. package/dist/r/litellm-gateway.json +2 -2
  41. package/dist/r/mcp.json +1 -1
  42. package/dist/r/openai-compatible-gateway.json +2 -2
  43. package/dist/r/openai-gateway.json +2 -2
  44. package/dist/r/openrouter-gateway.json +2 -2
  45. package/dist/r/projects.json +3 -3
  46. package/dist/r/radix/ai-titles.json +1 -1
  47. package/dist/r/radix/attach-workspace-file.json +82 -0
  48. package/dist/r/radix/attachment-uploads.json +1 -2
  49. package/dist/r/radix/deep-research.json +46 -123
  50. package/dist/r/radix/default-sandbox.json +35 -0
  51. package/dist/r/radix/docker-sandbox.json +35 -0
  52. package/dist/r/radix/generate-image.json +10 -4
  53. package/dist/r/radix/generate-video.json +9 -3
  54. package/dist/r/radix/guest-chat.json +2 -2
  55. package/dist/r/radix/image-viewer.json +55 -0
  56. package/dist/r/radix/just-bash-sandbox.json +32 -0
  57. package/dist/r/radix/litellm-gateway.json +2 -2
  58. package/dist/r/radix/mcp.json +1 -1
  59. package/dist/r/radix/openai-compatible-gateway.json +2 -2
  60. package/dist/r/radix/openai-gateway.json +2 -2
  61. package/dist/r/radix/openrouter-gateway.json +2 -2
  62. package/dist/r/radix/projects.json +3 -3
  63. package/dist/r/radix/registry.json +973 -1754
  64. package/dist/r/radix/search.json +6 -6
  65. package/dist/r/radix/sharing.json +3 -3
  66. package/dist/r/radix/spreadsheet-grid.json +20 -0
  67. package/dist/r/radix/spreadsheet-viewer.json +68 -0
  68. package/dist/r/radix/vercel-gateway.json +2 -2
  69. package/dist/r/radix/vercel-sandbox.json +8 -26
  70. package/dist/r/radix/video-viewer.json +48 -0
  71. package/dist/r/registry.json +970 -1751
  72. package/dist/r/search.json +6 -6
  73. package/dist/r/sharing.json +3 -3
  74. package/dist/r/spreadsheet-grid.json +20 -0
  75. package/dist/r/spreadsheet-viewer.json +68 -0
  76. package/dist/r/vercel-gateway.json +2 -2
  77. package/dist/r/vercel-sandbox.json +8 -26
  78. package/dist/r/video-viewer.json +48 -0
  79. package/package.json +5 -26
  80. package/dist/r/base/code-documents.json +0 -101
  81. package/dist/r/base/code-execution-runtime.json +0 -25
  82. package/dist/r/base/code-execution-ui.json +0 -32
  83. package/dist/r/base/code-execution.json +0 -69
  84. package/dist/r/base/daytona-sandbox.json +0 -55
  85. package/dist/r/base/delete-document.json +0 -58
  86. package/dist/r/base/firecrawl-search.json +0 -72
  87. package/dist/r/base/get-weather.json +0 -59
  88. package/dist/r/base/langfuse.json +0 -63
  89. package/dist/r/base/read-document.json +0 -34
  90. package/dist/r/base/retrieve-url.json +0 -72
  91. package/dist/r/base/saved-code-execution.json +0 -84
  92. package/dist/r/base/sheet-documents.json +0 -99
  93. package/dist/r/base/tavily-search.json +0 -72
  94. package/dist/r/base/text-documents.json +0 -122
  95. package/dist/r/base/vercel-analytics.json +0 -46
  96. package/dist/r/base/vercel-speed-insights.json +0 -46
  97. package/dist/r/base/word-count.json +0 -58
  98. package/dist/r/code-documents.json +0 -101
  99. package/dist/r/code-execution-runtime.json +0 -25
  100. package/dist/r/code-execution-ui.json +0 -32
  101. package/dist/r/code-execution.json +0 -69
  102. package/dist/r/daytona-sandbox.json +0 -55
  103. package/dist/r/delete-document.json +0 -58
  104. package/dist/r/firecrawl-search.json +0 -72
  105. package/dist/r/get-weather.json +0 -59
  106. package/dist/r/langfuse.json +0 -63
  107. package/dist/r/radix/code-documents.json +0 -101
  108. package/dist/r/radix/code-execution-runtime.json +0 -25
  109. package/dist/r/radix/code-execution-ui.json +0 -32
  110. package/dist/r/radix/code-execution.json +0 -69
  111. package/dist/r/radix/daytona-sandbox.json +0 -55
  112. package/dist/r/radix/delete-document.json +0 -58
  113. package/dist/r/radix/firecrawl-search.json +0 -72
  114. package/dist/r/radix/get-weather.json +0 -59
  115. package/dist/r/radix/langfuse.json +0 -63
  116. package/dist/r/radix/read-document.json +0 -34
  117. package/dist/r/radix/retrieve-url.json +0 -72
  118. package/dist/r/radix/saved-code-execution.json +0 -84
  119. package/dist/r/radix/sheet-documents.json +0 -99
  120. package/dist/r/radix/tavily-search.json +0 -72
  121. package/dist/r/radix/text-documents.json +0 -122
  122. package/dist/r/radix/vercel-analytics.json +0 -46
  123. package/dist/r/radix/vercel-speed-insights.json +0 -46
  124. package/dist/r/radix/word-count.json +0 -58
  125. package/dist/r/read-document.json +0 -34
  126. package/dist/r/retrieve-url.json +0 -72
  127. package/dist/r/saved-code-execution.json +0 -84
  128. package/dist/r/sheet-documents.json +0 -99
  129. package/dist/r/tavily-search.json +0 -72
  130. package/dist/r/text-documents.json +0 -122
  131. package/dist/r/vercel-analytics.json +0 -46
  132. package/dist/r/vercel-speed-insights.json +0 -46
  133. package/dist/r/word-count.json +0 -58
@@ -1,72 +0,0 @@
1
- {
2
- "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
- "name": "tavily-search",
4
- "description": "Use tavily-search for chat and deep research",
5
- "dependencies": [
6
- "ai@7.0.137",
7
- "zod@4.5.4",
8
- "@tavily/core@^0.3.3"
9
- ],
10
- "files": [
11
- {
12
- "path": "src/tools/tavily-search/tavily-search-env.ts",
13
- "content": "import { z } from \"zod\";\n\nconst environmentSchema = z.object({\n TAVILY_API_KEY: z.string().optional(),\n});\n\nconst readToolEnvironment = (\n environment: Readonly<NodeJS.ProcessEnv> = process.env\n) => environmentSchema.parse(environment);\n\nexport { readToolEnvironment };\n",
14
- "type": "registry:file",
15
- "target": "~/chatjs/tools/tavily-search/tavily-search-env.ts"
16
- },
17
- {
18
- "path": "src/tools/tavily-search/tool.ts",
19
- "content": "import type { ToolProgressWriter } from \"@/lib/ai/tool-context\";\nimport { tavily } from \"@tavily/core\";\nimport { defineTool } from \"eve/tools\";\nimport { readToolEnvironment } from \"./tavily-search-env\";\nimport { createModuleLogger } from \"@/lib/logger\";\nimport { executeWithResearchProgress } from \"@/lib/eve/research-progress\";\nimport {\n DEFAULT_MAX_RESULTS,\n executeMultiQuerySearch,\n} from \"@/tools/platform/search-presentation\";\nimport { toolResultToModelOutput } from \"@/lib/eve/tool-model-output\";\nimport { webSearchInput, webSearchResult } from \"./schemas\";\nimport type { z } from \"zod\";\n\nconst TAVILY_COST_CENTS = 5;\nconst CENTS_PER_USD = 100;\ntype SearchInput = z.infer<typeof webSearchInput>;\ntype ReadonlySearchInput = Readonly<{\n search_queries: readonly Readonly<SearchInput[\"search_queries\"][number]>[];\n exclude_domains: Readonly<SearchInput[\"exclude_domains\"]>;\n searchDepth: SearchInput[\"searchDepth\"];\n topics: Readonly<SearchInput[\"topics\"]>;\n}>;\ntype ExecutionContext = Readonly<{\n abortSignal: Readonly<AbortSignal>;\n callId: string;\n}>;\ntype ResearchExecution = Readonly<{\n abortSignal: Readonly<AbortSignal>;\n dataStream: Readonly<ToolProgressWriter>;\n usage: Readonly<{ addCostUsd: (cost: number) => void }>;\n}>;\n\nconst FIRST_TOPIC_INDEX = 0;\nconst NEWS_LOOKBACK_DAYS = 7;\nconst createTavilySearch =\n (\n options: Readonly<{\n topics: Readonly<NonNullable<SearchInput[\"topics\"]>>;\n excludeDomains: readonly string[];\n searchDepth: NonNullable<SearchInput[\"searchDepth\"]>;\n }>\n ): ((\n query: Readonly<{ query: string; maxResults: number }>,\n index: number\n ) => Promise<{ content: string; title: string; url: string }[]>) =>\n async ({ query, maxResults }, index) => {\n const env = readToolEnvironment();\n if (\n !(typeof env.TAVILY_API_KEY === \"string\" && env.TAVILY_API_KEY !== \"\")\n ) {\n throw new Error(\"Set TAVILY_API_KEY to enable Tavily search.\");\n }\n const topic =\n options.topics[index] ?? options.topics[FIRST_TOPIC_INDEX] ?? \"general\";\n const response = await tavily({ apiKey: env.TAVILY_API_KEY }).search(\n query,\n {\n days: topic === \"news\" ? NEWS_LOOKBACK_DAYS : undefined,\n excludeDomains: [...options.excludeDomains],\n includeAnswer: true,\n maxResults,\n searchDepth: options.searchDepth,\n topic,\n }\n );\n return response.results.map(\n ({\n title,\n url,\n content,\n }: Readonly<{ title: string; url: string; content: string }>) => ({\n content,\n title,\n url,\n })\n );\n };\nexport const webSearch = defineTool({\n description: `Multi-query web search (supports depth, topic & result limits). Always cite sources inline.\n\nUse for:\n- General information gathering via web search\n\nAvoid:\n- Pulling content from a single known URL (use retrieveUrl instead)`,\n execute: (\n {\n search_queries,\n topics,\n searchDepth,\n exclude_domains,\n }: ReadonlySearchInput,\n context: ExecutionContext\n ) =>\n executeWithResearchProgress(\n context,\n async ({ dataStream, usage, abortSignal }: ResearchExecution) => {\n const toolCallId = context.callId;\n abortSignal.throwIfAborted();\n const log = createModuleLogger(\"tools/web-search\");\n log.debug(\n {\n exclude_domains,\n queriesCount: search_queries.length,\n searchDepth,\n topics,\n },\n \"webSearch.execute\"\n );\n // Handle nullable arrays with defaults\n const safeTopics: Readonly<NonNullable<SearchInput[\"topics\"]>> =\n topics ?? [\"general\"];\n const safeSearchDepth = searchDepth ?? \"basic\";\n const safeExcludeDomains = exclude_domains ?? [];\n const result = await executeMultiQuerySearch({\n completeTitle: \"Search complete\",\n dataStream,\n search: createTavilySearch({\n excludeDomains: safeExcludeDomains,\n searchDepth: safeSearchDepth,\n topics: safeTopics,\n }),\n search_queries: search_queries.map((query) => ({\n maxResults: query.maxResults ?? DEFAULT_MAX_RESULTS,\n query: query.query,\n })),\n title: \"Searching\",\n toolCallId,\n writeTopLevelUpdates: true,\n });\n\n // Report API cost\n usage.addCostUsd(TAVILY_COST_CENTS / CENTS_PER_USD);\n\n return result;\n },\n webSearchResult\n ),\n // Keep defaultable fields required and nullable for strict tool calling.\n inputSchema: webSearchInput,\n toModelOutput: toolResultToModelOutput,\n});\n",
20
- "type": "registry:file",
21
- "target": "~/chatjs/tools/tavily-search/tool.ts"
22
- },
23
- {
24
- "path": "src/tools/tavily-search/renderer.tsx",
25
- "content": "\"use client\";\nimport { webSearchInput, webSearchResult } from \"./schemas\";\nimport React from \"react\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport type { ToolRendererProps } from \"@/chatjs/core/tools/define-renderer\";\nimport { WebSearch } from \"@/components/part/web-search\";\nimport { defineToolRenderer } from \"@/chatjs/core/tools/define-renderer\";\n\nconst WebSearchView = ({\n tool,\n messageId,\n}: ReadonlyNativeSurface<{\n tool: ToolRendererProps<\n typeof webSearchInput,\n typeof webSearchResult\n >[\"tool\"];\n messageId: string;\n isReadonly: boolean;\n}>): React.JSX.Element => <WebSearch messageId={messageId} part={tool} />;\n\nexport const WebSearchRenderer = defineToolRenderer({\n inputSchema: webSearchInput,\n outputSchema: webSearchResult,\n render: WebSearchView,\n});\n",
26
- "type": "registry:file",
27
- "target": "~/chatjs/tools/tavily-search/renderer.tsx"
28
- },
29
- {
30
- "path": "src/tools/tavily-search/schemas.ts",
31
- "content": "import { searchQueriesSchema } from \"@/tools/platform/search-presentation\";\nimport { z } from \"zod\";\n\nconst webSearchInput = z.object({\n exclude_domains: z\n .array(z.string())\n .describe(\n \"Domains to exclude from all results. Pass null for no exclusions.\"\n )\n .nullable(),\n searchDepth: z\n .enum([\"basic\", \"advanced\"])\n .describe('Search depth to use. Pass null for \"basic\".')\n .nullable(),\n search_queries: searchQueriesSchema,\n topics: z\n .array(z.enum([\"general\", \"news\"]))\n .describe(\n \"Array of topic types to search for. Pass null for general search.\"\n )\n .nullable(),\n});\n\nconst searchResult = z.object({\n content: z.string(),\n title: z.string(),\n url: z.string(),\n});\n\nconst searchQuery = z.object({ maxResults: z.number(), query: z.string() });\nconst queryResults = z.object({\n query: searchQuery,\n results: z.array(searchResult),\n});\nconst webSearchResult = z.object({\n error: z.string().optional(),\n searches: z.array(queryResults),\n});\nexport { webSearchInput, webSearchResult };\n",
32
- "type": "registry:file",
33
- "target": "~/chatjs/tools/tavily-search/schemas.ts"
34
- },
35
- {
36
- "path": "dist/source/tavily-search.json",
37
- "content": "{\n \"envRequirements\": [{ \"options\": [[\"TAVILY_API_KEY\"]] }],\n \"id\": \"tavily-search\",\n \"kind\": \"tool\",\n \"requiresTools\": [],\n \"slot\": \"webSearch\",\n \"tools\": [\n {\n \"composer\": {\n \"icon\": \"Globe\",\n \"name\": \"Web Search\",\n \"shortName\": \"Search\"\n },\n \"rendererExport\": \"WebSearchRenderer\",\n \"toolExport\": \"webSearch\"\n }\n ],\n \"contractVersion\": 1\n}\n",
38
- "type": "registry:file",
39
- "target": "~/chatjs/tools/tavily-search/chatjs.json"
40
- }
41
- ],
42
- "meta": {
43
- "chatjs": {
44
- "envRequirements": [
45
- {
46
- "options": [
47
- [
48
- "TAVILY_API_KEY"
49
- ]
50
- ]
51
- }
52
- ],
53
- "id": "tavily-search",
54
- "kind": "tool",
55
- "requiresTools": [],
56
- "slot": "webSearch",
57
- "tools": [
58
- {
59
- "composer": {
60
- "icon": "Globe",
61
- "name": "Web Search",
62
- "shortName": "Search"
63
- },
64
- "rendererExport": "WebSearchRenderer",
65
- "toolExport": "webSearch"
66
- }
67
- ],
68
- "contractVersion": 1
69
- }
70
- },
71
- "type": "registry:item"
72
- }
@@ -1,122 +0,0 @@
1
- {
2
- "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
- "name": "text-documents",
4
- "description": "Create and edit text documents with their editor UI",
5
- "dependencies": [
6
- "@lexical/code@^0.32.1",
7
- "@lexical/link@^0.32.1",
8
- "@lexical/list@^0.32.1",
9
- "@lexical/markdown@^0.32.1",
10
- "@lexical/react@^0.32.1",
11
- "@lexical/rich-text@^0.32.1",
12
- "lexical@^0.32.1",
13
- "diff@^8.0.2",
14
- "@tanstack/react-query@^5.104.1"
15
- ],
16
- "registryDependencies": [
17
- "@chatjs/read-document"
18
- ],
19
- "files": [
20
- {
21
- "path": "src/tools/text-documents/tool.ts",
22
- "content": "import {\n eveDocumentCreateInput,\n eveDocumentEditInput,\n eveDocumentWriteResult,\n} from \"@/chatjs/core/documents/contracts\";\nimport type { ToolContext } from \"eve/tools\";\nimport { defineTool } from \"eve/tools\";\nimport { executeEveDocumentTool } from \"@/lib/eve/document-tools\";\nimport { textGuidelines } from \"./guidelines\";\nimport type { z } from \"zod\";\n\ntype CreateTextDocumentInput = Readonly<\n Omit<z.infer<typeof eveDocumentCreateInput>, \"fileIds\"> & {\n fileIds: readonly string[];\n }\n>;\n\ntype EditTextDocumentInput = Readonly<\n Omit<z.infer<typeof eveDocumentEditInput>, \"fileIds\"> & {\n fileIds: readonly string[];\n }\n>;\n\ntype ReadonlyDocumentToolContext = Readonly<\n Pick<ToolContext, \"callId\" | \"session\"> & {\n abortSignal: Readonly<AbortSignal>;\n }\n>;\n\nconst createTextDocument = defineTool({\n description: `Create a new text document in this conversation. Supply the complete content and a descriptive title. ${textGuidelines}`,\n execute: async (\n input: CreateTextDocumentInput,\n context: ReadonlyDocumentToolContext\n ) =>\n eveDocumentWriteResult.parse(\n await executeEveDocumentTool(\"createTextDocument\", input, context)\n ),\n inputSchema: eveDocumentCreateInput,\n outputSchema: eveDocumentWriteResult,\n});\nconst editTextDocument = defineTool({\n description: `Edit an existing text document in this conversation. Read the document first and supply its revision ID. Supply the complete replacement content. ${textGuidelines}`,\n execute: async (\n input: EditTextDocumentInput,\n context: ReadonlyDocumentToolContext\n ) =>\n eveDocumentWriteResult.parse(\n await executeEveDocumentTool(\"editTextDocument\", input, context)\n ),\n inputSchema: eveDocumentEditInput,\n outputSchema: eveDocumentWriteResult,\n});\nexport { createTextDocument, editTextDocument };\n",
23
- "type": "registry:file",
24
- "target": "~/chatjs/tools/text-documents/tool.ts"
25
- },
26
- {
27
- "path": "src/tools/text-documents/definition.ts",
28
- "content": "import { z } from \"zod\";\nimport type { DocumentDefinition } from \"@/chatjs/core/documents/document-definition\";\n\nexport const documentDefinition = {\n kind: \"text\",\n contentSchema: z.string().max(2_000_000),\n createTool: \"createTextDocument\",\n editTool: \"editTextDocument\",\n} as const satisfies DocumentDefinition;\n",
29
- "type": "registry:file",
30
- "target": "~/chatjs/tools/text-documents/definition.ts"
31
- },
32
- {
33
- "path": "src/tools/text-documents/guidelines.ts",
34
- "content": "export const textGuidelines = `\nGuidelines:\n- Write clear, well-structured content about the given topic\n- Use markdown formatting effectively\n- Use headings (##, ###) to organize content where appropriate\n- Keep paragraphs focused and readable\n- Use lists, bold, and italics to enhance readability when suitable`;\n",
35
- "type": "registry:file",
36
- "target": "~/chatjs/tools/text-documents/guidelines.ts"
37
- },
38
- {
39
- "path": "src/tools/text-documents/configuration-schema.ts",
40
- "content": "import { z } from \"zod\";\nimport { languageModelSchema, modelRoles } from \"@/lib/config-models\";\n\nconst configSchema = z\n .strictObject({ polish: languageModelSchema.default(modelRoles.balanced) })\n .prefault({});\nexport { configSchema };\n",
41
- "type": "registry:file",
42
- "target": "~/chatjs/tools/text-documents/configuration-schema.ts"
43
- },
44
- {
45
- "path": "src/tools/text-documents/assistant-actions.ts",
46
- "content": "import type { DocumentAssistantAction } from \"@/chatjs/core/documents/contracts\";\nimport { config } from \"@/lib/config\";\n\nconst documentAssistantActions = (): DocumentAssistantAction[] => [\n {\n instruction:\n \"Add final polish, check grammar, add section titles for structure, and ensure the document reads smoothly.\",\n label: \"Add final polish\",\n modelId: config.ai.tools.text.polish,\n },\n];\nexport { documentAssistantActions };\n",
47
- "type": "registry:file",
48
- "target": "~/chatjs/tools/text-documents/assistant-actions.ts"
49
- },
50
- {
51
- "path": "src/tools/text-documents/document.tsx",
52
- "content": "\"use client\";\nimport type { DocumentBodyProps, DocumentUi } from \"@/chatjs/core/documents/ui\";\nimport { documentDefinition } from \"./definition\";\nimport { documentAssistantActions } from \"./assistant-actions\";\nimport React from \"react\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { ScrollArea } from \"@/components/ui/scroll-area\";\nimport { EveDocumentComparison } from \"./comparison\";\nimport dynamic from \"next/dynamic\";\n\nconst Editor = dynamic(\n async () => {\n const { Editor: TextEditor } = await import(\"./editor\");\n return TextEditor;\n },\n {\n ssr: false,\n }\n);\n\nexport const documentUi: DocumentUi = {\n supportsComparison: true,\n definition: documentDefinition,\n assistantActions: documentAssistantActions,\n Body: ({\n inline,\n editorProps,\n comparison,\n }: ReadonlyNativeSurface<DocumentBodyProps>) => (\n <ScrollArea className=\"min-h-0 flex-1\">\n {comparison ? (\n <EveDocumentComparison {...comparison} />\n ) : (\n <div\n className={\n inline === true\n ? \"p-4 sm:px-14 sm:py-16\"\n : \"mx-auto max-w-3xl px-4 py-8\"\n }\n >\n <Editor {...editorProps} />\n </div>\n )}\n </ScrollArea>\n ),\n};\n",
53
- "type": "registry:file",
54
- "target": "~/chatjs/tools/text-documents/document.tsx"
55
- },
56
- {
57
- "path": "src/tools/text-documents/editor.tsx",
58
- "content": "\"use client\";\n\nimport {\n $convertFromMarkdownString,\n $convertToMarkdownString,\n TRANSFORMERS,\n} from \"@lexical/markdown\";\nimport React, { memo, useEffect, useRef } from \"react\";\nimport { createEditorConfig, handleEditorChange } from \"./editor-config\";\nimport { $getRoot } from \"lexical\";\nimport { ContentEditable } from \"@lexical/react/LexicalContentEditable\";\nimport type { EditorState } from \"lexical\";\nimport { HistoryPlugin } from \"@lexical/react/LexicalHistoryPlugin\";\nimport { LexicalComposer } from \"@lexical/react/LexicalComposer\";\nimport { LexicalErrorBoundary } from \"@lexical/react/LexicalErrorBoundary\";\nimport { ListPlugin } from \"@lexical/react/LexicalListPlugin\";\nimport { MarkdownShortcutPlugin } from \"@lexical/react/LexicalMarkdownShortcutPlugin\";\nimport { OnChangePlugin } from \"@lexical/react/LexicalOnChangePlugin\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { RichTextPlugin } from \"@lexical/react/LexicalRichTextPlugin\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\n\ninterface EditorProps {\n content: string;\n currentVersionIndex: number;\n isCurrentVersion: boolean;\n isReadonly?: boolean;\n onSaveContent: (updatedContent: string, debounce: boolean) => void;\n status: \"streaming\" | \"idle\";\n}\n\n// Content update plugin\nconst ContentUpdatePlugin = ({\n content,\n status,\n onSaveContent,\n isReadonly,\n}: ReadonlyNativeSurface<{\n content: string;\n status: \"streaming\" | \"idle\";\n onSaveContent: (content: string, debounce: boolean) => void;\n isReadonly?: boolean;\n}>): React.JSX.Element => {\n const [editor] = useLexicalComposerContext();\n const isProgrammaticUpdate = useRef(false);\n\n useEffect((): void => {\n editor.setEditable(!(isReadonly === true));\n }, [editor, isReadonly]);\n\n useEffect((): void => {\n let currentMarkdown = \"\";\n editor.getEditorState().read((): void => {\n currentMarkdown = $convertToMarkdownString(TRANSFORMERS);\n });\n if (status !== \"streaming\" && currentMarkdown.trim() === content.trim()) {\n return;\n }\n isProgrammaticUpdate.current = true;\n editor.update(\n (): void => {\n $getRoot().clear();\n $convertFromMarkdownString(content);\n },\n {\n discrete: true,\n onUpdate: (): void => {\n isProgrammaticUpdate.current = false;\n },\n }\n );\n }, [content, status, editor]);\n\n const handleChange = (\n editorState: Readonly<Pick<EditorState, \"read\">>\n ): void => {\n if (!(isReadonly === true || isProgrammaticUpdate.current)) {\n handleEditorChange({\n editor,\n editorState,\n onSaveContent,\n });\n }\n };\n\n return <OnChangePlugin onChange={handleChange} />;\n};\n\nconst PureEditor = ({\n content,\n onSaveContent,\n status,\n isReadonly,\n}: ReadonlyNativeSurface<EditorProps>): React.JSX.Element => {\n const initialConfig = createEditorConfig();\n\n const editorConfig = {\n ...initialConfig,\n editable: !(isReadonly === true),\n };\n\n return (\n <div className=\"prose dark:prose-invert relative text-left\">\n <LexicalComposer initialConfig={editorConfig}>\n <RichTextPlugin\n contentEditable={\n <ContentEditable className=\"lexical-editor text-left outline-hidden\" />\n }\n ErrorBoundary={LexicalErrorBoundary}\n placeholder={\n <div className=\"text-muted-foreground\">Start typing...</div>\n }\n />\n <HistoryPlugin />\n <ListPlugin />\n <MarkdownShortcutPlugin transformers={TRANSFORMERS} />\n <ContentUpdatePlugin\n content={content}\n isReadonly={isReadonly}\n onSaveContent={onSaveContent}\n status={status}\n />\n </LexicalComposer>\n </div>\n );\n};\n\nconst areEqual = (\n prevProps: ReadonlyNativeSurface<EditorProps>,\n nextProps: ReadonlyNativeSurface<EditorProps>\n): boolean =>\n prevProps.currentVersionIndex === nextProps.currentVersionIndex &&\n prevProps.isCurrentVersion === nextProps.isCurrentVersion &&\n !(prevProps.status === \"streaming\" && nextProps.status === \"streaming\") &&\n prevProps.content === nextProps.content &&\n prevProps.onSaveContent === nextProps.onSaveContent &&\n prevProps.isReadonly === nextProps.isReadonly;\n\nexport const Editor = memo(PureEditor, areEqual);\n",
59
- "type": "registry:file",
60
- "target": "~/chatjs/tools/text-documents/editor.tsx"
61
- },
62
- {
63
- "path": "src/tools/text-documents/comparison.tsx",
64
- "content": "\"use client\";\nimport { Button } from \"@/components/ui/button\";\nimport { DocumentSkeleton } from \"@/components/document-skeleton\";\nimport React from \"react\";\nimport dynamic from \"next/dynamic\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useTRPC } from \"@/trpc/react\";\n\nconst DiffView = dynamic(\n async () => {\n const { DiffView: Comparison } = await import(\"./diffview\");\n return Comparison;\n },\n {\n loading: () => <DocumentSkeleton artifactKind=\"text\" />,\n ssr: false,\n }\n);\n\nexport const EveDocumentComparison = ({\n conversationId,\n documentId,\n previousRevisionId,\n content,\n version,\n}: {\n readonly conversationId: string;\n readonly documentId: string;\n readonly previousRevisionId: string;\n readonly content: string;\n readonly version: number;\n}): React.JSX.Element => {\n const trpc = useTRPC();\n const previous = useQuery(\n trpc.eve.document.queryOptions({\n conversationId,\n documentId,\n revisionId: previousRevisionId,\n })\n );\n return (\n <section\n aria-label=\"Document changes\"\n className=\"mx-auto max-w-3xl space-y-4 px-4 py-8\"\n >\n <p className=\"text-muted-foreground text-sm\">\n Changes from version {version - 1} to {version}\n </p>\n {previous.isPending && <DocumentSkeleton artifactKind=\"text\" />}\n {previous.isError && (\n <div className=\"space-y-2\" role=\"alert\">\n <p>The previous version could not be loaded.</p>\n {}\n <Button\n onClick={(): void => {\n void previous.refetch();\n }}\n variant=\"outline\"\n >\n Retry comparison\n </Button>\n </div>\n )}\n {previous.data && !previous.isError && (\n <DiffView\n newContent={content}\n oldContent={previous.data.revision.content}\n />\n )}\n </section>\n );\n};\n",
65
- "type": "registry:file",
66
- "target": "~/chatjs/tools/text-documents/comparison.tsx"
67
- },
68
- {
69
- "path": "src/tools/text-documents/diffview.tsx",
70
- "content": "import { $createParagraphNode, $getRoot, TextNode } from \"lexical\";\nimport type { EditorConfig, LexicalEditor, SerializedTextNode } from \"lexical\";\nimport React, { useEffect } from \"react\";\nimport type { ChangeObject } from \"diff\";\nimport { ContentEditable } from \"@lexical/react/LexicalContentEditable\";\nimport { LexicalComposer } from \"@lexical/react/LexicalComposer\";\nimport { LexicalErrorBoundary } from \"@lexical/react/LexicalErrorBoundary\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { RichTextPlugin } from \"@lexical/react/LexicalRichTextPlugin\";\nimport { createEditorConfig } from \"./editor-config\";\nimport { diffWords } from \"diff\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\n\nconst DiffType = {\n Deleted: -1,\n Inserted: 1,\n Unchanged: 0,\n};\n\n// Define diff types\ntype DiffTypeValue = (typeof DiffType)[keyof typeof DiffType];\ntype SerializedDiffTextNode = SerializedTextNode & {\n diffType?: DiffTypeValue;\n type: \"diff-text\";\n version: 1;\n};\n\n// Custom diff text node that supports styling\nclass DiffTextNode extends TextNode {\n public __diffType?: DiffTypeValue;\n\n public static getType(): string {\n return \"diff-text\";\n }\n\n public static clone(\n node: Readonly<Pick<DiffTextNode, \"__text\" | \"__key\" | \"__diffType\">>\n ): DiffTextNode {\n const newNode = new DiffTextNode(node.__text, node.__key);\n newNode.__diffType = node.__diffType;\n return newNode;\n }\n\n public static importJSON(\n serializedNode: ReadonlyNativeSurface<SerializedDiffTextNode>\n ): DiffTextNode {\n const { text, diffType } = serializedNode;\n const node = new DiffTextNode(text);\n if (diffType !== undefined) {\n node.setDiffType(diffType);\n }\n return node;\n }\n\n public exportJSON(): SerializedDiffTextNode {\n return {\n ...super.exportJSON(),\n diffType: this.__diffType,\n type: \"diff-text\",\n version: 1,\n };\n }\n\n public setDiffType(diffType: DiffTypeValue): void {\n const writable = this.getWritable();\n writable.__diffType = diffType;\n }\n\n public getDiffType(): DiffTypeValue | undefined {\n return this.__diffType;\n }\n\n public createDOM(config: EditorConfig, editor?: LexicalEditor): HTMLElement {\n const element = super.createDOM(config, editor);\n const diffType = this.getDiffType();\n\n if (\n diffType !== null &&\n diffType !== undefined &&\n diffType !== 0 &&\n !Number.isNaN(diffType)\n ) {\n let className = \"\";\n switch (diffType) {\n case DiffType.Inserted: {\n className =\n \"bg-green-100 text-green-700 dark:bg-green-500/70 dark:text-green-300\";\n break;\n }\n case DiffType.Deleted: {\n className =\n \"bg-red-100 line-through text-red-600 dark:bg-red-500/70 dark:text-red-300\";\n break;\n }\n default: {\n className = \"\";\n }\n }\n element.className = className;\n }\n\n return element;\n }\n\n public updateDOM(\n prevNode: this,\n dom: HTMLElement,\n config: EditorConfig\n ): boolean {\n const prevDiffType = prevNode.getDiffType();\n const currentDiffType = this.getDiffType();\n\n if (prevDiffType !== currentDiffType) {\n // Update classes if diff type changed\n // Recreate the span when its diff styling changes.\n return true;\n }\n\n return super.updateDOM(prevNode, dom, config);\n }\n}\n\n// Proper diff computation using the diff library\nconst computeProperDiff = (\n oldText: string,\n newText: string\n): { text: string; type: number }[] => {\n const changes = diffWords(oldText, newText);\n\n return changes.map((change: Readonly<ChangeObject<string>>) => {\n let type: DiffTypeValue;\n if (change.added) {\n type = DiffType.Inserted;\n } else if (change.removed) {\n type = DiffType.Deleted;\n } else {\n type = DiffType.Unchanged;\n }\n\n return {\n text: change.value,\n type,\n };\n });\n};\n\nconst DiffContentPlugin = ({\n oldContent,\n newContent,\n}: ReadonlyNativeSurface<{\n oldContent: string;\n newContent: string;\n}>): null => {\n const [editor] = useLexicalComposerContext();\n\n useEffect((): void => {\n editor.update((): void => {\n const root = $getRoot();\n\n // Clear existing content\n const children = root.getChildren();\n for (const child of children) {\n child.remove();\n }\n\n // Compute proper diff using LCS algorithm\n const diffResult = computeProperDiff(oldContent, newContent);\n\n // Create a single paragraph with all diff nodes\n const paragraphNode = $createParagraphNode();\n\n for (const { text, type } of diffResult) {\n const textNode = new DiffTextNode(text);\n textNode.setDiffType(type);\n paragraphNode.append(textNode);\n }\n\n root.append(paragraphNode);\n });\n }, [oldContent, newContent, editor]);\n\n return null;\n};\n\ninterface DiffEditorProps {\n newContent: string;\n oldContent: string;\n}\n\nexport const DiffView = ({\n oldContent,\n newContent,\n}: ReadonlyNativeSurface<DiffEditorProps>): React.JSX.Element => {\n const initialConfig = {\n ...createEditorConfig(),\n editable: false,\n nodes: [DiffTextNode],\n };\n\n return (\n <div className=\"prose dark:prose-invert relative w-full text-left\">\n <LexicalComposer initialConfig={initialConfig}>\n <RichTextPlugin\n contentEditable={\n <ContentEditable className=\"lexical-editor text-left outline-hidden\" />\n }\n ErrorBoundary={LexicalErrorBoundary}\n placeholder={null}\n />\n <DiffContentPlugin newContent={newContent} oldContent={oldContent} />\n </LexicalComposer>\n </div>\n );\n};\n",
71
- "type": "registry:file",
72
- "target": "~/chatjs/tools/text-documents/diffview.tsx"
73
- },
74
- {
75
- "path": "src/tools/text-documents/editor-config.ts",
76
- "content": "import { $convertToMarkdownString, TRANSFORMERS } from \"@lexical/markdown\";\nimport { CodeHighlightNode, CodeNode } from \"@lexical/code\";\nimport type { EditorState, LexicalEditor } from \"lexical\";\nimport { HeadingNode, QuoteNode } from \"@lexical/rich-text\";\nimport { ListItemNode, ListNode } from \"@lexical/list\";\nimport { LinkNode } from \"@lexical/link\";\n\nconst DOCUMENT_NODE_CLASSES = [\n HeadingNode,\n ListNode,\n ListItemNode,\n QuoteNode,\n CodeNode,\n CodeHighlightNode,\n LinkNode,\n];\ninterface DocumentEditorConfig {\n namespace: string;\n nodes: typeof DOCUMENT_NODE_CLASSES;\n onError: (error: Readonly<Error>) => void;\n}\n\n// Create initial editor configuration with a fresh node collection for each editor.\nconst createEditorConfig = (): DocumentEditorConfig => ({\n namespace: \"DocumentEditor\",\n nodes: [...DOCUMENT_NODE_CLASSES],\n onError: (error: Readonly<Error>): void => {\n console.error(\"Lexical error:\", error);\n },\n});\n\nconst handleEditorChange = ({\n editorState: _editorState,\n editor,\n onSaveContent,\n}: Readonly<{\n editorState: Readonly<Pick<EditorState, \"read\">>;\n editor: Readonly<Pick<LexicalEditor, \"getEditorState\">>;\n onSaveContent: (updatedContent: string, debounce: boolean) => void;\n}>): void => {\n let updatedContent = \"\";\n\n editor.getEditorState().read((): void => {\n updatedContent = $convertToMarkdownString(TRANSFORMERS);\n });\n\n // Check if this should be debounced (similar to ProseMirror's no-debounce meta)\n // Default to debounced saving\n const shouldDebounce = true;\n\n onSaveContent(updatedContent, shouldDebounce);\n};\nexport { createEditorConfig, handleEditorChange };\n",
77
- "type": "registry:file",
78
- "target": "~/chatjs/tools/text-documents/editor-config.ts"
79
- },
80
- {
81
- "path": "dist/source/text-documents.json",
82
- "content": "{\n \"config\": { \"key\": \"text\" },\n \"documentKind\": \"text\",\n \"envRequirements\": [],\n \"id\": \"text-documents\",\n \"kind\": \"tool\",\n \"requiresTools\": [\"readDocument\"],\n \"tools\": [\n {\n \"composer\": { \"icon\": \"Edit3\", \"name\": \"Canvas\", \"shortName\": \"Canvas\" },\n \"toolExport\": \"createTextDocument\"\n },\n {\n \"composer\": { \"icon\": \"Edit3\", \"name\": \"Canvas\", \"shortName\": \"Canvas\" },\n \"toolExport\": \"editTextDocument\"\n }\n ],\n \"contractVersion\": 2,\n \"uiBase\": \"base\"\n}\n",
83
- "type": "registry:file",
84
- "target": "~/chatjs/tools/text-documents/chatjs.json"
85
- }
86
- ],
87
- "meta": {
88
- "chatjs": {
89
- "config": {
90
- "key": "text"
91
- },
92
- "documentKind": "text",
93
- "envRequirements": [],
94
- "id": "text-documents",
95
- "kind": "tool",
96
- "requiresTools": [
97
- "readDocument"
98
- ],
99
- "tools": [
100
- {
101
- "composer": {
102
- "icon": "Edit3",
103
- "name": "Canvas",
104
- "shortName": "Canvas"
105
- },
106
- "toolExport": "createTextDocument"
107
- },
108
- {
109
- "composer": {
110
- "icon": "Edit3",
111
- "name": "Canvas",
112
- "shortName": "Canvas"
113
- },
114
- "toolExport": "editTextDocument"
115
- }
116
- ],
117
- "contractVersion": 2,
118
- "uiBase": "base"
119
- }
120
- },
121
- "type": "registry:item"
122
- }
@@ -1,46 +0,0 @@
1
- {
2
- "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
- "name": "vercel-analytics",
4
- "description": "Vercel Web Analytics",
5
- "dependencies": [
6
- "@vercel/analytics@^1.5.0"
7
- ],
8
- "files": [
9
- {
10
- "path": "src/plugins/vercel-analytics/src/component.tsx",
11
- "content": "import { Analytics } from \"@vercel/analytics/next\";\n\nimport type { ComponentType } from \"react\";\n\nexport const Component = Analytics satisfies ComponentType;\n",
12
- "type": "registry:file",
13
- "target": "~/chatjs/plugins/vercel-analytics/component.tsx"
14
- },
15
- {
16
- "path": "src/plugins/vercel-analytics/src/client-plugin.ts",
17
- "content": "\"use client\";\nimport { definePlugin, slot } from \"@/chatjs/core/ui/slots\";\nimport { LayoutEffects } from \"@/components/layout-slots\";\nimport { Component } from \"./component\";\n\nexport const vercelAnalyticsClient = definePlugin({\n id: \"vercel-analytics\",\n slots: [slot(LayoutEffects, Component)],\n});\n",
18
- "type": "registry:file",
19
- "target": "~/chatjs/plugins/vercel-analytics/client-plugin.ts"
20
- },
21
- {
22
- "path": "dist/source/vercel-analytics.json",
23
- "content": "{\n \"id\": \"vercel-analytics\",\n \"kind\": \"plugin\",\n \"files\": [\n \"chatjs/plugins/vercel-analytics/component.tsx\",\n \"chatjs/plugins/vercel-analytics/client-plugin.ts\"\n ],\n \"client\": {\n \"export\": \"vercelAnalyticsClient\",\n \"composerControls\": [],\n \"settingsItems\": [],\n \"layout\": true\n },\n \"contractVersion\": 1\n}\n",
24
- "type": "registry:file",
25
- "target": "~/chatjs/plugins/vercel-analytics/chatjs.json"
26
- }
27
- ],
28
- "meta": {
29
- "chatjs": {
30
- "id": "vercel-analytics",
31
- "kind": "plugin",
32
- "files": [
33
- "chatjs/plugins/vercel-analytics/component.tsx",
34
- "chatjs/plugins/vercel-analytics/client-plugin.ts"
35
- ],
36
- "client": {
37
- "export": "vercelAnalyticsClient",
38
- "composerControls": [],
39
- "settingsItems": [],
40
- "layout": true
41
- },
42
- "contractVersion": 1
43
- }
44
- },
45
- "type": "registry:item"
46
- }
@@ -1,46 +0,0 @@
1
- {
2
- "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
- "name": "vercel-speed-insights",
4
- "description": "Vercel Speed Insights",
5
- "dependencies": [
6
- "@vercel/speed-insights@^1.3.1"
7
- ],
8
- "files": [
9
- {
10
- "path": "src/plugins/vercel-speed-insights/src/component.tsx",
11
- "content": "import type { ComponentType } from \"react\";\nimport { SpeedInsights } from \"@vercel/speed-insights/next\";\n\nexport const Component = SpeedInsights satisfies ComponentType;\n",
12
- "type": "registry:file",
13
- "target": "~/chatjs/plugins/vercel-speed-insights/component.tsx"
14
- },
15
- {
16
- "path": "src/plugins/vercel-speed-insights/src/client-plugin.ts",
17
- "content": "\"use client\";\nimport { definePlugin, slot } from \"@/chatjs/core/ui/slots\";\nimport { LayoutEffects } from \"@/components/layout-slots\";\nimport { Component } from \"./component\";\n\nexport const vercelSpeedInsightsClient = definePlugin({\n id: \"vercel-speed-insights\",\n slots: [slot(LayoutEffects, Component)],\n});\n",
18
- "type": "registry:file",
19
- "target": "~/chatjs/plugins/vercel-speed-insights/client-plugin.ts"
20
- },
21
- {
22
- "path": "dist/source/vercel-speed-insights.json",
23
- "content": "{\n \"id\": \"vercel-speed-insights\",\n \"kind\": \"plugin\",\n \"files\": [\n \"chatjs/plugins/vercel-speed-insights/component.tsx\",\n \"chatjs/plugins/vercel-speed-insights/client-plugin.ts\"\n ],\n \"client\": {\n \"export\": \"vercelSpeedInsightsClient\",\n \"composerControls\": [],\n \"settingsItems\": [],\n \"layout\": true\n },\n \"contractVersion\": 1\n}\n",
24
- "type": "registry:file",
25
- "target": "~/chatjs/plugins/vercel-speed-insights/chatjs.json"
26
- }
27
- ],
28
- "meta": {
29
- "chatjs": {
30
- "id": "vercel-speed-insights",
31
- "kind": "plugin",
32
- "files": [
33
- "chatjs/plugins/vercel-speed-insights/component.tsx",
34
- "chatjs/plugins/vercel-speed-insights/client-plugin.ts"
35
- ],
36
- "client": {
37
- "export": "vercelSpeedInsightsClient",
38
- "composerControls": [],
39
- "settingsItems": [],
40
- "layout": true
41
- },
42
- "contractVersion": 1
43
- }
44
- },
45
- "type": "registry:item"
46
- }
@@ -1,58 +0,0 @@
1
- {
2
- "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
- "name": "word-count",
4
- "description": "Count the words, characters, and sentences in a given text",
5
- "dependencies": [
6
- "ai@7.0.137",
7
- "zod@4.5.4"
8
- ],
9
- "files": [
10
- {
11
- "path": "src/tools/word-count/definition.ts",
12
- "content": "import type { ToolDefinition } from \"@/chatjs/core/tools/tool-definition\";\nimport { wordCountInput, wordCountResult } from \"./schemas\";\n\nexport const toolDefinition = {\n name: \"wordCount\",\n description: \"Count the words, characters, and sentences in a given text\",\n inputSchema: wordCountInput,\n outputSchema: wordCountResult,\n display: { name: \"Word count\", shortName: \"Word count\" },\n} as const satisfies ToolDefinition;\n",
13
- "type": "registry:file",
14
- "target": "~/chatjs/tools/word-count/definition.ts"
15
- },
16
- {
17
- "path": "src/tools/word-count/tool.ts",
18
- "content": "import { validateToolOutput } from \"@/chatjs/core/tools/validate-output\";\nimport { toolDefinition } from \"./definition\";\nimport type { ToolUsage } from \"@/lib/eve/tool-usage\";\nimport { defineTool } from \"eve/tools\";\nimport { executeWithToolUsage } from \"@/lib/eve/tool-usage\";\nimport { toolResultToModelOutput } from \"@/lib/eve/tool-model-output\";\nimport type { wordCountInput } from \"./schemas\";\nimport type { z } from \"zod\";\n\nconst UNBILLED_TOOL_COST_USD = 0;\nconst EMPTY_COUNT = 0;\nconst WORD_SPLIT_REGEX = /\\s+/u;\nconst SENTENCE_SPLIT_REGEX = /[.!?]+/u;\n\nexport const wordCount = defineTool({\n description: toolDefinition.description,\n execute: async (\n { text }: Readonly<z.infer<typeof wordCountInput>>,\n context: Readonly<{ abortSignal: Readonly<AbortSignal> }>\n ) =>\n await executeWithToolUsage(\n context,\n (usage: Readonly<Pick<ToolUsage, \"addCostUsd\">>) => {\n usage.addCostUsd(UNBILLED_TOOL_COST_USD);\n const words =\n text.trim() === \"\"\n ? EMPTY_COUNT\n : text.trim().split(WORD_SPLIT_REGEX).length;\n const characters = text.length;\n const charactersNoSpaces = text.replaceAll(/\\s/gu, \"\").length;\n const sentences = text\n .split(SENTENCE_SPLIT_REGEX)\n .filter((sentence) => sentence.trim().length > EMPTY_COUNT).length;\n\n return validateToolOutput(toolDefinition.outputSchema, {\n characters,\n charactersNoSpaces,\n sentences,\n words,\n });\n }\n ),\n inputSchema: toolDefinition.inputSchema,\n toModelOutput: toolResultToModelOutput,\n});\n",
19
- "type": "registry:file",
20
- "target": "~/chatjs/tools/word-count/tool.ts"
21
- },
22
- {
23
- "path": "src/tools/word-count/renderer.tsx",
24
- "content": "\"use client\";\n\nimport { toolDefinition } from \"./definition\";\nimport type { wordCountInput, wordCountResult } from \"./schemas\";\nimport React from \"react\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport type { ToolRendererProps } from \"@/chatjs/core/tools/define-renderer\";\nimport { defineToolRenderer } from \"@/chatjs/core/tools/define-renderer\";\n\ntype WordCountRendererTool = ToolRendererProps<\n typeof wordCountInput,\n typeof wordCountResult\n>[\"tool\"];\n\nconst Stat = ({\n label,\n value,\n}: Readonly<{ label: string; value: number }>): React.JSX.Element => (\n <div className=\"flex flex-col items-center gap-1\">\n <span className=\"text-lg font-semibold\">{value}</span>\n <span className=\"text-muted-foreground text-xs\">{label}</span>\n </div>\n);\n\nconst WordCountView = ({\n tool,\n}: ReadonlyNativeSurface<{\n tool: WordCountRendererTool;\n messageId: string;\n isReadonly: boolean;\n}>): React.JSX.Element | null => {\n if (tool.state === \"input-available\") {\n return (\n <div className=\"text-muted-foreground rounded-lg border p-3 text-sm\">\n Counting words...\n </div>\n );\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 { words, characters, charactersNoSpaces, sentences } = tool.output;\n\n return (\n <div className=\"grid grid-cols-2 gap-2 rounded-lg border p-3 text-sm sm:grid-cols-4\">\n <Stat label=\"Words\" value={words} />\n <Stat label=\"Characters\" value={characters} />\n <Stat label=\"No spaces\" value={charactersNoSpaces} />\n <Stat label=\"Sentences\" value={sentences} />\n </div>\n );\n};\n\nexport const WordCountRenderer = defineToolRenderer({\n inputSchema: toolDefinition.inputSchema,\n outputSchema: toolDefinition.outputSchema,\n render: WordCountView,\n});\n",
25
- "type": "registry:file",
26
- "target": "~/chatjs/tools/word-count/renderer.tsx"
27
- },
28
- {
29
- "path": "src/tools/word-count/schemas.ts",
30
- "content": "import { z } from \"zod\";\n\nconst wordCountInput = z.object({\n text: z.string().describe(\"The text to analyze\"),\n});\n\nconst wordCountResult = z.object({\n characters: z.number(),\n charactersNoSpaces: z.number(),\n sentences: z.number(),\n words: z.number(),\n});\nexport { wordCountInput, wordCountResult };\n",
31
- "type": "registry:file",
32
- "target": "~/chatjs/tools/word-count/schemas.ts"
33
- },
34
- {
35
- "path": "dist/source/word-count.json",
36
- "content": "{\n \"envRequirements\": [],\n \"id\": \"word-count\",\n \"kind\": \"tool\",\n \"requiresTools\": [],\n \"tools\": [\n {\n \"rendererExport\": \"WordCountRenderer\",\n \"definitionExport\": \"toolDefinition\",\n \"toolExport\": \"wordCount\"\n }\n ],\n \"contractVersion\": 1\n}\n",
37
- "type": "registry:file",
38
- "target": "~/chatjs/tools/word-count/chatjs.json"
39
- }
40
- ],
41
- "meta": {
42
- "chatjs": {
43
- "envRequirements": [],
44
- "id": "word-count",
45
- "kind": "tool",
46
- "requiresTools": [],
47
- "tools": [
48
- {
49
- "rendererExport": "WordCountRenderer",
50
- "definitionExport": "toolDefinition",
51
- "toolExport": "wordCount"
52
- }
53
- ],
54
- "contractVersion": 1
55
- }
56
- },
57
- "type": "registry:item"
58
- }
@@ -1,101 +0,0 @@
1
- {
2
- "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
- "name": "code-documents",
4
- "description": "Create and edit code documents with their editor UI",
5
- "dependencies": [
6
- "@codemirror/lang-javascript@^6.2.2",
7
- "@codemirror/lang-python@^6.1.6",
8
- "@codemirror/state@^6.5.0",
9
- "@codemirror/theme-one-dark@^6.1.2",
10
- "@codemirror/view@^6.35.3",
11
- "codemirror@^6.0.1"
12
- ],
13
- "registryDependencies": [
14
- "@chatjs/read-document"
15
- ],
16
- "files": [
17
- {
18
- "path": "src/tools/code-documents/tool.ts",
19
- "content": "import {\n eveDocumentCreateInput,\n eveDocumentEditInput,\n eveDocumentWriteResult,\n} from \"@/chatjs/core/documents/contracts\";\nimport type { ToolContext } from \"eve/tools\";\nimport { codeGuidelines } from \"./guidelines\";\nimport { defineTool } from \"eve/tools\";\nimport { executeEveDocumentTool } from \"@/lib/eve/document-tools\";\nimport type { z } from \"zod\";\n\ntype CreateCodeDocumentInput = Readonly<\n Omit<z.infer<typeof eveDocumentCreateInput>, \"fileIds\"> & {\n fileIds: readonly string[];\n }\n>;\n\ntype EditCodeDocumentInput = Readonly<\n Omit<z.infer<typeof eveDocumentEditInput>, \"fileIds\"> & {\n fileIds: readonly string[];\n }\n>;\n\ntype ReadonlyDocumentToolContext = Readonly<\n Pick<ToolContext, \"callId\" | \"session\"> & {\n abortSignal: Readonly<AbortSignal>;\n }\n>;\n\nconst createCodeDocument = defineTool({\n description: `Create a new code document in this conversation. Supply the complete content and a descriptive title. ${codeGuidelines}`,\n execute: async (\n input: CreateCodeDocumentInput,\n context: ReadonlyDocumentToolContext\n ) =>\n eveDocumentWriteResult.parse(\n await executeEveDocumentTool(\"createCodeDocument\", input, context)\n ),\n inputSchema: eveDocumentCreateInput,\n outputSchema: eveDocumentWriteResult,\n});\nconst editCodeDocument = defineTool({\n description: `Edit an existing code document in this conversation. Read the document first and supply its revision ID. Supply the complete replacement content. ${codeGuidelines}`,\n execute: async (\n input: EditCodeDocumentInput,\n context: ReadonlyDocumentToolContext\n ) =>\n eveDocumentWriteResult.parse(\n await executeEveDocumentTool(\"editCodeDocument\", input, context)\n ),\n inputSchema: eveDocumentEditInput,\n outputSchema: eveDocumentWriteResult,\n});\nexport { createCodeDocument, editCodeDocument };\n",
20
- "type": "registry:file",
21
- "target": "~/chatjs/tools/code-documents/tool.ts"
22
- },
23
- {
24
- "path": "src/tools/code-documents/definition.ts",
25
- "content": "import { z } from \"zod\";\nimport type { DocumentDefinition } from \"@/chatjs/core/documents/document-definition\";\n\nexport const documentDefinition = {\n kind: \"code\",\n contentSchema: z.string().max(2_000_000),\n createTool: \"createCodeDocument\",\n editTool: \"editCodeDocument\",\n} as const satisfies DocumentDefinition;\n",
26
- "type": "registry:file",
27
- "target": "~/chatjs/tools/code-documents/definition.ts"
28
- },
29
- {
30
- "path": "src/tools/code-documents/guidelines.ts",
31
- "content": "export const codeGuidelines = `\nGuidelines for Python code:\n- Each snippet should be complete and runnable on its own\n- Prefer using print() statements to display outputs\n- Include helpful comments explaining the code\n- Keep snippets concise (generally under 15 lines)\n- Avoid external dependencies - use Python standard library\n- Handle potential errors gracefully\n- Return meaningful output that demonstrates the code's functionality\n- Don't use input() or other interactive functions\n- Don't access files or network resources\n- Don't use infinite loops\n\nThe title MUST include the file extension (e.g., \"script.py\", \"App.tsx\", \"utils.js\").\nThis extension determines syntax highlighting.`;\n",
32
- "type": "registry:file",
33
- "target": "~/chatjs/tools/code-documents/guidelines.ts"
34
- },
35
- {
36
- "path": "src/tools/code-documents/configuration-schema.ts",
37
- "content": "import { z } from \"zod\";\nimport { languageModelSchema, modelRoles } from \"@/lib/config-models\";\n\nconst configSchema = z\n .strictObject({ edits: languageModelSchema.default(modelRoles.balanced) })\n .prefault({});\nexport { configSchema };\n",
38
- "type": "registry:file",
39
- "target": "~/chatjs/tools/code-documents/configuration-schema.ts"
40
- },
41
- {
42
- "path": "src/tools/code-documents/assistant-actions.ts",
43
- "content": "import type { DocumentAssistantAction } from \"@/chatjs/core/documents/contracts\";\nimport { config } from \"@/lib/config\";\n\nconst documentAssistantActions = (): DocumentAssistantAction[] => [\n {\n instruction: \"Add comments to the code for understanding.\",\n label: \"Add comments\",\n modelId: config.ai.tools.code.edits,\n },\n {\n instruction: \"Add logs to the code for debugging.\",\n label: \"Add logs\",\n modelId: config.ai.tools.code.edits,\n },\n];\nexport { documentAssistantActions };\n",
44
- "type": "registry:file",
45
- "target": "~/chatjs/tools/code-documents/assistant-actions.ts"
46
- },
47
- {
48
- "path": "src/tools/code-documents/document.tsx",
49
- "content": "\"use client\";\nimport type { DocumentBodyProps, DocumentUi } from \"@/chatjs/core/documents/ui\";\nimport { documentDefinition } from \"./definition\";\nimport { documentAssistantActions } from \"./assistant-actions\";\nimport React from \"react\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { ScrollArea } from \"@/components/ui/scroll-area\";\nimport dynamic from \"next/dynamic\";\nimport { getLanguageFromFileName } from \"@/lib/file-language\";\n\nconst CodeEditor = dynamic(\n async () => {\n const { CodeEditor: Editor } = await import(\"./editor\");\n return Editor;\n },\n {\n ssr: false,\n }\n);\n\nexport const documentUi: DocumentUi = {\n copyLabel: \"Copy code to clipboard\",\n definition: documentDefinition,\n assistantActions: documentAssistantActions,\n Body: ({ title, editorProps }: ReadonlyNativeSurface<DocumentBodyProps>) => (\n <ScrollArea className=\"min-h-0 flex-1\">\n <CodeEditor\n {...editorProps}\n language={getLanguageFromFileName(title) || \"python\"}\n />\n </ScrollArea>\n ),\n};\n",
50
- "type": "registry:file",
51
- "target": "~/chatjs/tools/code-documents/document.tsx"
52
- },
53
- {
54
- "path": "src/tools/code-documents/editor.tsx",
55
- "content": "\"use client\";\n\nimport { Compartment, EditorState, Transaction } from \"@codemirror/state\";\nimport React, { memo, useEffect, useRef } from \"react\";\nimport { EditorView } from \"@codemirror/view\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport type { ViewUpdate } from \"@codemirror/view\";\nimport { javascript } from \"@codemirror/lang-javascript\";\nimport { python } from \"@codemirror/lang-python\";\nimport { oneDark } from \"@codemirror/theme-one-dark\";\nimport { basicSetup } from \"codemirror\";\n\ninterface EditorProps {\n content: string;\n currentVersionIndex: number;\n isCurrentVersion: boolean;\n isReadonly?: boolean;\n language?: string;\n onSaveContent: (updatedContent: string, debounce: boolean) => void;\n status: \"streaming\" | \"idle\";\n}\n\nconst getLanguageExtension = (language: string): ReturnType<typeof python> => {\n switch (language) {\n case \"typescript\": {\n return javascript({ jsx: false, typescript: true });\n }\n case \"javascript\": {\n return javascript({ jsx: false, typescript: false });\n }\n case \"jsx\": {\n return javascript({ jsx: true, typescript: false });\n }\n case \"tsx\": {\n return javascript({ jsx: true, typescript: true });\n }\n default: {\n return python();\n }\n }\n};\n\nconst PureCodeEditor = ({\n content,\n onSaveContent,\n isReadonly,\n language = \"python\",\n}: ReadonlyNativeSurface<EditorProps>): React.JSX.Element => {\n const containerRef = useRef<HTMLDivElement>(null);\n const editorRef = useRef<EditorView | null>(null);\n\n const configuration = useRef(new Compartment());\n\n useEffect((): (() => void) | undefined => {\n if (!containerRef.current) {\n return undefined;\n }\n const view = new EditorView({\n parent: containerRef.current,\n state: EditorState.create({\n extensions: [basicSetup, oneDark, configuration.current.of([])],\n }),\n });\n editorRef.current = view;\n return (): void => {\n view.destroy();\n editorRef.current = null;\n };\n }, []);\n\n useEffect((): void => {\n editorRef.current?.dispatch({\n effects: configuration.current.reconfigure([\n getLanguageExtension(language),\n EditorView.editable.of(!(isReadonly === true)),\n EditorState.readOnly.of(Boolean(isReadonly)),\n EditorView.updateListener.of(\n (\n update: ReadonlyNativeSurface<\n Pick<ViewUpdate, \"docChanged\" | \"state\" | \"transactions\">\n >\n ): void => {\n if (\n update.docChanged &&\n isReadonly !== true &&\n update.transactions.some(\n (transaction: ReadonlyNativeSurface<Transaction>): boolean =>\n transaction.annotation(Transaction.remote) !== true\n )\n ) {\n onSaveContent(update.state.doc.toString(), true);\n }\n }\n ),\n ]),\n });\n }, [onSaveContent, isReadonly, language]);\n\n useEffect((): void => {\n const view = editorRef.current;\n if (!view) {\n return;\n }\n const currentContent = view.state.doc.toString();\n if (currentContent !== content) {\n view.dispatch({\n annotations: [Transaction.remote.of(true)],\n changes: { from: 0, insert: content, to: currentContent.length },\n });\n }\n }, [content]);\n\n return (\n <div className=\"not-prose relative w-full text-sm\" ref={containerRef} />\n );\n};\n\nconst areEqual = (\n prevProps: ReadonlyNativeSurface<EditorProps>,\n nextProps: ReadonlyNativeSurface<EditorProps>\n): boolean => {\n if (prevProps.currentVersionIndex !== nextProps.currentVersionIndex) {\n return false;\n }\n if (prevProps.isCurrentVersion !== nextProps.isCurrentVersion) {\n return false;\n }\n if (prevProps.status === \"streaming\" && nextProps.status === \"streaming\") {\n return false;\n }\n if (prevProps.content !== nextProps.content) {\n return false;\n }\n if (prevProps.isReadonly !== nextProps.isReadonly) {\n return false;\n }\n if (prevProps.language !== nextProps.language) {\n return false;\n }\n\n return true;\n};\n\nexport const CodeEditor = memo(PureCodeEditor, areEqual);\n",
56
- "type": "registry:file",
57
- "target": "~/chatjs/tools/code-documents/editor.tsx"
58
- },
59
- {
60
- "path": "dist/source/code-documents.json",
61
- "content": "{\n \"config\": { \"key\": \"code\" },\n \"documentKind\": \"code\",\n \"envRequirements\": [],\n \"id\": \"code-documents\",\n \"kind\": \"tool\",\n \"requiresTools\": [\"readDocument\"],\n \"tools\": [\n {\n \"composer\": { \"icon\": \"Edit3\", \"name\": \"Canvas\", \"shortName\": \"Canvas\" },\n \"toolExport\": \"createCodeDocument\"\n },\n {\n \"composer\": { \"icon\": \"Edit3\", \"name\": \"Canvas\", \"shortName\": \"Canvas\" },\n \"toolExport\": \"editCodeDocument\"\n }\n ],\n \"contractVersion\": 2,\n \"uiBase\": \"base\"\n}\n",
62
- "type": "registry:file",
63
- "target": "~/chatjs/tools/code-documents/chatjs.json"
64
- }
65
- ],
66
- "meta": {
67
- "chatjs": {
68
- "config": {
69
- "key": "code"
70
- },
71
- "documentKind": "code",
72
- "envRequirements": [],
73
- "id": "code-documents",
74
- "kind": "tool",
75
- "requiresTools": [
76
- "readDocument"
77
- ],
78
- "tools": [
79
- {
80
- "composer": {
81
- "icon": "Edit3",
82
- "name": "Canvas",
83
- "shortName": "Canvas"
84
- },
85
- "toolExport": "createCodeDocument"
86
- },
87
- {
88
- "composer": {
89
- "icon": "Edit3",
90
- "name": "Canvas",
91
- "shortName": "Canvas"
92
- },
93
- "toolExport": "editCodeDocument"
94
- }
95
- ],
96
- "contractVersion": 2,
97
- "uiBase": "base"
98
- }
99
- },
100
- "type": "registry:item"
101
- }
@@ -1,25 +0,0 @@
1
- {
2
- "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
- "name": "code-execution-runtime",
4
- "files": [
5
- {
6
- "path": "src/tools/_shared/code-execution/python.ts",
7
- "content": "import type {\n CodeExecutionContext,\n CodeExecutionResult,\n ExecutionSandbox,\n} from \"./types\";\nimport { z } from \"zod\";\n\ntype PythonExecutionContext = Readonly<{\n sandbox: Readonly<ExecutionSandbox>;\n requestId: string;\n log: Readonly<Pick<CodeExecutionContext[\"log\"], \"error\" | \"info\">>;\n}>;\n\nconst pythonExecutionInfoSchema = z.looseObject({\n error: z\n .looseObject({\n name: z.string(),\n value: z.string(),\n traceback: z.string(),\n })\n .optional(),\n success: z.boolean().optional(),\n});\n\ntype PythonExecutionInfo = z.infer<typeof pythonExecutionInfoSchema>;\n\ninterface PythonExecutionOutput {\n chartData: Record<string, unknown> | null;\n execInfo: PythonExecutionInfo;\n outputText: string;\n}\n\nconst WHITESPACE_REGEX = /\\s+/u;\nconst PACKAGE_SPEC_SPLIT_RE = /[=<>![\\s]/u;\nconst isJsonObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst PROCESS_SUCCESS = 0;\nconst PACKAGE_NAME_INDEX = 0;\nconst EMPTY_PACKAGE_COUNT = 0;\nconst LAST_LINE_INDEX = -1;\nconst MISSING_CHART_INDEX = -1;\nconst CHART_LINE_COUNT = 1;\nconst EMPTY_STDERR_LENGTH = 0;\n\nconst CHART_JSON_PREFIX = \"__CHART_JSON__:\";\n\nconst packageName = (spec: string): string =>\n spec.split(PACKAGE_SPEC_SPLIT_RE)[PACKAGE_NAME_INDEX].toLowerCase();\n\nconst installBasePackages = async (\n basePackages: readonly string[],\n { sandbox, requestId, log }: PythonExecutionContext\n): Promise<{\n success: boolean;\n result?: CodeExecutionResult;\n}> => {\n const installStep = await sandbox.runCommand({\n args: [\"install\", ...basePackages],\n cmd: \"pip\",\n });\n if (installStep.exitCode !== PROCESS_SUCCESS) {\n const errorOutput = await installStep.stderr();\n const standardOutput =\n errorOutput.trim() === \"\" ? await installStep.stdout() : \"\";\n const installStderr = errorOutput.trim() || standardOutput.trim();\n log.error(\n { requestId, stderr: installStderr },\n \"base package installation failed\"\n );\n return {\n result: {\n chart: \"\",\n message: `Failed to install base packages: ${installStderr}`,\n },\n success: false,\n };\n }\n log.info({ requestId }, \"base packages installed\");\n return { success: true };\n};\n\nconst pythonPackagePlan = (\n code: string,\n basePackages: readonly string[]\n): { codeWithoutPipLines: string; extraPackages: string[] } => {\n const basePackageNames = new Set(\n basePackages.map((basePackageName) => basePackageName.toLowerCase())\n );\n const lines = code.split(\"\\n\");\n const pipLines = lines.filter((line) =>\n line.trim().startsWith(\"!pip install \")\n );\n const extraPackages = pipLines\n .flatMap((line) =>\n line\n .trim()\n .slice(\"!pip install \".length)\n .split(WHITESPACE_REGEX)\n .filter(Boolean)\n )\n .filter((spec) => !basePackageNames.has(packageName(spec)));\n\n const codeWithoutPipLines = lines\n .filter((line) => !line.trim().startsWith(\"!pip install \"))\n .join(\"\\n\");\n return { codeWithoutPipLines, extraPackages };\n};\n\ninterface PythonPackagePreparation {\n codeToRun: string;\n installResult: {\n success: boolean;\n result?: CodeExecutionResult;\n };\n}\n\nconst processExtraPackages = async (\n code: string,\n basePackages: readonly string[],\n { sandbox, requestId, log }: PythonExecutionContext\n): Promise<PythonPackagePreparation> => {\n const { codeWithoutPipLines, extraPackages } = pythonPackagePlan(\n code,\n basePackages\n );\n\n if (extraPackages.length === EMPTY_PACKAGE_COUNT) {\n return { codeToRun: codeWithoutPipLines, installResult: { success: true } };\n }\n\n log.info(\n { packageCount: extraPackages.length, requestId },\n \"installing extra packages\"\n );\n const dynamicInstall = await sandbox.runCommand({\n args: [\"install\", ...extraPackages],\n cmd: \"pip\",\n });\n if (dynamicInstall.exitCode !== PROCESS_SUCCESS) {\n const errorOutput = await dynamicInstall.stderr();\n const standardOutput =\n errorOutput.trim() === \"\" ? await dynamicInstall.stdout() : \"\";\n const stderr = errorOutput.trim() || standardOutput.trim();\n log.error(\n { exitCode: dynamicInstall.exitCode, requestId },\n \"dynamic package installation failed\"\n );\n return {\n codeToRun: code,\n installResult: {\n result: {\n chart: \"\",\n message: `Failed to install packages: ${stderr}`,\n },\n success: false,\n },\n };\n }\n\n return {\n codeToRun: codeWithoutPipLines,\n installResult: { success: true },\n };\n};\n\nconst createWrappedCode = (codeToRun: string, chartPath: string): string => `\nimport sys\nimport json\nimport traceback\n\ntry:\n import matplotlib.pyplot as _plt_module\n _orig_savefig = _plt_module.savefig\n def _intercepted_savefig(*args, **kwargs):\n _orig_savefig('${chartPath}', format='png', bbox_inches='tight', dpi=100)\n _user_target = args[0] if args else kwargs.get('fname')\n if _user_target not in (None, '${chartPath}'):\n return _orig_savefig(*args, **kwargs)\n _plt_module.savefig = _intercepted_savefig\nexcept ImportError:\n pass\n\ntry:\n exec(${JSON.stringify(codeToRun)})\n try:\n _locals = locals()\n _globals = globals()\n _chart_var = _locals.get(\"chart\") or _globals.get(\"chart\")\n if (isinstance(_chart_var, dict)\n and isinstance(_chart_var.get(\"type\"), str)\n and isinstance(_chart_var.get(\"elements\"), list)):\n print(\"__CHART_JSON__:\" + json.dumps(_chart_var))\n else:\n if \"result\" in _locals:\n print(_locals[\"result\"])\n elif \"result\" in _globals:\n print(_globals[\"result\"])\n elif \"results\" in _locals:\n print(_locals[\"results\"])\n elif \"results\" in _globals:\n print(_globals[\"results\"])\n except Exception:\n pass\n try:\n import matplotlib.pyplot as plt\n if plt.get_fignums():\n plt.savefig('${chartPath}', format='png', bbox_inches='tight', dpi=100)\n plt.close('all')\n except ImportError:\n pass\n print(json.dumps({\"success\": True}))\nexcept Exception as e:\n error_info = {\"success\": False, \"error\": {\"name\": type(e).__name__, \"value\": str(e), \"traceback\": traceback.format_exc()}}\n print(json.dumps(error_info))\n sys.exit(1)\n`;\n\nconst parseExecutionOutput = async (\n execResult: Readonly<{\n stdout: () => Promise<string>;\n exitCode: number;\n }>\n): Promise<PythonExecutionOutput> => {\n const stdout = await execResult.stdout();\n let execInfo: PythonExecutionInfo = { success: true };\n let outputText = \"\";\n let chartData: Record<string, unknown> | null = null;\n\n try {\n const outLines = (stdout ?? \"\").trim().split(\"\\n\");\n const lastLine = outLines.at(LAST_LINE_INDEX);\n execInfo = pythonExecutionInfoSchema.parse(JSON.parse(lastLine ?? \"{}\"));\n outLines.pop();\n\n const chartLineIdx = outLines.findIndex((line) =>\n line.startsWith(CHART_JSON_PREFIX)\n );\n if (chartLineIdx !== MISSING_CHART_INDEX) {\n const raw = outLines[chartLineIdx].slice(CHART_JSON_PREFIX.length);\n try {\n const value: unknown = JSON.parse(raw);\n if (isJsonObject(value)) {\n chartData = value;\n }\n } catch {\n // Ignore malformed chart JSON from the sandboxed snippet.\n }\n outLines.splice(chartLineIdx, CHART_LINE_COUNT);\n }\n\n outputText = outLines.join(\"\\n\");\n } catch {\n outputText = stdout ?? \"\";\n if (execResult.exitCode !== PROCESS_SUCCESS) {\n execInfo = {\n error: {\n name: \"SandboxExecutionError\",\n traceback: \"\",\n value: \"Execution completed without a parsable status trailer\",\n },\n success: false,\n };\n }\n }\n\n return { chartData, execInfo, outputText };\n};\n\nconst checkForChart = async (\n chartPath: string,\n { sandbox, requestId, log }: PythonExecutionContext\n): Promise<{ base64: string; format: string } | undefined> => {\n const chartCheck = await sandbox.runCommand({\n args: [\"-f\", chartPath],\n cmd: \"test\",\n });\n if (chartCheck.exitCode === PROCESS_SUCCESS) {\n const base64Command = await sandbox.runCommand({\n args: [\"-w\", \"0\", chartPath],\n cmd: \"base64\",\n });\n const b64 = await base64Command.stdout();\n log.info({ requestId }, \"chart generated\");\n return { base64: (b64 ?? \"\").trim(), format: \"png\" };\n }\n return undefined;\n};\n\nconst buildResponseMessage = ({\n outputText,\n stderr,\n execInfo,\n log,\n requestId,\n}: Readonly<{\n outputText: string;\n stderr: string;\n execInfo: Readonly<PythonExecutionInfo>;\n log: Readonly<Pick<CodeExecutionContext[\"log\"], \"error\">>;\n requestId: string;\n}>): string => {\n let message = \"\";\n\n if (outputText) {\n message += `${outputText}\\n`;\n }\n if (stderr && stderr.trim().length > EMPTY_STDERR_LENGTH) {\n message += `${stderr}\\n`;\n }\n if (execInfo.error) {\n message += `Error: ${execInfo.error.name}: ${execInfo.error.value}\\n`;\n log.error({ error: execInfo.error, requestId }, \"python execution error\");\n }\n\n return message;\n};\n\nexport const executePythonInSandbox = async ({\n sandbox,\n code,\n log,\n requestId,\n}: Readonly<\n Pick<CodeExecutionContext, \"code\" | \"requestId\"> & {\n sandbox: Readonly<Pick<CodeExecutionContext[\"sandbox\"], \"runCommand\">>;\n log: Readonly<Pick<CodeExecutionContext[\"log\"], \"error\" | \"info\">>;\n }\n>): Promise<CodeExecutionResult> => {\n const execution = { log, requestId, sandbox };\n const basePackages = [\n \"matplotlib\",\n \"pandas\",\n \"numpy\",\n \"sympy\",\n \"yfinance\",\n ] as const;\n const chartPath = \"/tmp/chart.png\";\n\n const baseInstallResult = await installBasePackages(basePackages, execution);\n if (!baseInstallResult.success) {\n return baseInstallResult.result ?? { chart: \"\", message: \"Unknown error\" };\n }\n\n const { codeToRun, installResult } = await processExtraPackages(\n code,\n basePackages,\n execution\n );\n if (!installResult.success) {\n return installResult.result ?? { chart: \"\", message: \"Unknown error\" };\n }\n\n const wrappedCode = createWrappedCode(codeToRun, chartPath);\n const execResult = await sandbox.runCommand({\n args: [\"-c\", wrappedCode],\n cmd: \"python3\",\n });\n\n const { outputText, chartData, execInfo } =\n await parseExecutionOutput(execResult);\n\n const message = buildResponseMessage({\n execInfo,\n log,\n outputText,\n requestId,\n stderr: await execResult.stderr(),\n });\n\n if (chartData) {\n log.info({ requestId }, \"interactive chart data returned\");\n return { chart: chartData, message: message.trim() };\n }\n\n const chartOut = await checkForChart(chartPath, execution);\n return {\n chart: chartOut ?? \"\",\n message: message.trim(),\n };\n};\n",
8
- "type": "registry:file",
9
- "target": "~/chatjs/tools/_shared/code-execution/python.ts"
10
- },
11
- {
12
- "path": "src/tools/_shared/code-execution/javascript.ts",
13
- "content": "import type { CodeExecutionContext, CodeExecutionResult } from \"./types\";\n\nconst SUCCESS_EXIT_CODE = 0;\nconst MISSING_STATUS_LINE_INDEX = -1;\nconst STATUS_TRAILER_LINE_COUNT = 1;\nconst EXECUTION_STATUS_PREFIX = \"__EXECUTION_STATUS__:\";\n\nconst JAVASCRIPT_EXECUTION_TEMPLATE = `\nimport { inspect } from \"node:util\";\n\nconst __formatOutput = (value) => {\n if (typeof value === \"string\") {\n return value;\n }\n\n return inspect(value, {\n depth: 4,\n colors: false,\n maxArrayLength: 100,\n breakLength: 120,\n });\n};\n\nconst __run = async () => {\n try {\n const __userCode = __USER_CODE_LITERAL__;\n const __execution = await (0, eval)(\n \"(async () => {\\\\n\" +\n __userCode + \"\\\\n\" +\n \"return { __kind: \\\\\"locals\\\\\",\" +\n \" result: typeof result !== \\\\\"undefined\\\\\" ? result : undefined,\" +\n \" results: typeof results !== \\\\\"undefined\\\\\" ? results : undefined };\\\\n\" +\n \"})()\"\n );\n\n const __result =\n __execution &&\n typeof __execution === \"object\" &&\n __execution.__kind === \"locals\"\n ? typeof __execution.result !== \"undefined\"\n ? __execution.result\n : typeof __execution.results !== \"undefined\"\n ? __execution.results\n : undefined\n : __execution;\n\n if (typeof __result !== \"undefined\") {\n console.log(__formatOutput(__result));\n }\n\n console.log(\"${EXECUTION_STATUS_PREFIX}\" + JSON.stringify({ success: true }));\n } catch (error) {\n const execError = error instanceof Error ? error : new Error(String(error));\n console.log(\n \"${EXECUTION_STATUS_PREFIX}\" +\n JSON.stringify({\n success: false,\n error: {\n name: execError.name,\n value: execError.message,\n traceback: execError.stack ?? execError.message,\n },\n })\n );\n process.exitCode = 1;\n }\n};\n\nawait __run();\n`;\n\nconst createWrappedCode = (code: string): string =>\n JAVASCRIPT_EXECUTION_TEMPLATE.replace(\"__USER_CODE_LITERAL__\", (): string =>\n JSON.stringify(code)\n );\n\ninterface JsExecInfo {\n success?: unknown;\n error?: unknown;\n}\n\nconst execInfoFromExitCode = (exitCode: number): JsExecInfo => {\n if (exitCode === SUCCESS_EXIT_CODE) {\n return { success: true };\n }\n return {\n error: {\n name: \"SandboxExecutionError\",\n traceback: \"\",\n value: \"Execution completed without a valid status trailer\",\n },\n success: false,\n };\n};\n\nconst readExecutionErrorField = (error: unknown, key: string): unknown =>\n Reflect.get(new Object(error), key);\n\nconst readExecutionError = (info: unknown): unknown => {\n if (info === null) {\n throw new TypeError(\"Sandbox execution status cannot be null.\");\n }\n return readExecutionErrorField(info, \"error\");\n};\n\nconst decodeExecutionTrailer = (\n raw: string\n): { valid: true; info: unknown } | { valid: false } => {\n try {\n const parsed: unknown = JSON.parse(raw);\n return { info: parsed, valid: true };\n } catch {\n return { valid: false };\n }\n};\n\nconst findExecutionTrailer = (\n lines: readonly string[]\n): { found: true; index: number; raw: string } | { found: false } => {\n // The final trailer wins over user output that happens to share the prefix.\n const index = lines.findLastIndex((line) =>\n line.startsWith(EXECUTION_STATUS_PREFIX)\n );\n if (index === MISSING_STATUS_LINE_INDEX) {\n return { found: false };\n }\n return {\n found: true,\n index,\n raw: lines[index].slice(EXECUTION_STATUS_PREFIX.length),\n };\n};\n\nconst parseExecutionOutput = async (\n execResult: Readonly<{\n stdout: () => Promise<string>;\n exitCode: number;\n }>\n): Promise<{\n outputText: string;\n execInfo: unknown;\n}> => {\n const stdout = await execResult.stdout();\n const lines = (stdout ?? \"\").split(\"\\n\");\n const trailer = findExecutionTrailer(lines);\n\n if (!trailer.found) {\n return {\n execInfo: execInfoFromExitCode(execResult.exitCode),\n outputText: stdout ?? \"\",\n };\n }\n\n const decoded = decodeExecutionTrailer(trailer.raw);\n if (!decoded.valid) {\n return {\n execInfo: execInfoFromExitCode(execResult.exitCode),\n outputText: stdout ?? \"\",\n };\n }\n lines.splice(trailer.index, STATUS_TRAILER_LINE_COUNT);\n\n return {\n execInfo: decoded.info,\n outputText: lines.join(\"\\n\").trim(),\n };\n};\nconst formatExecutionMessage = (\n parts: Readonly<{\n outputText: string;\n stderr: string;\n execInfo: unknown;\n }>,\n context: Readonly<{\n log: Readonly<Pick<CodeExecutionContext[\"log\"], \"error\">>;\n requestId: string;\n }>\n): string => {\n const lines = [parts.outputText, parts.stderr.trim()];\n const executionError = readExecutionError(parts.execInfo);\n const hasExecutionError = Boolean(executionError);\n if (hasExecutionError) {\n lines.push(\n `Error: ${String(readExecutionErrorField(executionError, \"name\"))}: ${String(readExecutionErrorField(executionError, \"value\"))}`\n );\n context.log.error(\n { error: executionError, requestId: context.requestId },\n \"javascript execution error\"\n );\n }\n return lines\n .filter((line) => line !== \"\")\n .join(\"\\n\")\n .trim();\n};\n\nexport const executeJavaScriptInSandbox = async ({\n sandbox,\n code,\n log,\n requestId,\n}: Readonly<\n Pick<CodeExecutionContext, \"code\" | \"requestId\"> & {\n sandbox: Readonly<Pick<CodeExecutionContext[\"sandbox\"], \"runCommand\">>;\n log: Readonly<Pick<CodeExecutionContext[\"log\"], \"error\">>;\n }\n>): Promise<CodeExecutionResult> => {\n const execResult = await sandbox.runCommand({\n args: [\"--input-type=module\", \"-e\", createWrappedCode(code)],\n cmd: \"node\",\n });\n\n const { outputText, execInfo } = await parseExecutionOutput(execResult);\n const stderr = await execResult.stderr();\n return {\n chart: \"\",\n message: formatExecutionMessage(\n { execInfo, outputText, stderr },\n { log, requestId }\n ),\n };\n};\n",
14
- "type": "registry:file",
15
- "target": "~/chatjs/tools/_shared/code-execution/javascript.ts"
16
- },
17
- {
18
- "path": "src/tools/_shared/code-execution/types.ts",
19
- "content": "import type { Sandbox } from \"@chat-js/sandboxes/provider\";\nimport type { createModuleLogger } from \"@/lib/logger\";\n\nconst supportedExecutionLanguages = [\"python\", \"javascript\"] as const;\n\ntype SupportedExecutionLanguage = (typeof supportedExecutionLanguages)[number];\n\ninterface CodeExecutionResult {\n chart: string | { base64: string; format: string } | Record<string, unknown>;\n message: string;\n}\n\ntype ExecutionSandbox = Pick<Sandbox, \"runCommand\">;\n\ninterface CodeExecutionContext {\n code: string;\n log: ReturnType<typeof createModuleLogger>;\n requestId: string;\n sandbox: ExecutionSandbox;\n}\nexport { supportedExecutionLanguages };\nexport type {\n ExecutionSandbox,\n CodeExecutionContext,\n CodeExecutionResult,\n SupportedExecutionLanguage,\n};\n",
20
- "type": "registry:file",
21
- "target": "~/chatjs/tools/_shared/code-execution/types.ts"
22
- }
23
- ],
24
- "type": "registry:item"
25
- }