diff --git a/.env.example b/.env.example index 1e12ba0..822cb13 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/README.md b/README.md index 6c84f7f..b220082 100644 --- a/README.md +++ b/README.md @@ -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` | | `_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` | @@ -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). @@ -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. diff --git a/src/app/toolset.ts b/src/app/toolset.ts index 8e73637..b591d27 100644 --- a/src/app/toolset.ts +++ b/src/app/toolset.ts @@ -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, @@ -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'; /** @@ -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 }; diff --git a/src/cli/renderer.ts b/src/cli/renderer.ts index fd582ef..8f2b67e 100644 --- a/src/cli/renderer.ts +++ b/src/cli/renderer.ts @@ -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; diff --git a/src/cli/tui/App.tsx b/src/cli/tui/App.tsx index 4254ea5..676a798 100644 --- a/src/cli/tui/App.tsx +++ b/src/cli/tui/App.tsx @@ -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) => { diff --git a/src/cli/tui/components/PlanBlock.tsx b/src/cli/tui/components/PlanBlock.tsx new file mode 100644 index 0000000..7c1209c --- /dev/null +++ b/src/cli/tui/components/PlanBlock.tsx @@ -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 ( + + + {running ? : glyphs.bullet} + + + Plan + + + + {plan.split('\n').map((line, i) => ( + + {line === '' ? ' ' : line} + + ))} + + + ); +} diff --git a/src/cli/tui/components/Timeline.tsx b/src/cli/tui/components/Timeline.tsx index e6f4d4c..a5cc0ef 100644 --- a/src/cli/tui/components/Timeline.tsx +++ b/src/cli/tui/components/Timeline.tsx @@ -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'; /** @@ -27,6 +30,8 @@ function renderItem( case 'assistant': return ; case 'tool': + if (item.name === TODO_TOOL_NAME) return ; + if (item.name === PLAN_TOOL_NAME) return ; return ; case 'notice': return ; diff --git a/src/cli/tui/components/TodoBlock.tsx b/src/cli/tui/components/TodoBlock.tsx new file mode 100644 index 0000000..124f6ac --- /dev/null +++ b/src/cli/tui/components/TodoBlock.tsx @@ -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 = { + pending: '☐', + in_progress: '◐', + completed: '☑', +}; + +function parseTodos(args: Record): 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)['content']; + const status = (entry as Record)['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 ( + + + {'⏺'} + + + Todos{' '} + + + ({done}/{todos.length}) + + + + {todos.length === 0 ? ( + (empty) + ) : ( + todos.map((t, i) => { + const color = + t.status === 'completed' + ? theme.success + : t.status === 'in_progress' + ? theme.accent + : theme.subtle; + return ( + + {MARK[t.status]}{' '} + {t.status === 'completed' ? {t.content} : t.content} + + ); + }) + )} + + + ); +} diff --git a/src/cli/tui/timeline.ts b/src/cli/tui/timeline.ts index 57ada32..ee39f17 100644 --- a/src/cli/tui/timeline.ts +++ b/src/cli/tui/timeline.ts @@ -98,6 +98,8 @@ export function toolLabel(name: string, args: Record): 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 ?? '')})`; @@ -111,11 +113,29 @@ export function toolLabel(name: string, args: Record): 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; @@ -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, diff --git a/src/config/index.ts b/src/config/index.ts index feecfcf..9f9712b 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -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, diff --git a/src/config/loadConfig.ts b/src/config/loadConfig.ts index 421cdf4..a5e6193 100644 --- a/src/config/loadConfig.ts +++ b/src/config/loadConfig.ts @@ -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'); +} diff --git a/src/config/schema.ts b/src/config/schema.ts index e98db9b..5a2f988 100644 --- a/src/config/schema.ts +++ b/src/config/schema.ts @@ -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), @@ -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; diff --git a/src/policy/PolicyEngine.ts b/src/policy/PolicyEngine.ts index 585a823..05b1543 100644 --- a/src/policy/PolicyEngine.ts +++ b/src/policy/PolicyEngine.ts @@ -1,4 +1,4 @@ -import { newApprovalId, type ToolRisk } from '../protocol/index.ts'; +import { newApprovalId, PLAN_TOOL_NAME, type ToolRisk } from '../protocol/index.ts'; import { classifyCommand } from './commandRisk.ts'; import type { PermissionContext, PermissionDecision } from './PermissionDecision.ts'; @@ -8,8 +8,9 @@ const READ_RISKS: ReadonlySet = new Set(['read']); * Deterministic ALLOW / ASK / DENY engine (blueprint §16). The model proposes, * this decides (Principle 1). Rules, in order: * 1. Any path escaping the workspace → DENY (blueprint §17). - * 2. read-only / plan mode → allow reads, DENY every mutating/side-effecting tool. - * 3. workspace mode → allow reads, ASK for writes/shell/destructive/network. + * 2. The `present_plan` gate: ASK in plan mode, ALLOW elsewhere. + * 3. read-only / plan mode → allow reads, DENY every mutating/side-effecting tool. + * 4. workspace mode → allow reads, ASK for writes/shell/destructive/network. * The engine never executes; it only classifies. */ export class PolicyEngine { @@ -21,6 +22,28 @@ export class PolicyEngine { }; } + // The plan-mode "exit gate". `present_plan` has no side effects of its own + // (risk `read`), but in plan mode it is the deliberate hand-off point: we ASK + // so approving it can flip the session to workspace mode (TurnController). In + // any other mode there is nothing to switch, so it is a plain ALLOW. + if (ctx.toolName === PLAN_TOOL_NAME) { + if (ctx.mode !== 'plan') { + return { kind: 'allow', reason: `${ctx.toolName}: plan presented (no mode change)` }; + } + return { + kind: 'ask', + reason: 'plan mode: approve to exit plan mode and start executing', + approval: { + id: newApprovalId(), + toolCallId: ctx.toolCallId, + toolName: ctx.toolName, + title: ctx.actionTitle, + ...(ctx.actionDetail !== undefined ? { detail: ctx.actionDetail } : {}), + risk: ctx.risk, + }, + }; + } + const isRead = READ_RISKS.has(ctx.risk); // `plan` gates identically to `read-only` (no side effects); it differs only diff --git a/src/protocol/events.ts b/src/protocol/events.ts index 8899ea8..b382f13 100644 --- a/src/protocol/events.ts +++ b/src/protocol/events.ts @@ -140,6 +140,19 @@ export const turnFailedEvent = z.object({ message: z.string(), }); +/** + * The session's permission mode changed mid-run (blueprint §16.3). Currently + * emitted when the `present_plan` gate is approved and the runtime flips the + * session from `plan` to `workspace`. UIs update their mode indicator; the + * timeline reducer folds it into `session.permissionMode`. + */ +export const modeChangedEvent = z.object({ + ...base, + type: z.literal('mode.changed'), + turnId: z.string(), + mode: z.string(), +}); + export const runtimeEventSchema = z.discriminatedUnion('type', [ sessionStartedEvent, turnStartedEvent, @@ -157,6 +170,7 @@ export const runtimeEventSchema = z.discriminatedUnion('type', [ turnCompletedEvent, turnCancelledEvent, turnFailedEvent, + modeChangedEvent, ]); export type RuntimeEvent = z.infer; diff --git a/src/protocol/ids.ts b/src/protocol/ids.ts index 461b09b..889cc70 100644 --- a/src/protocol/ids.ts +++ b/src/protocol/ids.ts @@ -8,8 +8,10 @@ export type SessionId = string; export type TurnId = string; export type ToolCallId = string; export type ApprovalId = string; +export type MessageId = string; export const newSessionId = (): SessionId => randomUUID(); export const newTurnId = (): TurnId => randomUUID(); export const newToolCallId = (): ToolCallId => randomUUID(); export const newApprovalId = (): ApprovalId => randomUUID(); +export const newMessageId = (): MessageId => randomUUID(); diff --git a/src/protocol/index.ts b/src/protocol/index.ts index edd757e..113b236 100644 --- a/src/protocol/index.ts +++ b/src/protocol/index.ts @@ -1,6 +1,7 @@ export * from './ids.ts'; export * from './risk.ts'; export * from './tool.ts'; +export * from './toolNames.ts'; export * from './approval.ts'; export * from './events.ts'; export * from './commands.ts'; diff --git a/src/protocol/toolNames.ts b/src/protocol/toolNames.ts new file mode 100644 index 0000000..f61079c --- /dev/null +++ b/src/protocol/toolNames.ts @@ -0,0 +1,15 @@ +/** + * Well-known tool names that the runtime/policy/UI treat specially, kept in + * `protocol` (a leaf layer) so `policy`, `runtime`, and `cli` can reference them + * without importing the `tools` layer (which would cross an architectural + * boundary; see eslint.config.js). The tool implementations import the same + * constants, so the string is defined exactly once. + * + * - `present_plan` is the plan-mode "exit gate": in `plan` mode it is the one + * tool the policy engine turns into an ASK, and approving it flips the session + * to `workspace` mode (see PolicyEngine + TurnController). + * - `update_todos` is the model's task-list tool; the TUI renders its arguments + * as a live checklist rather than a generic tool block. + */ +export const PLAN_TOOL_NAME = 'present_plan'; +export const TODO_TOOL_NAME = 'update_todos'; diff --git a/src/runtime/TurnController.ts b/src/runtime/TurnController.ts index b96b85b..440382b 100644 --- a/src/runtime/TurnController.ts +++ b/src/runtime/TurnController.ts @@ -1,4 +1,5 @@ import type { Logger } from '../observability/index.ts'; +import { PLAN_TOOL_NAME } from '../protocol/index.ts'; import type { EmittedEvent, EmittedEventBody, @@ -103,6 +104,9 @@ export class TurnController { } async run(ctx: TurnContext): Promise { + // The turn's live permission mode. It can change mid-turn: approving the + // `present_plan` gate flips plan → workspace so the same turn starts editing. + let mode: PermissionMode = ctx.mode; for (let step = 0; step < this.d.maxSteps; step += 1) { this.throwIfAborted(ctx); @@ -143,7 +147,8 @@ export class TurnController { for (const call of response.toolCalls) { this.throwIfAborted(ctx); - await this.handleToolCall(ctx, call); + const nextMode = await this.handleToolCall(ctx, call, mode); + if (nextMode) mode = nextMode; } } @@ -187,7 +192,11 @@ export class TurnController { return response; } - private async handleToolCall(ctx: TurnContext, call: ToolCall): Promise { + private async handleToolCall( + ctx: TurnContext, + call: ToolCall, + mode: PermissionMode, + ): Promise { await this.emit(ctx, { type: 'tool.proposed', turnId: ctx.turnId, call }); await this.d.store.recordToolCall({ id: call.id, @@ -246,7 +255,7 @@ export class TurnController { sessionId: ctx.sessionId, turnId: ctx.turnId, workspaceRoot: ctx.workspaceRoot, - mode: ctx.mode, + mode, toolName: tool.name, toolCallId: call.id, risk: tool.risk, @@ -284,7 +293,11 @@ export class TurnController { }); const outcome = await wait; // "Always allow" → remember so this tool won't prompt again this session. - if (outcome === 'allow_always') this.d.grantedTools.add(tool.name); + // The plan gate is excluded: it must re-prompt whenever the user returns to + // plan mode (and approving it switches modes anyway, so it won't re-ask). + if (outcome === 'allow_always' && tool.name !== PLAN_TOOL_NAME) { + this.d.grantedTools.add(tool.name); + } await this.emit(ctx, { type: 'approval.resolved', turnId: ctx.turnId, @@ -329,6 +342,17 @@ export class TurnController { } else { await this.emit(ctx, { type: 'tool.failed', turnId: ctx.turnId, result }); } + + // 8. The `present_plan` gate. Reaching here in plan mode means the plan was + // approved (a denial returns early above). Exit plan mode: persist the new + // mode, announce it (mode.changed), and hand `workspace` back to the turn + // loop so the same turn can start making changes. + if (tool.name === PLAN_TOOL_NAME && mode === 'plan' && result.ok) { + await this.d.store.updateSession(ctx.sessionId, { permissionMode: 'workspace' }); + await this.emit(ctx, { type: 'mode.changed', turnId: ctx.turnId, mode: 'workspace' }); + return 'workspace'; + } + return undefined; } private async finishFailed(ctx: TurnContext, call: ToolCall, result: ToolResult): Promise { diff --git a/src/sessions/InMemorySessionStore.ts b/src/sessions/InMemorySessionStore.ts index 1932479..16305de 100644 --- a/src/sessions/InMemorySessionStore.ts +++ b/src/sessions/InMemorySessionStore.ts @@ -1,4 +1,4 @@ -import { newSessionId, newTurnId, type RuntimeEvent } from '../protocol/index.ts'; +import { newMessageId, newSessionId, newTurnId, type RuntimeEvent } from '../protocol/index.ts'; import type { SessionStore } from './SessionStore.ts'; import type { PermissionMode } from '../protocol/index.ts'; import type { @@ -14,8 +14,6 @@ import type { TurnStatus, } from './records.ts'; -let messageSeq = 0; - /** * Non-durable SessionStore for tests and the fake-driven loop. Keeps the same * semantics as the SQLite store so swapping them is a wiring change only @@ -119,7 +117,7 @@ export class InMemorySessionStore implements SessionStore { appendMessage(input: AppendMessageInput): Promise { const record: MessageRecord = { - id: `m${(messageSeq += 1)}`, + id: newMessageId(), sessionId: input.sessionId, turnId: input.turnId, role: input.role, diff --git a/src/sessions/SqliteSessionStore.ts b/src/sessions/SqliteSessionStore.ts index 6504ef4..1a7c104 100644 --- a/src/sessions/SqliteSessionStore.ts +++ b/src/sessions/SqliteSessionStore.ts @@ -1,6 +1,7 @@ import { mkdirSync } from 'node:fs'; import { dirname } from 'node:path'; import { + newMessageId, newSessionId, newTurnId, parseRuntimeEvent, @@ -29,8 +30,6 @@ function nn(v: T | undefined): T | null { return v === undefined ? null : v; } -let messageCounter = 0; - interface SessionRow { id: string; created_at: number; @@ -191,11 +190,14 @@ export class SqliteSessionStore implements SessionStore { } appendMessage(input: AppendMessageInput): Promise { + // `seq` is the per-session ordering key (MAX(seq)+1); the row `id` must be + // globally unique across all sessions and process restarts, so it comes from + // a UUID rather than any counter derived from `seq`. const seqRow = this.db .prepare('SELECT COALESCE(MAX(seq), -1) + 1 AS s FROM messages WHERE session_id = ?') .get(input.sessionId) as { s: number }; const record: MessageRecord = { - id: `m${(messageCounter += 1)}-${seqRow.s}`, + id: newMessageId(), sessionId: input.sessionId, turnId: input.turnId, role: input.role, diff --git a/src/tools/core/errors.ts b/src/tools/core/errors.ts index d0c97ef..914c1be 100644 --- a/src/tools/core/errors.ts +++ b/src/tools/core/errors.ts @@ -17,6 +17,8 @@ export const ErrorCode = { OutputLimit: 'output_limit', UnknownTool: 'unknown_tool', Cancelled: 'cancelled', + NetworkError: 'network_error', + MissingCredential: 'missing_credential', InternalError: 'internal_error', } as const; diff --git a/src/tools/plan/index.ts b/src/tools/plan/index.ts new file mode 100644 index 0000000..2f2d3ed --- /dev/null +++ b/src/tools/plan/index.ts @@ -0,0 +1 @@ +export { createPresentPlanTool } from './presentPlan.ts'; diff --git a/src/tools/plan/presentPlan.ts b/src/tools/plan/presentPlan.ts new file mode 100644 index 0000000..b1c4423 --- /dev/null +++ b/src/tools/plan/presentPlan.ts @@ -0,0 +1,57 @@ +import { z } from 'zod'; +import { PLAN_TOOL_NAME } from '../../protocol/index.ts'; +import { ok, truncateMiddle, type ToolDefinition } from '../core/index.ts'; + +/** + * `present_plan` (Claude Code's ExitPlanMode). The agent researches read-only in + * `plan` mode, then calls this to present a concrete implementation plan for + * approval. The tool itself has no side effects (risk `read`) — it just echoes + * the plan so the TUI can render it (see PlanBlock). The *gate* behavior lives + * outside the tool: + * + * - PolicyEngine turns this one tool into an ASK when the session is in `plan` + * mode (it is a no-op ALLOW in other modes). + * - TurnController, on approval, flips the session from `plan` to `workspace` + * and emits `mode.changed`, so the same turn can start executing. + * + * Keeping the mode transition in the runtime (not the tool) respects the layer + * boundary: a tool has no access to the session store or event bus. + */ + +const inputSchema = z.object({ + /** The implementation plan, as Markdown. Shown to the user for approval. */ + plan: z.string().min(1), +}); + +type Input = z.infer; + +interface Output { + plan: string; +} + +export function createPresentPlanTool(deps: { + maxModelChars: number; +}): ToolDefinition { + return { + name: PLAN_TOOL_NAME, + description: + 'Present a concrete implementation plan and ask the user for approval to start executing it. Use ' + + 'ONLY when in plan mode, after you have finished researching (reading files, searching). Approving ' + + 'the plan exits plan mode and switches to workspace mode so you can make changes; do not call it ' + + 'when already in workspace mode. Pass the full plan as Markdown in `plan`.', + inputSchema, + risk: 'read', + resourceClass: 'pure_read', + describe(_ctx, _input) { + return Promise.resolve({ + title: 'Ready to code? Approve to exit plan mode and start executing', + }); + }, + execute(ctx, input) { + const modelContent = truncateMiddle(input.plan, { maxChars: deps.maxModelChars }).text; + return Promise.resolve( + ok(ctx.callId, 'presented plan for approval', { plan: input.plan }, { modelContent }), + ); + }, + }; +} diff --git a/src/tools/todo/index.ts b/src/tools/todo/index.ts new file mode 100644 index 0000000..4f5c9ef --- /dev/null +++ b/src/tools/todo/index.ts @@ -0,0 +1 @@ +export { createUpdateTodosTool, type Todo } from './updateTodos.ts'; diff --git a/src/tools/todo/updateTodos.ts b/src/tools/todo/updateTodos.ts new file mode 100644 index 0000000..1fde7f8 --- /dev/null +++ b/src/tools/todo/updateTodos.ts @@ -0,0 +1,87 @@ +import { z } from 'zod'; +import { TODO_TOOL_NAME } from '../../protocol/index.ts'; +import { ok, truncateMiddle, type ToolDefinition } from '../core/index.ts'; + +/** + * `update_todos` (Claude Code's TodoWrite). A stateless task-list tool: the model + * sends the *entire* list every call and the runtime simply echoes it back, so + * the "state" is just the latest call's arguments — the TUI renders them as a + * live checklist (see TodoBlock). No persistence table is needed; the durable + * message history already records each call. + * + * Risk is `read`: it has no side effects on the workspace, so it runs in every + * permission mode and never triggers an approval prompt — exactly like the + * planning scratchpad it models. + */ + +const todoSchema = z.object({ + /** The imperative task, e.g. "Add the web_fetch tool". */ + content: z.string().min(1), + status: z.enum(['pending', 'in_progress', 'completed']), + /** Present-continuous label shown while active, e.g. "Adding the web_fetch tool". */ + activeForm: z.string().min(1).optional(), +}); + +const inputSchema = z.object({ + todos: z.array(todoSchema), +}); + +export type Todo = z.infer; +type Input = z.infer; + +interface Output { + todos: Todo[]; + counts: { total: number; pending: number; inProgress: number; completed: number }; +} + +const STATUS_MARK: Record = { + pending: '[ ]', + in_progress: '[~]', + completed: '[x]', +}; + +/** Render the list as compact text the model re-reads as its own working plan. */ +function renderChecklist(todos: Todo[]): string { + if (todos.length === 0) return '(todo list cleared)'; + return todos.map((t) => `${STATUS_MARK[t.status]} ${t.content}`).join('\n'); +} + +export function createUpdateTodosTool(deps: { + maxModelChars: number; +}): ToolDefinition { + return { + name: TODO_TOOL_NAME, + description: + 'Create and maintain a structured task list for the current work. Send the COMPLETE list every ' + + 'time — it replaces the previous one. Use it to plan multi-step tasks and to show progress: keep ' + + 'exactly one task `in_progress` at a time and mark tasks `completed` as soon as they are done.', + inputSchema, + risk: 'read', + resourceClass: 'pure_read', + describe(_ctx, input) { + const active = input.todos.find((t) => t.status === 'in_progress'); + return Promise.resolve({ + title: active + ? `Todo: ${active.activeForm ?? active.content}` + : `Todo (${input.todos.length})`, + }); + }, + execute(ctx, input) { + const counts = { + total: input.todos.length, + pending: input.todos.filter((t) => t.status === 'pending').length, + inProgress: input.todos.filter((t) => t.status === 'in_progress').length, + completed: input.todos.filter((t) => t.status === 'completed').length, + }; + const summaryParts = [`${counts.total} todo${counts.total === 1 ? '' : 's'}`]; + if (counts.inProgress > 0) summaryParts.push(`${counts.inProgress} in progress`); + if (counts.completed > 0) summaryParts.push(`${counts.completed} done`); + const modelContent = truncateMiddle(renderChecklist(input.todos), { + maxChars: deps.maxModelChars, + }).text; + return Promise.resolve( + ok(ctx.callId, summaryParts.join(' · '), { todos: input.todos, counts }, { modelContent }), + ); + }, + }; +} diff --git a/src/tools/web/http.ts b/src/tools/web/http.ts new file mode 100644 index 0000000..597756f --- /dev/null +++ b/src/tools/web/http.ts @@ -0,0 +1,269 @@ +import { isIP } from 'node:net'; +import { lookup } from 'node:dns/promises'; +import { ErrorCode, ToolExecutionError } from '../core/index.ts'; + +/** + * Shared HTTP core for the network tools (`web_fetch`, `web_search`), with the + * egress guardrails those tools must not skip (blueprint Principle 1 — the model + * proposes a URL, the runtime decides what is reachable). Everything here is + * dependency-free and uses the global `fetch` (Node ≥22), matching + * `config/modelsDev.ts`. + * + * SSRF posture: only `http`/`https`, and never a host that resolves to a + * loopback / private / link-local address — which blocks `localhost`, RFC1918 + * ranges, and the cloud metadata endpoint (169.254.169.254). DNS is resolved and + * *every* answer checked, so a public name that points at a private IP (DNS + * rebinding) is refused too, and redirects are followed manually with the same + * check re-applied at each hop. + */ + +export type FetchImpl = typeof globalThis.fetch; + +export interface FetchTextOptions { + timeoutMs: number; + maxBytes: number; + signal?: AbortSignal | undefined; + fetchImpl?: FetchImpl | undefined; + /** Extra request headers (e.g. a User-Agent). */ + headers?: Record | undefined; +} + +export interface FetchTextResult { + finalUrl: string; + status: number; + contentType: string; + body: string; + truncated: boolean; +} + +const MAX_REDIRECTS = 5; + +function netError(message: string): ToolExecutionError { + return new ToolExecutionError(ErrorCode.NetworkError, message, false); +} + +/** Parse an IPv4 dotted-quad to a 32-bit unsigned int, or `undefined`. */ +function ipv4ToInt(ip: string): number | undefined { + const parts = ip.split('.'); + if (parts.length !== 4) return undefined; + let value = 0; + for (const part of parts) { + if (!/^\d{1,3}$/.test(part)) return undefined; + const n = Number(part); + if (n > 255) return undefined; + value = value * 256 + n; + } + return value >>> 0; +} + +/** True for loopback / private / link-local / reserved IPv4 addresses. */ +function isPrivateIPv4(ip: string): boolean { + const v = ipv4ToInt(ip); + if (v === undefined) return true; // unparseable → treat as unsafe + const inRange = (base: string, maskBits: number): boolean => { + const b = ipv4ToInt(base)!; + const mask = maskBits === 0 ? 0 : (0xffffffff << (32 - maskBits)) >>> 0; + return (v & mask) === (b & mask); + }; + return ( + inRange('0.0.0.0', 8) || // "this" network + inRange('10.0.0.0', 8) || // private + inRange('100.64.0.0', 10) || // carrier-grade NAT + inRange('127.0.0.0', 8) || // loopback + inRange('169.254.0.0', 16) || // link-local + cloud metadata (169.254.169.254) + inRange('172.16.0.0', 12) || // private + inRange('192.0.0.0', 24) || // IETF protocol assignments + inRange('192.168.0.0', 16) || // private + inRange('198.18.0.0', 15) || // benchmarking + inRange('224.0.0.0', 4) || // multicast + inRange('240.0.0.0', 4) // reserved / broadcast + ); +} + +/** True for loopback / unique-local / link-local / multicast IPv6 addresses. */ +function isPrivateIPv6(ip: string): boolean { + const addr = ip.toLowerCase(); + if (addr === '::1' || addr === '::') return true; + // IPv4-mapped (::ffff:a.b.c.d) — defer to the IPv4 check. + const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(addr); + if (mapped) return isPrivateIPv4(mapped[1]!); + const head = addr.split(':')[0] ?? ''; + const first = parseInt(head || '0', 16); + if (Number.isNaN(first)) return true; + if (first >= 0xfc00 && first <= 0xfdff) return true; // fc00::/7 unique-local + if ((first & 0xffc0) === 0xfe80) return true; // fe80::/10 link-local + if ((first & 0xff00) === 0xff00) return true; // ff00::/8 multicast + return false; +} + +function isPrivateAddress(ip: string): boolean { + return isIP(ip) === 6 ? isPrivateIPv6(ip) : isPrivateIPv4(ip); +} + +/** + * Validate a URL for outbound fetching and return the parsed `URL`, or throw a + * `NetworkError`. Rejects non-HTTP(S) schemes and any host that is — or resolves + * to — a non-public address. + */ +export async function assertPublicHttpUrl(raw: string): Promise { + let url: URL; + try { + url = new URL(raw); + } catch { + throw netError(`Invalid URL: ${raw}`); + } + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + throw netError(`Unsupported URL scheme "${url.protocol}" (only http/https)`); + } + const host = url.hostname.toLowerCase(); + if (host === '' || host === 'localhost' || host.endsWith('.localhost')) { + throw netError(`Refusing to fetch a local address: ${url.hostname}`); + } + if (host.endsWith('.local') || host.endsWith('.internal')) { + throw netError(`Refusing to fetch an internal address: ${url.hostname}`); + } + // IPv6 literals arrive bracketed from `URL.hostname` (e.g. "[::1]"); strip the + // brackets so `isIP`/the range checks see the bare address. + const ipHost = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host; + if (isIP(ipHost)) { + if (isPrivateAddress(ipHost)) { + throw netError(`Refusing to fetch a private/loopback address: ${url.hostname}`); + } + return url; + } + let addresses: Array<{ address: string }>; + try { + addresses = await lookup(host, { all: true }); + } catch { + throw netError(`Could not resolve host: ${url.hostname}`); + } + if (addresses.length === 0 || addresses.some((a) => isPrivateAddress(a.address))) { + throw netError(`Host resolves to a private/loopback address: ${url.hostname}`); + } + return url; +} + +/** Read a response body as UTF-8, stopping once `maxBytes` is reached. */ +async function readCapped( + res: Response, + maxBytes: number, +): Promise<{ body: string; truncated: boolean }> { + const reader = res.body?.getReader(); + if (!reader) return { body: '', truncated: false }; + const chunks: Uint8Array[] = []; + let total = 0; + let truncated = false; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + if (!value) continue; + if (total + value.byteLength > maxBytes) { + chunks.push(value.subarray(0, Math.max(0, maxBytes - total))); + truncated = true; + await reader.cancel(); + break; + } + chunks.push(value); + total += value.byteLength; + } + return { body: Buffer.concat(chunks).toString('utf8'), truncated }; +} + +/** + * Fetch a URL as text with a timeout, a byte cap, and manual redirect following + * (re-validating every hop with `assertPublicHttpUrl`). Honors an external abort + * signal (turn cancellation) distinctly from the timeout. + */ +export async function fetchText(raw: string, options: FetchTextOptions): Promise { + const doFetch = options.fetchImpl ?? globalThis.fetch; + let current = await assertPublicHttpUrl(raw); + + for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) { + const timeoutCtrl = new AbortController(); + const timer = setTimeout(() => timeoutCtrl.abort(), options.timeoutMs); + const signals: AbortSignal[] = [timeoutCtrl.signal]; + if (options.signal) signals.push(options.signal); + const signal = signals.length === 1 ? signals[0]! : AbortSignal.any(signals); + + let res: Response; + try { + res = await doFetch(current, { + redirect: 'manual', + signal, + headers: { 'user-agent': 'parallax', ...(options.headers ?? {}) }, + }); + } catch (err) { + if (options.signal?.aborted) { + throw new ToolExecutionError(ErrorCode.Cancelled, 'Request cancelled', false); + } + if (timeoutCtrl.signal.aborted) { + throw netError(`Request timed out after ${options.timeoutMs}ms: ${current.toString()}`); + } + throw netError(`Request failed: ${err instanceof Error ? err.message : String(err)}`); + } finally { + clearTimeout(timer); + } + + // Manual redirect handling (undici exposes the 3xx + Location). + if (res.status >= 300 && res.status < 400) { + const location = res.headers.get('location'); + if (!location) break; // 3xx without a target — treat as final + if (hop === MAX_REDIRECTS) throw netError(`Too many redirects: ${raw}`); + current = await assertPublicHttpUrl(new URL(location, current).toString()); + continue; + } + + const { body, truncated } = await readCapped(res, options.maxBytes); + return { + finalUrl: current.toString(), + status: res.status, + contentType: res.headers.get('content-type') ?? '', + body, + truncated, + }; + } + throw netError(`Too many redirects: ${raw}`); +} + +const NAMED_ENTITIES: Record = { + amp: '&', + lt: '<', + gt: '>', + quot: '"', + '#39': "'", + apos: "'", + nbsp: ' ', +}; + +/** Decode the handful of HTML entities that survive tag-stripping. */ +function decodeEntities(text: string): string { + return text.replace(/&(#x?[0-9a-f]+|[a-z0-9]+);/gi, (whole, body: string) => { + if (body[0] === '#') { + const code = + body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : Number(body.slice(1)); + return Number.isFinite(code) ? String.fromCodePoint(code) : whole; + } + return NAMED_ENTITIES[body.toLowerCase()] ?? whole; + }); +} + +/** + * Reduce an HTML document to readable plain text — dependency-free and lossy by + * design (this feeds a language model, not a browser). Drops script/style, + * turns block boundaries into newlines, strips remaining tags, decodes entities, + * and collapses runaway whitespace. + */ +export function htmlToText(html: string): string { + return decodeEntities( + html + .replace(//g, '') + .replace(/<(script|style)\b[\s\S]*?<\/\1>/gi, '') + .replace(/<\/(p|div|section|article|li|tr|h[1-6]|header|footer)>/gi, '\n') + .replace(/<(br|hr)\s*\/?>/gi, '\n') + .replace(/<[^>]+>/g, ''), + ) + .replace(/[ \t\f\v]+/g, ' ') + .replace(/\n{3,}/g, '\n\n') + .replace(/^[ \t]+|[ \t]+$/gm, '') + .trim(); +} diff --git a/src/tools/web/index.ts b/src/tools/web/index.ts new file mode 100644 index 0000000..9cd58ee --- /dev/null +++ b/src/tools/web/index.ts @@ -0,0 +1,10 @@ +export { createWebFetchTool, type WebFetchDeps } from './webFetch.ts'; +export { createWebSearchTool, type WebSearchDeps } from './webSearch.ts'; +export { + assertPublicHttpUrl, + fetchText, + htmlToText, + type FetchImpl, + type FetchTextOptions, + type FetchTextResult, +} from './http.ts'; diff --git a/src/tools/web/webFetch.ts b/src/tools/web/webFetch.ts new file mode 100644 index 0000000..26ccd00 --- /dev/null +++ b/src/tools/web/webFetch.ts @@ -0,0 +1,114 @@ +import { z } from 'zod'; +import { + ErrorCode, + fail, + ok, + truncateMiddle, + ToolExecutionError, + type ToolDefinition, +} from '../core/index.ts'; +import { assertPublicHttpUrl, fetchText, htmlToText, type FetchImpl } from './http.ts'; + +export interface WebFetchDeps { + timeoutMs: number; + /** Hard cap on bytes read from the response body. */ + maxBytes: number; + /** Cap on characters returned to the model. */ + maxModelChars: number; + /** Injectable for tests; defaults to global fetch. */ + fetchImpl?: FetchImpl; +} + +const inputSchema = z.object({ + url: z.string().url(), + /** Optional per-call cap on characters returned to the model. */ + maxChars: z.number().int().positive().max(200_000).optional(), +}); + +type Input = z.infer; + +interface Output { + url: string; + finalUrl: string; + status: number; + contentType: string; + content: string; + truncated: boolean; +} + +/** + * `web_fetch` (blueprint §8.4 network tool). Fetches a URL and returns readable + * text — HTML is reduced to plain text. Risk is `network`, so the policy engine + * ASKs in workspace mode and DENIes it in plan/read-only. All egress guardrails + * (scheme, private-address/DNS-rebind, redirect re-validation, byte cap) live in + * the shared `http.ts` core. + */ +export function createWebFetchTool(deps: WebFetchDeps): ToolDefinition { + return { + name: 'web_fetch', + description: + 'Fetch a public http(s) URL and return its content as text (HTML is converted to readable text). ' + + 'Use for reading a specific web page or API response. Local/private addresses are refused.', + inputSchema, + risk: 'network', + resourceClass: 'network', + describe(_ctx, input) { + let host = input.url; + try { + host = new URL(input.url).host; + } catch { + /* fall back to the raw string; validation happens in execute */ + } + return Promise.resolve({ + title: `Fetch ${host}`, + detail: input.url, + // Network egress is not a workspace path escape; the policy engine gates + // it purely on the `network` risk. + outsideWorkspace: false, + }); + }, + async execute(ctx, input) { + const maxChars = input.maxChars ?? deps.maxModelChars; + try { + await assertPublicHttpUrl(input.url); + const res = await fetchText(input.url, { + timeoutMs: deps.timeoutMs, + maxBytes: deps.maxBytes, + signal: ctx.signal, + ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}), + }); + const isHtml = /html/i.test(res.contentType) || /^\s*<(!doctype|html)/i.test(res.body); + const text = isHtml ? htmlToText(res.body) : res.body; + const { text: bounded, truncated } = truncateMiddle(text, { maxChars }); + const output: Output = { + url: input.url, + finalUrl: res.finalUrl, + status: res.status, + contentType: res.contentType, + content: bounded, + truncated: truncated || res.truncated, + }; + if (res.status >= 400) { + return { + ...fail(ctx.callId, ErrorCode.NetworkError, `HTTP ${res.status} for ${input.url}`), + data: output, + modelContent: `HTTP ${res.status}\n${bounded}`, + }; + } + return ok(ctx.callId, `fetched ${res.finalUrl} (${output.content.length} chars)`, output, { + truncated: output.truncated, + modelContent: bounded, + }); + } catch (err) { + if (err instanceof ToolExecutionError) { + return fail(ctx.callId, err.code, err.message, { retryable: err.retryable }); + } + return fail( + ctx.callId, + ErrorCode.NetworkError, + err instanceof Error ? err.message : String(err), + ); + } + }, + }; +} diff --git a/src/tools/web/webSearch.ts b/src/tools/web/webSearch.ts new file mode 100644 index 0000000..7ec849e --- /dev/null +++ b/src/tools/web/webSearch.ts @@ -0,0 +1,161 @@ +import { z } from 'zod'; +import { ErrorCode, fail, ok, truncateMiddle, type ToolDefinition } from '../core/index.ts'; +import type { FetchImpl } from './http.ts'; + +export interface WebSearchDeps { + /** + * Resolve the Tavily API key lazily (env `TAVILY_API_KEY`, then the on-disk + * credentials store). A thunk — not a value — so a key entered mid-session is + * picked up without rebuilding the toolset. + */ + getApiKey: () => string | undefined; + timeoutMs: number; + maxResults: number; + maxModelChars: number; + /** Injectable for tests; defaults to global fetch. */ + fetchImpl?: FetchImpl; +} + +const TAVILY_URL = 'https://api.tavily.com/search'; + +const inputSchema = z.object({ + query: z.string().min(1), + maxResults: z.number().int().positive().max(10).optional(), +}); + +type Input = z.infer; + +const tavilyResponseSchema = z.object({ + answer: z.string().optional().nullable(), + results: z + .array( + z.object({ + title: z.string().optional().nullable(), + url: z.string(), + content: z.string().optional().nullable(), + }), + ) + .default([]), +}); + +interface SearchResult { + title: string; + url: string; + snippet: string; +} + +interface Output { + query: string; + answer?: string; + results: SearchResult[]; +} + +/** Render results as the numbered list the model reads. */ +function renderResults(answer: string | undefined, results: SearchResult[]): string { + const lines: string[] = []; + if (answer) lines.push(`Answer: ${answer}`, ''); + results.forEach((r, i) => { + lines.push(`${i + 1}. ${r.title || r.url}`); + lines.push(` ${r.url}`); + if (r.snippet) lines.push(` ${r.snippet}`); + }); + return lines.join('\n').trim() || 'No results.'; +} + +/** + * `web_search` (blueprint §8.4 network tool). Queries the web via Tavily and + * returns a synthesized answer plus ranked results. Risk is `network` (policy + * ASKs in workspace, DENIes in plan/read-only). The endpoint is a fixed, trusted + * host, so no SSRF guard is needed here (unlike `web_fetch`); a timeout and + * cancellation are still honored. + */ +export function createWebSearchTool(deps: WebSearchDeps): ToolDefinition { + return { + name: 'web_search', + description: + 'Search the web for current information and return a short answer plus ranked results (title, URL, ' + + 'snippet). Use for facts likely outside your training data or that may have changed. Requires a ' + + 'Tavily API key (TAVILY_API_KEY).', + inputSchema, + risk: 'network', + resourceClass: 'network', + describe(_ctx, input) { + return Promise.resolve({ title: `Web search: ${input.query}`, outsideWorkspace: false }); + }, + async execute(ctx, input) { + const apiKey = deps.getApiKey(); + if (!apiKey) { + return fail( + ctx.callId, + ErrorCode.MissingCredential, + 'Web search needs a Tavily API key. Set TAVILY_API_KEY (get one at https://tavily.com), then retry.', + ); + } + const doFetch = deps.fetchImpl ?? globalThis.fetch; + const timeoutCtrl = new AbortController(); + const timer = setTimeout(() => timeoutCtrl.abort(), deps.timeoutMs); + const signal = ctx.signal + ? AbortSignal.any([timeoutCtrl.signal, ctx.signal]) + : timeoutCtrl.signal; + try { + const res = await doFetch(TAVILY_URL, { + method: 'POST', + headers: { 'content-type': 'application/json', 'user-agent': 'parallax' }, + body: JSON.stringify({ + api_key: apiKey, + query: input.query, + max_results: input.maxResults ?? deps.maxResults, + include_answer: true, + }), + signal, + }); + if (!res.ok) { + const detail = res.status === 401 ? ' (check TAVILY_API_KEY)' : ''; + return fail( + ctx.callId, + ErrorCode.NetworkError, + `Tavily responded ${res.status}${detail}`, + ); + } + const parsed = tavilyResponseSchema.safeParse(await res.json()); + if (!parsed.success) { + return fail(ctx.callId, ErrorCode.NetworkError, 'Unexpected response from Tavily'); + } + const results: SearchResult[] = parsed.data.results.map((r) => ({ + title: r.title ?? '', + url: r.url, + snippet: r.content ?? '', + })); + const answer = parsed.data.answer ?? undefined; + const output: Output = { query: input.query, results, ...(answer ? { answer } : {}) }; + const modelContent = truncateMiddle(renderResults(answer, results), { + maxChars: deps.maxModelChars, + }).text; + return ok( + ctx.callId, + `searched: ${input.query} (${results.length} result${results.length === 1 ? '' : 's'})`, + output, + { modelContent }, + ); + } catch (err) { + if (ctx.signal?.aborted) { + return fail(ctx.callId, ErrorCode.Cancelled, 'Search cancelled'); + } + if (timeoutCtrl.signal.aborted) { + return fail( + ctx.callId, + ErrorCode.NetworkError, + `Search timed out after ${deps.timeoutMs}ms`, + ); + } + return fail( + ctx.callId, + ErrorCode.NetworkError, + err instanceof Error ? err.message : String(err), + ); + } finally { + clearTimeout(timer); + } + }, + }; +} diff --git a/tests/plan-gate.test.ts b/tests/plan-gate.test.ts new file mode 100644 index 0000000..9e4edcd --- /dev/null +++ b/tests/plan-gate.test.ts @@ -0,0 +1,127 @@ +import { describe, it, expect } from 'vitest'; +import { z } from 'zod'; +import { createRuntime } from '../src/app/index.ts'; +import { defaultConfig } from '../src/config/index.ts'; +import { InMemorySessionStore } from '../src/sessions/index.ts'; +import { + FakeModelProvider, + modelText, + modelToolCall, + type FakeStep, +} from '../src/providers/index.ts'; +import { ok, type ToolDefinition } from '../src/tools/core/index.ts'; +import { createPresentPlanTool } from '../src/tools/plan/index.ts'; +import type { ApprovalDecision, RuntimeEvent } from '../src/protocol/index.ts'; + +/** A minimal write-risk tool so we can prove the mode actually flipped to workspace. */ +function makeWriteTool(): ToolDefinition<{ path: string }, { wrote: string }> & { calls: number } { + const tool = { + name: 'fake_write', + description: 'pretend to write a file', + inputSchema: z.object({ path: z.string() }), + risk: 'write' as const, + resourceClass: 'filesystem_write' as const, + calls: 0, + execute(ctx: { callId: string }, input: { path: string }) { + tool.calls += 1; + return Promise.resolve(ok(ctx.callId, `wrote ${input.path}`, { wrote: input.path })); + }, + }; + return tool; +} + +/** + * Drive a turn while auto-answering every approval with `decision`. Returns the + * captured event stream. Resolving inside the listener works because the runtime + * registers the approval waiter before emitting `approval.requested`. + */ +function harness(steps: FakeStep[], decision: ApprovalDecision) { + const store = new InMemorySessionStore(); + const provider = new FakeModelProvider(steps); + const write = makeWriteTool(); + const events: RuntimeEvent[] = []; + const facade = createRuntime({ + config: defaultConfig(), + provider, + store, + registerTools: (r) => { + r.register(createPresentPlanTool({ maxModelChars: 16_000 })); + r.register(write); + }, + }); + facade.subscribe((e) => { + events.push(e); + if (e.type === 'approval.requested') facade.resolveApproval(e.request.id, decision); + }); + return { store, provider, write, events, facade }; +} + +describe('present_plan mode gate', () => { + it('approving the plan switches the session plan → workspace mid-turn', async () => { + const h = harness( + [ + [ + modelText("Here's the plan."), + modelToolCall('present_plan', { plan: '1. edit\n2. test' }, 'p1'), + ], + // Next step: now in workspace mode, a write is ASK (approved) — not DENY. + [modelToolCall('fake_write', { path: 'a.ts' }, 'w1')], + [modelText('done')], + ], + 'allow_once', + ); + const session = await h.facade.createSession({ cwd: '/w', permissionMode: 'plan' }); + await h.facade.startTurn(session.id, 'plan then do it'); + + // The gate emitted mode.changed → workspace. + const changed = h.events.find((e) => e.type === 'mode.changed'); + expect(changed?.type).toBe('mode.changed'); + if (changed?.type === 'mode.changed') expect(changed.mode).toBe('workspace'); + + // The write actually executed — proving the turn was no longer plan-gated. + expect(h.write.calls).toBe(1); + expect(h.events.some((e) => e.type === 'tool.started' && e.toolName === 'fake_write')).toBe( + true, + ); + + // The switch is persisted for subsequent turns too. + const reloaded = await h.store.getSession(session.id); + expect(reloaded?.permissionMode).toBe('workspace'); + expect(h.events.at(-1)?.type).toBe('turn.completed'); + }); + + it('denying the plan keeps the session in plan mode', async () => { + const h = harness( + [ + [modelToolCall('present_plan', { plan: '1. edit' }, 'p1')], + [modelText('staying in plan then')], + ], + 'deny', + ); + const session = await h.facade.createSession({ cwd: '/w', permissionMode: 'plan' }); + await h.facade.startTurn(session.id, 'plan it'); + + // No mode change; the plan tool call was denied. + expect(h.events.some((e) => e.type === 'mode.changed')).toBe(false); + const failed = h.events.find((e) => e.type === 'tool.failed'); + expect(failed?.type).toBe('tool.failed'); + if (failed?.type === 'tool.failed') expect(failed.result.error?.code).toBe('approval_denied'); + + const reloaded = await h.store.getSession(session.id); + expect(reloaded?.permissionMode).toBe('plan'); + }); + + it('does not prompt for present_plan in workspace mode (nothing to switch)', async () => { + const h = harness( + [[modelToolCall('present_plan', { plan: 'fyi' }, 'p1')], [modelText('ok')]], + 'deny', // would fire if it asked — it must not + ); + const session = await h.facade.createSession({ cwd: '/w', permissionMode: 'workspace' }); + await h.facade.startTurn(session.id, 'here is a plan'); + + expect(h.events.some((e) => e.type === 'approval.requested')).toBe(false); + expect(h.events.some((e) => e.type === 'mode.changed')).toBe(false); + // The tool still ran (it just echoes the plan). + expect(h.events.some((e) => e.type === 'tool.completed')).toBe(true); + }); +}); diff --git a/tests/plan.test.ts b/tests/plan.test.ts new file mode 100644 index 0000000..9790fc4 --- /dev/null +++ b/tests/plan.test.ts @@ -0,0 +1,41 @@ +import { describe, it, expect } from 'vitest'; +import { createPresentPlanTool } from '../src/tools/plan/index.ts'; +import type { ToolExecutionContext } from '../src/tools/core/index.ts'; +import { getLogger } from '../src/observability/index.ts'; + +function ctx(): ToolExecutionContext { + return { + callId: 'c1', + workspaceRoot: process.cwd(), + signal: new AbortController().signal, + emitStdout: () => {}, + emitStderr: () => {}, + logger: getLogger(), + }; +} + +const tool = createPresentPlanTool({ maxModelChars: 16_000 }); + +describe('present_plan tool', () => { + it('is named present_plan and is read-risk (the gate lives in policy/runtime)', () => { + expect(tool.name).toBe('present_plan'); + expect(tool.risk).toBe('read'); + }); + + it('requires a non-empty plan', () => { + expect(tool.inputSchema.safeParse({ plan: '' }).success).toBe(false); + expect(tool.inputSchema.safeParse({ plan: '1. do a thing' }).success).toBe(true); + }); + + it('echoes the plan text back to the model', async () => { + const res = await tool.execute(ctx(), { plan: '1. Read files\n2. Edit\n3. Test' }); + expect(res.ok).toBe(true); + expect(res.data?.plan).toMatch(/Read files/); + expect(res.modelContent).toMatch(/3\. Test/); + }); + + it('describes itself as the exit-plan-mode gate for the approval prompt', async () => { + const desc = await tool.describe!(ctx(), { plan: 'x' }); + expect(desc.title.toLowerCase()).toMatch(/plan mode|start executing/); + }); +}); diff --git a/tests/policy.test.ts b/tests/policy.test.ts index b899471..4097687 100644 --- a/tests/policy.test.ts +++ b/tests/policy.test.ts @@ -136,6 +136,40 @@ describe('PolicyEngine decision table', () => { }); }); +describe('present_plan gate', () => { + it('ASKs in plan mode (approving it exits plan mode)', () => { + const decision = engine.evaluate( + ctx({ toolName: 'present_plan', risk: 'read', mode: 'plan', actionTitle: 'Ready to code?' }), + ); + expect(decision.kind).toBe('ask'); + if (decision.kind === 'ask') { + expect(decision.approval.toolName).toBe('present_plan'); + expect(decision.approval.title).toBe('Ready to code?'); + } + }); + + it('ALLOWs in workspace mode (nothing to switch)', () => { + const decision = engine.evaluate( + ctx({ toolName: 'present_plan', risk: 'read', mode: 'workspace' }), + ); + expect(decision.kind).toBe('allow'); + }); + + it('ALLOWs in read-only mode', () => { + const decision = engine.evaluate( + ctx({ toolName: 'present_plan', risk: 'read', mode: 'read-only' }), + ); + expect(decision.kind).toBe('allow'); + }); + + it('still DENYs when the (irrelevant) path escapes the workspace', () => { + const decision = engine.evaluate( + ctx({ toolName: 'present_plan', risk: 'read', mode: 'plan', outsideWorkspace: true }), + ); + expect(decision.kind).toBe('deny'); + }); +}); + describe('classifyCommand', () => { it('flags recursive force remove', () => { expect(classifyCommand('rm -rf /tmp/x').destructive).toBe(true); diff --git a/tests/sessions.test.ts b/tests/sessions.test.ts index bfd83e0..c864847 100644 --- a/tests/sessions.test.ts +++ b/tests/sessions.test.ts @@ -83,6 +83,53 @@ describe('SqliteSessionStore', () => { reopened.close(); }); + it('gives every message a globally unique id across sessions (regression: messages.id PK collision)', async () => { + // Repro of the original crash: message ids were `m-`. + // The per-session seq restarts at 0 for each new session and the counter restarted + // on every process launch, so the first message of the first session in any launch + // was always `m1-0` — colliding on the second launch against a persistent DB. + const ids = new Set(); + const first = new SqliteSessionStore(dbPath); + const s1 = await first.createSession({ + cwd: '/a', + provider: 'fake', + model: 'm', + permissionMode: 'workspace', + }); + const t1 = await first.createTurn(s1.id, 'hi'); + const m1 = await first.appendMessage({ + sessionId: s1.id, + turnId: t1.id, + role: 'user', + content: 'hi', + }); + ids.add(m1.id); + first.close(); + + // Reopen the same DB file — simulates a fresh process launch (counter would reset). + const second = new SqliteSessionStore(dbPath); + const s2 = await second.createSession({ + cwd: '/b', + provider: 'fake', + model: 'm', + permissionMode: 'workspace', + }); + const t2 = await second.createTurn(s2.id, 'hi again'); + // This is the append that used to throw `UNIQUE constraint failed: messages.id`. + const m2 = await second.appendMessage({ + sessionId: s2.id, + turnId: t2.id, + role: 'user', + content: 'hi again', + }); + expect(ids.has(m2.id)).toBe(false); + // Both sessions' first messages share seq 0 but must have distinct row ids. + expect(m1.id).not.toBe(m2.id); + expect(await second.listMessages(s1.id)).toHaveLength(1); + expect(await second.listMessages(s2.id)).toHaveLength(1); + second.close(); + }); + it('lists sessions most-recently-updated first', async () => { const store = new SqliteSessionStore(dbPath); const a = await store.createSession({ diff --git a/tests/todo.test.ts b/tests/todo.test.ts new file mode 100644 index 0000000..7188f81 --- /dev/null +++ b/tests/todo.test.ts @@ -0,0 +1,59 @@ +import { describe, it, expect } from 'vitest'; +import { createUpdateTodosTool } from '../src/tools/todo/index.ts'; +import type { ToolExecutionContext } from '../src/tools/core/index.ts'; +import { getLogger } from '../src/observability/index.ts'; + +function ctx(): ToolExecutionContext { + return { + callId: 'c1', + workspaceRoot: process.cwd(), + signal: new AbortController().signal, + emitStdout: () => {}, + emitStderr: () => {}, + logger: getLogger(), + }; +} + +const tool = createUpdateTodosTool({ maxModelChars: 16_000 }); + +describe('update_todos tool', () => { + it('is read-risk so it runs in every mode without approval', () => { + expect(tool.risk).toBe('read'); + expect(tool.resourceClass).toBe('pure_read'); + }); + + it('rejects an invalid status', () => { + const parsed = tool.inputSchema.safeParse({ todos: [{ content: 'x', status: 'bogus' }] }); + expect(parsed.success).toBe(false); + }); + + it('echoes the list back with counts in the summary', async () => { + const res = await tool.execute(ctx(), { + todos: [ + { content: 'Write tool', status: 'completed' }, + { content: 'Wire it', status: 'in_progress' }, + { content: 'Test it', status: 'pending' }, + ], + }); + expect(res.ok).toBe(true); + expect(res.data?.counts).toEqual({ total: 3, pending: 1, inProgress: 1, completed: 1 }); + expect(res.summary).toMatch(/3 todos/); + expect(res.summary).toMatch(/1 in progress/); + expect(res.modelContent).toMatch(/\[x\] Write tool/); + expect(res.modelContent).toMatch(/\[~\] Wire it/); + }); + + it("uses the active task's activeForm in the title", async () => { + const desc = await tool.describe!(ctx(), { + todos: [{ content: 'Add tool', status: 'in_progress', activeForm: 'Adding tool' }], + }); + expect(desc.title).toContain('Adding tool'); + }); + + it('handles an empty list (cleared)', async () => { + const res = await tool.execute(ctx(), { todos: [] }); + expect(res.ok).toBe(true); + expect(res.data?.counts.total).toBe(0); + expect(res.modelContent).toMatch(/cleared/); + }); +}); diff --git a/tests/tui-timeline.test.ts b/tests/tui-timeline.test.ts index ff43905..bff3631 100644 --- a/tests/tui-timeline.test.ts +++ b/tests/tui-timeline.test.ts @@ -46,6 +46,14 @@ describe('toolLabel', () => { expect(toolLabel('unknown_tool', {})).toBe('unknown_tool'); }); + it('labels the todo/plan/web tools', () => { + expect(toolLabel('update_todos', { todos: [{}, {}] })).toBe('Todo(2 items)'); + expect(toolLabel('update_todos', { todos: [{}] })).toBe('Todo(1 item)'); + expect(toolLabel('present_plan', { plan: 'x' })).toBe('Plan'); + expect(toolLabel('web_fetch', { url: 'https://example.com/a?b=c' })).toBe('Fetch(example.com)'); + expect(toolLabel('web_search', { query: 'weather' })).toBe('WebSearch(weather)'); + }); + it('truncates long command/query args', () => { const long = 'x'.repeat(80); expect(toolLabel('shell', { command: long }).length).toBeLessThan(60); @@ -71,6 +79,24 @@ describe('timeline reducer', () => { }); }); + it('folds mode.changed into the session permission mode', () => { + const s = fold([ + ev('session.started', { + cwd: '/w', + provider: 'anthropic', + model: 'claude-opus-4-8', + permissionMode: 'plan', + }), + ev('mode.changed', { turnId: 't1', mode: 'workspace' }), + ]); + expect(s.session?.permissionMode).toBe('workspace'); + }); + + it('ignores mode.changed before a session exists', () => { + const s = fold([ev('mode.changed', { turnId: 't1', mode: 'workspace' })]); + expect(s.session).toBeUndefined(); + }); + it('accumulates streaming assistant deltas into one block per step', () => { const s = fold([ ev('turn.started', { turnId: 't1', userText: 'hi' }), diff --git a/tests/web.test.ts b/tests/web.test.ts new file mode 100644 index 0000000..ead8a3a --- /dev/null +++ b/tests/web.test.ts @@ -0,0 +1,215 @@ +import { describe, it, expect } from 'vitest'; +import { createWebFetchTool } from '../src/tools/web/webFetch.ts'; +import { createWebSearchTool } from '../src/tools/web/webSearch.ts'; +import { assertPublicHttpUrl, htmlToText } from '../src/tools/web/http.ts'; +import type { ToolExecutionContext } from '../src/tools/core/index.ts'; +import { getLogger } from '../src/observability/index.ts'; + +function ctx(signal?: AbortSignal): ToolExecutionContext { + return { + callId: 'c1', + workspaceRoot: process.cwd(), + signal: signal ?? new AbortController().signal, + emitStdout: () => {}, + emitStderr: () => {}, + logger: getLogger(), + }; +} + +/** A fetch stub that serves canned responses by URL and records the last body. */ +function fakeFetch( + handler: (url: string, init: RequestInit | undefined) => Response | Promise, +): typeof globalThis.fetch { + return ((input: string | URL, init?: RequestInit) => + Promise.resolve(handler(String(input), init))) as unknown as typeof globalThis.fetch; +} + +const FETCH_DEPS = { timeoutMs: 1000, maxBytes: 1_000_000, maxModelChars: 16_000 }; + +describe('assertPublicHttpUrl (SSRF guard)', () => { + it('accepts a public IP literal without a DNS lookup', async () => { + const url = await assertPublicHttpUrl('http://1.1.1.1/path'); + expect(url.hostname).toBe('1.1.1.1'); + }); + + it.each([ + 'http://localhost/', + 'http://127.0.0.1/', + 'http://10.0.0.5/', + 'http://192.168.1.1/', + 'http://172.16.0.1/', + 'http://169.254.169.254/latest/meta-data/', // cloud metadata + 'http://[::1]/', + 'http://foo.internal/', + 'http://bar.local/', + ])('rejects the local/private target %s', async (u) => { + await expect(assertPublicHttpUrl(u)).rejects.toThrow(/local|private|internal|loopback/i); + }); + + it.each(['file:///etc/passwd', 'ftp://example.com/x', 'gopher://x'])( + 'rejects the non-http scheme %s', + async (u) => { + await expect(assertPublicHttpUrl(u)).rejects.toThrow(/scheme/i); + }, + ); +}); + +describe('htmlToText', () => { + it('strips scripts/styles/tags and decodes entities', () => { + const out = htmlToText( + '

Hi & bye

Line 1

', + ); + expect(out).not.toMatch(/bad\(\)/); + expect(out).not.toMatch(/<[^>]+>/); + expect(out).toMatch(/Hi & bye/); + expect(out).toMatch(/Line 1/); + }); +}); + +describe('web_fetch tool', () => { + const tool = createWebFetchTool(FETCH_DEPS); + + it('is a network-risk tool (policy gates it)', () => { + expect(tool.risk).toBe('network'); + expect(tool.resourceClass).toBe('network'); + }); + + it('fetches a page and converts HTML to text', async () => { + const fetchImpl = fakeFetch( + () => + new Response('

Hello world

', { + status: 200, + headers: { 'content-type': 'text/html' }, + }), + ); + const t = createWebFetchTool({ ...FETCH_DEPS, fetchImpl }); + const res = await t.execute(ctx(), { url: 'http://1.1.1.1/' }); + expect(res.ok).toBe(true); + expect(res.data?.content).toMatch(/Hello world/); + expect(res.data?.content).not.toMatch(/

/); + }); + + it('refuses a private URL before making any request', async () => { + let called = false; + const fetchImpl = fakeFetch(() => { + called = true; + return new Response('nope'); + }); + const t = createWebFetchTool({ ...FETCH_DEPS, fetchImpl }); + const res = await t.execute(ctx(), { url: 'http://127.0.0.1/secret' }); + expect(res.ok).toBe(false); + expect(res.error?.code).toBe('network_error'); + expect(called).toBe(false); + }); + + it('re-validates redirects and refuses a redirect to a private address', async () => { + const fetchImpl = fakeFetch((url) => { + if (url.startsWith('http://1.1.1.1')) { + return new Response(null, { + status: 302, + headers: { location: 'http://169.254.169.254/' }, + }); + } + return new Response('should not reach here', { status: 200 }); + }); + const t = createWebFetchTool({ ...FETCH_DEPS, fetchImpl }); + const res = await t.execute(ctx(), { url: 'http://1.1.1.1/redirect' }); + expect(res.ok).toBe(false); + expect(res.error?.code).toBe('network_error'); + expect(res.summary).toMatch(/private|loopback/i); + }); + + it('reports HTTP error status as a failure but keeps the body', async () => { + const fetchImpl = fakeFetch(() => new Response('not found', { status: 404 })); + const t = createWebFetchTool({ ...FETCH_DEPS, fetchImpl }); + const res = await t.execute(ctx(), { url: 'http://1.1.1.1/missing' }); + expect(res.ok).toBe(false); + expect(res.data?.status).toBe(404); + }); + + it('times out when the request hangs', async () => { + const fetchImpl = ((_input: string | URL, init?: RequestInit) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => + reject(new DOMException('aborted', 'AbortError')), + ); + })) as unknown as typeof globalThis.fetch; + const t = createWebFetchTool({ ...FETCH_DEPS, timeoutMs: 10, fetchImpl }); + const res = await t.execute(ctx(), { url: 'http://1.1.1.1/slow' }); + expect(res.ok).toBe(false); + expect(res.summary).toMatch(/timed out/i); + }); + + it('describes the action with the host for the approval prompt', async () => { + const desc = await tool.describe!(ctx(), { url: 'https://example.com/a/b?c=d' }); + expect(desc.title).toContain('example.com'); + expect(desc.outsideWorkspace).toBe(false); + }); +}); + +describe('web_search tool', () => { + const baseDeps = { + getApiKey: () => 'test-key', + timeoutMs: 1000, + maxResults: 5, + maxModelChars: 16_000, + }; + + it('is a network-risk tool', () => { + const tool = createWebSearchTool(baseDeps); + expect(tool.risk).toBe('network'); + }); + + it('returns an answer and results from Tavily', async () => { + const fetchImpl = fakeFetch( + () => + new Response( + JSON.stringify({ + answer: 'The answer is 42.', + results: [ + { title: 'A', url: 'https://a.example', content: 'aaa' }, + { title: 'B', url: 'https://b.example', content: 'bbb' }, + ], + }), + { status: 200, headers: { 'content-type': 'application/json' } }, + ), + ); + const tool = createWebSearchTool({ ...baseDeps, fetchImpl }); + const res = await tool.execute(ctx(), { query: 'meaning of life' }); + expect(res.ok).toBe(true); + expect(res.data?.answer).toMatch(/42/); + expect(res.data?.results).toHaveLength(2); + expect(res.modelContent).toMatch(/a\.example/); + }); + + it('fails clearly when no API key is configured', async () => { + const tool = createWebSearchTool({ ...baseDeps, getApiKey: () => undefined }); + const res = await tool.execute(ctx(), { query: 'x' }); + expect(res.ok).toBe(false); + expect(res.error?.code).toBe('missing_credential'); + expect(res.summary).toMatch(/TAVILY_API_KEY/); + }); + + it('surfaces a Tavily auth error', async () => { + const fetchImpl = fakeFetch(() => new Response('unauthorized', { status: 401 })); + const tool = createWebSearchTool({ ...baseDeps, fetchImpl }); + const res = await tool.execute(ctx(), { query: 'x' }); + expect(res.ok).toBe(false); + expect(res.error?.code).toBe('network_error'); + expect(res.summary).toMatch(/401/); + }); + + it('passes the query and key in the request body', async () => { + let sentBody: unknown; + const fetchImpl = fakeFetch((_url, init) => { + sentBody = JSON.parse(String(init?.body)); + return new Response(JSON.stringify({ results: [] }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); + }); + const tool = createWebSearchTool({ ...baseDeps, fetchImpl }); + await tool.execute(ctx(), { query: 'hello', maxResults: 3 }); + expect(sentBody).toMatchObject({ api_key: 'test-key', query: 'hello', max_results: 3 }); + }); +});