feat: enhance agent management with project-level support

- Added support for project-level agents, allowing agents to be created, updated, and deleted within a specified working directory.
- Introduced `getAgentScope` function to determine the scope of agents based on their existence in project or user directories.
- Updated `getAgentSources`, `createAgent`, `updateAgent`, and `deleteAgent` functions to handle project-level paths and configurations.
- Enhanced logging to provide clearer information about agent operations, including scope and working directory.
- Refactored configuration reading and writing to accommodate project-specific configurations alongside user-level settings.
This commit is contained in:
Bohdan Triapitsyn
2025-12-29 22:42:10 +02:00
parent 0adcba854b
commit c4b9c18c24
10 changed files with 2849 additions and 1323 deletions
File diff suppressed because it is too large Load Diff
@@ -4,22 +4,21 @@ import { ButtonLarge } from '@/components/ui/button-large';
import { Input } from '@/components/ui/input';
import { toast } from 'sonner';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { RiAddLine, RiAiAgentFill, RiAiAgentLine, RiDeleteBinLine, RiFileCopyLine, RiMore2Line, RiRobot2Line, RiRobotLine } from '@remixicon/react';
import { useAgentsStore, isAgentBuiltIn, isAgentHidden } from '@/stores/useAgentsStore';
import { RiAddLine, RiAiAgentFill, RiAiAgentLine, RiDeleteBinLine, RiFileCopyLine, RiMore2Line, RiRobot2Line, RiRobotLine, RiRestartLine, RiEditLine } from '@remixicon/react';
import { useAgentsStore, isAgentBuiltIn, isAgentHidden, type AgentScope } from '@/stores/useAgentsStore';
import { useUIStore } from '@/stores/useUIStore';
import { useDeviceInfo } from '@/lib/device';
import { isVSCodeRuntime } from '@/lib/desktop';
@@ -28,309 +27,451 @@ import type { Agent } from '@opencode-ai/sdk';
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
interface AgentsSidebarProps {
onItemSelect?: () => void;
onItemSelect?: () => void;
}
export const AgentsSidebar: React.FC<AgentsSidebarProps> = ({ onItemSelect }) => {
const [newAgentName, setNewAgentName] = React.useState('');
const [isCreateDialogOpen, setIsCreateDialogOpen] = React.useState(false);
const [renameDialogAgent, setRenameDialogAgent] = React.useState<Agent | null>(null);
const [renameNewName, setRenameNewName] = React.useState('');
const {
selectedAgentName,
agents,
setSelectedAgent,
deleteAgent,
loadAgents,
} = useAgentsStore();
const {
selectedAgentName,
agents,
setSelectedAgent,
setAgentDraft,
createAgent,
deleteAgent,
loadAgents,
} = useAgentsStore();
const { setSidebarOpen } = useUIStore();
const { isMobile } = useDeviceInfo();
const { setSidebarOpen } = useUIStore();
const { isMobile } = useDeviceInfo();
const [isDesktopRuntime, setIsDesktopRuntime] = React.useState<boolean>(() => {
if (typeof window === 'undefined') return false;
return typeof window.opencodeDesktop !== 'undefined';
const [isDesktopRuntime, setIsDesktopRuntime] = React.useState<boolean>(() => {
if (typeof window === 'undefined') return false;
return typeof window.opencodeDesktop !== 'undefined';
});
const isVSCode = React.useMemo(() => isVSCodeRuntime(), []);
React.useEffect(() => {
if (typeof window === 'undefined') return;
setIsDesktopRuntime(typeof window.opencodeDesktop !== 'undefined');
}, []);
React.useEffect(() => {
loadAgents();
}, [loadAgents]);
const bgClass = isDesktopRuntime
? 'bg-transparent'
: isVSCode
? 'bg-background'
: 'bg-sidebar';
const handleCreateNew = () => {
// Generate unique name
const baseName = 'new-agent';
let newName = baseName;
let counter = 1;
while (agents.some((a) => a.name === newName)) {
newName = `${baseName}-${counter}`;
counter++;
}
// Set draft and open the page for editing
setAgentDraft({ name: newName, scope: 'user' });
setSelectedAgent(newName);
if (isMobile) {
setSidebarOpen(false);
}
};
const handleDeleteAgent = async (agent: Agent) => {
if (isAgentBuiltIn(agent)) {
toast.error('Built-in agents cannot be deleted');
return;
}
if (window.confirm(`Are you sure you want to delete agent "${agent.name}"?`)) {
const success = await deleteAgent(agent.name);
if (success) {
toast.success(`Agent "${agent.name}" deleted successfully`);
} else {
toast.error('Failed to delete agent');
}
}
};
const handleResetAgent = async (agent: Agent) => {
if (!isAgentBuiltIn(agent)) {
return;
}
if (window.confirm(`Are you sure you want to reset agent "${agent.name}" to its default configuration?`)) {
const success = await deleteAgent(agent.name);
if (success) {
toast.success(`Agent "${agent.name}" reset to default`);
} else {
toast.error('Failed to reset agent');
}
}
};
const handleDuplicateAgent = (agent: Agent) => {
const baseName = agent.name;
let copyNumber = 1;
let newName = `${baseName}-copy`;
while (agents.some((a) => a.name === newName)) {
copyNumber++;
newName = `${baseName}-copy-${copyNumber}`;
}
// Set draft with prefilled values from source agent
const extAgent = agent as Agent & { scope?: AgentScope };
// Convert model object to string if needed (SDK type vs API type difference)
const modelStr = typeof agent.model === 'string'
? agent.model
: agent.model?.providerID && agent.model?.modelID
? `${agent.model.providerID}/${agent.model.modelID}`
: undefined;
const draftAgent = agent as Agent & { disable?: boolean };
setAgentDraft({
name: newName,
scope: extAgent.scope || 'user',
description: agent.description,
model: modelStr,
temperature: agent.temperature,
top_p: agent.topP,
prompt: agent.prompt,
mode: agent.mode,
tools: agent.tools,
permission: agent.permission,
disable: draftAgent.disable,
});
setSelectedAgent(newName);
if (isMobile) {
setSidebarOpen(false);
}
};
const handleOpenRenameDialog = (agent: Agent) => {
setRenameNewName(agent.name);
setRenameDialogAgent(agent);
};
const handleRenameAgent = async () => {
if (!renameDialogAgent) return;
const sanitizedName = renameNewName.trim().replace(/\s+/g, '-');
if (!sanitizedName) {
toast.error('Agent name is required');
return;
}
if (sanitizedName === renameDialogAgent.name) {
setRenameDialogAgent(null);
return;
}
if (agents.some((a) => a.name === sanitizedName)) {
toast.error('An agent with this name already exists');
return;
}
// Create new agent with new name and all existing config
// Convert model object to string if needed (SDK type vs API type difference)
const renameModelStr = typeof renameDialogAgent.model === 'string'
? renameDialogAgent.model
: renameDialogAgent.model?.providerID && renameDialogAgent.model?.modelID
? `${renameDialogAgent.model.providerID}/${renameDialogAgent.model.modelID}`
: undefined;
const renameExt = renameDialogAgent as Agent & { scope?: AgentScope; disable?: boolean };
const success = await createAgent({
name: sanitizedName,
description: renameDialogAgent.description,
model: renameModelStr,
temperature: renameDialogAgent.temperature,
top_p: renameDialogAgent.topP,
prompt: renameDialogAgent.prompt,
mode: renameDialogAgent.mode,
tools: renameDialogAgent.tools,
permission: renameDialogAgent.permission,
disable: renameExt.disable,
scope: renameExt.scope,
});
const isVSCode = React.useMemo(() => isVSCodeRuntime(), []);
if (success) {
// Delete old agent
const deleteSuccess = await deleteAgent(renameDialogAgent.name);
if (deleteSuccess) {
toast.success(`Agent renamed to "${sanitizedName}"`);
setSelectedAgent(sanitizedName);
} else {
toast.error('Failed to remove old agent after rename');
}
} else {
toast.error('Failed to rename agent');
}
React.useEffect(() => {
if (typeof window === 'undefined') return;
setIsDesktopRuntime(typeof window.opencodeDesktop !== 'undefined');
}, []);
setRenameDialogAgent(null);
};
React.useEffect(() => {
loadAgents();
}, [loadAgents]);
const getAgentModeIcon = (mode?: string) => {
switch (mode) {
case 'primary':
return <RiAiAgentLine className="h-3 w-3 text-primary" />;
case 'all':
return <RiAiAgentFill className="h-3 w-3 text-primary" />;
case 'subagent':
return <RiRobotLine className="h-3 w-3 text-primary" />;
default:
return null;
}
};
const bgClass = isDesktopRuntime
? 'bg-transparent'
: isVSCode
? 'bg-background'
: 'bg-sidebar';
// Filter out hidden agents (internal agents like title, compaction, summary)
const visibleAgents = agents.filter((agent) => !isAgentHidden(agent));
const builtInAgents = visibleAgents.filter(isAgentBuiltIn);
const customAgents = visibleAgents.filter((agent) => !isAgentBuiltIn(agent));
const handleCreateAgent = () => {
if (!newAgentName.trim()) {
toast.error('Agent name is required');
return;
}
if (agents.some((agent) => agent.name === newAgentName)) {
toast.error('An agent with this name already exists');
return;
}
setSelectedAgent(newAgentName);
setNewAgentName('');
setIsCreateDialogOpen(false);
if (isMobile) {
setSidebarOpen(false);
}
};
const handleDeleteAgent = async (agent: Agent) => {
if (isAgentBuiltIn(agent)) {
toast.error('Built-in agents cannot be deleted');
return;
}
if (window.confirm(`Are you sure you want to delete agent "${agent.name}"?`)) {
const success = await deleteAgent(agent.name);
if (success) {
toast.success(`Agent "${agent.name}" deleted successfully`);
} else {
toast.error('Failed to delete agent');
}
}
};
const handleDuplicateAgent = (agent: Agent) => {
const baseName = agent.name;
let copyNumber = 1;
let newName = `${baseName} Copy`;
while (agents.some((a) => a.name === newName)) {
copyNumber++;
newName = `${baseName} Copy ${copyNumber}`;
}
setSelectedAgent(newName);
setIsCreateDialogOpen(false);
if (isMobile) {
setSidebarOpen(false);
}
};
const getAgentModeIcon = (mode?: string) => {
switch (mode) {
case 'primary':
return <RiAiAgentLine className="h-3 w-3 text-primary" />;
case 'all':
return <RiAiAgentFill className="h-3 w-3 text-primary" />;
case 'subagent':
return <RiRobotLine className="h-3 w-3 text-primary" />;
default:
return null;
}
};
// Filter out hidden agents (internal agents like title, compaction, summary)
const visibleAgents = agents.filter((agent) => !isAgentHidden(agent));
const builtInAgents = visibleAgents.filter(isAgentBuiltIn);
const customAgents = visibleAgents.filter((agent) => !isAgentBuiltIn(agent));
return (
<div className={cn('flex h-full flex-col', bgClass)}>
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<div className={cn('border-b px-3', isMobile ? 'mt-2 py-3' : 'py-3')}>
<div className="flex items-center justify-between gap-2">
<span className="typography-meta text-muted-foreground">Total {visibleAgents.length}</span>
<DialogTrigger asChild>
<Button type="button" variant="ghost" size="icon" className="h-7 w-7 -my-1 text-muted-foreground">
<RiAddLine className="size-4" />
</Button>
</DialogTrigger>
</div>
</div>
<ScrollableOverlay outerClassName="flex-1 min-h-0" className="space-y-1 px-3 py-2 overflow-x-hidden">
{visibleAgents.length === 0 ? (
<div className="py-12 px-4 text-center text-muted-foreground">
<RiRobot2Line className="mx-auto mb-3 h-10 w-10 opacity-50" />
<p className="typography-ui-label font-medium">No agents configured</p>
<p className="typography-meta mt-1 opacity-75">Use the + button above to create one</p>
</div>
) : (
<>
{builtInAgents.length > 0 && (
<>
<div className="px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Built-in Agents
</div>
{builtInAgents.map((agent) => (
<AgentListItem
key={agent.name}
agent={agent}
isSelected={selectedAgentName === agent.name}
onSelect={() => {
setSelectedAgent(agent.name);
onItemSelect?.();
if (isMobile) {
setSidebarOpen(false);
}
}}
onDuplicate={() => handleDuplicateAgent(agent)}
getAgentModeIcon={getAgentModeIcon}
/>
))}
</>
)}
{customAgents.length > 0 && (
<>
<div className="px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Custom Agents
</div>
{customAgents.map((agent) => (
<AgentListItem
key={agent.name}
agent={agent}
isSelected={selectedAgentName === agent.name}
onSelect={() => {
setSelectedAgent(agent.name);
onItemSelect?.();
if (isMobile) {
setSidebarOpen(false);
}
}}
onDelete={() => handleDeleteAgent(agent)}
onDuplicate={() => handleDuplicateAgent(agent)}
getAgentModeIcon={getAgentModeIcon}
/>
))}
</>
)}
</>
)}
</ScrollableOverlay>
<DialogContent>
<DialogHeader>
<DialogTitle>Create New Agent</DialogTitle>
<DialogDescription>
Enter a unique name for your new agent
</DialogDescription>
</DialogHeader>
<Input
value={newAgentName}
onChange={(e) => setNewAgentName(e.target.value)}
placeholder="Agent name..."
className="text-foreground placeholder:text-muted-foreground"
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleCreateAgent();
}
}}
/>
<DialogFooter>
<Button
variant="ghost"
onClick={() => setIsCreateDialogOpen(false)}
className="text-foreground hover:bg-muted hover:text-foreground"
>
Cancel
</Button>
<ButtonLarge onClick={handleCreateAgent}>
Create
</ButtonLarge>
</DialogFooter>
</DialogContent>
</Dialog>
return (
<div className={cn('flex h-full flex-col', bgClass)}>
<div className={cn('border-b px-3', isMobile ? 'mt-2 py-3' : 'py-3')}>
<div className="flex items-center justify-between gap-2">
<span className="typography-meta text-muted-foreground">Total {visibleAgents.length}</span>
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7 -my-1 text-muted-foreground"
onClick={handleCreateNew}
>
<RiAddLine className="size-4" />
</Button>
</div>
);
</div>
<ScrollableOverlay outerClassName="flex-1 min-h-0" className="space-y-1 px-3 py-2 overflow-x-hidden">
{visibleAgents.length === 0 ? (
<div className="py-12 px-4 text-center text-muted-foreground">
<RiRobot2Line className="mx-auto mb-3 h-10 w-10 opacity-50" />
<p className="typography-ui-label font-medium">No agents configured</p>
<p className="typography-meta mt-1 opacity-75">Use the + button above to create one</p>
</div>
) : (
<>
{builtInAgents.length > 0 && (
<>
<div className="px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Built-in Agents
</div>
{builtInAgents.map((agent) => (
<AgentListItem
key={agent.name}
agent={agent}
isSelected={selectedAgentName === agent.name}
onSelect={() => {
setSelectedAgent(agent.name);
onItemSelect?.();
if (isMobile) {
setSidebarOpen(false);
}
}}
onReset={() => handleResetAgent(agent)}
onDuplicate={() => handleDuplicateAgent(agent)}
getAgentModeIcon={getAgentModeIcon}
/>
))}
</>
)}
{customAgents.length > 0 && (
<>
<div className="px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Custom Agents
</div>
{customAgents.map((agent) => (
<AgentListItem
key={agent.name}
agent={agent}
isSelected={selectedAgentName === agent.name}
onSelect={() => {
setSelectedAgent(agent.name);
onItemSelect?.();
if (isMobile) {
setSidebarOpen(false);
}
}}
onRename={() => handleOpenRenameDialog(agent)}
onDelete={() => handleDeleteAgent(agent)}
onDuplicate={() => handleDuplicateAgent(agent)}
getAgentModeIcon={getAgentModeIcon}
/>
))}
</>
)}
</>
)}
</ScrollableOverlay>
{/* Rename Dialog */}
<Dialog open={renameDialogAgent !== null} onOpenChange={(open) => !open && setRenameDialogAgent(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>Rename Agent</DialogTitle>
<DialogDescription>
Enter a new name for the agent "@{renameDialogAgent?.name}"
</DialogDescription>
</DialogHeader>
<Input
value={renameNewName}
onChange={(e) => setRenameNewName(e.target.value)}
placeholder="New agent name..."
className="text-foreground placeholder:text-muted-foreground"
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleRenameAgent();
}
}}
/>
<DialogFooter>
<Button
variant="ghost"
onClick={() => setRenameDialogAgent(null)}
className="text-foreground hover:bg-muted hover:text-foreground"
>
Cancel
</Button>
<ButtonLarge onClick={handleRenameAgent}>
Rename
</ButtonLarge>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
};
interface AgentListItemProps {
agent: Agent;
isSelected: boolean;
onSelect: () => void;
onDelete?: () => void;
onDuplicate: () => void;
getAgentModeIcon: (mode?: string) => React.ReactNode;
agent: Agent;
isSelected: boolean;
onSelect: () => void;
onDelete?: () => void;
onReset?: () => void;
onRename?: () => void;
onDuplicate: () => void;
getAgentModeIcon: (mode?: string) => React.ReactNode;
}
const AgentListItem: React.FC<AgentListItemProps> = ({
agent,
isSelected,
onSelect,
onDelete,
onDuplicate,
getAgentModeIcon,
agent,
isSelected,
onSelect,
onDelete,
onReset,
onRename,
onDuplicate,
getAgentModeIcon,
}) => {
return (
<div
className={cn(
'group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200',
isSelected ? 'dark:bg-accent/80 bg-primary/12' : 'hover:dark:bg-accent/40 hover:bg-primary/6'
)}
const extAgent = agent as Agent & { scope?: AgentScope };
return (
<div
className={cn(
'group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200',
isSelected ? 'dark:bg-accent/80 bg-primary/12' : 'hover:dark:bg-accent/40 hover:bg-primary/6'
)}
>
<div className="flex min-w-0 flex-1 items-center">
<button
onClick={onSelect}
className="flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"
tabIndex={0}
>
<div className="flex min-w-0 flex-1 items-center">
<button
onClick={onSelect}
className="flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"
tabIndex={0}
>
<div className="flex items-center gap-1.5">
<span className="typography-ui-label font-normal truncate text-foreground">
{agent.name}
</span>
{getAgentModeIcon(agent.mode)}
</div>
<div className="flex items-center gap-1.5">
<span className="typography-ui-label font-normal truncate text-foreground">
{agent.name}
</span>
{getAgentModeIcon(agent.mode)}
{(extAgent.scope || isAgentBuiltIn(agent)) && (
<span className="typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50">
{isAgentBuiltIn(agent) ? 'system' : extAgent.scope}
</span>
)}
</div>
{agent.description && (
<div className="typography-micro text-muted-foreground/60 truncate leading-tight">
{agent.description}
</div>
)}
</button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="icon"
variant="ghost"
className="h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100"
>
<RiMore2Line className="h-3.5 w-3.5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-fit min-w-20">
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onDuplicate();
}}
>
<RiFileCopyLine className="h-4 w-4 mr-px" />
Duplicate
</DropdownMenuItem>
{!isAgentBuiltIn(agent) && onDelete && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onDelete();
}}
className="text-destructive focus:text-destructive"
>
<RiDeleteBinLine className="h-4 w-4 mr-px" />
Delete
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
{agent.description && (
<div className="typography-micro text-muted-foreground/60 truncate leading-tight">
{agent.description}
</div>
</div>
);
)}
</button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="icon"
variant="ghost"
className="h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100"
>
<RiMore2Line className="h-3.5 w-3.5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-fit min-w-20">
{onRename && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onRename();
}}
>
<RiEditLine className="h-4 w-4 mr-px" />
Rename
</DropdownMenuItem>
)}
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onDuplicate();
}}
>
<RiFileCopyLine className="h-4 w-4 mr-px" />
Duplicate
</DropdownMenuItem>
{onReset && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onReset();
}}
>
<RiRestartLine className="h-4 w-4 mr-px" />
Reset
</DropdownMenuItem>
)}
{onDelete && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onDelete();
}}
className="text-destructive focus:text-destructive"
>
<RiDeleteBinLine className="h-4 w-4 mr-px" />
Delete
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
);
};
+92 -5
View File
@@ -12,6 +12,26 @@ import {
import { getSafeStorage } from "./utils/safeStorage";
import { useConfigStore } from "@/stores/useConfigStore";
// Note: useDirectoryStore cannot be imported at top level to avoid circular dependency
// useDirectoryStore -> useAgentsStore (for refreshAfterOpenCodeRestart)
// useAgentsStore -> useDirectoryStore (for currentDirectory)
// Instead we access it from the window object where it's exposed
const getCurrentDirectory = (): string | null => {
// Try to get from window if store is already loaded
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const store = (window as any).__zustand_directory_store__;
if (store) {
return store.getState().currentDirectory;
}
} catch {
// ignore
}
return null;
};
export type AgentScope = 'user' | 'project';
export interface AgentConfig {
name: string;
description?: string;
@@ -22,12 +42,16 @@ export interface AgentConfig {
mode?: "primary" | "subagent" | "all";
tools?: Record<string, boolean>;
permission?: {
edit?: "allow" | "ask" | "deny" | "full";
edit?: "allow" | "ask" | "deny";
bash?: "allow" | "ask" | "deny" | Record<string, "allow" | "ask" | "deny">;
skill?: "allow" | "ask" | "deny" | Record<string, "allow" | "ask" | "deny">;
webfetch?: "allow" | "ask" | "deny";
doom_loop?: "allow" | "ask" | "deny";
external_directory?: "allow" | "ask" | "deny";
};
disable?: boolean;
scope?: AgentScope;
}
// Extended Agent type for API properties not in SDK types
@@ -61,13 +85,36 @@ const SLOW_HEALTH_POLL_BASE_MS = 800;
const SLOW_HEALTH_POLL_INCREMENT_MS = 200;
const SLOW_HEALTH_POLL_MAX_MS = 2000;
export interface AgentDraft {
name: string;
scope: AgentScope;
description?: string;
model?: string | null;
temperature?: number;
top_p?: number;
prompt?: string;
mode?: "primary" | "subagent" | "all";
tools?: Record<string, boolean>;
permission?: {
edit?: "allow" | "ask" | "deny";
bash?: "allow" | "ask" | "deny" | Record<string, "allow" | "ask" | "deny">;
skill?: "allow" | "ask" | "deny" | Record<string, "allow" | "ask" | "deny">;
webfetch?: "allow" | "ask" | "deny";
doom_loop?: "allow" | "ask" | "deny";
external_directory?: "allow" | "ask" | "deny";
};
disable?: boolean;
}
interface AgentsStore {
selectedAgentName: string | null;
agents: Agent[];
isLoading: boolean;
agentDraft: AgentDraft | null;
setSelectedAgent: (name: string | null) => void;
setAgentDraft: (draft: AgentDraft | null) => void;
loadAgents: () => Promise<boolean>;
createAgent: (config: AgentConfig) => Promise<boolean>;
updateAgent: (name: string, config: Partial<AgentConfig>) => Promise<boolean>;
@@ -91,11 +138,16 @@ export const useAgentsStore = create<AgentsStore>()(
selectedAgentName: null,
agents: [],
isLoading: false,
agentDraft: null,
setSelectedAgent: (name: string | null) => {
set({ selectedAgentName: name });
},
setAgentDraft: (draft: AgentDraft | null) => {
set({ agentDraft: draft });
},
loadAgents: async () => {
set({ isLoading: true });
const previousAgents = get().agents;
@@ -104,7 +156,29 @@ export const useAgentsStore = create<AgentsStore>()(
for (let attempt = 0; attempt < 3; attempt++) {
try {
const agents = await opencodeClient.listAgents();
set({ agents, isLoading: false });
// Fetch scope info for each agent
const currentDirectory = getCurrentDirectory();
const queryParams = currentDirectory ? `?directory=${encodeURIComponent(currentDirectory)}` : '';
const agentsWithScope = await Promise.all(
agents.map(async (agent) => {
try {
const response = await fetch(`/api/config/agents/${encodeURIComponent(agent.name)}${queryParams}`);
if (response.ok) {
const data = await response.json();
// Handle web/desktop response formats; fall back to JSON scope if md scope missing
const scope = data.scope ?? data.sources?.md?.scope ?? data.sources?.json?.scope;
return { ...agent, scope: scope as AgentScope | undefined };
}
} catch (err) {
console.error(`[AgentsStore] Failed to fetch scope for agent "${agent.name}":`, err);
}
return agent;
})
);
set({ agents: agentsWithScope, isLoading: false });
return true;
} catch (error) {
lastError = error;
@@ -136,10 +210,15 @@ export const useAgentsStore = create<AgentsStore>()(
if (config.tools && Object.keys(config.tools).length > 0) agentConfig.tools = config.tools;
if (config.permission) agentConfig.permission = config.permission;
if (config.disable !== undefined) agentConfig.disable = config.disable;
if (config.scope) agentConfig.scope = config.scope;
console.log('[AgentsStore] Agent config to save:', agentConfig);
const response = await fetch(`/api/config/agents/${encodeURIComponent(config.name)}`, {
// Get current directory for project-level agent support
const currentDirectory = getCurrentDirectory();
const queryParams = currentDirectory ? `?directory=${encodeURIComponent(currentDirectory)}` : '';
const response = await fetch(`/api/config/agents/${encodeURIComponent(config.name)}${queryParams}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(agentConfig)
@@ -199,7 +278,11 @@ export const useAgentsStore = create<AgentsStore>()(
console.log('[AgentsStore] Agent config to update:', agentConfig);
const response = await fetch(`/api/config/agents/${encodeURIComponent(name)}`, {
// Get current directory for project-level agent support
const currentDirectory = getCurrentDirectory();
const queryParams = currentDirectory ? `?directory=${encodeURIComponent(currentDirectory)}` : '';
const response = await fetch(`/api/config/agents/${encodeURIComponent(name)}${queryParams}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(agentConfig)
@@ -242,7 +325,11 @@ export const useAgentsStore = create<AgentsStore>()(
startConfigUpdate("Deleting agent configuration…");
let requiresReload = false;
try {
const response = await fetch(`/api/config/agents/${encodeURIComponent(name)}`, {
// Get current directory for project-level agent support
const currentDirectory = getCurrentDirectory();
const queryParams = currentDirectory ? `?directory=${encodeURIComponent(currentDirectory)}` : '';
const response = await fetch(`/api/config/agents/${encodeURIComponent(name)}${queryParams}`, {
method: 'DELETE'
});