Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions configs/locus/examples/assistant.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# Assistant — an agent that uses tools to do tasks, not only chat
# Copy to ~/.locus/config.toml
#
# The same tool set the desktop app's Agent mode uses. Every tool here only
# reads, or writes to Locus's own memory: writing files, running commands and
# network access are left out until they can ask you in the chat first.
# An agent with tools that only read, or write to Locus's own memory. For
# writing files and running commands, turn on Agent mode in the desktop app or
# browser GUI: it asks you in the chat before each of those calls.
#
# Usage:
# locus ask "How many PDFs are in my Downloads folder?"
Expand All @@ -18,15 +18,18 @@ default_model = "qwen3.5:9b" # Small models often miss tool calls

[agent]
default_agent = "orchestrator" # Multi-turn with tool selection
max_turns = 10
max_turns = 25

[server]
agent = "orchestrator"
host = "127.0.0.1"
port = 8000

[tools]
enabled = ["think", "calculator", "file_read", "pdf_extract", "memory_manage"]
enabled = [
"think", "calculator", "file_read", "pdf_extract", "memory_manage",
"git_status", "git_diff", "git_log",
]

[security]
allowed_dirs = ["~"] # File tools stay in your home folder
8 changes: 8 additions & 0 deletions docs/design/2026-11-08-agent-mode-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,14 @@ Most of the agent machinery is in the repo. The gap is mostly wiring and UX.

**Goal:** the user sees what the agent plans, what it's doing and what it needs approved, without leaving the chat.

> **Status (2026-11-08): approvals, risk levels and Stop are implemented. The plan checklist and Undo are not done yet.** As built:
> - **Broker:** `src/locus/server/approvals.py`. The Agent mode agent's `before_tool_call` hook classifies each call as `read` (never asks), `change` (asks) or `run` (always asks; covers anything marked `requires_confirmation`). Unknown tools count as `change`, so new tools ask by default.
> - **Asking:** for a risky call, the agent's thread pauses, the stream sends `approval_required`, and the run waits up to 5 minutes for `POST /v1/chat/approvals/{id}` with `approve`, `approve_tool` (this tool for the rest of the run) or `deny`. No answer counts as a no. Requests that can't ask (non-streaming) deny risky calls.
> - **Stop:** each stream starts with an `agent_run` event. Stop calls `POST /v1/chat/runs/{run_id}/stop`, which ends the run at its next tool call (`AgentCancelled`), and the answer becomes "Stopped." Closing the stream does the same.
> - **Agent:** Agent mode now always uses its own `orchestrator`, not the server's configured agent, since only that agent has the hook. It adds `file_write`, `shell_exec`, `git_status`, `git_diff` and `git_log`, is kept to the home folder, runs tools one at a time (approvals are tracked per run on the agent's thread), and gets at least 25 turns.
> - **UI:** the tool card shows **Allow**, **Allow <tool> for this task** and **Deny**, with the command or path in words. The `assistant` preset stays read-only, because `locus serve` builds its agent without the hook.
> - **Not done yet:** a plan checklist before multi-step tasks, Undo for file changes, "always allow" rules that last beyond one run, and resuming a stopped run.

- **Plan step:** for multi-step requests, the agent first emits a short plan (a new stream event type in `stream_bridge.py`); the UI shows it as a checklist that ticks off as steps finish.
- **Inline approvals:** when a tool needs approval, stream an `approval_required` event carrying the action from `ApprovalStore`; render Approve, Deny and "Always allow for this folder/command" buttons in the message. Keep `ApprovalBell` for background agents.
- **Risk levels:** classify tools as read-only (no prompt), reversible write (prompt once per session or per folder) or irreversible/outward (always prompt: delete, send, purchase, system settings). Reuse `severity_policy.py` and `capabilities.py`.
Expand Down
68 changes: 60 additions & 8 deletions frontend/src/components/Chat/InputArea.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Send, Square, Paperclip, Search, Globe, Bot } from 'lucide-react';
import { toast } from 'sonner';
import { useAppStore, generateId } from '../../lib/store';
import { streamChat, streamResearch } from '../../lib/sse';
import { fetchSavings, getBase } from '../../lib/api';
import { fetchSavings, getBase, stopAgentRun } from '../../lib/api';
import { listConnectors, getSyncStatus } from '../../lib/connectors-api';
import { serializeToolCallArguments } from '../../lib/tool-call';
import { isSmallForAgent } from '../../lib/model-capabilities';
Expand Down Expand Up @@ -103,6 +103,8 @@ export function InputArea() {
const [input, setInput] = useState('');
const textareaRef = useRef<HTMLTextAreaElement>(null);
const abortRef = useRef<AbortController | null>(null);
// Agent mode run being streamed, so Stop can end it on the server too.
const agentRunRef = useRef<string | null>(null);
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);

const activeId = useAppStore((s) => s.activeId);
Expand Down Expand Up @@ -260,6 +262,10 @@ export function InputArea() {
}, [input]);

const stopStreaming = useCallback(() => {
if (agentRunRef.current) {
void stopAgentRun(agentRunRef.current).catch(() => {});
agentRunRef.current = null;
}
abortRef.current?.abort();
if (timerRef.current) {
clearInterval(timerRef.current);
Expand Down Expand Up @@ -343,6 +349,7 @@ export function InputArea() {

const controller = new AbortController();
abortRef.current = controller;
agentRunRef.current = null;

let accumulatedContent = '';
let usage: TokenUsage | undefined;
Expand Down Expand Up @@ -538,6 +545,41 @@ export function InputArea() {
: `Web search found ${sources.length} source(s)`,
});
} catch {}
} else if (eventName === 'agent_run') {
try {
agentRunRef.current = JSON.parse(sseEvent.data).run_id ?? null;
} catch {}
} else if (eventName === 'approval_required') {
try {
const data = JSON.parse(sseEvent.data);
toolCalls.push({
id: generateId(),
tool: data.tool,
arguments: serializeToolCallArguments(data.arguments),
status: 'awaiting_approval',
approvalId: data.id,
risk: data.risk,
});
setStreamState({
phase: 'Waiting for your approval...',
activeToolCalls: [...toolCalls],
});
updateLastAssistant(convId, accumulatedContent, [...toolCalls]);
} catch {}
} else if (eventName === 'approval_resolved') {
try {
const data = JSON.parse(sseEvent.data);
const tc = toolCalls.find((t) => t.approvalId === data.id);
if (tc) {
tc.status = data.approved ? 'approved' : 'denied';
if (data.timed_out) tc.result = 'No answer in time, so the agent skipped this step.';
}
setStreamState({
phase: data.approved ? `Calling ${data.tool}...` : 'Agent thinking...',
activeToolCalls: [...toolCalls],
});
updateLastAssistant(convId, accumulatedContent, [...toolCalls]);
} catch {}
} else if (eventName === 'agent_turn_start') {
setStreamState({ phase: 'Agent thinking...' });
} else if (eventName === 'inference_start') {
Expand All @@ -549,13 +591,18 @@ export function InputArea() {
} else if (eventName === 'tool_call_start') {
try {
const data = JSON.parse(sseEvent.data);
const tc: ToolCallInfo = {
id: generateId(),
tool: data.tool,
arguments: serializeToolCallArguments(data.arguments),
status: 'running',
};
toolCalls.push(tc);
// An approved call is already on screen; it starts running now.
const approved = toolCalls.find((t) => t.tool === data.tool && t.status === 'approved');
if (approved) {
approved.status = 'running';
} else {
toolCalls.push({
id: generateId(),
tool: data.tool,
arguments: serializeToolCallArguments(data.arguments),
status: 'running',
});
}
setStreamState({
phase: `Calling ${data.tool}...`,
activeToolCalls: [...toolCalls],
Expand Down Expand Up @@ -627,6 +674,11 @@ export function InputArea() {
// numbers don't get stuck on the last sample.
useAppStore.getState().setLiveEnergy(null);
} finally {
agentRunRef.current = null;
// A stopped run leaves no step waiting for an answer.
for (const tc of toolCalls) {
if (tc.status === 'awaiting_approval' || tc.status === 'approved') tc.status = 'denied';
}
if (!accumulatedContent) {
accumulatedContent = 'No response was generated. Please try again.';
}
Expand Down
26 changes: 26 additions & 0 deletions frontend/src/components/Chat/ToolCallCard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest';

import { describeToolCall } from './ToolCallCard';

describe('describeToolCall', () => {
it('shows the command for shell_exec', () => {
expect(describeToolCall('shell_exec', JSON.stringify({ command: 'dir' }))).toBe('Run `dir`');
expect(
describeToolCall('shell_exec', JSON.stringify({ command: 'ls', working_dir: 'C:/x' })),
).toBe('Run `ls` in C:/x');
});

it('shows the path for file_write', () => {
expect(describeToolCall('file_write', JSON.stringify({ path: 'a.txt', content: 'x' }))).toBe(
'Write a.txt',
);
expect(
describeToolCall('file_write', JSON.stringify({ path: 'a.txt', mode: 'append' })),
).toBe('Add to a.txt');
});

it('falls back to the tool name', () => {
expect(describeToolCall('git_commit', '{"message":"m"}')).toBe('Use git_commit');
expect(describeToolCall('shell_exec', 'not json')).toBe('Use shell_exec');
});
});
90 changes: 87 additions & 3 deletions frontend/src/components/Chat/ToolCallCard.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { useState } from 'react';
import { ChevronDown, ChevronRight, Loader2, CheckCircle2, XCircle } from 'lucide-react';
import { ChevronDown, ChevronRight, Loader2, CheckCircle2, XCircle, ShieldQuestion, Ban } from 'lucide-react';
import { toast } from 'sonner';
import type { ToolCallInfo } from '../../types';
import { serializeToolCallArguments } from '../../lib/tool-call';
import { answerApproval, type ApprovalDecision } from '../../lib/api';

interface Props {
toolCall: ToolCallInfo;
Expand All @@ -11,8 +13,82 @@ const statusConfig = {
running: { icon: Loader2, color: 'var(--color-accent)' },
success: { icon: CheckCircle2, color: 'var(--color-success)' },
error: { icon: XCircle, color: 'var(--color-error)' },
awaiting_approval: { icon: ShieldQuestion, color: 'var(--color-warning, var(--color-accent))' },
approved: { icon: Loader2, color: 'var(--color-accent)' },
denied: { icon: Ban, color: 'var(--color-text-tertiary)' },
};

/** What the agent wants to do, in words, for the approval prompt. */
export function describeToolCall(tool: string, argumentsText: string): string {
let args: Record<string, unknown> = {};
try {
const parsed = JSON.parse(argumentsText);
if (parsed && typeof parsed === 'object') args = parsed;
} catch {
/* fall through */
}
const text = (key: string) => (typeof args[key] === 'string' ? (args[key] as string) : '');
if (tool === 'shell_exec' && text('command')) {
const where = text('working_dir');
return where ? `Run \`${text('command')}\` in ${where}` : `Run \`${text('command')}\``;
}
if (tool === 'file_write' && text('path')) {
return text('mode') === 'append' ? `Add to ${text('path')}` : `Write ${text('path')}`;
}
return `Use ${tool}`;
}

function ApprovalPrompt({ toolCall, argumentsText }: { toolCall: ToolCallInfo; argumentsText: string }) {
const [sending, setSending] = useState(false);
const answer = async (decision: ApprovalDecision) => {
if (!toolCall.approvalId) return;
setSending(true);
try {
const waiting = await answerApproval(toolCall.approvalId, decision);
if (!waiting) toast.error('This request is no longer waiting for an answer.');
} catch (err: any) {
toast.error(err?.message || 'Could not send your answer.');
} finally {
setSending(false);
}
};
const button = (label: string, decision: ApprovalDecision, primary = false) => (
<button
type="button"
disabled={sending}
onClick={() => answer(decision)}
className="px-2.5 py-1 rounded-md text-xs cursor-pointer disabled:cursor-default disabled:opacity-50"
style={{
background: primary ? 'var(--color-accent)' : 'transparent',
color: primary ? 'var(--color-on-accent, #fff)' : 'var(--color-text-secondary)',
border: `1px solid ${primary ? 'var(--color-accent)' : 'var(--color-border)'}`,
fontFamily: 'inherit',
}}
>
{label}
</button>
);
return (
<div
className="px-2.5 py-2 flex flex-col gap-2"
style={{
borderTop: '1px solid var(--color-border-subtle, var(--color-border))',
fontFamily: 'var(--font-sans, inherit)',
}}
>
<div style={{ color: 'var(--color-text)', fontSize: 12 }}>
{toolCall.risk === 'run' ? 'Locus wants to run a command:' : 'Locus wants to make a change:'}{' '}
<span style={{ fontWeight: 500 }}>{describeToolCall(toolCall.tool, argumentsText)}</span>
</div>
<div className="flex flex-wrap gap-1.5">
{button('Allow', 'approve', true)}
{button(`Allow ${toolCall.tool} for this task`, 'approve_tool')}
{button('Deny', 'deny')}
</div>
</div>
);
}

function previewArgs(raw: string): string {
if (!raw) return '';
try {
Expand All @@ -34,7 +110,7 @@ function previewArgs(raw: string): string {

export function ToolCallCard({ toolCall }: Props) {
const [expanded, setExpanded] = useState(false);
const config = statusConfig[toolCall.status];
const config = statusConfig[toolCall.status] ?? statusConfig.running;
const StatusIcon = config.icon;
// Persisted conversations may contain the pre-fix object payload despite
// the TypeScript contract, so normalize again at the final render boundary.
Expand Down Expand Up @@ -64,7 +140,7 @@ export function ToolCallCard({ toolCall }: Props) {
<StatusIcon
size={11}
style={{ color: config.color, flexShrink: 0 }}
className={toolCall.status === 'running' ? 'animate-spin' : ''}
className={toolCall.status === 'running' || toolCall.status === 'approved' ? 'animate-spin' : ''}
/>
<span
style={{ color: 'var(--color-text)', fontWeight: 500, flexShrink: 0 }}
Expand All @@ -80,6 +156,11 @@ export function ToolCallCard({ toolCall }: Props) {
</span>
)}
<div className="flex-1" />
{toolCall.status === 'denied' && (
<span style={{ color: 'var(--color-text-tertiary)', fontSize: 10, flexShrink: 0 }}>
Denied
</span>
)}
{toolCall.latency != null && (
<span
style={{
Expand All @@ -94,6 +175,9 @@ export function ToolCallCard({ toolCall }: Props) {
</span>
)}
</button>
{toolCall.status === 'awaiting_approval' && toolCall.approvalId && (
<ApprovalPrompt toolCall={toolCall} argumentsText={argumentsText} />
)}
{expanded && (
<div
className="px-2.5 pb-2 pt-0.5"
Expand Down
21 changes: 21 additions & 0 deletions frontend/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1226,3 +1226,24 @@ export async function setInferenceSource(
export const stageInferenceSource = (
src: InferenceSource & { apiKey?: string },
): Promise<void> => setInferenceSource(src, { pending: true });

// ── Agent mode approvals ──────────────────────────────────────

export type ApprovalDecision = 'approve' | 'approve_tool' | 'deny';

/** Answer an Agent mode approval. Returns false if it's no longer waiting. */
export async function answerApproval(id: string, decision: ApprovalDecision): Promise<boolean> {
const res = await apiFetch(`/v1/chat/approvals/${encodeURIComponent(id)}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ decision }),
});
if (res.status === 404) return false;
if (!res.ok) throw new Error(`Approval failed: ${res.status}`);
return true;
}

/** Stop a running Agent mode task. */
export async function stopAgentRun(runId: string): Promise<void> {
await apiFetch(`/v1/chat/runs/${encodeURIComponent(runId)}/stop`, { method: 'POST' });
}
7 changes: 6 additions & 1 deletion frontend/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,14 @@ export interface ToolCallInfo {
id: string;
tool: string;
arguments: string;
status: 'running' | 'success' | 'error';
/** `awaiting_approval` and `approved`/`denied` come from Agent mode approvals. */
status: 'running' | 'success' | 'error' | 'awaiting_approval' | 'approved' | 'denied';
result?: string;
latency?: number;
/** Id to answer with `answerApproval`, while the agent waits for the user. */
approvalId?: string;
/** `change` writes something, `run` runs a command or code. */
risk?: 'change' | 'run';
}

export interface TokenUsage {
Expand Down
Loading
Loading