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
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# Provider-agnostic override (used before any provider-specific key above).
# PARALLAX_API_KEY=

# --- Web tools ---
# The web_search tool uses Tavily (https://tavily.com — free tier available).
# Set this to enable it; without it, web_search returns a friendly error.
# TAVILY_API_KEY=tvly-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

# Optional: override the model. Each provider has a sensible default, e.g.:
# anthropic claude-opus-4-8 (default)
# openai gpt-4o
Expand Down
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ Config resolves as `CLI flag > env > parallax.json > built-in default`:
| ----------------------------------------- | --------------------------------------- | ----------------------------- |
| `PARALLAX_PROVIDER` (or `-p`) | provider id (see table above) | `fake` |
| `<PROVIDER>_API_KEY` / `PARALLAX_API_KEY` | API key for the provider | — |
| `TAVILY_API_KEY` | API key for the `web_search` tool | — |
| `PARALLAX_MODEL` (or `-m`) | model id | provider's default |
| `PARALLAX_API_BASE_URL` | override the OpenAI-compatible endpoint | provider's default |
| `PARALLAX_MODELS_URL` | models.dev catalog endpoint | `https://models.dev/api.json` |
Expand Down Expand Up @@ -236,6 +237,12 @@ approval → execute → persist → model`.
read-before-write stale checks.
- `shell` tool over a `HostExecutor` with timeout, output caps, cancellation, and
process-group cleanup.
- Planning + task tools: `update_todos` (a live task checklist) and `present_plan`
(a Claude Code-style plan gate — approving it exits plan mode straight into
workspace mode so execution continues in the same turn).
- Web tools: `web_search` (via Tavily) and `web_fetch` (URL → readable text),
classified as `network` risk with SSRF guards (localhost / private / link-local
and cloud-metadata targets are refused, redirects re-validated).
- Deterministic `ALLOW / ASK / DENY` policy with `read-only`, `workspace`, and
`plan` modes; approvals support "allow once" and "allow always" (remembered
per session).
Expand All @@ -257,7 +264,7 @@ and the maintainer [release guide](docs/releasing.md).

## Not in v0.1 (designed-for extension points)

Context compaction, MCP / skills / hooks, browser & web tools,
Context compaction, MCP / skills / hooks, browser automation,
checkpoints/undo, subagents, and sandboxed executor backends.
The interfaces (`ModelProvider`, `Executor`, `ToolRegistry`, `SessionStore`) are
shaped so these slot in without reworking the runtime.
Expand Down
23 changes: 23 additions & 0 deletions src/app/toolset.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Config } from '../config/index.ts';
import { resolveSearchApiKey } from '../config/index.ts';
import { HostExecutor } from '../executor/index.ts';
import {
FileStateCache,
Expand All @@ -9,6 +10,9 @@ import {
createEditFileTool,
} from '../tools/fs/index.ts';
import { createShellTool } from '../tools/shell/index.ts';
import { createUpdateTodosTool } from '../tools/todo/index.ts';
import { createPresentPlanTool } from '../tools/plan/index.ts';
import { createWebFetchTool, createWebSearchTool } from '../tools/web/index.ts';
import type { ToolRegistry } from '../tools/core/index.ts';

/**
Expand Down Expand Up @@ -43,6 +47,25 @@ export function defaultToolset(config: Config): {
maxModelChars: config.maxToolResultChars,
}),
);
// Planning / task-tracking tools (no side effects; run in every mode).
registry.register(createUpdateTodosTool({ maxModelChars: config.maxToolResultChars }));
registry.register(createPresentPlanTool({ maxModelChars: config.maxToolResultChars }));
// Network tools (policy ASKs in workspace, DENIes in plan/read-only).
registry.register(
createWebFetchTool({
timeoutMs: config.webRequestTimeoutMs,
maxBytes: config.webFetchMaxBytes,
maxModelChars: config.maxToolResultChars,
}),
);
registry.register(
createWebSearchTool({
getApiKey: resolveSearchApiKey,
timeoutMs: config.webRequestTimeoutMs,
maxResults: config.webSearchMaxResults,
maxModelChars: config.maxToolResultChars,
}),
);
};

return { registerTools, fileState };
Expand Down
3 changes: 3 additions & 0 deletions src/cli/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ export class CliRenderer {
break;
case 'turn.completed':
break;
case 'mode.changed':
this.write(dim(` → permission mode: ${event.mode}\n`));
break;
case 'turn.cancelled':
this.write(yellow('\n[cancelled]\n'));
break;
Expand Down
13 changes: 13 additions & 0 deletions src/cli/tui/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,19 @@ export function App(props: AppProps): React.ReactElement {
}
}, [needsSetup, introDone, autoOpened, dialogOpen, openDialog, provider]);

// The runtime can change permission mode mid-turn: approving the `present_plan`
// gate emits `mode.changed`, which the reducer folds into
// `session.permissionMode`. Mirror that into local `mode` so the footer and the
// next Shift+Tab start from the new mode. Only the auto-switch updates the
// session mode in the reducer, so this never fights the manual Shift+Tab path.
const sessionMode = state.session?.permissionMode;
useEffect(() => {
// Keyed on sessionMode only (by design): a manual Shift+Tab updates local
// `mode` without changing `sessionMode`, so it must not re-run this and get
// reverted. Only the runtime's `mode.changed` moves `sessionMode`.
if (sessionMode && sessionMode !== mode) setMode(sessionMode as PermissionMode);
}, [sessionMode]);

// Global chords: Shift+Tab cycles mode; Esc/Ctrl-C cancels a turn or quits.
// While the dialog is open it owns the keyboard, so these must not fire.
useInput((input, key) => {
Expand Down
47 changes: 47 additions & 0 deletions src/cli/tui/components/PlanBlock.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import React from 'react';
import { Box, Text } from 'ink';
import Spinner from 'ink-spinner';
import type { ToolItem } from '../timeline.ts';
import { glyphs, type Theme } from '../theme.ts';

/**
* Renders a `present_plan` call: the proposed plan in a bordered panel (the plan
* text comes from the tool call's `plan` argument). Because `tool.proposed` is
* emitted before `approval.requested`, this block appears directly above the
* approval prompt — so the user reads the full plan, then answers "approve to
* exit plan mode and start executing".
*/
export function PlanBlock({ tool, theme }: { tool: ToolItem; theme: Theme }): React.ReactElement {
const plan = typeof tool.args['plan'] === 'string' ? (tool.args['plan'] as string) : '';
const running = tool.status === 'running' || tool.status === 'proposed';
const bulletColor =
tool.status === 'failed'
? theme.error
: tool.status === 'completed'
? theme.success
: theme.permission;
return (
<Box flexDirection="column" marginTop={1}>
<Box>
<Text color={bulletColor}>{running ? <Spinner type="dots" /> : glyphs.bullet}</Text>
<Text> </Text>
<Text color={theme.text} bold>
Plan
</Text>
</Box>
<Box
flexDirection="column"
marginLeft={2}
borderStyle="round"
borderColor={theme.permission}
paddingX={1}
>
{plan.split('\n').map((line, i) => (
<Text key={`${i}-${line}`} color={theme.text}>
{line === '' ? ' ' : line}
</Text>
))}
</Box>
</Box>
);
}
5 changes: 5 additions & 0 deletions src/cli/tui/components/Timeline.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import React from 'react';
import { Box, Static } from 'ink';
import type { ApprovalDecision } from '../../../protocol/index.ts';
import { PLAN_TOOL_NAME, TODO_TOOL_NAME } from '../../../protocol/index.ts';
import type { TimelineItem } from '../timeline.ts';
import { type Theme } from '../theme.ts';
import { UserMessage, AssistantMessage, Notice } from './Message.tsx';
import { ToolBlock } from './ToolBlock.tsx';
import { TodoBlock } from './TodoBlock.tsx';
import { PlanBlock } from './PlanBlock.tsx';
import { ApprovalPrompt } from './ApprovalPrompt.tsx';

/**
Expand All @@ -27,6 +30,8 @@ function renderItem(
case 'assistant':
return <AssistantMessage item={item} theme={theme} />;
case 'tool':
if (item.name === TODO_TOOL_NAME) return <TodoBlock tool={item} theme={theme} />;
if (item.name === PLAN_TOOL_NAME) return <PlanBlock tool={item} theme={theme} />;
return <ToolBlock tool={item} theme={theme} />;
case 'notice':
return <Notice item={item} theme={theme} />;
Expand Down
79 changes: 79 additions & 0 deletions src/cli/tui/components/TodoBlock.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import React from 'react';
import { Box, Text } from 'ink';
import type { ToolItem } from '../timeline.ts';
import { type Theme } from '../theme.ts';

/**
* Renders an `update_todos` call as a live checklist (Claude Code's todo panel).
* The list is read from the tool call's arguments (`item.args.todos`), which the
* reducer already captured — the tool has no separate state. Defensive parsing:
* the model's arguments are untrusted shape until the tool validates them, and
* this renders off the proposed args (before execution).
*/
interface TodoView {
content: string;
status: 'pending' | 'in_progress' | 'completed';
}

const MARK: Record<TodoView['status'], string> = {
pending: '☐',
in_progress: '◐',
completed: '☑',
};

function parseTodos(args: Record<string, unknown>): TodoView[] {
const raw = args['todos'];
if (!Array.isArray(raw)) return [];
const out: TodoView[] = [];
for (const entry of raw) {
if (entry && typeof entry === 'object') {
const content = (entry as Record<string, unknown>)['content'];
const status = (entry as Record<string, unknown>)['status'];
if (typeof content === 'string') {
const s: TodoView['status'] =
status === 'in_progress' || status === 'completed' ? status : 'pending';
out.push({ content, status: s });
}
}
}
return out;
}

export function TodoBlock({ tool, theme }: { tool: ToolItem; theme: Theme }): React.ReactElement {
const todos = parseTodos(tool.args);
const done = todos.filter((t) => t.status === 'completed').length;
return (
<Box flexDirection="column" marginTop={1}>
<Box>
<Text color={theme.accent}>{'⏺'}</Text>
<Text> </Text>
<Text color={theme.text} bold>
Todos{' '}
</Text>
<Text color={theme.subtle}>
({done}/{todos.length})
</Text>
</Box>
<Box flexDirection="column" marginLeft={2}>
{todos.length === 0 ? (
<Text color={theme.subtle}>(empty)</Text>
) : (
todos.map((t, i) => {
const color =
t.status === 'completed'
? theme.success
: t.status === 'in_progress'
? theme.accent
: theme.subtle;
return (
<Text key={`${i}-${t.content}`} color={color}>
{MARK[t.status]}{' '}
{t.status === 'completed' ? <Text strikethrough>{t.content}</Text> : t.content}
</Text>
);
})
)}
</Box>
</Box>
);
}
27 changes: 27 additions & 0 deletions src/cli/tui/timeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ export function toolLabel(name: string, args: Record<string, unknown>): string {
const path = typeof args['path'] === 'string' ? (args['path'] as string) : undefined;
const command = typeof args['command'] === 'string' ? (args['command'] as string) : undefined;
const query = typeof args['query'] === 'string' ? (args['query'] as string) : undefined;
const url = typeof args['url'] === 'string' ? (args['url'] as string) : undefined;
const todos = Array.isArray(args['todos']) ? (args['todos'] as unknown[]) : undefined;
switch (name) {
case 'shell':
return `Bash(${truncateArg(command ?? '')})`;
Expand All @@ -111,11 +113,29 @@ export function toolLabel(name: string, args: Record<string, unknown>): string {
return `List(${path ?? '.'})`;
case 'search_files':
return `Search(${truncateArg(query ?? '')})`;
case 'update_todos':
return `Todo(${todos ? todos.length : 0} item${todos && todos.length === 1 ? '' : 's'})`;
case 'present_plan':
return 'Plan';
case 'web_fetch':
return `Fetch(${truncateArg(hostOf(url) ?? url ?? '')})`;
case 'web_search':
return `WebSearch(${truncateArg(query ?? '')})`;
default:
return name;
}
}

/** Best-effort host extraction for a URL label; falls back to `undefined`. */
function hostOf(url: string | undefined): string | undefined {
if (!url) return undefined;
try {
return new URL(url).host;
} catch {
return undefined;
}
}

function truncateArg(s: string, max = 48): string {
const oneLine = s.replace(/\s+/g, ' ').trim();
return oneLine.length > max ? `${oneLine.slice(0, max - 1)}…` : oneLine;
Expand Down Expand Up @@ -300,6 +320,13 @@ export function reduceTimeline(state: TimelineState, event: RuntimeEvent): Timel
case 'turn.completed':
return { ...state, active: false };

case 'mode.changed':
// The runtime switched permission mode mid-run (e.g. the plan gate was
// approved). Reflect it in the session info the footer/header read.
return state.session
? { ...state, session: { ...state.session, permissionMode: event.mode } }
: state;

case 'turn.cancelled':
return {
...state,
Expand Down
2 changes: 1 addition & 1 deletion src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export {
type Config,
type ProviderName,
} from './schema.ts';
export { loadConfig, resolveApiKey } from './loadConfig.ts';
export { loadConfig, resolveApiKey, resolveSearchApiKey } from './loadConfig.ts';
export {
configHome,
databasePath,
Expand Down
11 changes: 11 additions & 0 deletions src/config/loadConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,14 @@ export function resolveApiKey(provider: string): string | undefined {
}
return getCredential(provider);
}

/**
* Resolve the web-search (Tavily) API key: the `TAVILY_API_KEY` environment
* variable first, then the on-disk credentials store under the `tavily` key
* (so a key can be saved once and reused, like a provider key). Read lazily by
* the `web_search` tool so a key added mid-session is picked up. Never persisted
* to `Config`, so it can't leak into the store or logs.
*/
export function resolveSearchApiKey(): string | undefined {
return process.env.TAVILY_API_KEY ?? getCredential('tavily');
}
13 changes: 12 additions & 1 deletion src/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,14 @@ export const configSchema = z.object({
systemPrompt: z
.string()
.default(
'You are Parallax, a careful general-purpose agent. Use the provided tools to inspect and act on the workspace. Prefer native file tools over shell for reading and editing. Explain what you did concisely.',
'You are Parallax, a careful general-purpose agent. Use the provided tools to inspect and act on ' +
'the workspace. Prefer native file tools over shell for reading and editing. ' +
'For any multi-step task, maintain a task list with `update_todos` (send the full list each time, ' +
'keep exactly one task in_progress, and mark tasks completed as you finish them). ' +
'When in plan mode, research read-only (read/list/search, and web tools if needed), then call ' +
'`present_plan` with a concrete Markdown plan; approving it exits plan mode so you can execute. ' +
'Use `web_search` for current information beyond your knowledge and `web_fetch` to read a specific ' +
'URL. Explain what you did concisely.',
),
maxToolResultChars: z.number().int().positive().default(16_000),
maxMessages: z.number().int().nonnegative().default(0),
Expand All @@ -49,6 +56,10 @@ export const configSchema = z.object({
maxSearchResults: z.number().int().positive().default(200),
shellTimeoutMs: z.number().int().positive().default(120_000),
shellMaxOutputBytes: z.number().int().positive().default(1_000_000),
// Web tool limits (network tools: web_fetch, web_search).
webRequestTimeoutMs: z.number().int().positive().default(15_000),
webFetchMaxBytes: z.number().int().positive().default(2_000_000),
webSearchMaxResults: z.number().int().positive().max(10).default(5),
});

export type Config = z.infer<typeof configSchema>;
Expand Down
Loading