Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ai): tool restyling + improve tool rendering pipeline (#2385)
Eric Hayes2986c063d998
diff --git a/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx b/js/app/packages/core/component/AI/component/message/AssistantMessage.tsxindex b414e33eec..ffdb95b724 100644--- a/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx+++ b/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx@@ -17,6 +17,7 @@ import type { ChatMessageWithAttachments } from '@service-cognition/generated/scimport { createCallback } from '@solid-primitives/rootless';import {createMemo,+ createSelector,createSignal,For,Match,@@ -59,44 +60,11 @@ export function AssistantMessage(props: {isStreaming?: true;ttft?: number;}) {- // const chat = chatStore.get;- // const blockData = chatBlockDataSignal.get;- // const attachments = () => attachedAttachments() ?? [];const [copied, setCopied] = createSignal(false);const [isLoading, setIsLoading] = createSignal<boolean>(false);-- // TODO: replace with new layout- // const { replaceOrInsertSplit } = useSplitLayout();-let markdownRootRef!: HTMLDivElement;- // const currentModel = blockData()?.allModels?.find(- // (model) => model.name === props.message.model- // ) ?? { name: 'anthropic/claude-sonnet-4', provider: 'anthropic' };-- // TODO- // const providerIcon = modelProviderIcon[currentModel];- // const isGenerating = createMemo(() => {- // return (- // props.message.id === chat.messages.at(-1)?.id &&- // chat.chatStatus === ChatStatus.Generating- // );- // });-- // tool call is complete but the response is notconst toolUsageMessageIncomplete = createMemo(() => false);- // if (!isGenerating()) return false;- // const lastMessageContent = props.message.content.at(-1);- // if (!lastMessageContent || typeof lastMessageContent === 'string')- // return false;- // if (- // lastMessageContent.type === 'toolCall' ||- // lastMessageContent.type === 'text'- // )- // return false;- // return true;- // });-const handleCopy = async () => {const text = extractMessageText(props.message.content);const cleanedText = text.replace(/\[\[.*?\]\]/g, '');@@ -217,10 +185,6 @@ export function AssistantMessage(props: {<Show when={!props.isStreaming}><div class="flex flex-row w-full justify-start items-center h-[32px] px-2 space-x-2 "><div class="flex flex-row space-x-2 items-center text-xs text-ink-muted">- {/* Only one model for now so don't show icon */}- {/*<Dynamic component={modelIcon()} width={12} height={12} />*/}- {/* <p>{modelName()}</p> */}-<div class="w-fit"><buttonclass="flex flex-row items-center space-x-1 hover:bg-hover hover-transition-bg p-1 text-xs font-sans"@@ -268,49 +232,11 @@ export function AssistantMessage(props: {);}-// tool response should follow tool call-function pairToolCalls(parts: AssistantMessagePart[]): AssistantMessagePart[] {- function takeResult(- parts: AssistantMessagePart[],- callId: string- ): [AssistantMessagePart | undefined, AssistantMessagePart[]] {- const ti = parts.findIndex(- (p) => p.type === 'toolCallResponseJson' && p.id === callId- );- if (ti === -1) return [undefined, parts];- const response = parts[ti];- parts.splice(ti, 1);- return [response, parts];- }-- function pairParts(- parts: AssistantMessagePart[],- newParts: AssistantMessagePart[]- ): AssistantMessagePart[] {- if (parts.length === 0) return newParts;- const first = parts[0];- if (first.type === 'toolCall') {- const [maybeResponse, rest] = takeResult(parts.slice(1), first.id);- newParts.push(first);- if (maybeResponse) newParts.push(maybeResponse);- return pairParts(rest, newParts);- } else {- newParts.push(first);- return pairParts(parts.slice(1), newParts);- }- }- return pairParts(parts, []);-}-function getAssistantPartKey(part: AssistantMessagePart,counts: Map<AssistantMessagePart['type'], number>): string {- if (- part.type === 'toolCall' ||- part.type === 'toolCallResponseJson' ||- part.type === 'toolCallErr'- ) {+ if (part.type === 'toolCall' || part.type === 'toolCallErr') {return `${part.type}:${part.id}`;}@@ -325,8 +251,38 @@ function AssistantMessageParts(props: {isStreaming: boolean;}) {const chat = useChatContext();+ const completedToolIds = createMemo(() => {+ const ids = new Set<string>();+ for (const part of props.parts) {+ if (part.type === 'toolCallResponseJson' || part.type === 'toolCallErr') {+ ids.add(part.id);+ }+ }+ return ids;+ });++ const isCompleteSelector = createSelector(+ completedToolIds,+ (id: string, completed) => completed.has(id)+ );++ const responseById = createMemo(() => {+ const responseMap = new Map<+ string,+ Extract<AssistantMessagePart, { type: 'toolCallResponseJson' }>+ >();++ for (const part of props.parts) {+ if (part.type === 'toolCallResponseJson') {+ responseMap.set(part.id, part);+ }+ }++ return responseMap;+ });+const parts = createMemo(() => {- return pairToolCalls(props.parts);+ return props.parts.filter((part) => part.type !== 'toolCallResponseJson');});const keyedParts = createMemo(() => {@@ -353,18 +309,18 @@ function AssistantMessageParts(props: {{(part, i) => {const currentPart = () => part();if (!currentPart()) return null;- const previousPart = () => stableParts()[i() - 1]?.();return match(currentPart()!).with({ type: 'toolCall' }, (toolCall) => (<RenderTooltool_id={toolCall.id}chat_id={chat.chatId()}- tool_call={toolCall.json}+ json={toolCall.json}name={toolCall.name}+ response={responseById().get(toolCall.id)}message_id={props.message.id}part_index={i()}- type="call"+ isComplete={isCompleteSelector(toolCall.id)}renderContext={{renderContext: {isStreaming: props.isStreaming,@@ -372,39 +328,12 @@ function AssistantMessageParts(props: {}}/>))- .with({ type: 'toolCallResponseJson' }, (toolResponse) => {- const callPart = previousPart();- if (- callPart?.type !== 'toolCall' ||- callPart.id !== toolResponse.id- ) {- return null;- }-- return (- <RenderTool- tool_id={toolResponse.id}- chat_id={chat.chatId()}- call_part_index={i() - 1}- name={toolResponse.name}- message_id={props.message.id}- part_index={i()}- tool_call={callPart.json}- tool_response={toolResponse.json}- type="response"- renderContext={{- renderContext: {- isStreaming: props.isStreaming,- },- }}- />- );- }).with({ type: 'toolCallErr' }, (toolError) => (<div class="px-2 py-1 text-sm text-ink-muted">Tool `{toolError.name}` failed: {toolError.description}</div>))+ .with({ type: 'toolCallResponseJson' }, () => null).with({ type: 'text' }, (textPart) => {if (textPart.text.trim().length === 0) return null;diff --git a/js/app/packages/core/component/AI/component/message/ChatMessages.tsx b/js/app/packages/core/component/AI/component/message/ChatMessages.tsxindex 05050eeae3..ddffad20af 100644--- a/js/app/packages/core/component/AI/component/message/ChatMessages.tsx+++ b/js/app/packages/core/component/AI/component/message/ChatMessages.tsx@@ -212,7 +212,7 @@ export function ChatMessages(props: ChatMessagesProps) {{(msg) => (<divid={'chat-' + msg.id}- class="w-full transition-colors duration-300"+ class="w-full transition-colors duration-300 flex flex-col gap-y-2"classList={{'bg-accent': activeIdSelector(msg.id),}}@@ -234,7 +234,7 @@ export function ChatMessages(props: ChatMessagesProps) {<Show when={isStream() || chat.isWaiting() || lastPair()}><div- class="shrink-0"+ class="shrink-0 flex flex-col gap-y-2"style={{'min-height': `${parentHeight()}px`,}}diff --git a/js/app/packages/core/component/AI/component/tool/BaseTool.tsx b/js/app/packages/core/component/AI/component/tool/BaseTool.tsxindex 1c0e29a628..301a07595d 100644--- a/js/app/packages/core/component/AI/component/tool/BaseTool.tsx+++ b/js/app/packages/core/component/AI/component/tool/BaseTool.tsx@@ -6,6 +6,7 @@ type ToolCallProps = {renderContext: RenderContext['renderContext'];type: 'call';children: JSX.Element;+ response?: JSX.Element;};type ToolResponseProps = {children: JSX.Element;@@ -16,12 +17,13 @@ type ToolResponseProps = {function BaseToolCall(props: ToolCallProps) {return (<div class="relative text-sm text-ink-extra-muted border-l pl-4 border-edge">- <div class="flex gap-x-2 items-center">- <Show when={props.type === 'call'}>- <props.icon class="h-[20px] w-[20px] shrink-0 text-accent" />- <div class="p-2">{props.children}</div>- </Show>+ <div class="flex w-full items-center gap-x-2">+ <props.icon class="h-[20px] w-[20px] shrink-0 text-accent" />+ <div class="min-w-0 flex-1 p-2">{props.children}</div></div>+ <Show when={props.response}>+ <div class="pl-8 mb-2">{props.response}</div>+ </Show></div>);}diff --git a/js/app/packages/core/component/AI/component/tool/BashCodeExecution.tsx b/js/app/packages/core/component/AI/component/tool/BashCodeExecution.tsxindex af0366af88..88393de67c 100644--- a/js/app/packages/core/component/AI/component/tool/BashCodeExecution.tsx+++ b/js/app/packages/core/component/AI/component/tool/BashCodeExecution.tsx@@ -7,26 +7,24 @@ import { BaseTool } from './BaseTool';import { createToolRenderer } from './ToolRenderer';const MAX_COMMAND_LENGTH = 80;-const MAX_OUTPUT_LINES = 3;-function truncateCommand(command: string): string {- const firstLine = command.split('\n')[0] ?? '';- const needsTruncation =- command.includes('\n') || firstLine.length > MAX_COMMAND_LENGTH;-- if (needsTruncation) {- return `${firstLine.slice(0, MAX_COMMAND_LENGTH)}...`;- }- return firstLine;-}--function CodeFence(props: { content: string; maxLines: number }) {+function CodeFence(props: {+ content: string;+ maxLines?: number;+ collapsible?: boolean;+}) {const [expanded, setExpanded] = createSignal(false);+ const isCollapsible = () => props.collapsible ?? true;const lines = () => props.content.split('\n');- const needsTruncation = () =>- lines().length > props.maxLines ||- props.content.length > MAX_COMMAND_LENGTH;+ const needsTruncation = () => {+ if (!isCollapsible()) return false;++ return (+ lines().length > (props.maxLines ?? Number.MAX_SAFE_INTEGER) ||+ props.content.length > MAX_COMMAND_LENGTH+ );+ };const displayContent = () => {if (expanded() || !needsTruncation()) {@@ -40,7 +38,7 @@ function CodeFence(props: { content: string; maxLines: number }) {return (<div class="relative">- <Show when={needsTruncation()}>+ <Show when={isCollapsible() && needsTruncation()}><buttontype="button"class="text-ink-extra-muted hover:text-ink-muted absolute top-1 right-1 p-1"@@ -54,7 +52,8 @@ function CodeFence(props: { content: string; maxLines: number }) {<preclass="text-ink-muted bg-background-secondary overflow-x-auto rounded p-2 pr-8 font-mono text-xs whitespace-pre-wrap"classList={{- 'max-h-24 overflow-hidden': !expanded() && needsTruncation(),+ 'max-h-24 overflow-hidden':+ isCollapsible() && !expanded() && needsTruncation(),}}>{displayContent()}@@ -83,7 +82,7 @@ function BashResult(props: { result: BashCodeExecutionResult }) {<span class="text-ink-error">Exit code {props.result.return_code}</span></Show><Show when={hasOutput()}>- <CodeFence content={output()} maxLines={MAX_OUTPUT_LINES} />+ <CodeFence content={output()} collapsible={false} /></Show><Show when={!hasOutput() && props.result.return_code === 0}><span class="text-ink-muted">No output</span>@@ -94,31 +93,63 @@ function BashResult(props: { result: BashCodeExecutionResult }) {const handler = createToolRenderer({name: 'bash_code_execution',- renderCall: (ctx) => (- <BaseTool icon={Terminal} renderContext={ctx.renderContext} type="call">- <code class="text-ink-muted font-mono text-xs">- {truncateCommand(ctx.tool.data.command)}- </code>- </BaseTool>- ),- renderResponse: (ctx) => {- const isError =- ctx.toolResponse.tool.data.content.type ===- 'bash_code_execution_tool_result_error';+ render: (ctx) => {+ const [isExpanded, setIsExpanded] = createSignal(false);+return (- <BaseTool renderContext={ctx.renderContext} type="response">- <Switch>- <Match when={isError}>- <span class="text-ink-error">Execution failed</span>- </Match>- <Match when={!isError}>- <BashResult- result={- ctx.toolResponse.tool.data.content as BashCodeExecutionResult- }+ <BaseTool+ icon={Terminal}+ renderContext={ctx.renderContext}+ type="call"+ response={+ isExpanded() ? (+ <div class="flex flex-col gap-2">+ <CodeFence content={ctx.tool.data.command} collapsible={false} />+ <Show when={ctx.response}>+ {(response) => {+ const isError =+ response().data.content.type ===+ 'bash_code_execution_tool_result_error';++ return (+ <Switch>+ <Match when={isError}>+ <span class="text-ink-error">Execution failed</span>+ </Match>+ <Match when={!isError}>+ <BashResult+ result={+ response().data.content as BashCodeExecutionResult+ }+ />+ </Match>+ </Switch>+ );+ }}+ </Show>+ </div>+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">+ <span>Code execution</span>+ <button+ type="button"+ class="shrink-0 text-ink-muted hover:text-ink p-1"+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ setIsExpanded((expanded) => !expanded);+ }}+ >+ <CaretRight+ class="h-4 w-4 transition-transform"+ classList={{+ 'rotate-90': isExpanded(),+ }}/>- </Match>- </Switch>+ </button>+ </div></BaseTool>);},diff --git a/js/app/packages/core/component/AI/component/tool/CreateDocument.tsx b/js/app/packages/core/component/AI/component/tool/CreateDocument.tsxindex 4a2c15e72f..d499c1b9dd 100644--- a/js/app/packages/core/component/AI/component/tool/CreateDocument.tsx+++ b/js/app/packages/core/component/AI/component/tool/CreateDocument.tsx@@ -1,21 +1,28 @@import { ItemPreview } from '@core/component/ItemPreview';import FilePlus from '@phosphor-icons/core/regular/file-plus.svg';+import { Show } from 'solid-js';import { BaseTool } from './BaseTool';import { createToolRenderer } from './ToolRenderer';const handler = createToolRenderer({name: 'CreateDocument',- renderCall: (ctx) => (+ render: (ctx) => (<BaseTool icon={FilePlus} renderContext={ctx.renderContext} type="call">- Create{' '}- <span class="text-accent">- {ctx.tool.data.documentName}.{ctx.tool.data.fileExtension}- </span>- </BaseTool>- ),- renderResponse: (ctx) => (- <BaseTool renderContext={ctx.renderContext} type="response">- <ItemPreview id={ctx.toolResponse.tool.data.documentId} type="document" />+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">+ <div class="min-w-0">+ Create{' '}+ <span class="text-accent">+ {ctx.tool.data.documentName}.{ctx.tool.data.fileExtension}+ </span>+ </div>+ <Show when={ctx.response}>+ {(response) => (+ <div class="shrink-0">+ <ItemPreview id={response().data.documentId} type="document" />+ </div>+ )}+ </Show>+ </div></BaseTool>),});diff --git a/js/app/packages/core/component/AI/component/tool/GetThread.tsx b/js/app/packages/core/component/AI/component/tool/GetThread.tsxindex 9d37ba73ec..f75cc6933c 100644--- a/js/app/packages/core/component/AI/component/tool/GetThread.tsx+++ b/js/app/packages/core/component/AI/component/tool/GetThread.tsx@@ -4,12 +4,11 @@ import { createToolRenderer } from './ToolRenderer';const handler = createToolRenderer({name: 'GetThread',- renderCall: (ctx) => (+ render: (ctx) => (<BaseTool icon={EnvelopeOpen} renderContext={ctx.renderContext} type="call">Read thread</BaseTool>),- renderResponse: (_) => undefined,});export const getThreadHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/ListEntities.tsx b/js/app/packages/core/component/AI/component/tool/ListEntities.tsxindex c051d9d859..5f8a25590f 100644--- a/js/app/packages/core/component/AI/component/tool/ListEntities.tsx+++ b/js/app/packages/core/component/AI/component/tool/ListEntities.tsx@@ -1,7 +1,6 @@import { EntityIcon } from '@core/component/EntityIcon';import { TruncatedText } from '@core/component/FileList/TruncatedText';-import ChevronDown from '@icon/regular/caret-down.svg?component-solid';-import ChevronUp from '@icon/regular/caret-up.svg?component-solid';+import CaretRight from '@icon/regular/caret-right.svg?component-solid';import List from '@phosphor-icons/core/regular/list.svg';import type { NamedTool } from '@service-cognition/generated/tools/tool';import { useSplitLayout } from 'app/component/split-layout/layout';@@ -19,8 +18,6 @@ const ListEntitiesToolResponse = (props: {items: ListEntitiesItem[];summary: string;}) => {- const [isExpanded, setIsExpanded] = createSignal(false);-const results = createMemo(() => {const seen = new Set<string>();return props.items.filter((item) => {@@ -94,104 +91,127 @@ const ListEntitiesToolResponse = (props: {};return (- <div class="border border-edge rounded w-full">- <Show- when={props.items.length > 0}- fallback={- <div class="flex items-center justify-between w-full text-left p-2 hover:bg-hover transition-colors">- No Results- </div>- }+ <div class="max-h-[480px] overflow-hidden">+ <VList+ data={results()}+ bufferSize={5 * 32}+ itemSize={32}+ style={{+ height: `${Math.min(results().length * 32, 480)}px`,+ contain: 'content',+ }}>- <button- class={`flex items-center justify-between w-full text-left p-2 hover:bg-hover transition-colors ${- isExpanded() ? 'rounded-t border-b border-edge' : 'rounded'- }`}- onClick={() => setIsExpanded((e) => !e)}- >- <div class="flex items-center gap-2">- <div class="text-sm font-medium text-ink">- Found- <span class="text-accent pr-1"> {results().length}</span>- Items- </div>- </div>- <div class="flex items-center gap-1 text-ink-muted">- <Show- when={isExpanded()}- fallback={<ChevronDown class="w-4 h-4" />}- >- <ChevronUp class="w-4 h-4" />- </Show>- </div>- </button>- </Show>-- <Show when={isExpanded()}>- <div class="max-h-[480px] overflow-hidden">- <VList- data={results()}- bufferSize={5 * 32}- itemSize={32}- style={{- height: `${Math.min(results().length * 32, 480)}px`,- contain: 'content',- }}- >- {(item) => {- const clickHandler = getClickHandler(item);+ {(item) => {+ const clickHandler = getClickHandler(item);- return (- <div- class="flex items-center w-full h-8 px-2 hover:bg-hover transition-colors"- onClick={clickHandler}- >- <div class="flex items-center flex-1 min-w-0 gap-2">- <EntityIcon- size="sm"- targetType={getIconType(item)}- shared={false}- />- <div class="flex-1 min-w-0">- <TruncatedText size="sm">- <span>{getItemTitle(item)}</span>- </TruncatedText>- </div>- </div>+ return (+ <div+ class="flex items-center w-full h-8 px-2 hover:bg-hover transition-colors"+ onClick={clickHandler}+ >+ <div class="flex items-center flex-1 min-w-0 gap-2">+ <EntityIcon+ size="sm"+ targetType={getIconType(item)}+ shared={false}+ />+ <div class="flex-1 min-w-0">+ <TruncatedText size="sm">+ <span>{getItemTitle(item)}</span>+ </TruncatedText></div>- );- }}- </VList>- </div>- </Show>+ </div>+ </div>+ );+ }}+ </VList></div>);};const handler = createToolRenderer({name: 'ListEntities',- renderCall: (ctx) => (- <BaseTool icon={List} renderContext={ctx.renderContext} type="call">- Filter for{' '}- <span class="text-accent">- {ctx.tool.data.includeTypes- ? ctx.tool.data.includeTypes.join(', ')- : 'All'}- </span>{' '}- ordered by{' '}- <span class="text-accent">- {ctx.tool.data.sortBy.split('_').join(' ')}- </span>- </BaseTool>- ),- renderResponse: (ctx) => (- <BaseTool renderContext={ctx.renderContext} type="response">- <ListEntitiesToolResponse- items={ctx.toolResponse.tool.data.items}- summary={ctx.toolResponse.tool.data.summary}- />- </BaseTool>- ),+ render: (ctx) => {+ const [isExpanded, setIsExpanded] = createSignal(false);+ const items = () => ctx.response?.data.items ?? [];+ const dedupedCount = () => {+ const seen = new Set<string>();+ let count = 0;++ for (const item of items()) {+ if (seen.has(item.id)) continue;+ seen.add(item.id);+ count += 1;+ }++ return count;+ };+ const hasResults = () => dedupedCount() > 0;+ const statusText = () => {+ if (!ctx.response) return undefined;+ if (dedupedCount() === 0) return 'No Results';+ if (dedupedCount() === 1) return '1 item';+ return `${dedupedCount()} items`;+ };++ return (+ <BaseTool+ icon={List}+ renderContext={ctx.renderContext}+ type="call"+ response={+ hasResults() && isExpanded() ? (+ <ListEntitiesToolResponse+ items={items()}+ summary={ctx.response?.data.summary ?? ''}+ />+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">+ <div class="flex min-w-0 flex-1 items-center gap-2">+ <span>+ Filter for{' '}+ <span class="text-accent">+ {ctx.tool.data.includeTypes+ ? ctx.tool.data.includeTypes.join(', ')+ : 'All'}+ </span>{' '}+ ordered by{' '}+ <span class="text-accent">+ {ctx.tool.data.sortBy.split('_').join(' ')}+ </span>+ </span>+ </div>+ <div class="flex shrink-0 items-center gap-1">+ <Show when={statusText()}>+ {(text) => (+ <span class="text-xs text-ink-extra-muted">{text()}</span>+ )}+ </Show>+ <Show when={hasResults()}>+ <button+ type="button"+ class="shrink-0 text-ink-muted hover:text-ink p-1"+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ setIsExpanded((expanded) => !expanded);+ }}+ >+ <CaretRight+ class="h-4 w-4 transition-transform"+ classList={{+ 'rotate-90': isExpanded(),+ }}+ />+ </button>+ </Show>+ </div>+ </div>+ </BaseTool>+ );+ },});export const listEntitiesHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/Properties.tsx b/js/app/packages/core/component/AI/component/tool/Properties.tsxindex ae5678d0bd..3e07d6b14c 100644--- a/js/app/packages/core/component/AI/component/tool/Properties.tsx+++ b/js/app/packages/core/component/AI/component/tool/Properties.tsx@@ -5,32 +5,22 @@ import { createToolRenderer } from './ToolRenderer';const getHandler = createToolRenderer({name: 'GetEntityProperties',- renderCall: (ctx) => (+ render: (ctx) => (<BaseTool icon={Sliders} renderContext={ctx.renderContext} type="call">Get properties for{' '}<span class="text-accent">{ctx.tool.data.entity_type}</span></BaseTool>),- renderResponse: (ctx) => (- <BaseTool renderContext={ctx.renderContext} type="response">- {ctx.toolResponse.tool.data.summary}- </BaseTool>- ),});const setHandler = createToolRenderer({name: 'SetEntityProperty',- renderCall: (ctx) => (+ render: (ctx) => (<BaseTool icon={PencilSimple} renderContext={ctx.renderContext} type="call">Update property on{' '}<span class="text-accent">{ctx.tool.data.entity_type}</span></BaseTool>),- renderResponse: (ctx) => (- <BaseTool renderContext={ctx.renderContext} type="response">- {ctx.toolResponse.tool.data.message}- </BaseTool>- ),});export const getEntityPropertiesHandler = getHandler;diff --git a/js/app/packages/core/component/AI/component/tool/ReadContent.tsx b/js/app/packages/core/component/AI/component/tool/ReadContent.tsxindex 3bbb81a247..b32a99fff4 100644--- a/js/app/packages/core/component/AI/component/tool/ReadContent.tsx+++ b/js/app/packages/core/component/AI/component/tool/ReadContent.tsx@@ -5,15 +5,14 @@ import { createToolRenderer } from './ToolRenderer';const handler = createToolRenderer({name: 'ReadContent',- renderCall: (ctx) => (+ render: (ctx) => (<BaseTool icon={FileText} renderContext={ctx.renderContext} type="call"><div class="flex flex-row gap-2">- <div> Read </div>+ <div>Read</div><ItemPreview id={ctx.tool.data.documentId} type="document" /></div></BaseTool>),- renderResponse: (_) => undefined,});export const readContentHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/ReadMetadata.tsx b/js/app/packages/core/component/AI/component/tool/ReadMetadata.tsxindex 5d0d1eae44..e89d1148a6 100644--- a/js/app/packages/core/component/AI/component/tool/ReadMetadata.tsx+++ b/js/app/packages/core/component/AI/component/tool/ReadMetadata.tsx@@ -5,15 +5,14 @@ import { createToolRenderer } from './ToolRenderer';const handler = createToolRenderer({name: 'ReadMetadata',- renderCall: (ctx) => (+ render: (ctx) => (<BaseTool icon={Info} renderContext={ctx.renderContext} type="call"><div class="flex flex-row gap-2">- <div>Get info of </div>+ <div>Read metadata</div><ItemPreview id={ctx.tool.data.documentId} type="document" /></div></BaseTool>),- renderResponse: (_) => undefined,});export const readMetadataHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/ReadThread.tsx b/js/app/packages/core/component/AI/component/tool/ReadThread.tsxindex a60cff108c..eb904ab759 100644--- a/js/app/packages/core/component/AI/component/tool/ReadThread.tsx+++ b/js/app/packages/core/component/AI/component/tool/ReadThread.tsx@@ -4,7 +4,7 @@ import { createToolRenderer } from './ToolRenderer';const handler = createToolRenderer({name: 'ReadThread',- renderCall: (ctx) => (+ render: (ctx) => (<BaseTool type="call" icon={EyeIcon} renderContext={ctx.renderContext}>Read{' '}<span class="text-accent">@@ -13,7 +13,6 @@ const handler = createToolRenderer({</span></BaseTool>),- renderResponse: (_) => undefined,});export const readThreadHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/Search.tsx b/js/app/packages/core/component/AI/component/tool/Search.tsxindex 7b95c36417..a3a1f75910 100644--- a/js/app/packages/core/component/AI/component/tool/Search.tsx+++ b/js/app/packages/core/component/AI/component/tool/Search.tsx@@ -1,14 +1,12 @@-import type { ToolContext } from '@service-cognition/generated/tools/tool';import { fileTypeToBlockName } from '@core/constant/allBlocks';-import ChevronDown from '@icon/regular/caret-down.svg?component-solid';-import ChevronUp from '@icon/regular/caret-up.svg?component-solid';+import CaretRight from '@icon/regular/caret-right.svg?component-solid';import MagnifyingGlass from '@phosphor-icons/core/regular/magnifying-glass.svg';import type { NamedTool } from '@service-cognition/generated/tools/tool';import { useSplitLayout } from 'app/component/split-layout/layout';import { useChannelsContext } from '@core/context/channels';import { createMemo, createSignal, For, Show } from 'solid-js';import { BaseTool } from './BaseTool';-import { createToolRenderer } from './ToolRenderer';+import { createToolRenderer, type ToolRenderContext } from './ToolRenderer';import { ListEntity } from '@entity';import type { WithNotification } from '@entity/types/notification';import type {@@ -229,8 +227,6 @@ function searchResultsToEntities(const UnifiedSearchToolResponse = (props: {results: UnifiedSearchResult[];}) => {- const [isExpanded, setIsExpanded] = createSignal(true);-const channelsCtx = useChannelsContext();const entities = createMemo(() =>searchResultsToEntities(props.results, channelsCtx.channelsById())@@ -260,87 +256,95 @@ const UnifiedSearchToolResponse = (props: {};return (- <div>- <Show- when={props.results.length > 0}- fallback={- <div class="flex items-center justify-between w-full text-left p-2 transition-colors">- No Results- </div>- }- >- <button- class={`flex items-center justify-between w-full text-left p-2 hover:bg-hover transition-colors`}- onClick={() => setIsExpanded((e) => !e)}- >- <div class="flex items-center gap-2">- <div class="text-sm font-medium text-ink">- Search Results ({entities().length})- </div>- </div>- <div class="flex items-center gap-1 text-ink-muted">- <Show- when={isExpanded()}- fallback={<ChevronDown class="w-4 h-4" />}- >- <ChevronUp class="w-4 h-4" />- </Show>- </div>- </button>- </Show>-- <Show when={isExpanded()}>- <div class="max-h-[480px] overflow-y-auto">- <For each={entities()}>- {(entity) => {- const clickHandler = getClickHandler(entity);- return (- <ListEntity- entity={entity as WithNotification<EntityData>}- onClick={clickHandler}- />- );- }}- </For>- </div>- </Show>+ <div class="max-h-[480px] overflow-y-auto">+ <For each={entities()}>+ {(entity) => {+ const clickHandler = getClickHandler(entity);+ return (+ <ListEntity+ entity={entity as WithNotification<EntityData>}+ onClick={clickHandler}+ />+ );+ }}+ </For></div>);};function SearchText(props: {- ctx: ToolContext<NamedTool<'ContentSearch' | 'NameSearch', 'call'>>;+ ctx: ToolRenderContext<'ContentSearch' | 'NameSearch'>;}) {const ctx = props.ctx;const queryString ='query' in ctx.tool.data ? ctx.tool.data.query : ctx.tool.data.name;return (- <div>+ <span>Search <span class="text-accent"> {queryString} </span>- </div>+ </span>);}const createHandler = (name: 'NameSearch' | 'ContentSearch') =>createToolRenderer({name,- renderCall: (ctx) => (- <BaseTool- icon={MagnifyingGlass}- renderContext={ctx.renderContext}- type="call"- >- <SearchText ctx={ctx} />- </BaseTool>- ),- renderResponse: (ctx) => (- <BaseTool renderContext={ctx.renderContext} type="response">- <UnifiedSearchToolResponse- results={ctx.toolResponse.tool.data.results}- />- </BaseTool>- ),+ render: (ctx) => {+ const [isExpanded, setIsExpanded] = createSignal(false);+ const results = () => ctx.response?.data.results ?? [];+ const hitCount = () => results().length;+ const hasResults = () => hitCount() > 0;+ const statusText = () => {+ if (!ctx.response) return undefined;+ if (hitCount() === 0) return 'No Results';+ if (hitCount() === 1) return '1 hit';+ return `${hitCount()} hits`;+ };++ return (+ <BaseTool+ icon={MagnifyingGlass}+ renderContext={ctx.renderContext}+ type="call"+ response={+ hasResults() && isExpanded() ? (+ <UnifiedSearchToolResponse results={results()} />+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">+ <div class="flex min-w-0 flex-1 items-center gap-2">+ <SearchText ctx={ctx} />+ </div>+ <div class="flex shrink-0 items-center gap-1">+ <Show when={statusText()}>+ {(text) => (+ <span class="text-xs text-ink-extra-muted">{text()}</span>+ )}+ </Show>+ <Show when={hasResults()}>+ <button+ type="button"+ class="shrink-0 text-ink-muted hover:text-ink p-1"+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ setIsExpanded((expanded) => !expanded);+ }}+ >+ <CaretRight+ class="h-4 w-4 transition-transform"+ classList={{+ 'rotate-90': isExpanded(),+ }}+ />+ </button>+ </Show>+ </div>+ </div>+ </BaseTool>+ );+ },});export const nameSearchHandler = createHandler('NameSearch');diff --git a/js/app/packages/core/component/AI/component/tool/SendEmail.tsx b/js/app/packages/core/component/AI/component/tool/SendEmail.tsxindex 67251d3cd7..e76a7a9555 100644--- a/js/app/packages/core/component/AI/component/tool/SendEmail.tsx+++ b/js/app/packages/core/component/AI/component/tool/SendEmail.tsx@@ -1,14 +1,14 @@-import { ComposeTool } from './email/ChatCompose';import { useSplitLayout } from '@app/component/split-layout/layout';import { ItemPreview } from '@core/component/ItemPreview';import { EntityIcon } from '@core/component/EntityIcon';-import type { NamedTool } from '@service-cognition/generated/tools/tool';import CaretRight from '@icon/regular/caret-right.svg';-import { Match, Switch } from 'solid-js';+import type { NamedTool } from '@service-cognition/generated/tools/tool';+import type { SendEmail } from '@service-cognition/generated/tools/types';+import { Show, Match, Switch } from 'solid-js';+import { cn } from '@ui/utils/classname';import { BaseTool } from './BaseTool';import { createToolRenderer } from './ToolRenderer';-import { cn } from '@ui/utils/classname';-import type { SendEmail } from '@service-cognition/generated/tools/types';+import { ComposeTool } from './email/ChatCompose';type SendEmailResponse = NamedTool<'SendEmail', 'response'>['data'];@@ -29,7 +29,7 @@ function getRecipientsLabel(data: SendEmail) {return `${labels[0]}, ${labels[1]}, +${labels.length - 2} more`;}-function getUserAction(response: SendEmailResponse) {+function getUserAction(response: SendEmailResponse | undefined) {if (typeof response === 'object' &&response !== null &&@@ -41,7 +41,7 @@ function getUserAction(response: SendEmailResponse) {return null;}-function getSentResponse(response: SendEmailResponse) {+function getSentResponse(response: SendEmailResponse | undefined) {const userAction = getUserAction(response);if (typeof userAction === 'object' &&@@ -54,7 +54,7 @@ function getSentResponse(response: SendEmailResponse) {return null;}-function getDraftResponse(response: SendEmailResponse) {+function getDraftResponse(response: SendEmailResponse | undefined) {const userAction = getUserAction(response);if (typeof userAction === 'object' &&@@ -179,61 +179,63 @@ function DraftEmailResponse(props: {const handler = createToolRenderer({name: 'SendEmail',- renderCall: () => undefined,- renderResponse: (ctx) => {- const response = ctx.toolResponse.tool.data;- const args = ctx.toolCall.tool.data;- const userAction = getUserAction(response);- const sentResponse = getSentResponse(response);- const draftResponse = getDraftResponse(response);+ render: (ctx) => {+ const response = () => ctx.response?.data;+ const args = ctx.tool.data;+ const userAction = getUserAction(response());+ const sentResponse = getSentResponse(response());+ const draftResponse = getDraftResponse(response());return (- <Switch>- <Match- when={- response === 'PendingUserExecution' || userAction === 'userEdited'- }- >- <ComposeTool- chatId={ctx.toolResponse.chat_id}- initialData={ctx.toolCall.tool.data}- messageId={ctx.toolResponse.message_id}- toolCallId={ctx.toolCall.tool.id}- streamLocked={ctx.renderContext.isStreaming}- header={- ctx.renderContext.isStreaming ? (- <div class="text-xs text-ink-extra-muted/60">- Waiting for the response to finish before this email can be- edited.- </div>- ) : undefined+ <Show when={ctx.response}>+ <Switch>+ <Match+ when={+ response() === 'PendingUserExecution' ||+ userAction === 'userEdited'}- />- </Match>- <Match when={response === 'Rejected'}>- <BaseTool renderContext={ctx.renderContext} type="response">- Email send rejected- </BaseTool>- </Match>- <Match when={sentResponse}>- <SentEmailResponse- args={args}- chatId={ctx.toolResponse.chat_id}- messageId={ctx.toolResponse.message_id}- renderContext={ctx.renderContext}- threadId={sentResponse!.thread_id}- toolCallId={ctx.toolCall.tool.id}- />- </Match>- <Match when={draftResponse}>- <DraftEmailResponse- args={args}- draftId={draftResponse!.draft_id}- renderContext={ctx.renderContext}- threadId={draftResponse!.thread_id}- />- </Match>- </Switch>+ >+ <ComposeTool+ chatId={ctx.chat_id}+ initialData={ctx.tool.data}+ messageId={ctx.message_id}+ toolCallId={ctx.tool.id}+ streamLocked={ctx.renderContext.isStreaming}+ header={+ ctx.renderContext.isStreaming ? (+ <div class="text-xs text-ink-extra-muted/60">+ Waiting for the response to finish before this email can be+ edited.+ </div>+ ) : undefined+ }+ />+ </Match>+ <Match when={response() === 'Rejected'}>+ <BaseTool renderContext={ctx.renderContext} type="response">+ Email send rejected+ </BaseTool>+ </Match>+ <Match when={sentResponse}>+ <SentEmailResponse+ args={args}+ chatId={ctx.chat_id}+ messageId={ctx.message_id}+ renderContext={ctx.renderContext}+ threadId={sentResponse!.thread_id}+ toolCallId={ctx.tool.id}+ />+ </Match>+ <Match when={draftResponse}>+ <DraftEmailResponse+ args={args}+ draftId={draftResponse!.draft_id}+ renderContext={ctx.renderContext}+ threadId={draftResponse!.thread_id}+ />+ </Match>+ </Switch>+ </Show>);},});diff --git a/js/app/packages/core/component/AI/component/tool/TextEditorCodeExecution.tsx b/js/app/packages/core/component/AI/component/tool/TextEditorCodeExecution.tsxindex bc3d5cf66c..89861248ac 100644--- a/js/app/packages/core/component/AI/component/tool/TextEditorCodeExecution.tsx+++ b/js/app/packages/core/component/AI/component/tool/TextEditorCodeExecution.tsx@@ -9,9 +9,7 @@ import {isCodeEditorExtensionSupported,} from '@core/util/languageQuery';import { isOk } from '@core/util/maybeResult';-import CaretDown from '@phosphor-icons/core/regular/caret-down.svg';-import CaretRight from '@phosphor-icons/core/regular/caret-right.svg';-import File from '@phosphor-icons/core/regular/file.svg';+import Terminal from '@phosphor-icons/core/regular/terminal.svg';import { cognitionApiServiceClient } from '@service-cognition/client';import type {TextEditorCodeExecutionContent,@@ -20,25 +18,26 @@ import type {import { useSplitLayout } from 'app/component/split-layout/layout';import { createSignal, Match, onMount, Show, Switch } from 'solid-js';-// Type aliases for backwards compatibility with discriminated union variants-type TextEditorCodeExecutionViewResult = TextEditorCodeExecutionResult & {- type: 'text_editor_code_execution_view_result';-};+// Type alias for backwards compatibility with discriminated union varianttype TextEditorCodeExecutionCreateResult = TextEditorCodeExecutionResult & {type: 'text_editor_code_execution_create_result';};-type TextEditorCodeExecutionStrReplaceResult = TextEditorCodeExecutionResult & {- type: 'text_editor_code_execution_str_replace_result';-};+import { BaseTool } from './BaseTool';import { createToolRenderer } from './ToolRenderer';+type FileCreationData = {+ path: string;+ fileText: string;+};+type CreatedFileInfo = {documentId: string;fileName: string;extension: string;};+const toolFileDataMap: Record<string, FileCreationData> = {};const createdFilesMap: Record<string, CreatedFileInfo> = {};function getExtensionFromPath(path: string): string | null {@@ -52,61 +51,6 @@ function getFileNameFromPath(path: string): string {return path.split('/').pop() ?? 'file';}-const MAX_OUTPUT_LINES = 5;--function CodeFence(props: { content: string; maxLines: number }) {- const [expanded, setExpanded] = createSignal(false);-- const lines = () => props.content.split('\n');- const needsTruncation = () => lines().length > props.maxLines;- const displayContent = () => {- if (expanded() || !needsTruncation()) {- return props.content;- }- return lines().slice(0, props.maxLines).join('\n');- };-- return (- <div class="relative">- <Show when={needsTruncation()}>- <button- type="button"- class="text-ink-extra-muted hover:text-ink-muted absolute top-1 right-1 p-1"- onClick={() => setExpanded(!expanded())}- >- <Show when={expanded()} fallback={<CaretRight class="h-4 w-4" />}>- <CaretDown class="h-4 w-4" />- </Show>- </button>- </Show>- <pre- class="text-ink-muted bg-background-secondary overflow-x-auto rounded p-2 pr-8 font-mono text-xs whitespace-pre-wrap"- classList={{- 'max-h-32 overflow-hidden': !expanded() && needsTruncation(),- }}- >- {displayContent()}- </pre>- </div>- );-}--function ViewResult(props: { result: TextEditorCodeExecutionViewResult }) {- const hasContent = () => !!props.result.content?.trim();-- return (- <Show- when={hasContent()}- fallback={<span class="text-ink-muted">Empty file</span>}- >- <CodeFence- content={props.result.content ?? ''}- maxLines={MAX_OUTPUT_LINES}- />- </Show>- );-}-function CreateResult(props: {result: TextEditorCodeExecutionCreateResult;toolId: string;@@ -144,10 +88,7 @@ function CreateResult(props: {};return (- <div class="flex items-center gap-2">- <span class="text-ink-muted">- {props.result.is_file_update ? 'File updated' : 'File created'}- </span>+ <div class="flex items-center"><Show when={createdFile()}>{(file) => (<button@@ -168,38 +109,12 @@ function CreateResult(props: {);}-function StrReplaceResult(props: {- result: TextEditorCodeExecutionStrReplaceResult;-}) {- const diffContent = () => props.result.lines?.join('\n') ?? '';- const hasContent = () => diffContent().trim().length > 0;-- return (- <Show- when={hasContent()}- fallback={<span class="text-ink-muted">Edit applied</span>}- >- <CodeFence content={diffContent()} maxLines={MAX_OUTPUT_LINES} />- </Show>- );-}--function TextEditorResult(props: {+function InlineTextEditorResult(props: {content: TextEditorCodeExecutionContent;toolId: string;}) {return (<Switch>- <Match- when={- props.content.type === 'text_editor_code_execution_view_result' &&- props.content- }- >- {(result) => (- <ViewResult result={result() as TextEditorCodeExecutionViewResult} />- )}- </Match><Matchwhen={props.content.type === 'text_editor_code_execution_create_result' &&@@ -215,22 +130,22 @@ function TextEditorResult(props: {</Match><Matchwhen={- props.content.type ===- 'text_editor_code_execution_str_replace_result' && props.content+ props.content.type === 'text_editor_code_execution_tool_result_error'}>- {(result) => (- <StrReplaceResult- result={result() as TextEditorCodeExecutionStrReplaceResult}- />- )}+ <span class="text-ink-error">Failed</span>+ </Match>+ <Match+ when={props.content.type === 'text_editor_code_execution_view_result'}+ >+ <span class="text-ink-extra-muted">Viewed file</span></Match><Matchwhen={- props.content.type === 'text_editor_code_execution_tool_result_error'+ props.content.type === 'text_editor_code_execution_str_replace_result'}>- <span class="text-ink-error">Failed</span>+ <span class="text-ink-extra-muted">Edit applied</span></Match></Switch>);@@ -238,20 +153,29 @@ function TextEditorResult(props: {const handler = createToolRenderer({name: 'text_editor_code_execution',+ handleCall: async (ctx) => {+ if (ctx.tool.data.command === 'create' && ctx.tool.data.file_text) {+ toolFileDataMap[ctx.tool.id] = {+ path: ctx.tool.data.path,+ fileText: ctx.tool.data.file_text,+ };+ }+ },handleResponse: async (ctx) => {- const { content } = ctx.toolResponse.tool.data;- const { command, file_text: fileText, path } = ctx.toolCall.tool.data;+ const { content } = ctx.tool.data;+ const fileData = toolFileDataMap[ctx.tool.id];++ if (content.type !== 'text_editor_code_execution_create_result') {+ return;+ }- // Only create macro files for successful file creations- if (- content.type !== 'text_editor_code_execution_create_result' ||- command !== 'create' ||- !fileText- ) {+ if (!fileData) {return;}- const extension = getExtensionFromPath(path);+ delete toolFileDataMap[ctx.tool.id];++ const extension = getExtensionFromPath(fileData.path);if (!extension || !allSupportedExtensionSet.has(extension)) {return;}@@ -261,17 +185,17 @@ const handler = createToolRenderer({return;}- const fileName = getFileNameFromPath(path);+ const fileName = getFileNameFromPath(fileData.path);const result = await createCodeFileFromText({- code: fileText,+ code: fileData.fileText,extension: extension as CodeFileExtension,title: fileName,});if (isOk(result)) {const documentId = result[1].documentId;- createdFilesMap[ctx.toolResponse.tool.id] = {+ createdFilesMap[ctx.tool.id] = {documentId,fileName,extension,@@ -279,26 +203,28 @@ const handler = createToolRenderer({// Persist the mapping to the backend for retrieval on chat refreshawait cognitionApiServiceClient.createIdMapping({- source_id: ctx.toolResponse.tool.id,+ source_id: ctx.tool.id,target_id: JSON.stringify({ documentId, fileName, extension }),});}},- renderCall: (ctx) => (- <BaseTool icon={File} renderContext={ctx.renderContext} type="call">- <code class="text-ink-muted font-mono text-xs">{ctx.tool.data.path}</code>+ render: (ctx) => (+ <BaseTool icon={Terminal} renderContext={ctx.renderContext} type="call">+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">+ <span>Uploaded code</span>+ <Show when={ctx.response}>+ {(response) => (+ <div class="shrink-0">+ <InlineTextEditorResult+ content={response().data.content}+ toolId={ctx.tool.id}+ />+ </div>+ )}+ </Show>+ </div></BaseTool>),- renderResponse: (ctx) => {- return (- <BaseTool renderContext={ctx.renderContext} type="response">- <TextEditorResult- content={ctx.toolResponse.tool.data.content}- toolId={ctx.toolResponse.tool.id}- />- </BaseTool>- );- },});export const textEditorCodeExecutionHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/ToolRenderer.tsx b/js/app/packages/core/component/AI/component/tool/ToolRenderer.tsxindex fad307603d..159eaa08c3 100644--- a/js/app/packages/core/component/AI/component/tool/ToolRenderer.tsx+++ b/js/app/packages/core/component/AI/component/tool/ToolRenderer.tsx@@ -1,7 +1,6 @@import type { Component } from 'solid-js';import type {NamedTool,- ToolContext,ToolName,} from '@service-cognition/generated/tools/tool';@@ -11,70 +10,51 @@ export type RenderContext = {};};-export type ToolCallContext<TName extends ToolName = ToolName> = ToolContext<- NamedTool<TName, 'call'>->;--export type ToolResponseContext<TName extends ToolName = ToolName> =- ToolContext<NamedTool<TName, 'response'>>;+export type ToolContext<TTool extends NamedTool = NamedTool> = {+ tool: TTool;+ chat_id: string;+ message_id: string;+ part_index: number;+ isComplete: boolean;+};-export type ToolResponseRenderContext<TName extends ToolName = ToolName> = {- toolCall: ToolCallContext<TName>;- toolResponse: ToolResponseContext<TName>;+export type ToolRenderContext<TName extends ToolName = ToolName> = ToolContext<+ NamedTool<TName, 'call'>+> & {+ response?: NamedTool<TName, 'response'>;};-export interface ToolRendererHandler<- TContext extends Record<string, unknown>,- TRenderContext extends Record<string, unknown>,-> {- handle?: (context: TContext) => void | Promise<void>;- render?: Component<TContext & TRenderContext>;-}+export type ToolHandlerMap<TRenderContext> = {+ [K in ToolName]: ToolHandler<K, TRenderContext>;+};-export interface AnyToolRenderer<- TRenderContext extends Record<string, unknown>,-> {- call: ToolRendererHandler<ToolCallContext, TRenderContext>;- response: ToolRendererHandler<ToolResponseRenderContext, TRenderContext>;+export interface ToolHandler<TName extends ToolName, TRenderContext> {+ handleCall?: (+ context: ToolContext<NamedTool<TName, 'call'>>+ ) => void | Promise<void>;+ handleResponse?: (+ context: ToolContext<NamedTool<TName, 'response'>>+ ) => void | Promise<void>;+ render: Component<ToolRenderContext<TName> & TRenderContext>;}-export type ToolRendererMap<TRenderContext extends Record<string, unknown>> =- Record<ToolName, AnyToolRenderer<TRenderContext>>;--export interface ToolRendererConfig<- TName extends ToolName,- TRenderContext extends Record<string, unknown>,-> {+export interface ToolRendererConfig<TName extends ToolName, TRenderContext> {name: TName;- renderCall: Component<ToolCallContext<TName> & TRenderContext>;- renderResponse: Component<ToolResponseRenderContext<TName> & TRenderContext>;- handleCall?: (context: ToolCallContext<TName>) => void | Promise<void>;+ render: Component<ToolRenderContext<TName> & TRenderContext>;+ handleCall?: (+ context: ToolContext<NamedTool<TName, 'call'>>+ ) => void | Promise<void>;handleResponse?: (- context: ToolResponseRenderContext<TName>+ context: ToolContext<NamedTool<TName, 'response'>>) => void | Promise<void>;}export function createToolRenderer<TName extends ToolName>(config: ToolRendererConfig<TName, RenderContext>-): AnyToolRenderer<RenderContext> {- const callHandler: AnyToolRenderer<RenderContext>['call'] = {- render: config.renderCall as Component<ToolCallContext & RenderContext>,- handle: config.handleCall as- | ((context: ToolCallContext) => void | Promise<void>)- | undefined,- };-- const responseHandler: AnyToolRenderer<RenderContext>['response'] = {- render: config.renderResponse as Component<- ToolResponseRenderContext & RenderContext- >,- handle: config.handleResponse as- | ((context: ToolResponseRenderContext) => void | Promise<void>)- | undefined,- };-+) {return {- call: callHandler,- response: responseHandler,+ render: config.render,+ handleCall: config.handleCall,+ handleResponse: config.handleResponse,};}diff --git a/js/app/packages/core/component/AI/component/tool/UpdateThreadLabels.tsx b/js/app/packages/core/component/AI/component/tool/UpdateThreadLabels.tsxindex 5f0c0b9b22..275f8490a1 100644--- a/js/app/packages/core/component/AI/component/tool/UpdateThreadLabels.tsx+++ b/js/app/packages/core/component/AI/component/tool/UpdateThreadLabels.tsx@@ -4,12 +4,11 @@ import { createToolRenderer } from './ToolRenderer';const handler = createToolRenderer({name: 'UpdateThreadLabels',- renderCall: (ctx) => (+ render: (ctx) => (<BaseTool icon={TagSimple} renderContext={ctx.renderContext} type="call">{ctx.tool.data.add ? 'Add' : 'Remove'} label on thread</BaseTool>),- renderResponse: (_) => undefined,});export const updateThreadLabelsHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/WebFetch.tsx b/js/app/packages/core/component/AI/component/tool/WebFetch.tsxindex 97f09c30d2..0aa3a4c22b 100644--- a/js/app/packages/core/component/AI/component/tool/WebFetch.tsx+++ b/js/app/packages/core/component/AI/component/tool/WebFetch.tsx@@ -5,7 +5,7 @@ import { createToolRenderer } from './ToolRenderer';// Runtime type for successful web fetch (schema differs from generated types)const handler = createToolRenderer({name: 'web_fetch',- renderCall: (ctx) => (+ render: (ctx) => (<BaseTool icon={Globe} renderContext={ctx.renderContext} type="call">Fetched{' '}<a@@ -18,7 +18,6 @@ const handler = createToolRenderer({</a></BaseTool>),- renderResponse: (_) => undefined,});export const webFetchHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/WebSearch.tsx b/js/app/packages/core/component/AI/component/tool/WebSearch.tsxindex d9c7a2abc1..da207aaf1d 100644--- a/js/app/packages/core/component/AI/component/tool/WebSearch.tsx+++ b/js/app/packages/core/component/AI/component/tool/WebSearch.tsx@@ -1,25 +1,82 @@-import { UnfurledLinkCollection } from '@core/component/Link';+import { UnfurlLink } from '@core/component/Link';+import CaretRight from '@icon/regular/caret-right.svg?component-solid';import Globe from '@phosphor-icons/core/regular/globe.svg';+import { createSignal, For, Show } from 'solid-js';import { BaseTool } from './BaseTool';import { createToolRenderer } from './ToolRenderer';const handler = createToolRenderer({name: 'web_search',- renderCall: (ctx) => (- <BaseTool icon={Globe} renderContext={ctx.renderContext} type="call">- Searched for <span class="text-accent">{ctx.tool.data.query}</span>- </BaseTool>- ),- renderResponse: (ctx) => (- <BaseTool renderContext={ctx.renderContext} type="response">- <UnfurledLinkCollection- links={ctx.toolResponse.tool.data.content.map((result) => ({- title: result.title,- url: result.url,- }))}- />- </BaseTool>- ),+ render: (ctx) => {+ const [isExpanded, setIsExpanded] = createSignal(false);+ const results = () => ctx.response?.data.content ?? [];+ const hitCount = () => results().length;+ const hasResults = () => hitCount() > 0;+ const statusText = () => {+ if (!ctx.response) return undefined;+ if (hitCount() === 0) return 'No Results';+ if (hitCount() === 1) return '1 result';+ return `${hitCount()} results`;+ };++ return (+ <BaseTool+ icon={Globe}+ renderContext={ctx.renderContext}+ type="call"+ response={+ hasResults() && isExpanded() ? (+ <div class="flex flex-col">+ <For each={results()}>+ {(result) => (+ <UnfurlLink+ unfurled={{+ title: result.title,+ url: result.url,+ }}+ />+ )}+ </For>+ </div>+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">+ <div class="flex min-w-0 flex-1 items-center gap-2">+ <span>+ Searched for{' '}+ <span class="text-accent">{ctx.tool.data.query}</span>+ </span>+ </div>+ <div class="flex shrink-0 items-center gap-1">+ <Show when={statusText()}>+ {(text) => (+ <span class="text-xs text-ink-extra-muted">{text()}</span>+ )}+ </Show>+ <Show when={hasResults()}>+ <button+ type="button"+ class="shrink-0 text-ink-muted hover:text-ink p-1"+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ setIsExpanded((expanded) => !expanded);+ }}+ >+ <CaretRight+ class="h-4 w-4 transition-transform"+ classList={{+ 'rotate-90': isExpanded(),+ }}+ />+ </button>+ </Show>+ </div>+ </div>+ </BaseTool>+ );+ },});export const webSearchHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/handler.tsx b/js/app/packages/core/component/AI/component/tool/handler.tsxindex da31249e2b..f5e35c6afe 100644--- a/js/app/packages/core/component/AI/component/tool/handler.tsx+++ b/js/app/packages/core/component/AI/component/tool/handler.tsx@@ -4,7 +4,6 @@ import {deserializeToolResponse,type ToolName,} from '@service-cognition/generated/tools/tool';-import type { Component } from 'solid-js';import { Dynamic } from 'solid-js/web';import { bashCodeExecutionHandler } from './BashCodeExecution';import { createDocumentHandler } from './CreateDocument';@@ -22,15 +21,15 @@ import { sendEmailHandler } from './SendEmail';import { textEditorCodeExecutionHandler } from './TextEditorCodeExecution';import type {RenderContext,- ToolCallContext,- ToolRendererMap,- ToolResponseRenderContext,+ ToolHandler,+ ToolHandlerMap,+ ToolRenderContext,} from './ToolRenderer';import { updateThreadLabelsHandler } from './UpdateThreadLabels';import { webFetchHandler } from './WebFetch';import { webSearchHandler } from './WebSearch';-const toolHandlers: ToolRendererMap<RenderContext> = {+const toolHandlers: ToolHandlerMap<RenderContext> = {GetEntityProperties: getEntityPropertiesHandler,ListEntities: listEntitiesHandler,bash_code_execution: bashCodeExecutionHandler,@@ -49,185 +48,111 @@ const toolHandlers: ToolRendererMap<RenderContext> = {web_search: webSearchHandler,};-type BaseToolProps = {+type ToolProps = {tool_id: string;+ json: unknown;name: string;+ response?: {+ json: unknown;+ name: string;+ };part_index: number;chat_id: string;message_id: string;+ isComplete: boolean;renderContext: RenderContext;};-type ToolCallProps = BaseToolProps & {- type: 'call';- tool_call: unknown;-};--type ToolResponseProps = BaseToolProps & {- type: 'response';- call_part_index: number;- tool_call: unknown;- tool_response: unknown;+type TriggerToolArgs = Omit<+ ToolProps,+ 'renderContext' | 'response' | 'isComplete'+> & {+ type: 'call' | 'response' | 'error';};-type RenderToolProps = ToolCallProps | ToolResponseProps;--type TriggerToolCallArgs =- | Omit<ToolCallProps, 'renderContext'>- | (Omit<- ToolResponseProps,- 'renderContext' | 'call_part_index' | 'tool_call'- > & {- type: 'response';- });--const pendingToolCalls = new Map<string, ToolCallContext>();--function createCallContext(args: {- tool_id: string;- tool_call: unknown;- name: string;- part_index: number;- chat_id: string;- message_id: string;-}): ToolCallContext | null {+export function RenderTool(props: ToolProps) {const maybeTool = deserializeToolCall({- id: args.tool_id,- json: args.tool_call,- name: args.name as ToolName,+ id: props.tool_id,+ json: props.json,+ name: props.name as ToolName,});-if (isErr(maybeTool)) return null;- return {- chat_id: args.chat_id,- isComplete: true,- message_id: args.message_id,- part_index: args.part_index,- tool: maybeTool[1],+ const tool = maybeTool[1];+ const handler = toolHandlers[tool.name] as ToolHandler<+ ToolName,+ RenderContext+ >;+ const context: Omit<ToolRenderContext<ToolName>, 'response'> = {+ chat_id: props.chat_id,+ message_id: props.message_id,+ part_index: props.part_index,+ tool,+ isComplete: props.isComplete,};-}--function createResponseContext(args: {- tool_id: string;- tool_call: unknown;- tool_response: unknown;- name: string;- call_part_index: number;- part_index: number;- chat_id: string;- message_id: string;-}): ToolResponseRenderContext | null {- const toolCall = createCallContext({- chat_id: args.chat_id,- message_id: args.message_id,- name: args.name,- part_index: args.call_part_index,- tool_call: args.tool_call,- tool_id: args.tool_id,- });- if (!toolCall) return null;+ const response = () => {+ if (!props.response) return undefined;- const maybeToolResponse = deserializeToolResponse({- id: args.tool_id,- json: args.tool_response,- name: args.name as ToolName,- });+ const maybeResponse = deserializeToolResponse({+ id: props.tool_id,+ json: props.response.json,+ name: props.response.name as ToolName,+ });- if (isErr(maybeToolResponse)) return null;-- return {- toolCall,- toolResponse: {- chat_id: args.chat_id,- isComplete: true,- message_id: args.message_id,- part_index: args.part_index,- tool: maybeToolResponse[1],- },+ if (isErr(maybeResponse)) return undefined;+ return maybeResponse[1];};-}--function renderWithContext<TContext extends Record<string, unknown>>(- handler:- | {- render?: Component<TContext & RenderContext>;- }- | undefined,- context: TContext,- renderContext: RenderContext-) {- if (!handler?.render) return null;return (<Dynamiccomponent={handler.render}{...context}+ response={response()}renderContext={{- isStreaming: renderContext.renderContext.isStreaming,+ isStreaming: props.renderContext.renderContext.isStreaming,}}/>);}-export function RenderToolCall(props: ToolCallProps) {- const context = createCallContext(props);- if (!context) return null;-- return renderWithContext(- toolHandlers[context.tool.name].call,- context,- props.renderContext- );-}--export function RenderToolResponse(props: ToolResponseProps) {- const context = createResponseContext(props);- if (!context) return null;-- return renderWithContext(- toolHandlers[context.toolResponse.tool.name].response,- context,- props.renderContext- );-}--export function RenderTool(props: RenderToolProps) {- if (props.type === 'call') {- return <RenderToolCall {...props} />;- }-- return <RenderToolResponse {...props} />;-}--export async function triggerToolCall(args: TriggerToolCallArgs) {- if (args.type === 'call') {- const context = createCallContext(args);- if (!context) return;+export async function triggerToolCall(args: TriggerToolArgs) {+ const { tool_id, json, name, chat_id, message_id, part_index, type } = args;- pendingToolCalls.set(context.tool.id, context);- return toolHandlers[context.tool.name].call.handle?.(context);+ if (type === 'error') {+ return;}- const toolCall = pendingToolCalls.get(args.tool_id);- if (!toolCall) return;-- const context = createResponseContext({- chat_id: args.chat_id,- message_id: args.message_id,- name: args.name,- part_index: args.part_index,- call_part_index: toolCall.part_index,- tool_call: toolCall.tool.data,- tool_response: args.tool_response,- tool_id: args.tool_id,- });-- if (!context) return;+ const maybeTool =+ type === 'call'+ ? deserializeToolCall({+ id: tool_id,+ json,+ name: name as ToolName,+ })+ : deserializeToolResponse({+ id: tool_id,+ json,+ name: name as ToolName,+ });++ if (isErr(maybeTool)) return;++ const tool = maybeTool[1];+ const handler = toolHandlers[tool.name] as ToolHandler<+ ToolName,+ RenderContext+ >;+ const handle = type === 'call' ? handler.handleCall : handler.handleResponse;+ if (!handle) return;++ const context = {+ chat_id,+ message_id,+ part_index,+ tool,+ isComplete: type !== 'call',+ };- pendingToolCalls.delete(args.tool_id);- return toolHandlers[context.toolResponse.tool.name].response.handle?.(- context- );+ return handle(context as never);}diff --git a/js/app/packages/core/component/AI/signal/tool.ts b/js/app/packages/core/component/AI/signal/tool.tsindex d70e76dd80..dfcecb4d9c 100644--- a/js/app/packages/core/component/AI/signal/tool.ts+++ b/js/app/packages/core/component/AI/signal/tool.ts@@ -21,11 +21,11 @@ export function registerToolHandler(stream: () => StreamLike | undefined) {) {await triggerToolCall({chat_id: latest.chat_id,+ json: latest.content.json,message_id: latest.message_id,name: latest.content.name,part_index: -1,tool_id: latest.content.id,- tool_call: latest.content.json,type: 'call',});} else if (@@ -34,11 +34,11 @@ export function registerToolHandler(stream: () => StreamLike | undefined) {) {await triggerToolCall({chat_id: latest.chat_id,+ json: latest.content.json,message_id: latest.message_id,name: latest.content.name,part_index: -1,tool_id: latest.content.id,- tool_response: latest.content.json,type: 'response',});}diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts b/js/app/packages/service-clients/service-cognition/generated/tools/tool.tsindex 471e90421e..2cbdec4bba 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts@@ -4,7 +4,6 @@*/import { err, type MaybeResult, ok } from 'core/util/maybeResult';-import type { Component } from 'solid-js';import * as schemas from './schemas';import type * as types from './types';@@ -181,19 +180,6 @@ export type NamedTool<data: ToolDataMap[TName][TDirection];};-export type ToolContext<TTool extends NamedTool = NamedTool> = {- tool: TTool;- chat_id: string;- message_id: string;- part_index: number;- isComplete: boolean;-};--export interface ToolHandler<T extends NamedTool, RenderContext> {- handle?: (context: ToolContext<T>) => void | Promise<void>;- render?: Component<ToolContext<T> & RenderContext>;-}-function deserializeTool<T extends NamedTool>(tool: NamedRawTool,direction: 'call' | 'response'@@ -224,10 +210,3 @@ export function deserializeToolResponse(): MaybeResult<'parse_error' | 'not_found', NamedTool<ToolName, 'response'>> {return deserializeTool(tool, 'response');}--export type ToolHandlerMap<RenderContext> = {- [K in ToolName]: {- call: ToolHandler<NamedTool<K, 'call'>, RenderContext>;- response: ToolHandler<NamedTool<K, 'response'>, RenderContext>;- };-};diff --git a/js/app/scripts/generate-dcs-tools.ts b/js/app/scripts/generate-dcs-tools.tsindex 663521555a..e242c20ffd 100644--- a/js/app/scripts/generate-dcs-tools.ts+++ b/js/app/scripts/generate-dcs-tools.ts@@ -4,19 +4,22 @@// This script generates AI tool schemas by running the local Rust binary// and generates TS types for use in the chat block and service package.-import { mkdir, readFile } from "node:fs/promises";-import * as path from "node:path";-import { join } from "node:path";-import { $ } from "bun";-import { resolveRefs } from "json-refs";-import { compile } from "json-schema-to-typescript";-import { jsonSchemaToZod } from "json-schema-to-zod";-import { z } from "zod";-import { documentCognitionBase } from "./services";--const rustCloudStorageDir = path.resolve(import.meta.dirname, "../../../rust/cloud-storage");-const aiToolsDir = path.join(rustCloudStorageDir, "ai_tools");-const schemasJsonPath = path.join(aiToolsDir, "schemas", "tools.json");+import { mkdir, readFile } from 'node:fs/promises';+import * as path from 'node:path';+import { join } from 'node:path';+import { $ } from 'bun';+import { resolveRefs } from 'json-refs';+import { compile } from 'json-schema-to-typescript';+import { jsonSchemaToZod } from 'json-schema-to-zod';+import { z } from 'zod';+import { documentCognitionBase } from './services';++const rustCloudStorageDir = path.resolve(+ import.meta.dirname,+ '../../../rust/cloud-storage'+);+const aiToolsDir = path.join(rustCloudStorageDir, 'ai_tools');+const schemasJsonPath = path.join(aiToolsDir, 'schemas', 'tools.json');/*** Pre-process JSON Schema to convert $ref with sibling properties into allOf.@@ -24,58 +27,58 @@ const schemasJsonPath = path.join(aiToolsDir, "schemas", "tools.json");* so we need to restructure the schema to use allOf for proper composition.*/function preprocessSchemaForRefs(schema: unknown): unknown {- if (schema === null || typeof schema !== "object") {- return schema;- }-- if (Array.isArray(schema)) {- return schema.map(preprocessSchemaForRefs);- }-- const obj = schema as Record<string, unknown>;- const result: Record<string, unknown> = {};-- // Check if this object has $ref along with other schema keywords- if ("$ref" in obj) {- const siblingKeys = Object.keys(obj).filter(- (k) => k !== "$ref" && k !== "$schema" && k !== "description",- );-- if (siblingKeys.length > 0) {- // Convert to allOf structure: merge $ref schema with sibling properties- const refPart = { $ref: obj.$ref };- const siblingPart: Record<string, unknown> = {};-- for (const key of siblingKeys) {- siblingPart[key] = preprocessSchemaForRefs(obj[key]);- }-- // Keep description at top level if present- if ("description" in obj) {- result.description = obj.description;- }-- result.allOf = [refPart, siblingPart];- return result;- }- }-- // Recursively process all properties- for (const [key, value] of Object.entries(obj)) {- result[key] = preprocessSchemaForRefs(value);- }-- return result;+ if (schema === null || typeof schema !== 'object') {+ return schema;+ }++ if (Array.isArray(schema)) {+ return schema.map(preprocessSchemaForRefs);+ }++ const obj = schema as Record<string, unknown>;+ const result: Record<string, unknown> = {};++ // Check if this object has $ref along with other schema keywords+ if ('$ref' in obj) {+ const siblingKeys = Object.keys(obj).filter(+ (k) => k !== '$ref' && k !== '$schema' && k !== 'description'+ );++ if (siblingKeys.length > 0) {+ // Convert to allOf structure: merge $ref schema with sibling properties+ const refPart = { $ref: obj.$ref };+ const siblingPart: Record<string, unknown> = {};++ for (const key of siblingKeys) {+ siblingPart[key] = preprocessSchemaForRefs(obj[key]);+ }++ // Keep description at top level if present+ if ('description' in obj) {+ result.description = obj.description;+ }++ result.allOf = [refPart, siblingPart];+ return result;+ }+ }++ // Recursively process all properties+ for (const [key, value] of Object.entries(obj)) {+ result[key] = preprocessSchemaForRefs(value);+ }++ return result;}const serviceDir = path.resolve(- import.meta.dirname,- documentCognitionBase.output,+ import.meta.dirname,+ documentCognitionBase.output);-const outputDir = join(serviceDir, "generated", "tools");-const schemasFile = join(outputDir, "schemas.ts");-const typesFile = join(outputDir, "types.ts");-const toolFile = join(outputDir, "tool.ts");+const outputDir = join(serviceDir, 'generated', 'tools');+const schemasFile = join(outputDir, 'schemas.ts');+const typesFile = join(outputDir, 'types.ts');+const toolFile = join(outputDir, 'tool.ts');await $`rm ${schemasFile} ${toolFile} ${typesFile}|| true`;@@ -87,88 +90,93 @@ const warning = `/* Generated by scripts/generate-dcs-tools.tsawait mkdir(outputDir, { recursive: true });const AiToolsResponseSchema = z.object({- schemas: z.array(- z.object({- name: z.string(),- inputSchema: z.any(),- outputSchema: z.any(),- }),- ),+ schemas: z.array(+ z.object({+ name: z.string(),+ inputSchema: z.any(),+ outputSchema: z.any(),+ })+ ),});-type AiToolsResponse = z.infer<typeof AiToolsResponseSchema>["schemas"];+type AiToolsResponse = z.infer<typeof AiToolsResponseSchema>['schemas'];async function buildAndRunSchemaGenerator(): Promise<void> {- console.log("Building gen_tool_schemas binary...");- await $`cd ${rustCloudStorageDir} && SQLX_OFFLINE=true cargo build --bin gen_tool_schemas`;- console.log("Build complete.");-- // Remove existing schemas dir if it exists (the binary expects to create it)- await $`rm -rf ${path.join(aiToolsDir, "schemas")}`.quiet();-- console.log("Running gen_tool_schemas...");- const binaryPath = path.join(rustCloudStorageDir, "target", "debug", "gen_tool_schemas");- await $`cd ${aiToolsDir} && ${binaryPath}`;- console.log("Schema generation complete.");+ console.log('Building gen_tool_schemas binary...');+ await $`cd ${rustCloudStorageDir} && SQLX_OFFLINE=true cargo build --bin gen_tool_schemas`;+ console.log('Build complete.');++ // Remove existing schemas dir if it exists (the binary expects to create it)+ await $`rm -rf ${path.join(aiToolsDir, 'schemas')}`.quiet();++ console.log('Running gen_tool_schemas...');+ const binaryPath = path.join(+ rustCloudStorageDir,+ 'target',+ 'debug',+ 'gen_tool_schemas'+ );+ await $`cd ${aiToolsDir} && ${binaryPath}`;+ console.log('Schema generation complete.');}async function fetchAIToolsSchemas(): Promise<AiToolsResponse> {- try {- // Build and run the Rust binary to generate schemas- await buildAndRunSchemaGenerator();-- const data = await readFile(schemasJsonPath, "utf-8");- const parsed = AiToolsResponseSchema.parse(JSON.parse(data));- console.log(`Successfully loaded ${parsed.schemas.length} AI tool schemas`);- return parsed.schemas;- } catch (error) {- console.error("Failed to load AI tools schemas:", error);- throw error;- }+ try {+ // Build and run the Rust binary to generate schemas+ await buildAndRunSchemaGenerator();++ const data = await readFile(schemasJsonPath, 'utf-8');+ const parsed = AiToolsResponseSchema.parse(JSON.parse(data));+ console.log(`Successfully loaded ${parsed.schemas.length} AI tool schemas`);+ return parsed.schemas;+ } catch (error) {+ console.error('Failed to load AI tools schemas:', error);+ throw error;+ }}async function generateSchemasFile(tools: AiToolsResponse) {- // Generate all schemas, deduplicating by title- const generatedSchemas = new Set<string>();- const content: Array<string> = [];-- for (const tool of tools) {- // jsonSchemaToZod with name option generates a proper export- // Preprocess to handle $ref with sibling properties- const preprocessedInput = preprocessSchemaForRefs(tool.inputSchema);- const { resolved: inputSchema } = await resolveRefs(preprocessedInput);- if (!generatedSchemas.has(inputSchema.title)) {- const inputCode = jsonSchemaToZod(inputSchema, {- module: "esm",- name: inputSchema.title,- withoutDescribes: true,- noImport: true,- });- content.push(inputCode);- generatedSchemas.add(inputSchema.title);- }-- const preprocessedOutput = preprocessSchemaForRefs(tool.outputSchema);- const { resolved: outputSchema } = await resolveRefs(preprocessedOutput);- if (!generatedSchemas.has(outputSchema.title)) {- const outputCode = jsonSchemaToZod(outputSchema, {- module: "esm",- name: outputSchema.title,- withoutDescribes: true,- noImport: true,- });- content.push(outputCode);- generatedSchemas.add(outputSchema.title);- }- }-- const contents = `${warning}+ // Generate all schemas, deduplicating by title+ const generatedSchemas = new Set<string>();+ const content: Array<string> = [];++ for (const tool of tools) {+ // jsonSchemaToZod with name option generates a proper export+ // Preprocess to handle $ref with sibling properties+ const preprocessedInput = preprocessSchemaForRefs(tool.inputSchema);+ const { resolved: inputSchema } = await resolveRefs(preprocessedInput);+ if (!generatedSchemas.has(inputSchema.title)) {+ const inputCode = jsonSchemaToZod(inputSchema, {+ module: 'esm',+ name: inputSchema.title,+ withoutDescribes: true,+ noImport: true,+ });+ content.push(inputCode);+ generatedSchemas.add(inputSchema.title);+ }++ const preprocessedOutput = preprocessSchemaForRefs(tool.outputSchema);+ const { resolved: outputSchema } = await resolveRefs(preprocessedOutput);+ if (!generatedSchemas.has(outputSchema.title)) {+ const outputCode = jsonSchemaToZod(outputSchema, {+ module: 'esm',+ name: outputSchema.title,+ withoutDescribes: true,+ noImport: true,+ });+ content.push(outputCode);+ generatedSchemas.add(outputSchema.title);+ }+ }++ const contents = `${warning}import { z } from 'zod';-${content.join("\n\n")}+${content.join('\n\n')}`;- await Bun.write(schemasFile, contents);+ await Bun.write(schemasFile, contents);}/**@@ -177,160 +185,159 @@ ${content.join("\n\n")}* when multiple schemas reference the same type.*/function deduplicateTypes(code: string): string {- const seenTypes = new Set<string>();- const lines = code.split("\n");- const result: string[] = [];- let skipUntilNextExport = false;- let braceCount = 0;-- for (let i = 0; i < lines.length; i++) {- const line = lines[i];-- // Check if we're starting a new export type or interface- const typeMatch = line.match(- /^export\s+(type|interface)\s+(\w+)(?:\s*=|\s*\{|\s*$)/,- );-- if (typeMatch && !skipUntilNextExport) {- const typeName = typeMatch[2];-- if (seenTypes.has(typeName)) {- // Skip this duplicate type definition- skipUntilNextExport = true;- braceCount = 0;- // Count opening braces on this line- braceCount += (line.match(/\{/g) || []).length;- braceCount -= (line.match(/\}/g) || []).length;- // If it's a type alias (ends with ;), skip just this line- if (line.includes(";") && braceCount === 0) {- skipUntilNextExport = false;- }- continue;- }- seenTypes.add(typeName);- }-- if (skipUntilNextExport) {- // Count braces to know when the type/interface ends- braceCount += (line.match(/\{/g) || []).length;- braceCount -= (line.match(/\}/g) || []).length;-- // For type aliases, check if line ends with semicolon at brace level 0- if (braceCount <= 0 && (line.includes(";") || line.trim() === "}")) {- skipUntilNextExport = false;- }- continue;- }-- result.push(line);- }-- return result.join("\n");+ const seenTypes = new Set<string>();+ const lines = code.split('\n');+ const result: string[] = [];+ let skipUntilNextExport = false;+ let braceCount = 0;++ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];++ // Check if we're starting a new export type or interface+ const typeMatch = line.match(+ /^export\s+(type|interface)\s+(\w+)(?:\s*=|\s*\{|\s*$)/+ );++ if (typeMatch && !skipUntilNextExport) {+ const typeName = typeMatch[2];++ if (seenTypes.has(typeName)) {+ // Skip this duplicate type definition+ skipUntilNextExport = true;+ braceCount = 0;+ // Count opening braces on this line+ braceCount += (line.match(/\{/g) || []).length;+ braceCount -= (line.match(/\}/g) || []).length;+ // If it's a type alias (ends with ;), skip just this line+ if (line.includes(';') && braceCount === 0) {+ skipUntilNextExport = false;+ }+ continue;+ }+ seenTypes.add(typeName);+ }++ if (skipUntilNextExport) {+ // Count braces to know when the type/interface ends+ braceCount += (line.match(/\{/g) || []).length;+ braceCount -= (line.match(/\}/g) || []).length;++ // For type aliases, check if line ends with semicolon at brace level 0+ if (braceCount <= 0 && (line.includes(';') || line.trim() === '}')) {+ skipUntilNextExport = false;+ }+ continue;+ }++ result.push(line);+ }++ return result.join('\n');}async function generateToolTypesFile(tools: AiToolsResponse) {- // Generate all schemas, deduplicating by title- const generatedTypes = new Set<string>();- const content: Array<string> = [];-- for (const tool of tools) {- // Preprocess to handle $ref with sibling properties- const preprocessedInput = preprocessSchemaForRefs(tool.inputSchema);- if (!generatedTypes.has(tool.inputSchema.title)) {- const inputCode = await compile(- preprocessedInput,- tool.inputSchema.title,- {- // override top level name for export- customName: (schema) => {- if (schema.title) {- console.log(`Using schema title: ${schema.title}`);- return schema.title;- }- },- additionalProperties: false,- style: {- singleQuote: true,- },- },- );- content.push(inputCode);- generatedTypes.add(tool.inputSchema.title);- }-- const preprocessedOutput = preprocessSchemaForRefs(tool.outputSchema);- if (!generatedTypes.has(tool.outputSchema.title)) {- const outputCode = await compile(- preprocessedOutput,- tool.outputSchema.title,- {- // override top level name for export- customName: (schema) => {- if (schema.title) {- console.log(`Using schema title: ${schema.title}`);- return schema.title;- }- return undefined;- },- additionalProperties: false,- style: {- singleQuote: true,- },- },- );- content.push(outputCode);- generatedTypes.add(tool.outputSchema.title);- }- }-- // Deduplicate nested types that may have been generated multiple times- const rawContents = `${warning}-${content.join("\n\n")}+ // Generate all schemas, deduplicating by title+ const generatedTypes = new Set<string>();+ const content: Array<string> = [];++ for (const tool of tools) {+ // Preprocess to handle $ref with sibling properties+ const preprocessedInput = preprocessSchemaForRefs(tool.inputSchema);+ if (!generatedTypes.has(tool.inputSchema.title)) {+ const inputCode = await compile(+ preprocessedInput,+ tool.inputSchema.title,+ {+ // override top level name for export+ customName: (schema) => {+ if (schema.title) {+ console.log(`Using schema title: ${schema.title}`);+ return schema.title;+ }+ },+ additionalProperties: false,+ style: {+ singleQuote: true,+ },+ }+ );+ content.push(inputCode);+ generatedTypes.add(tool.inputSchema.title);+ }++ const preprocessedOutput = preprocessSchemaForRefs(tool.outputSchema);+ if (!generatedTypes.has(tool.outputSchema.title)) {+ const outputCode = await compile(+ preprocessedOutput,+ tool.outputSchema.title,+ {+ // override top level name for export+ customName: (schema) => {+ if (schema.title) {+ console.log(`Using schema title: ${schema.title}`);+ return schema.title;+ }+ return undefined;+ },+ additionalProperties: false,+ style: {+ singleQuote: true,+ },+ }+ );+ content.push(outputCode);+ generatedTypes.add(tool.outputSchema.title);+ }+ }++ // Deduplicate nested types that may have been generated multiple times+ const rawContents = `${warning}+${content.join('\n\n')}`;- const deduplicatedContents = deduplicateTypes(rawContents);+ const deduplicatedContents = deduplicateTypes(rawContents);- await Bun.write(typesFile, deduplicatedContents);+ await Bun.write(typesFile, deduplicatedContents);}async function generateToolsFile(tools: AiToolsResponse) {- // Resolve schemas to get titles- const toolsWithTitles = await Promise.all(- tools.map(async (tool) => {- const preprocessedInput = preprocessSchemaForRefs(tool.inputSchema);- const preprocessedOutput = preprocessSchemaForRefs(tool.outputSchema);- const { resolved: inputSchema } = await resolveRefs(preprocessedInput);- const { resolved: outputSchema } = await resolveRefs(preprocessedOutput);- return {- name: tool.name,- inputTitle: inputSchema.title,- outputTitle: outputSchema.title,- };- }),- );-- const contents = `${warning}+ // Resolve schemas to get titles+ const toolsWithTitles = await Promise.all(+ tools.map(async (tool) => {+ const preprocessedInput = preprocessSchemaForRefs(tool.inputSchema);+ const preprocessedOutput = preprocessSchemaForRefs(tool.outputSchema);+ const { resolved: inputSchema } = await resolveRefs(preprocessedInput);+ const { resolved: outputSchema } = await resolveRefs(preprocessedOutput);+ return {+ name: tool.name,+ inputTitle: inputSchema.title,+ outputTitle: outputSchema.title,+ };+ })+ );++ const contents = `${warning}import { err, type MaybeResult, ok } from 'core/util/maybeResult';-import type { Component } from 'solid-js';import * as schemas from './schemas';import type * as types from './types';type ToolParserMap = {${toolsWithTitles- .map(- (tool) =>- `${tool.name}: { call: types.${tool.inputTitle}, response: types.${tool.outputTitle} }`,- )- .join("\n")}+ .map(+ (tool) =>+ `${tool.name}: { call: types.${tool.inputTitle}, response: types.${tool.outputTitle} }`+ )+ .join('\n')}};const toolParserMap = {${toolsWithTitles- .map(- (tool) =>- `${tool.name}: { call: schemas.${tool.inputTitle}, response: schemas.${tool.outputTitle} }`,- )- .join(",\n")}+ .map(+ (tool) =>+ `${tool.name}: { call: schemas.${tool.inputTitle}, response: schemas.${tool.outputTitle} }`+ )+ .join(',\n')}};export type ToolName = keyof ToolParserMap;@@ -343,11 +350,11 @@ type NamedRawTool = {type ToolDataMap = {${toolsWithTitles- .map(- (tool) =>- `${tool.name}: { call: types.${tool.inputTitle}, response: types.${tool.outputTitle} }`,- )- .join(";\n")};+ .map(+ (tool) =>+ `${tool.name}: { call: types.${tool.inputTitle}, response: types.${tool.outputTitle} }`+ )+ .join(';\n')};};export type NamedTool<@@ -359,19 +366,6 @@ export type NamedTool<data: ToolDataMap[TName][TDirection];};-export type ToolContext<TTool extends NamedTool = NamedTool> = {- tool: TTool;- chat_id: string;- message_id: string;- part_index: number;- isComplete: boolean;-};--export interface ToolHandler<T extends NamedTool, RenderContext> {- handle?: (context: ToolContext<T>) => void | Promise<void>;- render?: Component<ToolContext<T> & RenderContext>;-}-function deserializeTool<T extends NamedTool>(tool: NamedRawTool,direction: 'call' | 'response'@@ -402,15 +396,8 @@ export function deserializeToolResponse(): MaybeResult<'parse_error' | 'not_found', NamedTool<ToolName, 'response'>> {return deserializeTool(tool, 'response');}--export type ToolHandlerMap<RenderContext>= {- [K in ToolName]: {- call: ToolHandler<NamedTool<K, 'call'>,RenderContext>;- response: ToolHandler<NamedTool<K, 'response'>, RenderContext>;- };-};`;- await Bun.write(toolFile, contents);+ await Bun.write(toolFile, contents);}// Fetch AI tools schemas@@ -423,16 +410,20 @@ await generateToolsFile(tools);await generateToolTypesFile(tools);// On NixOS, the npm-installed biome binary doesn't work due to dynamic linking issues.// We detect NixOS and use the system biome instead.-const isNixOS = process.env.NIX_PATH !== undefined || (await Bun.file("/etc/os-release").exists() && (await Bun.file("/etc/os-release").text()).includes("NixOS"));+const isNixOS =+ process.env.NIX_PATH !== undefined ||+ ((await Bun.file('/etc/os-release').exists()) &&+ (await Bun.file('/etc/os-release').text()).includes('NixOS'));if (isNixOS) {- const systemBiomePath = await $`bash -c 'PATH=$(echo "$PATH" | tr ":" "\n" | grep -v node_modules | tr "\n" ":") which biome'`.text();- await $`${systemBiomePath.trim()} format --write --no-errors-on-unmatched ${toolFile} ${schemasFile} ${typesFile}`;+ const systemBiomePath =+ await $`bash -c 'PATH=$(echo "$PATH" | tr ":" "\n" | grep -v node_modules | tr "\n" ":") which biome'`.text();+ await $`${systemBiomePath.trim()} format --write --no-errors-on-unmatched ${toolFile} ${schemasFile} ${typesFile}`;} else {- await $`biome format --write --no-errors-on-unmatched ${toolFile} ${schemasFile} ${typesFile}`;+ await $`biome format --write --no-errors-on-unmatched ${toolFile} ${schemasFile} ${typesFile}`;}console.log(- `Generated AI tools types at: ${serviceDir}/generated/tools/tools.ts`,+ `Generated AI tools types at: ${serviceDir}/generated/tools/tools.ts`);-console.log("✅ AI tools types generation completed successfully");+console.log('✅ AI tools types generation completed successfully');