@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
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "deep-research",
3
+ "description": "Research with installed EVE capabilities; produces a sandbox report. ChatJS adds optional progress UI.",
4
+ "dependencies": [
5
+ "eve@npm:@chat-js/eve@1.0.0-rc.6-chatjs.1",
6
+ "zod@4.5.4"
7
+ ],
8
+ "files": [
9
+ {
10
+ "path": "src/tools/deep-research/agent/tools/deep-research.ts",
11
+ "content": "// ChatJS source: deep-research. Ownership: chatjs/tools/deep-research/chatjs.json.\nimport { defineWorkflowTool, toolOutput } from \"eve/tools\";\nimport {\n clarifyWithUserInstructions,\n compressResearchSimpleHumanMessage,\n compressResearchSystemPrompt,\n finalReportGenerationPrompt,\n leadResearcherPrompt,\n researchSystemPrompt,\n transformMessagesIntoResearchTopicPrompt,\n} from \"../lib/research/prompts\";\nimport { prepareResearch, researchCompletedAt } from \"../lib/research/steps\";\nimport {\n researchBrief,\n researchInput,\n researchClarification,\n researchDecision,\n researchFindings,\n researchReport,\n researchResult,\n} from \"../lib/research/schemas\";\nimport type { ResearchUpdate } from \"../lib/research/schemas\";\nimport type { AgentSession, WorkflowToolContext } from \"eve/tools\";\nimport { z } from \"zod\";\n\nimport {\n readResearchFiles,\n writeResearchFile,\n} from \"../lib/research/workspace\";\n\ntype ResearchResult = ReturnType<typeof researchResult>;\n\ntype ResearchWorkflowContext = Readonly<\n Omit<WorkflowToolContext, \"abortSignal\"> & {\n abortSignal: Readonly<AbortSignal>;\n }\n>;\n\nconst structuredMessage = (message: string): string =>\n `${message}\\n\\nDeliver the requested fields through the eve__reply tool. Put any Markdown inside its string fields; do not return prose or JSON text instead of calling the tool.`;\n\nconst outputSchema = (schema: z.ZodType): Record<string, z.JSONType> =>\n z.record(z.string(), z.json()).parse(z.toJSONSchema(schema));\n\nconst researchReply = async (\n agent: Readonly<AgentSession>,\n options: Readonly<{\n message: string;\n outputSchema: Record<string, z.JSONType>;\n signal: AbortSignal;\n }>\n): Promise<unknown> => {\n options.signal.throwIfAborted();\n const response = await agent.send(options.message, {\n outputSchema: options.outputSchema,\n signal: options.signal,\n });\n const result = await response.result();\n options.signal.throwIfAborted();\n if (result.status === \"failed\") {\n throw new Error(result.error?.message ?? \"Research agent failed\");\n }\n if (result.data === undefined) {\n throw new Error(\"Research agent ended without structured output\");\n }\n return result.data;\n};\n\nconst INITIAL_RESEARCH_ROUND = 0;\nconst RESEARCH_ROUND_INCREMENT = 1;\nconst BRIEF_UPDATE_INDEX = 1;\nconst EMPTY_TOPIC_COUNT = 0;\n\nexport default defineWorkflowTool({\n availableInSubagents: false,\n description:\n \"Conduct deep research using installed EVE capabilities and sandbox files. Supply the full task and relevant conversation context in request. Use only for explicit deep research requests, once per turn. Returns a Markdown report path in the shared sandbox. After completion, deliver the file using attach_workspace_file when installed or your channel's native file delivery. If no delivery mechanism exists, explain where the file is and do not invent a download URL. If clarification is needed, ask the returned questions. If research fails, report the error instead of starting duplicate research.\",\n async *execute(\n input: Readonly<z.infer<typeof researchInput>>,\n context: ResearchWorkflowContext\n ): AsyncGenerator<ResearchResult, void> {\n \"use workflow\";\n const { config, date, messages, timestamp } = await prepareResearch(\n input.request\n );\n const updates: ResearchUpdate[] = [];\n const progress = (): ResearchResult =>\n researchResult({ format: \"progress\" }, updates);\n if (config.allow_clarification) {\n const clarification = researchClarification.parse(\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n clarifyWithUserInstructions({ date, messages })\n ),\n outputSchema: outputSchema(researchClarification),\n })\n );\n if (clarification.need_clarification) {\n yield researchResult({\n answer: clarification.question,\n format: \"clarifying_questions\",\n });\n return;\n }\n }\n updates.push(\n {\n timestamp,\n title: \"Starting research\",\n toolCallId: context.callId,\n type: \"started\",\n },\n {\n status: \"running\",\n title: \"Writing research brief\",\n toolCallId: context.callId,\n type: \"writing\",\n }\n );\n yield progress();\n const brief = researchBrief.parse(\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n transformMessagesIntoResearchTopicPrompt({ date, messages })\n ),\n outputSchema: outputSchema(researchBrief),\n })\n );\n await writeResearchFile(context, \"brief.md\", brief.research_brief);\n updates[BRIEF_UPDATE_INDEX] = {\n message: brief.research_brief,\n status: \"completed\",\n title: \"Writing research brief\",\n toolCallId: context.callId,\n type: \"writing\",\n };\n yield progress();\n\n const noteFiles: string[] = [];\n const decisionSchema = researchDecision.extend({\n topics: researchDecision.shape.topics.max(\n config.max_concurrent_research_units\n ),\n });\n // Preserve the SDK's max_researcher_iterations + 1 decision steps, including\n // its allowance for research on the final step if the supervisor has not finished.\n for (\n let round = INITIAL_RESEARCH_ROUND;\n round <= config.max_researcher_iterations;\n round += RESEARCH_ROUND_INCREMENT\n ) {\n context.abortSignal.throwIfAborted();\n // oxlint-disable-next-line no-await-in-loop -- Each decision reads the notes completed by preceding research rounds.\n const findings = await readResearchFiles(context, [\n \"brief.md\",\n ...noteFiles,\n ]);\n const decision = decisionSchema.parse(\n // oxlint-disable-next-line no-await-in-loop -- Each decision consumes the findings added by the preceding round.\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n `${leadResearcherPrompt({ date, max_concurrent_research_units: config.max_concurrent_research_units })}\\n\\nResearch brief: ${findings[0]}\\n\\nFindings so far:\\n${findings.slice(1).join(\"\\n\\n\")}\\n\\nDecision round ${round + RESEARCH_ROUND_INCREMENT} of ${config.max_researcher_iterations + RESEARCH_ROUND_INCREMENT}. Return your next decision.`\n ),\n outputSchema: outputSchema(decisionSchema),\n })\n );\n if (decision.complete) {\n break;\n }\n if (decision.topics.length === EMPTY_TOPIC_COUNT) {\n throw new Error(\n \"The research supervisor must select topics or finish.\"\n );\n }\n for (const topic of decision.topics) {\n context.abortSignal.throwIfAborted();\n const updateIndex = updates.length;\n updates.push({\n message: topic,\n status: \"running\",\n title: \"Researching topic\",\n toolCallId: context.callId,\n type: \"thoughts\",\n });\n yield progress();\n const raw = researchFindings.parse(\n // oxlint-disable-next-line no-await-in-loop -- Complete the topic before moving to the next research stage.\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n `${researchSystemPrompt({ date, max_search_queries: config.search_api_max_queries, mcp_prompt: \"Use eve__search to discover installed search/retrieval connections and eve__tool to call them. Use native read_file or bash for relevant sandbox files. Do not call deepResearch recursively. If current external evidence is needed but no search capability is installed, say so explicitly; never fabricate sources.\" })}\\n\\nResearch brief:\\n${findings[0]}\\n\\nTopic:\\n${topic}\\n\\nReturn comprehensive raw findings with source URLs, citations, uncertainties, and conflicting evidence.`\n ),\n outputSchema: outputSchema(researchFindings),\n })\n );\n const topicNumber = noteFiles.length + 1;\n const sourceFile = `topic-${topicNumber}-sources.md`;\n // oxlint-disable-next-line no-await-in-loop -- Preserve cited source findings before compression.\n await writeResearchFile(\n context,\n sourceFile,\n `# ${topic}\\n\\n${raw.findings}`\n );\n // oxlint-disable-next-line no-await-in-loop -- Compression consumes the saved source file.\n const [sources] = await readResearchFiles(context, [sourceFile]);\n const compressed = researchFindings.parse(\n // oxlint-disable-next-line no-await-in-loop -- Commit this topic's compressed notes before the next topic and supervisor decision.\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n `${compressResearchSystemPrompt({ date })}\\n\\n${sources}\\n\\n${compressResearchSimpleHumanMessage}`\n ),\n outputSchema: outputSchema(researchFindings),\n })\n );\n const noteFile = `topic-${topicNumber}-notes.md`;\n // oxlint-disable-next-line no-await-in-loop -- Commit notes before advancing the supervisor.\n await writeResearchFile(\n context,\n noteFile,\n `# ${topic}\\n\\n${compressed.findings}`\n );\n noteFiles.push(noteFile);\n updates[updateIndex] = {\n message: topic,\n status: \"completed\",\n title: \"Research topic completed\",\n toolCallId: context.callId,\n type: \"thoughts\",\n };\n yield progress();\n }\n }\n const reportUpdateIndex = updates.length;\n updates.push({\n status: \"running\",\n title: \"Writing final report\",\n toolCallId: context.callId,\n type: \"writing\",\n });\n yield progress();\n const [savedBrief, ...savedNotes] = await readResearchFiles(context, [\n \"brief.md\",\n ...noteFiles,\n ]);\n const report = researchReport.parse(\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n `${finalReportGenerationPrompt({ date, findings: savedNotes.join(\"\\n\"), research_brief: savedBrief })}\\n\\nWrite the complete Markdown report with title ${JSON.stringify(brief.title)}. Return title and content; the workflow will publish the report as a Markdown file.`\n ),\n outputSchema: outputSchema(researchReport),\n })\n );\n context.abortSignal.throwIfAborted();\n const reportPath = await writeResearchFile(\n context,\n \"report.md\",\n report.content\n );\n const completedAt = await researchCompletedAt();\n updates[reportUpdateIndex] = {\n status: \"completed\",\n title: \"Writing final report\",\n toolCallId: context.callId,\n type: \"writing\",\n };\n updates.push({\n timestamp: completedAt,\n title: \"Research complete\",\n toolCallId: context.callId,\n type: \"completed\",\n });\n yield researchResult(\n { path: reportPath, title: report.title, format: \"report\" },\n updates\n );\n },\n inputSchema: researchInput,\n toModelOutput: (result) => toolOutput.json(result.output),\n});\n",
12
+ "type": "registry:file",
13
+ "target": "~/agent/tools/deepResearch.ts"
14
+ },
15
+ {
16
+ "path": "src/tools/deep-research/agent/lib/research/configuration.ts",
17
+ "content": "/** Workflow-specific bounds. Model, reasoning, approvals, connections, and sandbox belong to agent/agent.ts and native EVE files. */\nexport const researchOptions = {\n allow_clarification: true,\n max_concurrent_research_units: 2,\n max_researcher_iterations: 1,\n search_api_max_queries: 2,\n};\n",
18
+ "type": "registry:file",
19
+ "target": "~/agent/lib/research/configuration.ts"
20
+ },
21
+ {
22
+ "path": "src/tools/deep-research/agent/lib/research/prompts.ts",
23
+ "content": "const clarifyWithUserInstructions = ({\n messages,\n date,\n}: Readonly<{\n messages: string;\n date: string;\n}>): string =>\n `These are the messages that have been exchanged so far from the user asking for the report:\n<Messages>\n${messages}\n</Messages>\n\nToday's date is ${date}.\n\nAssess whether you need to ask a clarifying question, or if the user has already provided enough information for you to start research.\nIMPORTANT: If you can see in the messages history that you have already asked a clarifying question, you almost always do not need to ask another one. Only ask another question if ABSOLUTELY NECESSARY.\n\nIf there are acronyms, abbreviations, or unknown terms, ask the user to clarify.\nIf you need to ask a question, follow these guidelines:\n- Be concise while gathering all necessary information\n- Make sure to gather all the information needed to carry out the research task in a concise, well-structured manner.\n- Use bullet points or numbered lists if appropriate for clarity. Make sure that this uses markdown formatting and will be rendered correctly if the string output is passed to a markdown renderer.\n- Don't ask for unnecessary information, or information that the user has already provided. If you can see that the user has already provided the information, do not ask for it again.\n\nRespond in valid JSON format with these exact keys:\n\"need_clarification\": boolean,\n\"question\": \"<question to ask the user to clarify the report scope>\",\n\"verification\": \"<verification message that we will start research>\"\n\nIf you need to ask a clarifying question, return:\n\"need_clarification\": true,\n\"question\": \"<your clarifying question>\",\n\"verification\": \"\"\n\nIf you do not need to ask a clarifying question, return:\n\"need_clarification\": false,\n\"question\": \"\",\n\"verification\": \"<acknowledgement message that you will now start research based on the provided information>\"\n\nFor the verification message when no clarification is needed:\n- Acknowledge that you have sufficient information to proceed\n- Briefly summarize the key aspects of what you understand from their request\n- Confirm that you will now begin the research process\n- Keep the message concise and professional`;\n\nconst transformMessagesIntoResearchTopicPrompt = ({\n messages,\n date,\n}: Readonly<{\n messages: string;\n date: string;\n}>): string =>\n `You will be given a set of messages that have been exchanged so far between yourself and the user.\nYour job is to translate these messages into a more detailed and concrete research question that will be used to guide the research.\n\nThe messages that have been exchanged so far between yourself and the user are:\n<Messages>\n${messages}\n</Messages>\n\nToday's date is ${date}.\n\nYou will return a single research question that will be used to guide the research.\n\nGuidelines:\n1. Maximize Specificity and Detail\n- Include all known user preferences and explicitly list key attributes or dimensions to consider.\n- It is important that all details from the user are included in the instructions.\n\n2. Fill in Unstated But Necessary Dimensions as Open-Ended\n- If certain attributes are essential for a meaningful output but the user has not provided them, explicitly state that they are open-ended or default to no specific constraint.\n\n3. Avoid Unwarranted Assumptions\n- If the user has not provided a particular detail, do not invent one.\n- Instead, state the lack of specification and guide the researcher to treat it as flexible or accept all possible options.\n\n4. Use the First Person\n- Phrase the request from the perspective of the user.\n\n5. Sources\n- If specific sources should be prioritized, specify them in the research question.\n- For product and travel research, prefer linking directly to official or primary websites (e.g., official brand sites, manufacturer pages, or reputable e-commerce platforms like Amazon for user reviews) rather than aggregator sites or SEO-heavy blogs.\n- For academic or scientific queries, prefer linking directly to the original paper or official journal publication rather than survey papers or secondary summaries.\n- For people, try linking directly to their LinkedIn profile, or their personal website if they have one.\n- If the query is in a specific language, prioritize sources published in that language.`;\n\nconst leadResearcherPrompt = ({\n date,\n max_concurrent_research_units,\n}: Readonly<{\n date: string;\n max_concurrent_research_units: number;\n}>): string =>\n `You are a research supervisor. Today's date is ${date}.\nYou receive a research brief and findings from all completed topics. Decide whether the evidence is sufficient for a comprehensive report or identify specific gaps requiring follow-up research.\n\nReturn JSON with complete (boolean) and topics (array of strings).\n- To research, set complete to false and provide up to ${max_concurrent_research_units} detailed, self-contained topics. The workflow will run them sequentially and return their findings before your next decision.\n- To finish, set complete to true and topics to []. A separate writer synthesizes the report.\n- Start by researching the brief. On later rounds, request only net new information that is necessary to answer it. Do not ask researchers to synthesize existing findings.\n- Each topic must include all necessary context, explain acronyms, and state the desired depth of effort. Researchers do not see your other topics or findings.\n- Split independent questions when that improves coverage. Resolve dependencies first. More topics increase cost; prefer fewer comprehensive investigations over redundant subtopics.\n- Judge evidence coverage and reliability, not formatting. Findings may be raw or messy.\n- Match depth to the user's request. Detailed or comprehensive requests warrant more follow-up than broad overviews.\n- As research accumulates, require a stronger reason to request additional work. Finish when the findings adequately answer the brief. Do not repeat topics with minor rephrasing.`;\n\nconst researchSystemPrompt = ({\n date,\n mcp_prompt,\n max_search_queries,\n}: Readonly<{\n date: string;\n mcp_prompt: string;\n max_search_queries: number;\n}>): string =>\n `You are a research assistant conducting deep research on the user's input topic. Use the tools and search methods provided to research the user's input topic. For context, today's date is ${date}.\n\n<Task>\nYour job is to use tools and search methods to find information that can answer the question that a user asks.\nYou can use any of the tools provided to you to find resources that can help answer the research question. You can call these tools in series or in parallel, your research is conducted in a tool-calling loop.\n</Task>\n\n<Tool Calling Guidelines>\n- Make sure you review all of the tools you have available to you, match the tools to the user's request, and select the tool that is most likely to be the best fit.\n- In each iteration, select the BEST tool for the job, this may or may not be general websearch.\n- When selecting the next tool to call, make sure that you are calling tools with arguments that you have not already tried.\n- Tool calling is costly, so be sure to be very intentional about what you look up. Some of the tools may have implicit limitations. As you call tools, feel out what these limitations are, and adjust your tool calls accordingly.\n- You have a maximum of ${max_search_queries} web search queries available, so use them strategically and efficiently.\n- This could mean that you need to call a different tool or stop searching, e.g. it's okay to recognize that a tool has limitations and cannot do what you need it to.\n- Don't mention any tool limitations in your output, but adjust your tool calls accordingly.\n- ${mcp_prompt}\n<Tool Calling Guidelines>\n\n<Criteria for Finishing Research>\n- The user will give you a sense of how much effort you should put into the research. This does not translate ~directly~ to the number of tool calls you should make, but it does give you a sense of the depth of the research you should conduct.\n- Once you have enough evidence, stop searching and call eve__reply with your findings, including source URLs, citations, uncertainties, and conflicting evidence.\n- One case where you should stop is if your previous tool calls have stopped yielding useful information.\n</Criteria for Finishing Research>\n\n<Helpful Tips>\n1. If you haven't conducted any searches yet, start with broad searches to get necessary context and background information. Once you have some background, you can start to narrow down your searches to get more specific information.\n2. Different topics require different levels of research depth. If the question is broad, your research can be more shallow, and you may not need to iterate and call tools as many times.\n3. If the question is detailed, you may need to be more stingy about the depth of your findings, and you may need to iterate and call tools more times to get a fully detailed answer.\n</Helpful Tips>\n\n<Critical Reminders>\n- You MUST conduct research using web search or a different tool before finishing! You cannot finish without conducting research first!\n- The caller needs your findings, not just your search activity. Always finish by calling eve__reply with the collected evidence; a separate agent will compress it and write the user-facing report.\n</Critical Reminders>`;\n\nconst compressResearchSystemPrompt = ({\n date,\n}: Readonly<{ date: string }>): string =>\n `You are a research assistant that has conducted research on a topic by calling several tools and web searches. Your job is now to clean up the findings, but preserve all of the relevant statements and information that the researcher has gathered. For context, today's date is ${date}.\n\n<Task>\nYou need to clean up information gathered from tool calls and web searches in the existing messages.\nAll relevant information should be repeated and rewritten verbatim, but in a cleaner format.\nThe purpose of this step is just to remove any obviously irrelevant or duplicative information.\nFor example, if three sources all say \"X\", you could say \"These three sources all stated X\".\nOnly these fully comprehensive cleaned findings are going to be returned to the user, so it's crucial that you don't lose any information from the raw messages.\n</Task>\n\n<Guidelines>\n1. Your output findings should be fully comprehensive and include ALL of the information and sources that the researcher has gathered from tool calls and web searches. It is expected that you repeat key information verbatim.\n2. This report can be as long as necessary to return ALL of the information that the researcher has gathered.\n3. In your report, you should return inline citations for each source that the researcher found.\n4. You should include a \"Sources\" section at the end of the report that lists all of the sources the researcher found with corresponding citations, cited against statements in the report.\n5. Make sure to include ALL of the sources that the researcher gathered in the report, and how they were used to answer the question!\n6. It's really important not to lose any sources. A later LLM will be used to merge this report with others, so having all of the sources is critical.\n</Guidelines>\n\n<Output Format>\nThe report should be structured like this:\n**List of Queries and Tool Calls Made**\n**Fully Comprehensive Findings**\n**List of All Relevant Sources (with citations in the report)**\n</Output Format>\n\n<Citation Rules>\n- Assign each unique URL a single citation number in your text\n- End with ### Sources that lists each source with corresponding numbers\n- IMPORTANT: Number sources sequentially without gaps (1,2,3,4...) in the final list regardless of which sources you choose\n- Example format:\n [1] Source Title: URL\n [2] Source Title: URL\n</Citation Rules>\n\nCritical Reminder: It is extremely important that any information that is even remotely relevant to the user's research topic is preserved verbatim (e.g. don't rewrite it, don't summarize it, don't paraphrase it).`;\n\nconst compressResearchSimpleHumanMessage = `All above messages are about research conducted by an AI Researcher. Please clean up these findings.\n\nDO NOT summarize the information. I want the raw information returned, just in a cleaner format. Make sure all relevant information is preserved - you can rewrite findings verbatim.`;\n\nconst FINAL_REPORT_INSTRUCTIONS = `\n\nPlease create a detailed answer to the overall research brief that:\n1. Is well-organized with proper headings (# for title, ## for sections, ### for subsections)\n2. Includes specific facts and insights from the research\n3. References relevant sources using [Title](URL) format\n4. Provides a balanced, thorough analysis. Be as comprehensive as possible, and include all information that is relevant to the overall research question. People are using you for deep research and will expect detailed, comprehensive answers.\n5. Includes a \"Sources\" section at the end with all referenced links\n\nYou can structure your report in a number of different ways. Here are some examples:\n\nTo answer a question that asks you to compare two things, you might structure your report like this:\n1/ intro\n2/ overview of topic A\n3/ overview of topic B\n4/ comparison between A and B\n5/ conclusion\n\nTo answer a question that asks you to return a list of things, you might only need a single section which is the entire list.\n1/ list of things or table of things\nOr, you could choose to make each item in the list a separate section in the report. When asked for lists, you don't need an introduction or conclusion.\n1/ item 1\n2/ item 2\n3/ item 3\n\nTo answer a question that asks you to summarize a topic, give a report, or give an overview, you might structure your report like this:\n1/ overview of topic\n2/ concept 1\n3/ concept 2\n4/ concept 3\n5/ conclusion\n\nIf you think you can answer the question with a single section, you can do that too!\n1/ answer\n\nREMEMBER: Section is a VERY fluid and loose concept. You can structure your report however you think is best, including in ways that are not listed above!\nMake sure that your sections are cohesive, and make sense for the reader.\n\nFor each section of the report, do the following:\n- Use simple, clear language\n- Use ## for section title (Markdown format) for each section of the report\n- Do NOT ever refer to yourself as the writer of the report. This should be a professional report without any self-referential language.\n- Do not say what you are doing in the report. Just write the report without any commentary from yourself.\n\nFormat the report in clear markdown with proper structure and include source references where appropriate.\n\n<Citation Rules>\n- Assign each unique URL a single citation number in your text\n- End with ### Sources that lists each source with corresponding numbers\n- IMPORTANT: Number sources sequentially without gaps (1,2,3,4...) in the final list regardless of which sources you choose\n- Each source should be a separate line item in a list, so that in markdown it is rendered as a list.\n- Example format:\n [1] Source Title: URL\n [2] Source Title: URL\n- Citations are extremely important. Make sure to include these, and pay a lot of attention to getting these right. Users will often use these citations to look into more information.\n</Citation Rules>`;\n\nconst finalReportGenerationPrompt = ({\n research_brief,\n date,\n findings,\n}: Readonly<{\n research_brief: string;\n date: string;\n findings: string;\n}>): string =>\n `Based on all the research conducted, create a comprehensive, well-structured answer to the overall research brief:\n<Research Brief>\n${research_brief}\n</Research Brief>\n\nToday's date is ${date}.\n\nHere are the findings from the research that you conducted:\n<Findings>\n${findings}\n</Findings>${FINAL_REPORT_INSTRUCTIONS}`;\nexport {\n clarifyWithUserInstructions,\n compressResearchSimpleHumanMessage,\n compressResearchSystemPrompt,\n finalReportGenerationPrompt,\n leadResearcherPrompt,\n researchSystemPrompt,\n transformMessagesIntoResearchTopicPrompt,\n};\n",
24
+ "type": "registry:file",
25
+ "target": "~/agent/lib/research/prompts.ts"
26
+ },
27
+ {
28
+ "path": "src/tools/deep-research/agent/lib/research/schemas.ts",
29
+ "content": "import { z } from \"zod\";\n\nconst MINIMUM_RESEARCH_TEXT_LENGTH = 1;\n\nconst researchOutput = z.union([\n z.object({ format: z.literal(\"progress\") }),\n z.object({ answer: z.string(), format: z.literal(\"clarifying_questions\") }),\n z.object({\n format: z.literal(\"report\"),\n path: z.string(),\n title: z.string(),\n }),\n]);\n\nconst researchInput = z.object({\n request: z\n .string()\n .min(1)\n .describe(\n \"The full research task, relevant conversation context, scope, and any input sandbox file paths.\"\n ),\n});\n\nconst researchClarification = z.object({\n need_clarification: z.boolean(),\n question: z.string(),\n verification: z.string(),\n});\n\nconst researchBrief = z.object({\n research_brief: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n title: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n});\n\nconst researchDecision = z.object({\n complete: z.boolean(),\n topics: z.array(z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH)),\n});\n\nconst researchFindings = z.object({\n findings: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n});\n\nconst researchReport = z.object({\n content: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n title: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n});\nexport {\n researchBrief,\n researchClarification,\n researchDecision,\n researchFindings,\n researchInput,\n researchOutput,\n researchReport,\n};\n\nexport interface ResearchUpdate {\n type: \"started\" | \"writing\" | \"thoughts\" | \"completed\";\n title: string;\n toolCallId: string;\n timestamp?: number;\n message?: string;\n status?: \"running\" | \"completed\";\n}\n\n// Optional presentation metadata; plain JSON that any EVE channel can consume.\nexport const researchResult = (\n output: z.input<typeof researchOutput>,\n updates: readonly ResearchUpdate[] = []\n) => ({\n kind: \"chatjs.tool-result\" as const,\n version: 1 as const,\n status: \"success\" as const,\n output: researchOutput.parse(output),\n updates: updates.map((update) => ({ ...update })),\n usage: { costUsd: 0 },\n});\n",
30
+ "type": "registry:file",
31
+ "target": "~/agent/lib/research/schemas.ts"
32
+ },
33
+ {
34
+ "path": "src/tools/deep-research/agent/lib/research/steps.ts",
35
+ "content": "import { researchOptions } from \"./configuration\";\n\n// oxlint-disable-next-line eslint/func-style, eslint/require-await -- EVE requires async step declarations. Record the clock and authored options once for workflow replay.\nexport async function prepareResearch(request: string) {\n \"use step\";\n return {\n config: researchOptions,\n date: new Date().toLocaleDateString(\"en-US\", {\n day: \"numeric\",\n month: \"short\",\n weekday: \"short\",\n year: \"numeric\",\n }),\n messages: request,\n timestamp: Date.now(),\n };\n}\n\n// oxlint-disable-next-line eslint/func-style, eslint/require-await -- EVE requires async step declarations. Completion time is a durable workflow step.\nexport async function researchCompletedAt() {\n \"use step\";\n return Date.now();\n}\n",
36
+ "type": "registry:file",
37
+ "target": "~/agent/lib/research/steps.ts"
38
+ },
39
+ {
40
+ "path": "src/tools/deep-research/agent/lib/research/workspace.ts",
41
+ "content": "import type { WorkflowStepToolContext } from \"eve/tools\";\nimport type { SandboxSession } from \"eve/sandbox\";\n\ntype Context = Readonly<\n Pick<WorkflowStepToolContext, \"callId\" | \"abortSignal\"> & {\n getSandbox: () => PromiseLike<\n Pick<SandboxSession, \"resolvePath\" | \"readTextFile\" | \"writeTextFile\">\n >;\n }\n>;\n\n// Per-call paths keep follow-up research from overwriting an earlier report.\nconst researchPath = (callId: string, name: string): string => {\n if (!/^[a-z0-9-]+\\.md$/u.test(name)) {\n throw new Error(\"Invalid research workspace filename.\");\n }\n return `research/run-${encodeURIComponent(callId)}/${name}`;\n};\n\n// oxlint-disable-next-line eslint/func-style -- EVE durable steps require function declarations. Whole-file writes are safe to retry.\nexport async function writeResearchFile(\n context: Context,\n name: string,\n content: string\n): Promise<string> {\n \"use step\";\n context.abortSignal.throwIfAborted();\n const sandbox = await context.getSandbox();\n const path = sandbox.resolvePath(researchPath(context.callId, name));\n await sandbox.writeTextFile({ path, content, signal: context.abortSignal });\n return path;\n}\n\n// oxlint-disable-next-line eslint/func-style -- Read the current workspace in a durable step, not during workflow replay.\nexport async function readResearchFiles(\n context: Context,\n names: readonly string[]\n): Promise<string[]> {\n \"use step\";\n context.abortSignal.throwIfAborted();\n const sandbox = await context.getSandbox();\n return await Promise.all(\n names.map(async (name) => {\n const path = sandbox.resolvePath(researchPath(context.callId, name));\n const content = await sandbox.readTextFile({\n path,\n signal: context.abortSignal,\n });\n if (content === null) {\n throw new Error(\n `Research workspace file is no longer available: ${path}`\n );\n }\n return content;\n })\n );\n}\n",
42
+ "type": "registry:file",
43
+ "target": "~/agent/lib/research/workspace.ts"
44
+ }
45
+ ],
46
+ "type": "registry:item"
47
+ }
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "chatjs",
3
+ "homepage": "https://chatjs.dev",
4
+ "items": [
5
+ {
6
+ "name": "deep-research",
7
+ "description": "Research with installed EVE capabilities; produces a sandbox report. ChatJS adds optional progress UI.",
8
+ "dependencies": [
9
+ "eve@npm:@chat-js/eve@1.0.0-rc.6-chatjs.1",
10
+ "zod@4.5.4"
11
+ ],
12
+ "files": [
13
+ {
14
+ "path": "src/tools/deep-research/agent/tools/deep-research.ts",
15
+ "content": "// ChatJS source: deep-research. Ownership: chatjs/tools/deep-research/chatjs.json.\nimport { defineWorkflowTool, toolOutput } from \"eve/tools\";\nimport {\n clarifyWithUserInstructions,\n compressResearchSimpleHumanMessage,\n compressResearchSystemPrompt,\n finalReportGenerationPrompt,\n leadResearcherPrompt,\n researchSystemPrompt,\n transformMessagesIntoResearchTopicPrompt,\n} from \"../lib/research/prompts\";\nimport { prepareResearch, researchCompletedAt } from \"../lib/research/steps\";\nimport {\n researchBrief,\n researchInput,\n researchClarification,\n researchDecision,\n researchFindings,\n researchReport,\n researchResult,\n} from \"../lib/research/schemas\";\nimport type { ResearchUpdate } from \"../lib/research/schemas\";\nimport type { AgentSession, WorkflowToolContext } from \"eve/tools\";\nimport { z } from \"zod\";\n\nimport {\n readResearchFiles,\n writeResearchFile,\n} from \"../lib/research/workspace\";\n\ntype ResearchResult = ReturnType<typeof researchResult>;\n\ntype ResearchWorkflowContext = Readonly<\n Omit<WorkflowToolContext, \"abortSignal\"> & {\n abortSignal: Readonly<AbortSignal>;\n }\n>;\n\nconst structuredMessage = (message: string): string =>\n `${message}\\n\\nDeliver the requested fields through the eve__reply tool. Put any Markdown inside its string fields; do not return prose or JSON text instead of calling the tool.`;\n\nconst outputSchema = (schema: z.ZodType): Record<string, z.JSONType> =>\n z.record(z.string(), z.json()).parse(z.toJSONSchema(schema));\n\nconst researchReply = async (\n agent: Readonly<AgentSession>,\n options: Readonly<{\n message: string;\n outputSchema: Record<string, z.JSONType>;\n signal: AbortSignal;\n }>\n): Promise<unknown> => {\n options.signal.throwIfAborted();\n const response = await agent.send(options.message, {\n outputSchema: options.outputSchema,\n signal: options.signal,\n });\n const result = await response.result();\n options.signal.throwIfAborted();\n if (result.status === \"failed\") {\n throw new Error(result.error?.message ?? \"Research agent failed\");\n }\n if (result.data === undefined) {\n throw new Error(\"Research agent ended without structured output\");\n }\n return result.data;\n};\n\nconst INITIAL_RESEARCH_ROUND = 0;\nconst RESEARCH_ROUND_INCREMENT = 1;\nconst BRIEF_UPDATE_INDEX = 1;\nconst EMPTY_TOPIC_COUNT = 0;\n\nexport default defineWorkflowTool({\n availableInSubagents: false,\n description:\n \"Conduct deep research using installed EVE capabilities and sandbox files. Supply the full task and relevant conversation context in request. Use only for explicit deep research requests, once per turn. Returns a Markdown report path in the shared sandbox. After completion, deliver the file using attach_workspace_file when installed or your channel's native file delivery. If no delivery mechanism exists, explain where the file is and do not invent a download URL. If clarification is needed, ask the returned questions. If research fails, report the error instead of starting duplicate research.\",\n async *execute(\n input: Readonly<z.infer<typeof researchInput>>,\n context: ResearchWorkflowContext\n ): AsyncGenerator<ResearchResult, void> {\n \"use workflow\";\n const { config, date, messages, timestamp } = await prepareResearch(\n input.request\n );\n const updates: ResearchUpdate[] = [];\n const progress = (): ResearchResult =>\n researchResult({ format: \"progress\" }, updates);\n if (config.allow_clarification) {\n const clarification = researchClarification.parse(\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n clarifyWithUserInstructions({ date, messages })\n ),\n outputSchema: outputSchema(researchClarification),\n })\n );\n if (clarification.need_clarification) {\n yield researchResult({\n answer: clarification.question,\n format: \"clarifying_questions\",\n });\n return;\n }\n }\n updates.push(\n {\n timestamp,\n title: \"Starting research\",\n toolCallId: context.callId,\n type: \"started\",\n },\n {\n status: \"running\",\n title: \"Writing research brief\",\n toolCallId: context.callId,\n type: \"writing\",\n }\n );\n yield progress();\n const brief = researchBrief.parse(\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n transformMessagesIntoResearchTopicPrompt({ date, messages })\n ),\n outputSchema: outputSchema(researchBrief),\n })\n );\n await writeResearchFile(context, \"brief.md\", brief.research_brief);\n updates[BRIEF_UPDATE_INDEX] = {\n message: brief.research_brief,\n status: \"completed\",\n title: \"Writing research brief\",\n toolCallId: context.callId,\n type: \"writing\",\n };\n yield progress();\n\n const noteFiles: string[] = [];\n const decisionSchema = researchDecision.extend({\n topics: researchDecision.shape.topics.max(\n config.max_concurrent_research_units\n ),\n });\n // Preserve the SDK's max_researcher_iterations + 1 decision steps, including\n // its allowance for research on the final step if the supervisor has not finished.\n for (\n let round = INITIAL_RESEARCH_ROUND;\n round <= config.max_researcher_iterations;\n round += RESEARCH_ROUND_INCREMENT\n ) {\n context.abortSignal.throwIfAborted();\n // oxlint-disable-next-line no-await-in-loop -- Each decision reads the notes completed by preceding research rounds.\n const findings = await readResearchFiles(context, [\n \"brief.md\",\n ...noteFiles,\n ]);\n const decision = decisionSchema.parse(\n // oxlint-disable-next-line no-await-in-loop -- Each decision consumes the findings added by the preceding round.\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n `${leadResearcherPrompt({ date, max_concurrent_research_units: config.max_concurrent_research_units })}\\n\\nResearch brief: ${findings[0]}\\n\\nFindings so far:\\n${findings.slice(1).join(\"\\n\\n\")}\\n\\nDecision round ${round + RESEARCH_ROUND_INCREMENT} of ${config.max_researcher_iterations + RESEARCH_ROUND_INCREMENT}. Return your next decision.`\n ),\n outputSchema: outputSchema(decisionSchema),\n })\n );\n if (decision.complete) {\n break;\n }\n if (decision.topics.length === EMPTY_TOPIC_COUNT) {\n throw new Error(\n \"The research supervisor must select topics or finish.\"\n );\n }\n for (const topic of decision.topics) {\n context.abortSignal.throwIfAborted();\n const updateIndex = updates.length;\n updates.push({\n message: topic,\n status: \"running\",\n title: \"Researching topic\",\n toolCallId: context.callId,\n type: \"thoughts\",\n });\n yield progress();\n const raw = researchFindings.parse(\n // oxlint-disable-next-line no-await-in-loop -- Complete the topic before moving to the next research stage.\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n `${researchSystemPrompt({ date, max_search_queries: config.search_api_max_queries, mcp_prompt: \"Use eve__search to discover installed search/retrieval connections and eve__tool to call them. Use native read_file or bash for relevant sandbox files. Do not call deepResearch recursively. If current external evidence is needed but no search capability is installed, say so explicitly; never fabricate sources.\" })}\\n\\nResearch brief:\\n${findings[0]}\\n\\nTopic:\\n${topic}\\n\\nReturn comprehensive raw findings with source URLs, citations, uncertainties, and conflicting evidence.`\n ),\n outputSchema: outputSchema(researchFindings),\n })\n );\n const topicNumber = noteFiles.length + 1;\n const sourceFile = `topic-${topicNumber}-sources.md`;\n // oxlint-disable-next-line no-await-in-loop -- Preserve cited source findings before compression.\n await writeResearchFile(\n context,\n sourceFile,\n `# ${topic}\\n\\n${raw.findings}`\n );\n // oxlint-disable-next-line no-await-in-loop -- Compression consumes the saved source file.\n const [sources] = await readResearchFiles(context, [sourceFile]);\n const compressed = researchFindings.parse(\n // oxlint-disable-next-line no-await-in-loop -- Commit this topic's compressed notes before the next topic and supervisor decision.\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n `${compressResearchSystemPrompt({ date })}\\n\\n${sources}\\n\\n${compressResearchSimpleHumanMessage}`\n ),\n outputSchema: outputSchema(researchFindings),\n })\n );\n const noteFile = `topic-${topicNumber}-notes.md`;\n // oxlint-disable-next-line no-await-in-loop -- Commit notes before advancing the supervisor.\n await writeResearchFile(\n context,\n noteFile,\n `# ${topic}\\n\\n${compressed.findings}`\n );\n noteFiles.push(noteFile);\n updates[updateIndex] = {\n message: topic,\n status: \"completed\",\n title: \"Research topic completed\",\n toolCallId: context.callId,\n type: \"thoughts\",\n };\n yield progress();\n }\n }\n const reportUpdateIndex = updates.length;\n updates.push({\n status: \"running\",\n title: \"Writing final report\",\n toolCallId: context.callId,\n type: \"writing\",\n });\n yield progress();\n const [savedBrief, ...savedNotes] = await readResearchFiles(context, [\n \"brief.md\",\n ...noteFiles,\n ]);\n const report = researchReport.parse(\n await researchReply(context.agent(\"agent\"), {\n signal: context.abortSignal,\n message: structuredMessage(\n `${finalReportGenerationPrompt({ date, findings: savedNotes.join(\"\\n\"), research_brief: savedBrief })}\\n\\nWrite the complete Markdown report with title ${JSON.stringify(brief.title)}. Return title and content; the workflow will publish the report as a Markdown file.`\n ),\n outputSchema: outputSchema(researchReport),\n })\n );\n context.abortSignal.throwIfAborted();\n const reportPath = await writeResearchFile(\n context,\n \"report.md\",\n report.content\n );\n const completedAt = await researchCompletedAt();\n updates[reportUpdateIndex] = {\n status: \"completed\",\n title: \"Writing final report\",\n toolCallId: context.callId,\n type: \"writing\",\n };\n updates.push({\n timestamp: completedAt,\n title: \"Research complete\",\n toolCallId: context.callId,\n type: \"completed\",\n });\n yield researchResult(\n { path: reportPath, title: report.title, format: \"report\" },\n updates\n );\n },\n inputSchema: researchInput,\n toModelOutput: (result) => toolOutput.json(result.output),\n});\n",
16
+ "type": "registry:file",
17
+ "target": "~/agent/tools/deepResearch.ts"
18
+ },
19
+ {
20
+ "path": "src/tools/deep-research/agent/lib/research/configuration.ts",
21
+ "content": "/** Workflow-specific bounds. Model, reasoning, approvals, connections, and sandbox belong to agent/agent.ts and native EVE files. */\nexport const researchOptions = {\n allow_clarification: true,\n max_concurrent_research_units: 2,\n max_researcher_iterations: 1,\n search_api_max_queries: 2,\n};\n",
22
+ "type": "registry:file",
23
+ "target": "~/agent/lib/research/configuration.ts"
24
+ },
25
+ {
26
+ "path": "src/tools/deep-research/agent/lib/research/prompts.ts",
27
+ "content": "const clarifyWithUserInstructions = ({\n messages,\n date,\n}: Readonly<{\n messages: string;\n date: string;\n}>): string =>\n `These are the messages that have been exchanged so far from the user asking for the report:\n<Messages>\n${messages}\n</Messages>\n\nToday's date is ${date}.\n\nAssess whether you need to ask a clarifying question, or if the user has already provided enough information for you to start research.\nIMPORTANT: If you can see in the messages history that you have already asked a clarifying question, you almost always do not need to ask another one. Only ask another question if ABSOLUTELY NECESSARY.\n\nIf there are acronyms, abbreviations, or unknown terms, ask the user to clarify.\nIf you need to ask a question, follow these guidelines:\n- Be concise while gathering all necessary information\n- Make sure to gather all the information needed to carry out the research task in a concise, well-structured manner.\n- Use bullet points or numbered lists if appropriate for clarity. Make sure that this uses markdown formatting and will be rendered correctly if the string output is passed to a markdown renderer.\n- Don't ask for unnecessary information, or information that the user has already provided. If you can see that the user has already provided the information, do not ask for it again.\n\nRespond in valid JSON format with these exact keys:\n\"need_clarification\": boolean,\n\"question\": \"<question to ask the user to clarify the report scope>\",\n\"verification\": \"<verification message that we will start research>\"\n\nIf you need to ask a clarifying question, return:\n\"need_clarification\": true,\n\"question\": \"<your clarifying question>\",\n\"verification\": \"\"\n\nIf you do not need to ask a clarifying question, return:\n\"need_clarification\": false,\n\"question\": \"\",\n\"verification\": \"<acknowledgement message that you will now start research based on the provided information>\"\n\nFor the verification message when no clarification is needed:\n- Acknowledge that you have sufficient information to proceed\n- Briefly summarize the key aspects of what you understand from their request\n- Confirm that you will now begin the research process\n- Keep the message concise and professional`;\n\nconst transformMessagesIntoResearchTopicPrompt = ({\n messages,\n date,\n}: Readonly<{\n messages: string;\n date: string;\n}>): string =>\n `You will be given a set of messages that have been exchanged so far between yourself and the user.\nYour job is to translate these messages into a more detailed and concrete research question that will be used to guide the research.\n\nThe messages that have been exchanged so far between yourself and the user are:\n<Messages>\n${messages}\n</Messages>\n\nToday's date is ${date}.\n\nYou will return a single research question that will be used to guide the research.\n\nGuidelines:\n1. Maximize Specificity and Detail\n- Include all known user preferences and explicitly list key attributes or dimensions to consider.\n- It is important that all details from the user are included in the instructions.\n\n2. Fill in Unstated But Necessary Dimensions as Open-Ended\n- If certain attributes are essential for a meaningful output but the user has not provided them, explicitly state that they are open-ended or default to no specific constraint.\n\n3. Avoid Unwarranted Assumptions\n- If the user has not provided a particular detail, do not invent one.\n- Instead, state the lack of specification and guide the researcher to treat it as flexible or accept all possible options.\n\n4. Use the First Person\n- Phrase the request from the perspective of the user.\n\n5. Sources\n- If specific sources should be prioritized, specify them in the research question.\n- For product and travel research, prefer linking directly to official or primary websites (e.g., official brand sites, manufacturer pages, or reputable e-commerce platforms like Amazon for user reviews) rather than aggregator sites or SEO-heavy blogs.\n- For academic or scientific queries, prefer linking directly to the original paper or official journal publication rather than survey papers or secondary summaries.\n- For people, try linking directly to their LinkedIn profile, or their personal website if they have one.\n- If the query is in a specific language, prioritize sources published in that language.`;\n\nconst leadResearcherPrompt = ({\n date,\n max_concurrent_research_units,\n}: Readonly<{\n date: string;\n max_concurrent_research_units: number;\n}>): string =>\n `You are a research supervisor. Today's date is ${date}.\nYou receive a research brief and findings from all completed topics. Decide whether the evidence is sufficient for a comprehensive report or identify specific gaps requiring follow-up research.\n\nReturn JSON with complete (boolean) and topics (array of strings).\n- To research, set complete to false and provide up to ${max_concurrent_research_units} detailed, self-contained topics. The workflow will run them sequentially and return their findings before your next decision.\n- To finish, set complete to true and topics to []. A separate writer synthesizes the report.\n- Start by researching the brief. On later rounds, request only net new information that is necessary to answer it. Do not ask researchers to synthesize existing findings.\n- Each topic must include all necessary context, explain acronyms, and state the desired depth of effort. Researchers do not see your other topics or findings.\n- Split independent questions when that improves coverage. Resolve dependencies first. More topics increase cost; prefer fewer comprehensive investigations over redundant subtopics.\n- Judge evidence coverage and reliability, not formatting. Findings may be raw or messy.\n- Match depth to the user's request. Detailed or comprehensive requests warrant more follow-up than broad overviews.\n- As research accumulates, require a stronger reason to request additional work. Finish when the findings adequately answer the brief. Do not repeat topics with minor rephrasing.`;\n\nconst researchSystemPrompt = ({\n date,\n mcp_prompt,\n max_search_queries,\n}: Readonly<{\n date: string;\n mcp_prompt: string;\n max_search_queries: number;\n}>): string =>\n `You are a research assistant conducting deep research on the user's input topic. Use the tools and search methods provided to research the user's input topic. For context, today's date is ${date}.\n\n<Task>\nYour job is to use tools and search methods to find information that can answer the question that a user asks.\nYou can use any of the tools provided to you to find resources that can help answer the research question. You can call these tools in series or in parallel, your research is conducted in a tool-calling loop.\n</Task>\n\n<Tool Calling Guidelines>\n- Make sure you review all of the tools you have available to you, match the tools to the user's request, and select the tool that is most likely to be the best fit.\n- In each iteration, select the BEST tool for the job, this may or may not be general websearch.\n- When selecting the next tool to call, make sure that you are calling tools with arguments that you have not already tried.\n- Tool calling is costly, so be sure to be very intentional about what you look up. Some of the tools may have implicit limitations. As you call tools, feel out what these limitations are, and adjust your tool calls accordingly.\n- You have a maximum of ${max_search_queries} web search queries available, so use them strategically and efficiently.\n- This could mean that you need to call a different tool or stop searching, e.g. it's okay to recognize that a tool has limitations and cannot do what you need it to.\n- Don't mention any tool limitations in your output, but adjust your tool calls accordingly.\n- ${mcp_prompt}\n<Tool Calling Guidelines>\n\n<Criteria for Finishing Research>\n- The user will give you a sense of how much effort you should put into the research. This does not translate ~directly~ to the number of tool calls you should make, but it does give you a sense of the depth of the research you should conduct.\n- Once you have enough evidence, stop searching and call eve__reply with your findings, including source URLs, citations, uncertainties, and conflicting evidence.\n- One case where you should stop is if your previous tool calls have stopped yielding useful information.\n</Criteria for Finishing Research>\n\n<Helpful Tips>\n1. If you haven't conducted any searches yet, start with broad searches to get necessary context and background information. Once you have some background, you can start to narrow down your searches to get more specific information.\n2. Different topics require different levels of research depth. If the question is broad, your research can be more shallow, and you may not need to iterate and call tools as many times.\n3. If the question is detailed, you may need to be more stingy about the depth of your findings, and you may need to iterate and call tools more times to get a fully detailed answer.\n</Helpful Tips>\n\n<Critical Reminders>\n- You MUST conduct research using web search or a different tool before finishing! You cannot finish without conducting research first!\n- The caller needs your findings, not just your search activity. Always finish by calling eve__reply with the collected evidence; a separate agent will compress it and write the user-facing report.\n</Critical Reminders>`;\n\nconst compressResearchSystemPrompt = ({\n date,\n}: Readonly<{ date: string }>): string =>\n `You are a research assistant that has conducted research on a topic by calling several tools and web searches. Your job is now to clean up the findings, but preserve all of the relevant statements and information that the researcher has gathered. For context, today's date is ${date}.\n\n<Task>\nYou need to clean up information gathered from tool calls and web searches in the existing messages.\nAll relevant information should be repeated and rewritten verbatim, but in a cleaner format.\nThe purpose of this step is just to remove any obviously irrelevant or duplicative information.\nFor example, if three sources all say \"X\", you could say \"These three sources all stated X\".\nOnly these fully comprehensive cleaned findings are going to be returned to the user, so it's crucial that you don't lose any information from the raw messages.\n</Task>\n\n<Guidelines>\n1. Your output findings should be fully comprehensive and include ALL of the information and sources that the researcher has gathered from tool calls and web searches. It is expected that you repeat key information verbatim.\n2. This report can be as long as necessary to return ALL of the information that the researcher has gathered.\n3. In your report, you should return inline citations for each source that the researcher found.\n4. You should include a \"Sources\" section at the end of the report that lists all of the sources the researcher found with corresponding citations, cited against statements in the report.\n5. Make sure to include ALL of the sources that the researcher gathered in the report, and how they were used to answer the question!\n6. It's really important not to lose any sources. A later LLM will be used to merge this report with others, so having all of the sources is critical.\n</Guidelines>\n\n<Output Format>\nThe report should be structured like this:\n**List of Queries and Tool Calls Made**\n**Fully Comprehensive Findings**\n**List of All Relevant Sources (with citations in the report)**\n</Output Format>\n\n<Citation Rules>\n- Assign each unique URL a single citation number in your text\n- End with ### Sources that lists each source with corresponding numbers\n- IMPORTANT: Number sources sequentially without gaps (1,2,3,4...) in the final list regardless of which sources you choose\n- Example format:\n [1] Source Title: URL\n [2] Source Title: URL\n</Citation Rules>\n\nCritical Reminder: It is extremely important that any information that is even remotely relevant to the user's research topic is preserved verbatim (e.g. don't rewrite it, don't summarize it, don't paraphrase it).`;\n\nconst compressResearchSimpleHumanMessage = `All above messages are about research conducted by an AI Researcher. Please clean up these findings.\n\nDO NOT summarize the information. I want the raw information returned, just in a cleaner format. Make sure all relevant information is preserved - you can rewrite findings verbatim.`;\n\nconst FINAL_REPORT_INSTRUCTIONS = `\n\nPlease create a detailed answer to the overall research brief that:\n1. Is well-organized with proper headings (# for title, ## for sections, ### for subsections)\n2. Includes specific facts and insights from the research\n3. References relevant sources using [Title](URL) format\n4. Provides a balanced, thorough analysis. Be as comprehensive as possible, and include all information that is relevant to the overall research question. People are using you for deep research and will expect detailed, comprehensive answers.\n5. Includes a \"Sources\" section at the end with all referenced links\n\nYou can structure your report in a number of different ways. Here are some examples:\n\nTo answer a question that asks you to compare two things, you might structure your report like this:\n1/ intro\n2/ overview of topic A\n3/ overview of topic B\n4/ comparison between A and B\n5/ conclusion\n\nTo answer a question that asks you to return a list of things, you might only need a single section which is the entire list.\n1/ list of things or table of things\nOr, you could choose to make each item in the list a separate section in the report. When asked for lists, you don't need an introduction or conclusion.\n1/ item 1\n2/ item 2\n3/ item 3\n\nTo answer a question that asks you to summarize a topic, give a report, or give an overview, you might structure your report like this:\n1/ overview of topic\n2/ concept 1\n3/ concept 2\n4/ concept 3\n5/ conclusion\n\nIf you think you can answer the question with a single section, you can do that too!\n1/ answer\n\nREMEMBER: Section is a VERY fluid and loose concept. You can structure your report however you think is best, including in ways that are not listed above!\nMake sure that your sections are cohesive, and make sense for the reader.\n\nFor each section of the report, do the following:\n- Use simple, clear language\n- Use ## for section title (Markdown format) for each section of the report\n- Do NOT ever refer to yourself as the writer of the report. This should be a professional report without any self-referential language.\n- Do not say what you are doing in the report. Just write the report without any commentary from yourself.\n\nFormat the report in clear markdown with proper structure and include source references where appropriate.\n\n<Citation Rules>\n- Assign each unique URL a single citation number in your text\n- End with ### Sources that lists each source with corresponding numbers\n- IMPORTANT: Number sources sequentially without gaps (1,2,3,4...) in the final list regardless of which sources you choose\n- Each source should be a separate line item in a list, so that in markdown it is rendered as a list.\n- Example format:\n [1] Source Title: URL\n [2] Source Title: URL\n- Citations are extremely important. Make sure to include these, and pay a lot of attention to getting these right. Users will often use these citations to look into more information.\n</Citation Rules>`;\n\nconst finalReportGenerationPrompt = ({\n research_brief,\n date,\n findings,\n}: Readonly<{\n research_brief: string;\n date: string;\n findings: string;\n}>): string =>\n `Based on all the research conducted, create a comprehensive, well-structured answer to the overall research brief:\n<Research Brief>\n${research_brief}\n</Research Brief>\n\nToday's date is ${date}.\n\nHere are the findings from the research that you conducted:\n<Findings>\n${findings}\n</Findings>${FINAL_REPORT_INSTRUCTIONS}`;\nexport {\n clarifyWithUserInstructions,\n compressResearchSimpleHumanMessage,\n compressResearchSystemPrompt,\n finalReportGenerationPrompt,\n leadResearcherPrompt,\n researchSystemPrompt,\n transformMessagesIntoResearchTopicPrompt,\n};\n",
28
+ "type": "registry:file",
29
+ "target": "~/agent/lib/research/prompts.ts"
30
+ },
31
+ {
32
+ "path": "src/tools/deep-research/agent/lib/research/schemas.ts",
33
+ "content": "import { z } from \"zod\";\n\nconst MINIMUM_RESEARCH_TEXT_LENGTH = 1;\n\nconst researchOutput = z.union([\n z.object({ format: z.literal(\"progress\") }),\n z.object({ answer: z.string(), format: z.literal(\"clarifying_questions\") }),\n z.object({\n format: z.literal(\"report\"),\n path: z.string(),\n title: z.string(),\n }),\n]);\n\nconst researchInput = z.object({\n request: z\n .string()\n .min(1)\n .describe(\n \"The full research task, relevant conversation context, scope, and any input sandbox file paths.\"\n ),\n});\n\nconst researchClarification = z.object({\n need_clarification: z.boolean(),\n question: z.string(),\n verification: z.string(),\n});\n\nconst researchBrief = z.object({\n research_brief: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n title: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n});\n\nconst researchDecision = z.object({\n complete: z.boolean(),\n topics: z.array(z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH)),\n});\n\nconst researchFindings = z.object({\n findings: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n});\n\nconst researchReport = z.object({\n content: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n title: z.string().min(MINIMUM_RESEARCH_TEXT_LENGTH),\n});\nexport {\n researchBrief,\n researchClarification,\n researchDecision,\n researchFindings,\n researchInput,\n researchOutput,\n researchReport,\n};\n\nexport interface ResearchUpdate {\n type: \"started\" | \"writing\" | \"thoughts\" | \"completed\";\n title: string;\n toolCallId: string;\n timestamp?: number;\n message?: string;\n status?: \"running\" | \"completed\";\n}\n\n// Optional presentation metadata; plain JSON that any EVE channel can consume.\nexport const researchResult = (\n output: z.input<typeof researchOutput>,\n updates: readonly ResearchUpdate[] = []\n) => ({\n kind: \"chatjs.tool-result\" as const,\n version: 1 as const,\n status: \"success\" as const,\n output: researchOutput.parse(output),\n updates: updates.map((update) => ({ ...update })),\n usage: { costUsd: 0 },\n});\n",
34
+ "type": "registry:file",
35
+ "target": "~/agent/lib/research/schemas.ts"
36
+ },
37
+ {
38
+ "path": "src/tools/deep-research/agent/lib/research/steps.ts",
39
+ "content": "import { researchOptions } from \"./configuration\";\n\n// oxlint-disable-next-line eslint/func-style, eslint/require-await -- EVE requires async step declarations. Record the clock and authored options once for workflow replay.\nexport async function prepareResearch(request: string) {\n \"use step\";\n return {\n config: researchOptions,\n date: new Date().toLocaleDateString(\"en-US\", {\n day: \"numeric\",\n month: \"short\",\n weekday: \"short\",\n year: \"numeric\",\n }),\n messages: request,\n timestamp: Date.now(),\n };\n}\n\n// oxlint-disable-next-line eslint/func-style, eslint/require-await -- EVE requires async step declarations. Completion time is a durable workflow step.\nexport async function researchCompletedAt() {\n \"use step\";\n return Date.now();\n}\n",
40
+ "type": "registry:file",
41
+ "target": "~/agent/lib/research/steps.ts"
42
+ },
43
+ {
44
+ "path": "src/tools/deep-research/agent/lib/research/workspace.ts",
45
+ "content": "import type { WorkflowStepToolContext } from \"eve/tools\";\nimport type { SandboxSession } from \"eve/sandbox\";\n\ntype Context = Readonly<\n Pick<WorkflowStepToolContext, \"callId\" | \"abortSignal\"> & {\n getSandbox: () => PromiseLike<\n Pick<SandboxSession, \"resolvePath\" | \"readTextFile\" | \"writeTextFile\">\n >;\n }\n>;\n\n// Per-call paths keep follow-up research from overwriting an earlier report.\nconst researchPath = (callId: string, name: string): string => {\n if (!/^[a-z0-9-]+\\.md$/u.test(name)) {\n throw new Error(\"Invalid research workspace filename.\");\n }\n return `research/run-${encodeURIComponent(callId)}/${name}`;\n};\n\n// oxlint-disable-next-line eslint/func-style -- EVE durable steps require function declarations. Whole-file writes are safe to retry.\nexport async function writeResearchFile(\n context: Context,\n name: string,\n content: string\n): Promise<string> {\n \"use step\";\n context.abortSignal.throwIfAborted();\n const sandbox = await context.getSandbox();\n const path = sandbox.resolvePath(researchPath(context.callId, name));\n await sandbox.writeTextFile({ path, content, signal: context.abortSignal });\n return path;\n}\n\n// oxlint-disable-next-line eslint/func-style -- Read the current workspace in a durable step, not during workflow replay.\nexport async function readResearchFiles(\n context: Context,\n names: readonly string[]\n): Promise<string[]> {\n \"use step\";\n context.abortSignal.throwIfAborted();\n const sandbox = await context.getSandbox();\n return await Promise.all(\n names.map(async (name) => {\n const path = sandbox.resolvePath(researchPath(context.callId, name));\n const content = await sandbox.readTextFile({\n path,\n signal: context.abortSignal,\n });\n if (content === null) {\n throw new Error(\n `Research workspace file is no longer available: ${path}`\n );\n }\n return content;\n })\n );\n}\n",
46
+ "type": "registry:file",
47
+ "target": "~/agent/lib/research/workspace.ts"
48
+ }
49
+ ],
50
+ "type": "registry:item"
51
+ }
52
+ ]
53
+ }
@@ -22,7 +22,7 @@
22
22
  },
23
23
  {
24
24
  "path": "src/tools/generate-image/renderer.tsx",
25
- "content": "\"use client\";\nimport { ImageActions, ImageModal } from \"@/components/image-modal\";\nimport React, { useState } from \"react\";\nimport { generateImageInput, generateImageResult } from \"./schemas\";\nimport Image from \"next/image\";\nimport { ImageOffIcon } from \"lucide-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\";\nimport { useImageLoadError } from \"@/hooks/use-image-load-error\";\n\ntype GenerateImageTool = ToolRendererProps<\n typeof generateImageInput,\n typeof generateImageResult\n>[\"tool\"];\n\nconst GenerateImageView = ({\n tool,\n}: ReadonlyNativeSurface<{\n tool: GenerateImageTool;\n}>): React.JSX.Element | null => {\n const [dialogOpen, setDialogOpen] = useState(false);\n const imageUrl = tool.output?.imageUrl;\n const { handleImageError, imageUnavailable } = useImageLoadError(imageUrl);\n\n if (tool.state === \"input-streaming\" || tool.state === \"input-available\") {\n return (\n <div className=\"flex w-full flex-col items-center justify-center gap-4 rounded-lg border p-8\">\n <div className=\"bg-muted-foreground/20 h-64 w-full animate-pulse rounded-lg\" />\n <div className=\"text-muted-foreground\">\n Generating image: &quot;\n {tool.input?.prompt ?? \"Preparing prompt…\"}\n &quot;\n </div>\n </div>\n );\n }\n const { output } = tool;\n if (output === undefined) {\n return null;\n }\n\n return (\n <>\n <div className=\"flex w-full flex-col gap-4 overflow-hidden rounded-lg border\">\n <div className=\"group relative\">\n {imageUnavailable ? (\n <output className=\"bg-muted/30 text-muted-foreground flex min-h-64 w-full flex-col items-center justify-center gap-2\">\n <ImageOffIcon className=\"size-8\" />\n <span>Generated image unavailable</span>\n </output>\n ) : (\n <>\n <button\n className=\"w-full cursor-pointer text-left\"\n onClick={(): void => {\n setDialogOpen(true);\n }}\n type=\"button\"\n >\n <Image\n alt={output.prompt}\n loading=\"eager\"\n unoptimized\n className=\"h-auto w-full max-w-full\"\n height={512}\n onError={handleImageError}\n src={output.imageUrl}\n width={512}\n />\n </button>\n <ImageActions\n className=\"absolute top-2 right-2 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100\"\n imageUrl={output.imageUrl}\n />\n </>\n )}\n </div>\n <div className=\"p-4 pt-0\">\n <p className=\"text-muted-foreground text-sm\">\n Generated from: &quot;{output.prompt}&quot;\n </p>\n </div>\n </div>\n\n <ImageModal\n imageName={output.prompt}\n imageUrl={output.imageUrl}\n isOpen={dialogOpen}\n onClose={(): void => {\n setDialogOpen(false);\n }}\n />\n </>\n );\n};\n\nexport const GenerateImageRenderer = defineToolRenderer({\n inputSchema: generateImageInput,\n outputSchema: generateImageResult,\n render: GenerateImageView,\n});\n",
25
+ "content": "\"use client\";\nimport { ImageActions } from \"@/components/image-actions\";\nimport { ArtifactViewerActions } from \"@/components/artifact-actions\";\nimport React from \"react\";\nimport { generateImageInput, generateImageResult } from \"./schemas\";\nimport Image from \"next/image\";\nimport { ImageOffIcon } from \"lucide-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\";\nimport { useImageLoadError } from \"@/hooks/use-image-load-error\";\n\ntype GenerateImageTool = ToolRendererProps<\n typeof generateImageInput,\n typeof generateImageResult\n>[\"tool\"];\n\nconst GenerateImageView = ({\n tool,\n}: ReadonlyNativeSurface<{\n tool: GenerateImageTool;\n}>): React.JSX.Element | null => {\n const imageUrl = tool.output?.imageUrl;\n const { handleImageError, imageUnavailable } = useImageLoadError(imageUrl);\n\n if (tool.state === \"input-streaming\" || tool.state === \"input-available\") {\n return (\n <div className=\"flex w-full flex-col items-center justify-center gap-4 rounded-lg border p-8\">\n <div className=\"bg-muted-foreground/20 h-64 w-full animate-pulse rounded-lg\" />\n <div className=\"text-muted-foreground\">\n Generating image: &quot;\n {tool.input?.prompt ?? \"Preparing prompt…\"}\n &quot;\n </div>\n </div>\n );\n }\n const { output } = tool;\n if (output === undefined) {\n return null;\n }\n\n return (\n <div className=\"flex w-full flex-col gap-4 overflow-hidden rounded-lg border\">\n <div className=\"group relative\">\n {imageUnavailable ? (\n <output className=\"bg-muted/30 text-muted-foreground flex min-h-64 w-full flex-col items-center justify-center gap-2\">\n <ImageOffIcon className=\"size-8\" />\n <span>Generated image unavailable</span>\n </output>\n ) : (\n <>\n <Image\n alt={output.prompt}\n loading=\"eager\"\n unoptimized\n className=\"h-auto w-full max-w-full\"\n height={512}\n onError={handleImageError}\n src={output.imageUrl}\n width={512}\n />\n <div className=\"absolute top-2 right-2 flex items-center gap-1\">\n <ArtifactViewerActions\n artifact={{\n fileId: output.fileId,\n url: output.imageUrl,\n name: output.prompt,\n mediaType: \"image/*\",\n }}\n />\n <ImageActions imageUrl={output.imageUrl} />\n </div>\n </>\n )}\n </div>\n <div className=\"p-4 pt-0\">\n <p className=\"text-muted-foreground text-sm\">\n Generated from: &quot;{output.prompt}&quot;\n </p>\n </div>\n </div>\n );\n};\n\nexport const GenerateImageRenderer = defineToolRenderer({\n inputSchema: generateImageInput,\n outputSchema: generateImageResult,\n render: GenerateImageView,\n});\n",
26
26
  "type": "registry:file",
27
27
  "target": "~/chatjs/tools/generate-image/renderer.tsx"
28
28
  },
@@ -52,7 +52,7 @@
52
52
  },
53
53
  {
54
54
  "path": "src/tools/generate-image/image-generation.ts",
55
- "content": "import { generateImage, generateText } from \"ai\";\nimport type { FileUIPart } from \"ai\";\nimport type { FileUploader } from \"@/lib/file-storage\";\nimport type { ImageModelSelection } from \"./image-model\";\nimport type { ToolModelProvider } from \"@/lib/ai/tool-context\";\nimport type { createEveToolCost } from \"@/lib/eve/tool-cost\";\nimport { createModuleLogger } from \"@/lib/logger\";\nimport { collectEditImages } from \"./image-input\";\nimport type { generateImageResult } from \"./schemas\";\nimport type { z } from \"zod\";\n\nconst log = createModuleLogger(\"ai.tools.generate-image\");\nconst EMPTY_IMAGE_BYTES = 0;\nconst GENERATED_IMAGE_COUNT = 1;\nconst NO_GENERATED_IMAGES = 0;\ntype ReadonlyNativeSurface<Value> = Value extends\n | string\n | number\n | bigint\n | boolean\n | symbol\n | null\n | undefined\n ? Value\n : Value extends (...parameters: readonly never[]) => unknown\n ? Value\n : Value extends abstract new (...parameters: readonly never[]) => unknown\n ? Value\n : Value extends object\n ? {\n readonly [Property in keyof Value]: ReadonlyNativeSurface<\n Value[Property]\n >;\n }\n : Value;\ntype ImageStoreFile = (\n filename: string,\n body: ReadonlyNativeSurface<Buffer>,\n mediaType?: string\n) => ReturnType<FileUploader>;\ntype ImageMode = \"edit\" | \"generate\";\ninterface ImageGenerationOptions {\n readonly mode: ImageMode;\n readonly prompt: string;\n readonly imageParts: readonly Readonly<Pick<FileUIPart, \"url\">>[];\n readonly lastGeneratedImage: Readonly<{\n imageUrl: string;\n name: string;\n }> | null;\n readonly startMs: number;\n readonly costAccumulator?: Readonly<ReturnType<typeof createEveToolCost>>;\n readonly abortSignal?: Readonly<AbortSignal>;\n readonly storeFile: ImageStoreFile;\n readonly modelProvider: Readonly<ToolModelProvider>;\n}\ntype GeneratedImageResult = Required<z.infer<typeof generateImageResult>>;\nconst traditionalPrompt = async (\n options: Readonly<ImageGenerationOptions>\n): Promise<string | { text: string; images: Buffer[] }> => {\n if (options.mode !== \"edit\") {\n return options.prompt;\n }\n log.debug(\n {\n attachmentCount: options.imageParts.length,\n lastGeneratedCount: options.lastGeneratedImage\n ? GENERATED_IMAGE_COUNT\n : NO_GENERATED_IMAGES,\n note: \"OpenAI edit mode\",\n },\n \"generateImage: preparing edit images\"\n );\n return { images: await collectEditImages(options), text: options.prompt };\n};\nconst storeImage = async (\n options: Readonly<ImageGenerationOptions>,\n image: Readonly<{\n buffer: ReadonlyNativeSurface<Buffer>;\n filename: string;\n mediaType: string;\n }>,\n model: Readonly<{ modelId: string; multimodal: boolean }>\n): Promise<GeneratedImageResult> => {\n const result = await options.storeFile(\n image.filename,\n image.buffer,\n image.mediaType\n );\n log.info(\n {\n imageUrl: result.url,\n mode: options.mode,\n ms: Date.now() - options.startMs,\n uploadedFilename: image.filename,\n ...(model.multimodal ? { modelId: model.modelId } : {}),\n },\n model.multimodal\n ? \"generateImage: multimodal success\"\n : \"generateImage: success\"\n );\n return {\n fileId: result.fileId,\n imageUrl: result.url,\n prompt: options.prompt,\n };\n};\nconst runGenerateImageTraditional = async (\n options: Readonly<ImageGenerationOptions>,\n modelId: string\n): Promise<GeneratedImageResult> => {\n const prompt = await traditionalPrompt(options);\n const res = await generateImage({\n abortSignal: options.abortSignal,\n model: options.modelProvider.createImageModel(modelId),\n prompt,\n providerOptions: { telemetry: { isEnabled: true } },\n });\n const [firstImage] = res.images;\n log.debug(\n {\n base64Length: firstImage?.base64?.length ?? EMPTY_IMAGE_BYTES,\n mode: options.mode,\n },\n \"generateImage: provider response received\"\n );\n const buffer = Buffer.from(firstImage.base64, \"base64\");\n const filename = `generated-image-${Date.now()}.png`;\n // Provider usage remains billable if the subsequent storage upload fails.\n const { costAccumulator } = options;\n if (costAccumulator) {\n costAccumulator.addImageCost(\n modelId,\n res.images.length,\n res.usage ?? {},\n \"generateImage-traditional\"\n );\n }\n return await storeImage(\n options,\n { buffer, filename, mediaType: \"image/png\" },\n { modelId, multimodal: false }\n );\n};\ninterface ImageContent {\n image: Readonly<Buffer>;\n type: \"image\";\n}\ninterface TextContent {\n text: string;\n type: \"text\";\n}\nconst multimodalContent = async (\n options: Readonly<ImageGenerationOptions>\n): Promise<(ImageContent | TextContent)[]> => {\n const buffers =\n options.mode === \"edit\" ? await collectEditImages(options) : [];\n const images = buffers.map(\n (image: ReadonlyNativeSurface<Buffer>): ImageContent => ({\n image,\n type: \"image\",\n })\n );\n return [\n ...images,\n {\n text:\n options.mode === \"edit\"\n ? `Based on the provided image(s), ${options.prompt}`\n : `Generate an image: ${options.prompt}`,\n type: \"text\",\n },\n ];\n};\nconst storeMultimodalImage = async (\n options: Readonly<ImageGenerationOptions>,\n selection: Readonly<Extract<ImageModelSelection, { multimodal: true }>>,\n imageFile: ReadonlyNativeSurface<{\n mediaType: string;\n base64: string;\n uint8Array: Uint8Array;\n }>\n): Promise<GeneratedImageResult> => {\n log.debug(\n {\n hasBase64: Boolean(imageFile.base64),\n mediaType: imageFile.mediaType,\n mode: options.mode,\n },\n \"generateImage: multimodal response received\"\n );\n const buffer = Buffer.from(imageFile.uint8Array);\n const timestamp = Date.now();\n const [, subtype] = imageFile.mediaType.split(\"/\");\n const ext = typeof subtype === \"string\" && subtype !== \"\" ? subtype : \"png\";\n return await storeImage(\n options,\n {\n buffer,\n filename: `generated-image-${timestamp}.${ext}`,\n mediaType: imageFile.mediaType,\n },\n selection\n );\n};\nconst multimodalProviderOptions = (\n modelId: string\n): {\n google?: { responseModalities: string[] };\n openai?: { modalities: string[] };\n} => ({\n ...((modelId.startsWith(\"google/\") || modelId.includes(\"gemini\")) && {\n google: { responseModalities: [\"TEXT\", \"IMAGE\"] },\n }),\n ...(modelId.startsWith(\"openai/\") && {\n openai: { modalities: [\"text\", \"image\"] },\n }),\n});\nconst runGenerateImageMultimodal = async (\n options: Readonly<ImageGenerationOptions>,\n selection: Readonly<Extract<ImageModelSelection, { multimodal: true }>>\n): Promise<GeneratedImageResult> => {\n const userContent = await multimodalContent(options);\n log.debug(\n {\n imageCount: userContent.filter(\n (part: Readonly<{ type: string }>): boolean => part.type === \"image\"\n ).length,\n mode: options.mode,\n modelId: selection.modelId,\n },\n \"generateImage: using multimodal model\"\n );\n const res = await generateText({\n abortSignal: options.abortSignal,\n messages: [{ content: userContent, role: \"user\" }],\n model: options.modelProvider.createLanguageModel(selection.modelId),\n providerOptions: multimodalProviderOptions(selection.modelId),\n });\n const { costAccumulator } = options;\n if (costAccumulator) {\n costAccumulator.addLLMCost(\n selection.usageModelId,\n res.usage,\n \"generateImage-multimodal\"\n );\n }\n const imageFile = (res.files ?? []).find(\n (file: Readonly<{ mediaType: string }>): boolean =>\n file.mediaType.startsWith(\"image/\")\n );\n if (!imageFile) {\n throw new Error(\"No image generated by multimodal model\");\n }\n return await storeMultimodalImage(options, selection, imageFile);\n};\nexport { runGenerateImageTraditional, runGenerateImageMultimodal };\nexport type { ImageGenerationOptions, GeneratedImageResult, ImageStoreFile };\n",
55
+ "content": "import { generateImage, generateText } from \"ai\";\nimport type { FileUIPart } from \"ai\";\nimport type { FileUploader } from \"@/lib/file-storage\";\nimport type { ImageModelSelection } from \"./image-model\";\nimport type { ToolModelProvider } from \"@/lib/ai/tool-context\";\nimport type { createEveToolCost } from \"@/lib/eve/tool-cost\";\nimport { createModuleLogger } from \"@/lib/logger\";\nimport { collectEditImages } from \"./image-input\";\nimport type { generateImageResult } from \"./schemas\";\nimport type { z } from \"zod\";\n\nconst log = createModuleLogger(\"ai.tools.generate-image\");\nconst EMPTY_IMAGE_BYTES = 0;\nconst GENERATED_IMAGE_COUNT = 1;\nconst NO_GENERATED_IMAGES = 0;\ntype ReadonlyNativeSurface<Value> = Value extends\n | string\n | number\n | bigint\n | boolean\n | symbol\n | null\n | undefined\n ? Value\n : Value extends (...parameters: readonly never[]) => unknown\n ? Value\n : Value extends abstract new (...parameters: readonly never[]) => unknown\n ? Value\n : Value extends object\n ? {\n readonly [Property in keyof Value]: ReadonlyNativeSurface<\n Value[Property]\n >;\n }\n : Value;\ntype ImageStoreFile = (\n filename: string,\n body: ReadonlyNativeSurface<Buffer>,\n mediaType?: string\n) => ReturnType<FileUploader>;\ntype ImageMode = \"edit\" | \"generate\";\ninterface ImageGenerationOptions {\n readonly mode: ImageMode;\n readonly prompt: string;\n readonly imageParts: readonly Readonly<Pick<FileUIPart, \"url\">>[];\n readonly lastGeneratedImage: Readonly<{\n imageUrl: string;\n name: string;\n }> | null;\n readonly startMs: number;\n readonly costAccumulator?: Readonly<ReturnType<typeof createEveToolCost>>;\n readonly abortSignal?: Readonly<AbortSignal>;\n readonly storeFile: ImageStoreFile;\n readonly modelProvider: Readonly<ToolModelProvider>;\n}\ntype GeneratedImageResult = Required<z.infer<typeof generateImageResult>>;\nconst traditionalPrompt = async (\n options: Readonly<ImageGenerationOptions>\n): Promise<string | { text: string; images: Buffer[] }> => {\n if (options.mode !== \"edit\") {\n return options.prompt;\n }\n log.debug(\n {\n attachmentCount: options.imageParts.length,\n lastGeneratedCount: options.lastGeneratedImage\n ? GENERATED_IMAGE_COUNT\n : NO_GENERATED_IMAGES,\n note: \"OpenAI edit mode\",\n },\n \"generateImage: preparing edit images\"\n );\n return { images: await collectEditImages(options), text: options.prompt };\n};\nconst storeImage = async (\n options: Readonly<ImageGenerationOptions>,\n image: Readonly<{\n buffer: ReadonlyNativeSurface<Buffer>;\n filename: string;\n mediaType: string;\n }>,\n model: Readonly<{ modelId: string; multimodal: boolean }>\n): Promise<GeneratedImageResult> => {\n const result = await options.storeFile(\n image.filename,\n image.buffer,\n image.mediaType\n );\n log.info(\n {\n imageUrl: result.url,\n mode: options.mode,\n ms: Date.now() - options.startMs,\n uploadedFilename: image.filename,\n ...(model.multimodal ? { modelId: model.modelId } : {}),\n },\n model.multimodal\n ? \"generateImage: multimodal success\"\n : \"generateImage: success\"\n );\n return {\n fileId: result.fileId,\n imageUrl: result.url,\n prompt: options.prompt,\n };\n};\nconst runGenerateImageTraditional = async (\n options: Readonly<ImageGenerationOptions>,\n modelId: string\n): Promise<GeneratedImageResult> => {\n const prompt = await traditionalPrompt(options);\n const res = await generateImage({\n abortSignal: options.abortSignal,\n model: options.modelProvider.createImageModel(modelId),\n prompt,\n });\n const [firstImage] = res.images;\n log.debug(\n {\n base64Length: firstImage?.base64?.length ?? EMPTY_IMAGE_BYTES,\n mode: options.mode,\n },\n \"generateImage: provider response received\"\n );\n const buffer = Buffer.from(firstImage.base64, \"base64\");\n const filename = `generated-image-${Date.now()}.png`;\n // Provider usage remains billable if the subsequent storage upload fails.\n const { costAccumulator } = options;\n if (costAccumulator) {\n costAccumulator.addImageCost(\n modelId,\n res.images.length,\n res.usage ?? {},\n \"generateImage-traditional\"\n );\n }\n return await storeImage(\n options,\n { buffer, filename, mediaType: \"image/png\" },\n { modelId, multimodal: false }\n );\n};\ninterface ImageContent {\n image: Readonly<Buffer>;\n type: \"image\";\n}\ninterface TextContent {\n text: string;\n type: \"text\";\n}\nconst multimodalContent = async (\n options: Readonly<ImageGenerationOptions>\n): Promise<(ImageContent | TextContent)[]> => {\n const buffers =\n options.mode === \"edit\" ? await collectEditImages(options) : [];\n const images = buffers.map(\n (image: ReadonlyNativeSurface<Buffer>): ImageContent => ({\n image,\n type: \"image\",\n })\n );\n return [\n ...images,\n {\n text:\n options.mode === \"edit\"\n ? `Based on the provided image(s), ${options.prompt}`\n : `Generate an image: ${options.prompt}`,\n type: \"text\",\n },\n ];\n};\nconst storeMultimodalImage = async (\n options: Readonly<ImageGenerationOptions>,\n selection: Readonly<Extract<ImageModelSelection, { multimodal: true }>>,\n imageFile: ReadonlyNativeSurface<{\n mediaType: string;\n base64: string;\n uint8Array: Uint8Array;\n }>\n): Promise<GeneratedImageResult> => {\n log.debug(\n {\n hasBase64: Boolean(imageFile.base64),\n mediaType: imageFile.mediaType,\n mode: options.mode,\n },\n \"generateImage: multimodal response received\"\n );\n const buffer = Buffer.from(imageFile.uint8Array);\n const timestamp = Date.now();\n const [, subtype] = imageFile.mediaType.split(\"/\");\n const ext = typeof subtype === \"string\" && subtype !== \"\" ? subtype : \"png\";\n return await storeImage(\n options,\n {\n buffer,\n filename: `generated-image-${timestamp}.${ext}`,\n mediaType: imageFile.mediaType,\n },\n selection\n );\n};\nconst multimodalProviderOptions = (\n modelId: string\n): {\n google?: { responseModalities: string[] };\n openai?: { modalities: string[] };\n} => ({\n ...((modelId.startsWith(\"google/\") || modelId.includes(\"gemini\")) && {\n google: { responseModalities: [\"TEXT\", \"IMAGE\"] },\n }),\n ...(modelId.startsWith(\"openai/\") && {\n openai: { modalities: [\"text\", \"image\"] },\n }),\n});\nconst runGenerateImageMultimodal = async (\n options: Readonly<ImageGenerationOptions>,\n selection: Readonly<Extract<ImageModelSelection, { multimodal: true }>>\n): Promise<GeneratedImageResult> => {\n const userContent = await multimodalContent(options);\n log.debug(\n {\n imageCount: userContent.filter(\n (part: Readonly<{ type: string }>): boolean => part.type === \"image\"\n ).length,\n mode: options.mode,\n modelId: selection.modelId,\n },\n \"generateImage: using multimodal model\"\n );\n const res = await generateText({\n abortSignal: options.abortSignal,\n messages: [{ content: userContent, role: \"user\" }],\n model: options.modelProvider.createLanguageModel(selection.modelId),\n providerOptions: multimodalProviderOptions(selection.modelId),\n });\n const { costAccumulator } = options;\n if (costAccumulator) {\n costAccumulator.addLLMCost(\n selection.usageModelId,\n res.usage,\n \"generateImage-multimodal\"\n );\n }\n const imageFile = (res.files ?? []).find(\n (file: Readonly<{ mediaType: string }>): boolean =>\n file.mediaType.startsWith(\"image/\")\n );\n if (!imageFile) {\n throw new Error(\"No image generated by multimodal model\");\n }\n return await storeMultimodalImage(options, selection, imageFile);\n};\nexport { runGenerateImageTraditional, runGenerateImageMultimodal };\nexport type { ImageGenerationOptions, GeneratedImageResult, ImageStoreFile };\n",
56
56
  "type": "registry:file",
57
57
  "target": "~/chatjs/tools/generate-image/image-generation.ts"
58
58
  },
@@ -64,13 +64,15 @@
64
64
  },
65
65
  {
66
66
  "path": "dist/source/generate-image.json",
67
- "content": "{\n \"config\": { \"key\": \"image\" },\n \"envRequirements\": [],\n \"id\": \"generate-image\",\n \"kind\": \"tool\",\n \"requiresGateway\": [\"image\"],\n \"requiresStorage\": true,\n \"requiresTools\": [],\n \"slot\": \"generateImage\",\n \"tools\": [\n {\n \"composer\": {\n \"icon\": \"Images\",\n \"name\": \"Create an image\",\n \"shortName\": \"Image\"\n },\n \"rendererExport\": \"GenerateImageRenderer\",\n \"toolExport\": \"generateImageTool\"\n }\n ],\n \"contractVersion\": 1\n}\n",
67
+ "content": "{\n \"agentCategory\": \"tool\",\n \"requiresChatJS\": true,\n \"config\": { \"key\": \"image\" },\n \"envRequirements\": [],\n \"id\": \"generate-image\",\n \"kind\": \"tool\",\n \"requiresGateway\": [\"image\"],\n \"requiresStorage\": true,\n \"requiresTools\": [],\n \"slot\": \"generateImage\",\n \"tools\": [\n {\n \"composer\": {\n \"icon\": \"Images\",\n \"name\": \"Create an image\",\n \"shortName\": \"Image\"\n },\n \"rendererExport\": \"GenerateImageRenderer\",\n \"toolExport\": \"generateImageTool\"\n }\n ],\n \"contractVersion\": 1,\n \"channelSupport\": { \"web\": \"supported\", \"slack\": \"unverified\" }\n}\n",
68
68
  "type": "registry:file",
69
69
  "target": "~/chatjs/tools/generate-image/chatjs.json"
70
70
  }
71
71
  ],
72
72
  "meta": {
73
73
  "chatjs": {
74
+ "agentCategory": "tool",
75
+ "requiresChatJS": true,
74
76
  "config": {
75
77
  "key": "image"
76
78
  },
@@ -94,7 +96,11 @@
94
96
  "toolExport": "generateImageTool"
95
97
  }
96
98
  ],
97
- "contractVersion": 1
99
+ "contractVersion": 1,
100
+ "channelSupport": {
101
+ "web": "supported",
102
+ "slack": "unverified"
103
+ }
98
104
  }
99
105
  },
100
106
  "type": "registry:item"
@@ -21,7 +21,7 @@
21
21
  },
22
22
  {
23
23
  "path": "src/tools/generate-video/renderer.tsx",
24
- "content": "\"use client\";\nimport { generateVideoInput, generateVideoResult } 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 GenerateVideoTool = ToolRendererProps<\n typeof generateVideoInput,\n typeof generateVideoResult\n>[\"tool\"];\n\nconst GenerateVideoView = ({\n tool,\n}: ReadonlyNativeSurface<{ tool: GenerateVideoTool }>): React.JSX.Element => {\n if (tool.state === \"input-streaming\" || tool.state === \"input-available\") {\n return (\n <div className=\"flex w-full flex-col items-center justify-center gap-4 rounded-lg border p-8\">\n <div className=\"bg-muted-foreground/20 h-64 w-full animate-pulse rounded-lg\" />\n <div className=\"text-muted-foreground\">\n Generating video: &quot;\n {tool.input?.prompt ?? \"Preparing prompt…\"}\n &quot;\n </div>\n </div>\n );\n }\n\n const { output } = tool;\n\n return (\n <div className=\"flex w-full flex-col gap-4 overflow-hidden rounded-lg border\">\n <video\n autoPlay\n className=\"h-auto w-full max-w-full\"\n controls\n loop\n muted\n playsInline\n src={output.videoUrl}\n />\n <div className=\"p-4 pt-0\">\n <p className=\"text-muted-foreground text-sm\">\n Generated from: &quot;{output.prompt}&quot;\n </p>\n </div>\n </div>\n );\n};\n\nexport const GenerateVideoRenderer = defineToolRenderer({\n inputSchema: generateVideoInput,\n outputSchema: generateVideoResult,\n render: GenerateVideoView,\n});\n",
24
+ "content": "\"use client\";\nimport { generateVideoInput, generateVideoResult } from \"./schemas\";\nimport React, { useRef } from \"react\";\nimport { ArtifactViewerActions } from \"@/components/artifact-actions\";\nimport { ArtifactDownloadAction } from \"@/components/artifact-download-action\";\nimport { VideoPlayer } from \"@/components/video-player\";\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 GenerateVideoTool = ToolRendererProps<\n typeof generateVideoInput,\n typeof generateVideoResult\n>[\"tool\"];\n\nconst GenerateVideoView = ({\n tool,\n}: ReadonlyNativeSurface<{ tool: GenerateVideoTool }>): React.JSX.Element => {\n const player = useRef<HTMLVideoElement>(null);\n if (tool.state === \"input-streaming\" || tool.state === \"input-available\") {\n return (\n <div className=\"flex w-full flex-col items-center justify-center gap-4 rounded-lg border p-8\">\n <div className=\"bg-muted-foreground/20 h-64 w-full animate-pulse rounded-lg\" />\n <div className=\"text-muted-foreground\">\n Generating video: &quot;\n {tool.input?.prompt ?? \"Preparing prompt…\"}\n &quot;\n </div>\n </div>\n );\n }\n\n const { output } = tool;\n const artifact = {\n fileId: output.fileId,\n url: output.videoUrl,\n name: output.prompt,\n mediaType: \"video/*\",\n };\n\n return (\n <div className=\"flex w-full flex-col gap-4 overflow-hidden rounded-lg border\">\n <VideoPlayer ref={player} src={output.videoUrl} name={output.prompt} />\n <div className=\"flex items-start justify-between gap-3 px-4 pb-4\">\n <p className=\"text-muted-foreground text-sm\">\n Generated from: &quot;{output.prompt}&quot;\n </p>\n <div className=\"flex shrink-0 items-center gap-1\">\n <ArtifactViewerActions\n artifact={artifact}\n onOpen={() => {\n player.current?.pause();\n }}\n />\n <ArtifactDownloadAction artifact={artifact} label=\"Download video\" />\n </div>\n </div>\n </div>\n );\n};\n\nexport const GenerateVideoRenderer = defineToolRenderer({\n inputSchema: generateVideoInput,\n outputSchema: generateVideoResult,\n render: GenerateVideoView,\n});\n",
25
25
  "type": "registry:file",
26
26
  "target": "~/chatjs/tools/generate-video/renderer.tsx"
27
27
  },
@@ -33,13 +33,15 @@
33
33
  },
34
34
  {
35
35
  "path": "dist/source/generate-video.json",
36
- "content": "{\n \"config\": { \"key\": \"video\" },\n \"envRequirements\": [],\n \"id\": \"generate-video\",\n \"kind\": \"tool\",\n \"requiresGateway\": [\"video\"],\n \"requiresStorage\": true,\n \"requiresTools\": [],\n \"slot\": \"generateVideo\",\n \"tools\": [\n {\n \"composer\": {\n \"icon\": \"Video\",\n \"name\": \"Create a video\",\n \"shortName\": \"Video\"\n },\n \"rendererExport\": \"GenerateVideoRenderer\",\n \"toolExport\": \"generateVideoTool\"\n }\n ],\n \"contractVersion\": 1\n}\n",
36
+ "content": "{\n \"agentCategory\": \"tool\",\n \"requiresChatJS\": true,\n \"config\": { \"key\": \"video\" },\n \"envRequirements\": [],\n \"id\": \"generate-video\",\n \"kind\": \"tool\",\n \"requiresGateway\": [\"video\"],\n \"requiresStorage\": true,\n \"requiresTools\": [],\n \"slot\": \"generateVideo\",\n \"tools\": [\n {\n \"composer\": {\n \"icon\": \"Video\",\n \"name\": \"Create a video\",\n \"shortName\": \"Video\"\n },\n \"rendererExport\": \"GenerateVideoRenderer\",\n \"toolExport\": \"generateVideoTool\"\n }\n ],\n \"contractVersion\": 1,\n \"channelSupport\": { \"web\": \"supported\", \"slack\": \"unverified\" }\n}\n",
37
37
  "type": "registry:file",
38
38
  "target": "~/chatjs/tools/generate-video/chatjs.json"
39
39
  }
40
40
  ],
41
41
  "meta": {
42
42
  "chatjs": {
43
+ "agentCategory": "tool",
44
+ "requiresChatJS": true,
43
45
  "config": {
44
46
  "key": "video"
45
47
  },
@@ -63,7 +65,11 @@
63
65
  "toolExport": "generateVideoTool"
64
66
  }
65
67
  ],
66
- "contractVersion": 1
68
+ "contractVersion": 1,
69
+ "channelSupport": {
70
+ "web": "supported",
71
+ "slack": "unverified"
72
+ }
67
73
  }
68
74
  },
69
75
  "type": "registry:item"
@@ -100,13 +100,13 @@
100
100
  },
101
101
  {
102
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 resolveModel: resolveGuestModel,\n instructions: GUEST_INSTRUCTIONS,\n} satisfies SessionProfile;\n",
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
104
  "type": "registry:file",
105
105
  "target": "~/chatjs/plugins/guest-chat/session-profile.ts"
106
106
  },
107
107
  {
108
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 } 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 { ChatLayout, ChatLayoutMain } from \"@/components/chat/chat-layout\";\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 { EveMessages } from \"@/components/eve/eve-messages\";\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 <EveMessages\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\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 <ChatLayout isSecondaryPanelVisible={false}>\n <ChatLayoutMain defaultSize=\"100%\">\n <section className=\"flex h-full min-h-0 flex-col\">\n <ChatHeaderView breadcrumb={null} className=\"h-(--header-height)\" />\n {binding ? (\n <GuestConversation binding={binding} key={binding.sessionId} />\n ) : (\n <ChatWelcomeView>\n {commandError && (\n <p role=\"alert\" className=\"text-destructive mb-3 text-sm\">\n {commandError}\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={setDraft}\n onSubmit={() => {\n void submit();\n }}\n />\n </ChatWelcomeView>\n )}\n </section>\n </ChatLayoutMain>\n </ChatLayout>\n );\n};\n\nexport { GuestChatScreen, GuestConversationView };\n",
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
110
  "type": "registry:file",
111
111
  "target": "~/chatjs/plugins/guest-chat/signed-out.tsx"
112
112
  },
@@ -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\": \"base\"\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": "base"
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,9 +1,9 @@
1
1
  {
2
2
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
3
  "name": "litellm-gateway",
4
- "title": "LiteLLMGateway",
4
+ "title": "LiteLLM",
5
5
  "dependencies": [
6
- "@chat-js/gateways@0.2.0",
6
+ "@chat-js/gateways@0.2.1",
7
7
  "@ai-sdk/openai-compatible@3.0.44"
8
8
  ],
9
9
  "files": [