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): subagents (#2838)
Eric Hayes08d2018387a1
diff --git a/js/app/packages/core/component/AI/component/tool/Subagent.tsx b/js/app/packages/core/component/AI/component/tool/Subagent.tsxnew file mode 100644index 0000000000..331d446efc--- /dev/null+++ b/js/app/packages/core/component/AI/component/tool/Subagent.tsx@@ -0,0 +1,82 @@+import { ChatMessageMarkdown } from '@core/component/AI/component/message/ChatMessageMarkdown';+import { PulsingStar } from '@entity/components/PulsingStar';+import CaretRight from '@icon/regular/caret-right.svg?component-solid';+import StarIcon from '@macro-icons/wide/star.svg';+import { createSignal, Show } from 'solid-js';+import { createToolRenderer, useToolError } from './ToolRenderer';++const handler = createToolRenderer({+ name: 'Subagent',+ render: (ctx) => {+ const [isExpanded, setIsExpanded] = createSignal(false);+ const error = useToolError();+ const isLoading = () => !ctx.response && !error;+ const result = () => ctx.response?.data.result;+ const hasResult = () => !!result();+ const statusText = () => {+ if (isLoading()) return 'Working…';+ if (error) return undefined;+ return hasResult() ? 'Done' : 'No result';+ };++ return (+ <div+ class="relative text-sm text-ink-extra-muted border-l pl-4 border-edge"+ classList={{ 'opacity-50': !!error }}+ >+ <div class="flex w-full items-center gap-x-2">+ <div class="size-[20px] shrink-0 flex items-center justify-center">+ <Show+ when={!isLoading()}+ fallback={<PulsingStar kind="streamIndicator" animate />}+ >+ <StarIcon class="size-4 text-accent" />+ </Show>+ </div>+ <div class="min-w-0 flex-1 p-2">+ <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 class="truncate">{ctx.tool.data.task}</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={hasResult()}>+ <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>+ </div>+ <Show when={error}>+ <span class="shrink-0 pr-2 text-ink-muted">Failed</span>+ </Show>+ </div>+ <Show when={hasResult() && isExpanded()}>+ <div class="pl-8 mb-2 max-h-[480px] overflow-y-auto text-sm">+ <ChatMessageMarkdown text={result()!} generating={() => false} />+ </div>+ </Show>+ </div>+ );+ },+});++export const subagentHandler = 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 47ee5498ed..3009910953 100644--- a/js/app/packages/core/component/AI/component/tool/handler.tsx+++ b/js/app/packages/core/component/AI/component/tool/handler.tsx@@ -20,6 +20,7 @@ import { readMetadataHandler } from './ReadMetadata';import { readThreadHandler } from './ReadThread';import { contentSearchHandler, nameSearchHandler } from './Search';import { sendEmailHandler } from './SendEmail';+import { subagentHandler } from './Subagent';import { textEditorCodeExecutionHandler } from './TextEditorCodeExecution';import {ToolErrorContext,@@ -47,6 +48,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {ReadMetadata: readMetadataHandler,SendEmail: sendEmailHandler,SetEntityProperty: setEntityPropertyHandler,+ Subagent: subagentHandler,text_editor_code_execution: textEditorCodeExecutionHandler,UpdateThreadLabels: updateThreadLabelsHandler,web_fetch: webFetchHandler,diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.tsindex 6622772ddb..e109bece30 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts@@ -870,6 +870,10 @@ export const SetEntityPropertyResponse = z.object({success: z.boolean(),});+export const Subagent = z.object({ task: z.string() }).strict();++export const SubagentResponse = z.object({ result: z.string() });+export const TextEditorCodeExecutionToolCall = z.object({command: z.string(),file_text: z.union([z.string(), z.null()]).optional(),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 27429352a6..2d14ded4b1 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@@ -49,6 +49,7 @@ type ToolParserMap = {call: types.SetEntityProperty;response: types.SetEntityPropertyResponse;};+ Subagent: { call: types.Subagent; response: types.SubagentResponse };text_editor_code_execution: {call: types.TextEditorCodeExecutionToolCall;response: types.TextEditorCodeExecutionResponse;@@ -112,6 +113,7 @@ const toolParserMap = {call: schemas.SetEntityProperty,response: schemas.SetEntityPropertyResponse,},+ Subagent: { call: schemas.Subagent, response: schemas.SubagentResponse },text_editor_code_execution: {call: schemas.TextEditorCodeExecutionToolCall,response: schemas.TextEditorCodeExecutionResponse,@@ -180,6 +182,7 @@ type ToolDataMap = {call: types.SetEntityProperty;response: types.SetEntityPropertyResponse;};+ Subagent: { call: types.Subagent; response: types.SubagentResponse };text_editor_code_execution: {call: types.TextEditorCodeExecutionToolCall;response: types.TextEditorCodeExecutionResponse;diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.tsindex a8c5a51684..cb83c7c768 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts@@ -1603,6 +1603,34 @@ export interface SetEntityPropertyResponse {success: boolean;}+/* eslint-disable */+/**+ * This file was automatically generated by json-schema-to-typescript.+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,+ * and run json-schema-to-typescript to regenerate this file.+ */++/**+ * Delegate a task to a subagent that can independently use tools to research and complete it. The subagent has access to search, documents, properties, and call tools. Use this for tasks that require multiple tool calls or independent research.+ */+export interface Subagent {+ /**+ * A detailed description of the task for the subagent to complete. Be specific about what information to find or what action to take.+ */+ task: string;+}++/* eslint-disable */+/**+ * This file was automatically generated by json-schema-to-typescript.+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,+ * and run json-schema-to-typescript to regenerate this file.+ */++export interface SubagentResponse {+ result: string;+}+/* eslint-disable *//*** This file was automatically generated by json-schema-to-typescript.diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex cb56fb0b33..29b44f7311 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -109,6 +109,7 @@ dependencies = ["entity_access","entity_access_management","frecency",+ "futures","item_filters","lazy_static","lexical_client",diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.tomlindex fc2d98b3ce..40cc82bb2a 100644--- a/rust/cloud-storage/ai_tools/Cargo.toml+++ b/rust/cloud-storage/ai_tools/Cargo.toml@@ -30,6 +30,7 @@ email_service_client = { path = "../email_service_client" }entity_access = { path = "../entity_access" }entity_access_management = { path = "../entity_access_management" }frecency = { path = "../frecency", features = ["outbound", "postgres"] }+futures.workspace = trueitem_filters = { path = "../item_filters" }lazy_static.workspace = truelexical_client = { path = "../lexical_client" }diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rsindex 098a7b1d56..5878e23730 100644--- a/rust/cloud-storage/ai_tools/src/lib.rs+++ b/rust/cloud-storage/ai_tools/src/lib.rs@@ -10,6 +10,7 @@ pub mod read;mod rewrite;pub mod search;pub mod serde_utils;+mod subagent;mod tool_context;pub mod web_fetch;use call::inbound::toolset::call_toolset;@@ -22,6 +23,7 @@ use properties::inbound::toolset::properties_toolset;use search::web::anthropic_web_search::anthropic_web_search_tool;use soup::inbound::toolset::{ListEntities, SoupToolContext};use std::sync::Arc;+use subagent::Subagent;use web_fetch::anthropic_web_fetch_tool;pub use build_context::build_tool_service_context_from_env;@@ -41,16 +43,23 @@ impl ToolSchemaGenerator for ToolSetWithPrompt {}}-/// These are actually sent to the AI provider-pub fn all_tools() -> ToolSetWithPrompt {- let toolset = AsyncToolSet::new()+/// Toolset available to subagents — everything except email and the Subagent+/// tool itself (subagents cannot create subagents).+pub(crate) fn subagent_toolset() -> AiToolSet {+ AsyncToolSet::new().add_toolset(search_toolset()).add_tool::<ListEntities, SoupToolContext<ToolSoupService, ToolEmailService>>().add_tool::<read::ReadThread, Arc<ToolScribe>>().add_subtoolset::<ToolDocumentToolContext>(document_toolset()).add_subtoolset::<ToolPropertiesToolContext>(properties_toolset())+ .add_subtoolset::<ToolCallToolContext>(call_toolset())+}++/// These are actually sent to the AI provider+pub fn all_tools() -> ToolSetWithPrompt {+ let toolset = subagent_toolset().add_subtoolset::<ToolEmailToolContext>(email_toolset())- .add_subtoolset::<ToolCallToolContext>(call_toolset());+ .add_tool::<Subagent, ToolServiceContext>();let prompt = prompts::TOOLS_PROMPT;let toolset = Arc::new(toolset);ToolSetWithPrompt { toolset, prompt }diff --git a/rust/cloud-storage/ai_tools/src/prompts/mod.rs b/rust/cloud-storage/ai_tools/src/prompts/mod.rsindex 0f99f8fdf5..7c9aca12ee 100644--- a/rust/cloud-storage/ai_tools/src/prompts/mod.rs+++ b/rust/cloud-storage/ai_tools/src/prompts/mod.rs@@ -1,2 +1,2 @@-pub const BASE_PROMPT: &str = include_str!("base.md");-pub const TOOLS_PROMPT: &str = include_str!("all_tools.md");+pub static BASE_PROMPT: &str = include_str!("base.md");+pub static TOOLS_PROMPT: &str = include_str!("all_tools.md");diff --git a/rust/cloud-storage/ai_tools/src/prompts/subagent.md b/rust/cloud-storage/ai_tools/src/prompts/subagent.mdnew file mode 100644index 0000000000..a0daaa872f--- /dev/null+++ b/rust/cloud-storage/ai_tools/src/prompts/subagent.md@@ -0,0 +1,7 @@+You are a subagent completing a delegated task. Use your tools to research, gather information, and complete the task described in the user message.++- Use tools proactively to find the information needed+- Be thorough but concise in your response+- Focus on facts and findings, not formatting+- Do not use citation syntax or mention tags — your output is consumed by another agent, not displayed to users+- Include all relevant details the parent agent needs to answer the user's questiondiff --git a/rust/cloud-storage/ai_tools/src/subagent.rs b/rust/cloud-storage/ai_tools/src/subagent.rsnew file mode 100644index 0000000000..2245f64186--- /dev/null+++ b/rust/cloud-storage/ai_tools/src/subagent.rs@@ -0,0 +1,81 @@+use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolLoop, ToolResult};+use ai::types::{Model, RequestBuilder};+use async_trait::async_trait;+use futures::stream::StreamExt;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use std::sync::Arc;++use crate::{ToolServiceContext, subagent_toolset};++static SUBAGENT_MODEL: Model = Model::Claude46Sonnet;++static SUBAGENT_PROMPT: &str = include_str!("prompts/subagent.md");++#[derive(Debug, Serialize, JsonSchema)]+pub struct SubagentResponse {+ pub result: String,+}++#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(+ title = "Subagent",+ description = "Delegate a task to a subagent that can independently use tools to research and complete it. The subagent has access to search, documents, properties, and call tools. Use this for tasks that require multiple tool calls or independent research."+)]+pub struct Subagent {+ #[schemars(+ description = "A detailed description of the task for the subagent to complete. Be specific about what information to find or what action to take."+ )]+ pub task: String,+}++#[async_trait]+impl AsyncTool<ToolServiceContext> for Subagent {+ type Output = SubagentResponse;++ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]+ async fn call(+ &self,+ service_context: ServiceContext<ToolServiceContext>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ let toolset = Arc::new(subagent_toolset());++ let request = RequestBuilder::new()+ .model(SUBAGENT_MODEL)+ .system_prompt(SUBAGENT_PROMPT)+ .user_message(&self.task)+ .build();++ let mut chat = ToolLoop::new(toolset, service_context.0.clone()).chat();++ {+ let mut stream = chat+ .send_message(+ request,+ request_context.clone(),+ request_context.user_id.to_string(),+ )+ .await+ .map_err(|e| ToolCallError {+ description: "failed to start subagent".to_string(),+ internal_error: e.into(),+ })?;++ while let Some(next) = stream.next().await {+ next.map_err(|e| ToolCallError {+ description: "subagent encountered an error".to_string(),+ internal_error: e.into(),+ })?;+ }+ }++ let messages = chat.get_new_conversation_messages();+ let text = messages+ .last()+ .map(|m| m.content.message_text())+ .unwrap_or_default();++ Ok(SubagentResponse { result: text })+ }+}