Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

7.2 KB
Raw Blame
import { throwOnErr } from '@core/util/result';
import { botKeys, botProfileKeys } from '@queries/bots/keys';
import { channelKeys } from '@queries/channel/keys';
import { queryClient } from '@queries/client';
import { storageServiceClient } from '@service-storage/client';
import type { Agent } from '@service-storage/generated/schemas/agent';
import type { AgentChannelScope } from '@service-storage/generated/schemas/agentChannelScope';
import type { AgentMcpServers } from '@service-storage/generated/schemas/agentMcpServers';
import { useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { agentKeys } from './keys';

/**
 * `Agent` plus the macrod harness binding the backend now returns; the field
 * is not yet in the generated schema.
 */
export type AgentWithHarnessId = Agent & { harness_id?: string | null };

export type CreateAgentParams = {
  avatarUrl?: string;
  channelIds: string[];
  channelScope: AgentChannelScope;
  defaultModel: string;
  description?: string;
  handle: string;
  harness: string;
  /** The registered macrod harness to run on; omit for built-in harnesses. */
  harnessId?: string;
  name: string;
  instructions: string;
  /** Which Pipedream MCP servers the agent's sessions are handed. */
  mcp: AgentMcpServers;
  teamId?: string;
  /**
   * Whether the agent's sessions approve permission requests without asking.
   * Omit to defer to the runtime's default: built-in runtimes auto-accept,
   * macrod prompts.
   */
  autoAcceptPermissions?: boolean;
  /**
   * Whether the agent is a coding agent, which decides how it answers a
   * channel mention: a magic chip into its live session, or a reply in the
   * thread.
   */
  isCoding: boolean;
};

export type UpdateAgentParams = CreateAgentParams & {
  agentId: string;
};

export type DeleteAgentParams = {
  agentId: string;
  channelIds: string[];
};

async function fetchAgents(): Promise<AgentWithHarnessId[]> {
  return await throwOnErr(() => storageServiceClient.getAgents());
}

export function useAgentsQuery(enabled: Accessor<boolean> = () => true) {
  return useQuery(() => ({
    queryKey: agentKeys.list.queryKey,
    enabled: enabled(),
    queryFn: fetchAgents,
  }));
}

/** The saved agents, from the cache when fresh, for imperative callers. */
export async function fetchAgentsList(): Promise<AgentWithHarnessId[]> {
  return await queryClient.fetchQuery({
    queryKey: agentKeys.list.queryKey,
    queryFn: fetchAgents,
  });
}

export function invalidateAgents() {
  return queryClient.invalidateQueries({ queryKey: agentKeys.list.queryKey });
}

function invalidateAgentChannelBots(channelIds: string[]) {
  return Promise.all(
    [...new Set(channelIds)].map((channelId) =>
      queryClient.invalidateQueries({
        queryKey: channelKeys.channelBots(channelId).queryKey,
      })
    )
  );
}

export function useCreateAgentMutation() {
  return useMutation(() => ({
    gcTime: 0,
    mutationFn: async (vars: CreateAgentParams) =>
      await throwOnErr(() =>
        storageServiceClient.createAgent({
          avatar_url: vars.avatarUrl,
          channel_ids: vars.channelIds,
          channel_scope: vars.channelScope,
          default_model: vars.defaultModel,
          description: vars.description,
          handle: vars.handle,
          harness: vars.harness,
          harness_id: vars.harnessId,
          name: vars.name,
          instructions: vars.instructions,
          mcp: vars.mcp,
          team_id: vars.teamId,
          auto_accept_permissions: vars.autoAcceptPermissions ?? null,
          is_coding: vars.isCoding,
        })
      ),
    onSuccess: async (agent) => {
      queryClient.setQueryData<Agent[]>(
        agentKeys.list.queryKey,
        (current = []) => [...current, agent]
      );
      queryClient.setQueryData(
        botKeys.detail(agent.bot.id).queryKey,
        agent.bot
      );
      await Promise.all([
        invalidateAgentChannelBots(agent.channel_ids),
        queryClient.invalidateQueries({ queryKey: botKeys.list.queryKey }),
      ]);
    },
    onError: (error) => console.error('failed to create agent', error),
  }));
}

export function useUpdateAgentMutation() {
  return useMutation(() => ({
    gcTime: 0,
    mutationFn: async (vars: UpdateAgentParams) =>
      await throwOnErr(() =>
        storageServiceClient.updateAgent({
          agent_id: vars.agentId,
          avatar_url: vars.avatarUrl,
          channel_ids: vars.channelIds,
          channel_scope: vars.channelScope,
          default_model: vars.defaultModel,
          description: vars.description,
          handle: vars.handle,
          harness: vars.harness,
          harness_id: vars.harnessId,
          name: vars.name,
          instructions: vars.instructions,
          mcp: vars.mcp,
          team_id: vars.teamId,
          auto_accept_permissions: vars.autoAcceptPermissions ?? null,
          is_coding: vars.isCoding,
        })
      ),
    onSuccess: async (updated) => {
      queryClient.setQueryData<Agent[]>(
        agentKeys.list.queryKey,
        (current = []) =>
          current.map((agent) =>
            agent.bot.id === updated.bot.id ? updated : agent
          )
      );
      queryClient.setQueryData(
        botKeys.detail(updated.bot.id).queryKey,
        updated.bot
      );
      await Promise.all([
        queryClient.invalidateQueries({ queryKey: botKeys.list.queryKey }),
        queryClient.invalidateQueries({
          queryKey: botProfileKeys.detail(updated.bot.id).queryKey,
        }),
        // Global agents have no selected channel IDs but can still appear in
        // a channel's bot list, which takes precedence in the mention menu.
        queryClient.invalidateQueries({
          queryKey: channelKeys.channelBots._def,
        }),
      ]);
    },
    onError: (error) => console.error('failed to update agent', error),
  }));
}

export function useDeleteAgentMutation() {
  return useMutation(() => ({
    gcTime: 0,
    mutationFn: async (vars: DeleteAgentParams) =>
      await throwOnErr(() =>
        storageServiceClient.deleteBot({ bot_id: vars.agentId })
      ),
    onSuccess: async (_data, vars) => {
      queryClient.setQueryData<Agent[]>(
        agentKeys.list.queryKey,
        (current = []) =>
          current.filter((agent) => agent.bot.id !== vars.agentId)
      );
      queryClient.removeQueries({
        queryKey: botKeys.detail(vars.agentId).queryKey,
      });
      queryClient.removeQueries({
        queryKey: botKeys.channels(vars.agentId).queryKey,
      });
      queryClient.removeQueries({
        queryKey: botKeys.tokens(vars.agentId).queryKey,
      });

      await Promise.all([
        queryClient.invalidateQueries({ queryKey: botKeys.list.queryKey }),
        queryClient.invalidateQueries({
          queryKey: botProfileKeys.detail(vars.agentId).queryKey,
        }),
        ...[...new Set(vars.channelIds)].flatMap((channelId) => [
          queryClient.invalidateQueries({
            queryKey: channelKeys.channelBots(channelId).queryKey,
          }),
          queryClient.invalidateQueries({
            queryKey: channelKeys.participants(channelId).queryKey,
          }),
        ]),
      ]);
    },
    onError: (error) => console.error('failed to delete agent', error),
  }));
}