From 3b54e9c2545aff036c7c32249c1ca339cbdb5a6e Mon Sep 17 00:00:00 2001 From: kahme247 <61059522+kahme247@users.noreply.github.com> Date: Mon, 26 Oct 2026 02:31:04 +0300 Subject: [PATCH] feat(agent): add server-side cross-session agent tools (#275) --- app/api/web-settings/route.ts | 9 +- components/SettingsConfig.tsx | 38 ++++ lib/agent-tools.test.mjs | 187 +++++++++++++++++++ lib/agent-tools.ts | 340 ++++++++++++++++++++++++++++++++++ lib/i18n/locales/en.json | 3 + lib/rpc-manager.test.mjs | 60 +++++- lib/rpc-manager.ts | 209 ++++++++++++++++++++- lib/web-settings.test.mjs | 21 ++- lib/web-settings.ts | 11 +- 9 files changed, 868 insertions(+), 10 deletions(-) create mode 100644 lib/agent-tools.test.mjs create mode 100644 lib/agent-tools.ts diff --git a/app/api/web-settings/route.ts b/app/api/web-settings/route.ts index 48c0372af..391a860f8 100644 --- a/app/api/web-settings/route.ts +++ b/app/api/web-settings/route.ts @@ -27,7 +27,7 @@ export async function PUT(req: Request) { if (!isRecord(body)) { return NextResponse.json({ error: "Request body must be a settings object", code: "invalid_settings" }, { status: 400 }); } - const payload = body as { autoResumeSessions?: unknown; agentEnv?: unknown }; + const payload = body as { autoResumeSessions?: unknown; agentToolsEnabled?: unknown; agentEnv?: unknown }; const patch: Partial = {}; // Both keys are optional so a caller can update one without reading the other; @@ -41,6 +41,13 @@ export async function PUT(req: Request) { resumeProvided = true; } + if (payload.agentToolsEnabled !== undefined) { + if (typeof payload.agentToolsEnabled !== "boolean") { + return NextResponse.json({ error: "agentToolsEnabled must be a boolean", code: "invalid_settings" }, { status: 400 }); + } + patch.agentToolsEnabled = payload.agentToolsEnabled; + } + if (payload.agentEnv !== undefined) { // Either raw KEY=VALUE text (what the settings textarea holds) or a record. let parsed: AgentEnvParseResult; diff --git a/components/SettingsConfig.tsx b/components/SettingsConfig.tsx index 554d37567..02688217b 100644 --- a/components/SettingsConfig.tsx +++ b/components/SettingsConfig.tsx @@ -210,6 +210,7 @@ const SETTING_INDEX: SettingIndexEntry[] = [ { id: "model-breakdown", tab: "usage", sectionKey: "settingsTabs.usage.label", labelKey: "usageConfig.breakdown", descKey: "usageConfig.model", fallbackSection: "Usage", fallbackLabel: "Model Breakdown", fallbackDesc: "Historical token usage and cost per model, day, and project", scope: "UI" }, // Windows Background Service & System Tray { id: "auto-resume-sessions", tab: "system", sectionKey: "settingsConfig.systemUpdates", labelKey: "settingsConfig.autoResumeSessions", descKey: "settingsConfig.autoResumeSessionsDesc", fallbackSection: "System & Updates", fallbackLabel: "Resume running sessions after a restart", fallbackDesc: "When omp-web restarts while agents are working, restart those sessions and tell each agent: \"Session interrupted and resumed. Continue as you would have done without the interruption.\" Work in progress at the moment of the restart, such as a running command, is lost." }, + { id: "agent-tools-cross-session", tab: "system", sectionKey: "settingsConfig.systemUpdates", labelKey: "settingsConfig.agentTools", descKey: "settingsConfig.agentToolsDesc", fallbackSection: "System & Updates", fallbackLabel: "Agent tools (cross-session)", fallbackDesc: "Allow agents to call list_sessions, new_session and send_to_session to reach other omp-web sessions, even with no browser tab open. Delivered messages are prefixed with the sending session's ID." }, { id: "agent-env", tab: "system", sectionKey: "settingsConfig.systemUpdates", labelKey: "settingsConfig.agentEnv", descKey: "settingsConfig.agentEnvDesc", fallbackSection: "System & Updates", fallbackLabel: "Agent environment variables", fallbackDesc: "Extra environment variables passed to the omp process, one KEY=VALUE per line. Applied to sessions started after saving.", scope: "UI" }, { id: "windows-service-autostart", tab: "system", sectionKey: "settingsConfig.windowsServiceTitle", labelKey: "settingsConfig.windowsServiceAutostart", descKey: "settingsConfig.windowsServiceAutostartDesc", fallbackSection: "Windows Background Service & System Tray", fallbackLabel: "Start with Windows", fallbackDesc: "Launch background service quietly in system tray when logging into Windows.", scope: "UI" }, { id: "windows-service-shortcuts", tab: "system", sectionKey: "settingsConfig.windowsServiceTitle", labelKey: "settingsConfig.windowsServiceInstallBtn", descKey: "settingsConfig.windowsServiceDesc", fallbackSection: "Windows Background Service & System Tray", fallbackLabel: "Install Service & Shortcuts", fallbackDesc: "Manage background service execution, system tray monitor, Windows logon autostart, and Desktop shortcuts.", scope: "UI" }, @@ -382,6 +383,41 @@ function AutoResumeSessionsSetting() { ); } +/** Server-side omp-web setting (issue #275): cross-session agent tools. + * Off by default; mirrors AutoResumeSessionsSetting above. */ +function AgentToolsSetting() { + const { t } = useI18n(); + const [enabled, setEnabled] = useState(null); + useEffect(() => { + let alive = true; + fetch("/api/web-settings") + .then((res) => (res.ok ? res.json() : null)) + .then((data: { agentToolsEnabled?: boolean } | null) => { if (alive) setEnabled(data?.agentToolsEnabled === true); }) + .catch(() => { if (alive) setEnabled(false); }); + return () => { alive = false; }; + }, []); + const change = async (next: boolean) => { + const previous = enabled; + setEnabled(next); + try { + const res = await fetch("/api/web-settings", { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ agentToolsEnabled: next }), + }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + } catch (error) { + setEnabled(previous); + toast.error(t("settingsConfig.agentToolsSaveFailed"), error instanceof Error ? error.message : String(error)); + } + }; + return ( + + void change(next)} /> + + ); +} + /** Server-side omp-web setting (issue #104): KEY=VALUE text injected into the * `omp` child process. Parsing/validation lives in lib/omp/agent-env.ts; this only * feeds it localized messages and renders the result. */ @@ -1759,6 +1795,8 @@ export function SettingsConfig({ activeTab, toolCallsDefaultCollapsed, onToolCal + + {/* ompweb app update card */} diff --git a/lib/agent-tools.test.mjs b/lib/agent-tools.test.mjs new file mode 100644 index 000000000..8be0a9384 --- /dev/null +++ b/lib/agent-tools.test.mjs @@ -0,0 +1,187 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url); +const { + AGENT_TOOL_DEFINITIONS, + AGENT_TOOL_NAMES, + AgentToolGuard, + executeAgentTool, + formatAttributedMessage, +} = await jiti.import("./agent-tools.ts"); + +function fakeOps(overrides = {}) { + const calls = { list: 0, create: [], deliver: [] }; + return { + calls, + async listSessions() { + calls.list += 1; + return [{ id: "target-1", name: "Release", cwd: "/tmp/release", running: false }]; + }, + async createSession(input) { + calls.create.push(input); + return { sessionId: "new-1" }; + }, + async deliver(input) { + calls.deliver.push(input); + return { accepted: true, targetSessionId: input.sessionId, delivery: input.delivery, waited: false, responseText: null }; + }, + ...overrides, + }; +} + +const ctx = (overrides = {}) => ({ + sourceSessionId: "source-1", + sourceCwd: "/tmp/source", + enabled: true, + guard: new AgentToolGuard(), + ...overrides, +}); + +test("agent tool definitions cover the three cross-session tools (#275)", () => { + assert.deepEqual([...AGENT_TOOL_NAMES].sort(), ["list_sessions", "new_session", "send_to_session"]); + assert.deepEqual(AGENT_TOOL_DEFINITIONS.map((t) => t.name).sort(), ["list_sessions", "new_session", "send_to_session"]); + const send = AGENT_TOOL_DEFINITIONS.find((t) => t.name === "send_to_session"); + assert.deepEqual(send.parameters.required, ["sessionId", "message"]); + assert.deepEqual(send.parameters.properties.delivery.enum, ["prompt", "steer", "followUp"]); +}); + +test("agent tools refuse every call while the Settings gate is off (#275)", async () => { + const off = ctx({ enabled: false }); + await assert.rejects(() => executeAgentTool("list_sessions", {}, fakeOps(), off), /disabled/); + await assert.rejects( + () => executeAgentTool("send_to_session", { sessionId: "t", message: "hi" }, fakeOps(), off), + /disabled/, + ); +}); + +test("list_sessions returns the sessions the ops layer reports (#275)", async () => { + const ops = fakeOps(); + const result = await executeAgentTool("list_sessions", {}, ops, ctx()); + assert.deepEqual(result, { sessions: [{ id: "target-1", name: "Release", cwd: "/tmp/release", running: false }] }); + assert.equal(ops.calls.list, 1); +}); + +test("new_session defaults cwd, attributes the prompt, and splits provider/model (#275)", async () => { + const ops = fakeOps(); + const result = await executeAgentTool( + "new_session", + { prompt: "Do the release checklist", model: "anthropic/claude-sonnet-4-5", name: "Release worker" }, + ops, + ctx(), + ); + assert.deepEqual(result, { sessionId: "new-1" }); + assert.equal(ops.calls.create.length, 1); + const input = ops.calls.create[0]; + assert.equal(input.cwd, "/tmp/source"); + assert.equal(input.prompt, "[From session source-1 via omp-web agent tools]: Do the release checklist"); + assert.equal(input.provider, "anthropic"); + assert.equal(input.modelId, "claude-sonnet-4-5"); + assert.equal(input.name, "Release worker"); +}); + +test("new_session without a prompt creates an idle session, and bad models are rejected (#275)", async () => { + const ops = fakeOps(); + await executeAgentTool("new_session", { cwd: "/tmp/other" }, ops, ctx()); + assert.equal(ops.calls.create[0].prompt, null); + assert.equal(ops.calls.create[0].cwd, "/tmp/other"); + await assert.rejects(() => executeAgentTool("new_session", { model: "no-slash" }, fakeOps(), ctx()), /provider\/modelId/); + await assert.rejects( + () => executeAgentTool("new_session", { provider: "anthropic" }, fakeOps(), ctx()), + /together/, + ); + await assert.rejects(() => executeAgentTool("new_session", {}, fakeOps(), ctx({ sourceCwd: "" })), /cwd/); +}); + +test("send_to_session attributes, defaults to prompt, and passes wait through (#275)", async () => { + const ops = fakeOps(); + const result = await executeAgentTool( + "send_to_session", + { sessionId: "target-1", message: "The build passed", wait: true, waitTimeoutMs: 5000 }, + ops, + ctx(), + ); + assert.equal(ops.calls.deliver.length, 1); + const input = ops.calls.deliver[0]; + assert.equal(input.message, "[From session source-1 via omp-web agent tools]: The build passed"); + assert.equal(input.delivery, "prompt"); + assert.equal(input.wait, true); + assert.equal(input.waitTimeoutMs, 5000); + assert.equal(result.targetSessionId, "target-1"); +}); + +test("send_to_session rejects self-targets, bad deliveries, and bad waits (#275)", async () => { + const base = ctx(); + await assert.rejects( + () => executeAgentTool("send_to_session", { sessionId: "source-1", message: "hi" }, fakeOps(), base), + /itself/, + ); + await assert.rejects( + () => executeAgentTool("send_to_session", { sessionId: "t", message: "hi", delivery: "shout" }, fakeOps(), ctx()), + /delivery/, + ); + await assert.rejects( + () => executeAgentTool("send_to_session", { sessionId: "t", message: "hi", wait: "yes" }, fakeOps(), ctx()), + /wait/, + ); + await assert.rejects( + () => executeAgentTool("send_to_session", { sessionId: "t" }, fakeOps(), ctx()), + /message/, + ); +}); + +test("send_to_session wait timeout defaults and caps (#275)", async () => { + const ops = fakeOps(); + await executeAgentTool("send_to_session", { sessionId: "t", message: "hi" }, ops, ctx()); + assert.equal(ops.calls.deliver[0].wait, false); + assert.equal(ops.calls.deliver[0].waitTimeoutMs, 120000); + const capped = fakeOps(); + await executeAgentTool("send_to_session", { sessionId: "t", message: "hi", waitTimeoutMs: 9999999 }, capped, ctx()); + assert.equal(capped.calls.deliver[0].waitTimeoutMs, 300000); +}); + +test("attribution format keeps the full source ID for sidebar lookup (#275)", () => { + assert.equal( + formatAttributedMessage("019c625b-b900-7000-8000-000000000277", "hello"), + "[From session 019c625b-b900-7000-8000-000000000277 via omp-web agent tools]: hello", + ); +}); + +test("chain depth stops a loop and a failed delivery does not advance it (#275)", async () => { + const guard = new AgentToolGuard(); + guard.setDepth("source-1", 5); + await assert.rejects( + () => executeAgentTool("send_to_session", { sessionId: "t", message: "hi" }, fakeOps(), ctx({ guard })), + /chain depth/, + ); + + const failing = fakeOps({ + async deliver() { + throw new Error("target vanished"); + }, + }); + const guard2 = new AgentToolGuard(); + await assert.rejects( + () => executeAgentTool("send_to_session", { sessionId: "t", message: "hi" }, failing, ctx({ guard: guard2 })), + /target vanished/, + ); + assert.equal(guard2.depthFor("t"), 0); + + const ok = fakeOps(); + await executeAgentTool("send_to_session", { sessionId: "t", message: "hi" }, ok, ctx({ guard: guard2 })); + assert.equal(guard2.depthFor("t"), 1); +}); + +test("rate limit caps a source at 20 agent tool calls per minute (#275)", async () => { + const guard = new AgentToolGuard(); + const ops = fakeOps(); + for (let i = 0; i < 20; i++) { + await executeAgentTool("list_sessions", {}, ops, ctx({ guard })); + } + await assert.rejects(() => executeAgentTool("list_sessions", {}, ops, ctx({ guard })), /rate limit/); +}); + +test("unknown agent tools are rejected (#275)", async () => { + await assert.rejects(() => executeAgentTool("delete_everything", {}, fakeOps(), ctx()), /Unknown agent tool/); +}); diff --git a/lib/agent-tools.ts b/lib/agent-tools.ts new file mode 100644 index 000000000..0ba322821 --- /dev/null +++ b/lib/agent-tools.ts @@ -0,0 +1,340 @@ +import type { HostToolDefinition } from "./pi-types"; +import { isRecord } from "./type-guards"; + +/** + * Server-side agent tools for issue #275: tools an agent running inside + * omp-web can call to reach *other* top-level omp-web sessions. omp's own + * `task` tool and `write agent://` only work inside one omp process, + * so cross-session work has to be answered by the omp-web server itself — + * never by an attached browser tab (the issue's key requirement: these + * tools keep working with no tab open). + * + * This module is deliberately pure: it knows nothing about RpcProcess, + * the session registry, or the session files. The caller (lib/rpc-manager) + * supplies those through AgentToolSessionOps, which keeps the validation, + * gating, attribution and loop-guard logic unit-testable without a live + * omp child. The only omp-web surface this module touches is the + * HostToolDefinition shape omp already understands for set_host_tools. + */ + +/** Tools the server answers itself. Browser-routed tools are unaffected. */ +export const AGENT_TOOL_NAMES = new Set(["list_sessions", "new_session", "send_to_session"]); + +export const AGENT_TOOL_DEFINITIONS: HostToolDefinition[] = [ + { + name: "list_sessions", + description: + "List omp-web sessions (ID, name, working directory, running or idle) so send_to_session can address one without the user copying IDs.", + parameters: { type: "object", properties: {} }, + }, + { + name: "new_session", + description: + "Start a new omp-web session. The new session appears in the omp-web sidebar like any other session. Returns its session ID.", + parameters: { + type: "object", + properties: { + cwd: { type: "string", description: "Project directory. Defaults to the calling session's directory." }, + prompt: { type: "string", description: "First message for the new session. If omitted, the session is created idle." }, + model: { type: "string", description: "Model as \"provider/modelId\", e.g. \"anthropic/claude-sonnet-4-5\"." }, + provider: { type: "string", description: "Model provider, used with modelId instead of model." }, + modelId: { type: "string", description: "Model ID, used with provider instead of model." }, + name: { type: "string", description: "Display name for the new session." }, + }, + }, + }, + { + name: "send_to_session", + description: + "Send a message to another omp-web session by ID. If the target is not running it is resumed first, as when a user opens it. The delivered message is prefixed with the sending session's ID so the target transcript shows where it came from.", + parameters: { + type: "object", + properties: { + sessionId: { type: "string", description: "Target session ID (see list_sessions)." }, + message: { type: "string", description: "Message to deliver to the target session." }, + delivery: { + type: "string", + description: + "How to deliver while the target is running: \"prompt\" starts a new turn (only when the target is idle), \"steer\" steers the running turn, \"followUp\" queues after it. Defaults to \"prompt\".", + enum: ["prompt", "steer", "followUp"], + }, + wait: { + type: "boolean", + description: + "When true, wait for the target turn to finish (up to waitTimeoutMs) and return its final assistant text. When false, return as soon as the target accepts the message.", + }, + waitTimeoutMs: { type: "number", description: "Maximum wait for a waited delivery, in milliseconds. Defaults to 120000, capped at 300000." }, + }, + required: ["sessionId", "message"], + }, + }, +]; + +/** A message that would also be rejected by the HTTP body limit is too big to relay. */ +export const MAX_AGENT_TOOL_MESSAGE_CHARS = 100_000; +/** Per-source rate cap: a runaway agent cannot spam sessions faster than this. */ +export const MAX_AGENT_TOOL_CALLS_PER_MINUTE = 20; +/** + * Chain-depth cap: a delivery from session A to session B makes B's depth + * A's depth + 1. A ping-pong (A→B→A→B…) therefore stops at the cap instead + * of looping forever. A session never touched by an agent tool has depth 0. + */ +export const MAX_AGENT_TOOL_CHAIN_DEPTH = 5; +export const DEFAULT_WAIT_TIMEOUT_MS = 120_000; +export const MAX_WAIT_TIMEOUT_MS = 300_000; + +export interface AgentToolSessionSummary { + id: string; + name?: string; + cwd?: string; + running: boolean; +} + +export interface AgentToolCreateSessionInput { + cwd: string; + /** Already sender-attributed by executeAgentTool, or null for an idle session. */ + prompt: string | null; + provider?: string; + modelId?: string; + name?: string; +} + +export interface AgentToolDeliverInput { + sessionId: string; + /** Already sender-attributed by executeAgentTool. */ + message: string; + delivery: "prompt" | "steer" | "followUp"; + wait: boolean; + waitTimeoutMs: number; +} + +export interface AgentToolDeliverResult { + accepted: boolean; + targetSessionId: string; + delivery: "prompt" | "steer" | "followUp"; + /** True only when wait was requested and the turn actually finished. */ + waited: boolean; + /** Final assistant text of the waited turn, or null when wait was false. */ + responseText: string | null; +} + +/** Session operations supplied by lib/rpc-manager; fakes replace them in tests. */ +export interface AgentToolSessionOps { + listSessions(): Promise; + createSession(input: AgentToolCreateSessionInput): Promise<{ sessionId: string }>; + deliver(input: AgentToolDeliverInput): Promise; +} + +export interface AgentToolContext { + sourceSessionId: string; + sourceCwd: string; + /** The off-by-default Settings gate (lib/web-settings agentToolsEnabled). */ + enabled: boolean; + guard: AgentToolGuard; +} + +/** + * Loop + spam guard. Two independent mechanisms, because neither alone + * stops every loop: the rate cap stops a fast ping-pong, and the chain + * depth stops a slow one that would otherwise run for hours. + */ +export class AgentToolGuard { + private callsBySource = new Map(); + private depthBySession = new Map(); + private readonly now: () => number; + + constructor(now: () => number = Date.now) { + this.now = now; + } + + /** Throws when the source already used its per-minute budget. */ + checkRate(sourceSessionId: string): void { + const now = this.now(); + const recent = (this.callsBySource.get(sourceSessionId) ?? []).filter((t) => now - t < 60_000); + if (recent.length >= MAX_AGENT_TOOL_CALLS_PER_MINUTE) { + throw new Error( + `Agent tool rate limit exceeded for this session (${MAX_AGENT_TOOL_CALLS_PER_MINUTE} calls per minute).`, + ); + } + recent.push(now); + this.callsBySource.set(sourceSessionId, recent); + } + + depthFor(sessionId: string): number { + return this.depthBySession.get(sessionId) ?? 0; + } + + /** + * Depth a delivery from `source` to `target` would give `target`. + * Throws when that depth would exceed the cap. The depth is only + * recorded (setDepth) after a successful delivery, so a rejected or + * failed call never advances the chain. + */ + checkChainDepth(sourceSessionId: string): number { + const depth = this.depthFor(sourceSessionId) + 1; + if (depth > MAX_AGENT_TOOL_CHAIN_DEPTH) { + throw new Error( + `Agent tool chain depth limit exceeded (${MAX_AGENT_TOOL_CHAIN_DEPTH}): sessions messaging each other in a loop are stopped here.`, + ); + } + return depth; + } + + setDepth(sessionId: string, depth: number): void { + this.depthBySession.set(sessionId, depth); + } + + reset(): void { + this.callsBySource.clear(); + this.depthBySession.clear(); + } +} + +/** Attribution that lands in the target transcript itself, so any reader + * (user or target agent) can see where the message came from. The full + * source ID is kept so it can be found in the sidebar. */ +export function formatAttributedMessage(sourceSessionId: string, message: string): string { + return `[From session ${sourceSessionId} via omp-web agent tools]: ${message}`; +} + +function asRecord(value: unknown): Record { + if (!isRecord(value)) throw new Error("Agent tool arguments must be an object."); + return value; +} + +function requiredString(args: Record, field: string): string { + const value = args[field]; + if (typeof value !== "string" || !value.trim()) throw new Error(`Agent tool argument "${field}" is required and must be a non-empty string.`); + return value.trim(); +} + +function optionalString(args: Record, field: string): string | undefined { + const value = args[field]; + if (value === undefined || value === null) return undefined; + if (typeof value !== "string" || !value.trim()) throw new Error(`Agent tool argument "${field}" must be a non-empty string when provided.`); + return value.trim(); +} + +function parseSessionId(value: string): string { + if (value.length > 200 || /[\s/\\]/.test(value)) { + throw new Error("Agent tool argument \"sessionId\" is not a valid session ID."); + } + return value; +} + +function parseModel(args: Record): { provider?: string; modelId?: string } { + const model = optionalString(args, "model"); + const provider = optionalString(args, "provider"); + const modelId = optionalString(args, "modelId"); + if (model) { + const slash = model.indexOf("/"); + if (slash <= 0 || slash === model.length - 1) { + throw new Error("Agent tool argument \"model\" must be \"provider/modelId\"."); + } + if (provider && provider !== model.slice(0, slash)) { + throw new Error("Agent tool arguments \"model\" and \"provider\" disagree."); + } + if (modelId && modelId !== model.slice(slash + 1)) { + throw new Error("Agent tool arguments \"model\" and \"modelId\" disagree."); + } + return { provider: model.slice(0, slash), modelId: model.slice(slash + 1) }; + } + if ((provider && !modelId) || (!provider && modelId)) { + throw new Error("Agent tool arguments \"provider\" and \"modelId\" must be provided together."); + } + return { provider, modelId }; +} + +function parseDelivery(args: Record): "prompt" | "steer" | "followUp" { + const delivery = args.delivery; + if (delivery === undefined || delivery === null) return "prompt"; + if (delivery === "prompt" || delivery === "steer" || delivery === "followUp") return delivery; + throw new Error("Agent tool argument \"delivery\" must be \"prompt\", \"steer\", or \"followUp\"."); +} + +function parseWait(args: Record): { wait: boolean; waitTimeoutMs: number } { + const wait = args.wait; + if (wait !== undefined && typeof wait !== "boolean") { + throw new Error("Agent tool argument \"wait\" must be a boolean."); + } + const timeout = args.waitTimeoutMs; + if (timeout !== undefined && (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0)) { + throw new Error("Agent tool argument \"waitTimeoutMs\" must be a positive number."); + } + return { + wait: wait === true, + waitTimeoutMs: Math.min(MAX_WAIT_TIMEOUT_MS, Math.floor(timeout ?? DEFAULT_WAIT_TIMEOUT_MS)), + }; +} + +function checkMessageLength(message: string, field: string): void { + if (message.length > MAX_AGENT_TOOL_MESSAGE_CHARS) { + throw new Error(`Agent tool argument "${field}" exceeds ${MAX_AGENT_TOOL_MESSAGE_CHARS} characters.`); + } +} + +/** + * Execute one server-side agent tool. Returns a plain JSON-able result the + * caller renders as the host_tool_result text payload. Throws on every + * rejection (disabled gate, validation, rate/chain limits, unknown tool, + * or an ops failure) so the agent gets an explicit error, never a hang. + */ +export async function executeAgentTool( + toolName: string, + args: unknown, + ops: AgentToolSessionOps, + ctx: AgentToolContext, +): Promise { + if (!ctx.enabled) { + throw new Error("Agent tools are disabled. Enable \"Agent tools\" in omp-web Settings (System & Updates) first."); + } + if (!AGENT_TOOL_NAMES.has(toolName)) throw new Error(`Unknown agent tool: ${toolName}.`); + const record = asRecord(args); + + if (toolName === "list_sessions") { + ctx.guard.checkRate(ctx.sourceSessionId); + return { sessions: await ops.listSessions() }; + } + + if (toolName === "new_session") { + ctx.guard.checkRate(ctx.sourceSessionId); + const depth = ctx.guard.checkChainDepth(ctx.sourceSessionId); + const cwd = optionalString(record, "cwd") ?? ctx.sourceCwd; + if (!cwd) throw new Error("Agent tool argument \"cwd\" is required when the calling session has no directory."); + const prompt = optionalString(record, "prompt"); + if (prompt) checkMessageLength(prompt, "prompt"); + const { provider, modelId } = parseModel(record); + const name = optionalString(record, "name"); + if (name && name.length > 200) throw new Error("Agent tool argument \"name\" exceeds 200 characters."); + const created = await ops.createSession({ + cwd, + prompt: prompt ? formatAttributedMessage(ctx.sourceSessionId, prompt) : null, + provider, + modelId, + name, + }); + ctx.guard.setDepth(created.sessionId, depth); + return { sessionId: created.sessionId }; + } + + // send_to_session + ctx.guard.checkRate(ctx.sourceSessionId); + const sessionId = parseSessionId(requiredString(record, "sessionId")); + if (sessionId === ctx.sourceSessionId) { + throw new Error("Agent tool \"send_to_session\" cannot target the calling session itself."); + } + const message = requiredString(record, "message"); + checkMessageLength(message, "message"); + const delivery = parseDelivery(record); + const { wait, waitTimeoutMs } = parseWait(record); + const depth = ctx.guard.checkChainDepth(ctx.sourceSessionId); + const result = await ops.deliver({ + sessionId, + message: formatAttributedMessage(ctx.sourceSessionId, message), + delivery, + wait, + waitTimeoutMs, + }); + ctx.guard.setDepth(sessionId, depth); + return result; +} diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 3724f5ca5..1fabe5ebe 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -112,6 +112,9 @@ "settingsConfig.autoResumeSessionsSaveFailed": "Could not save the resume setting", "settingsConfig.autoResumeSessionsDesc": "When omp-web restarts while agents are working, restart those sessions and tell each agent: \"Session interrupted and resumed. Continue as you would have done without the interruption.\" Work in progress at the moment of the restart, such as a running command, is lost.", "settingsConfig.autoResumeSessions": "Resume running sessions after a restart", + "settingsConfig.agentTools": "Agent tools (cross-session)", + "settingsConfig.agentToolsDesc": "Allow agents to call list_sessions, new_session and send_to_session to reach other omp-web sessions, even with no browser tab open. Messages delivered this way are prefixed with the sending session's ID. A per-session rate limit and a chain-depth limit stop sessions looping messages to each other. Applies to sessions started or reconnected after saving.", + "settingsConfig.agentToolsSaveFailed": "Could not save the agent tools setting", "settingsConfig.agentEnv": "Agent environment variables", "settingsConfig.agentEnvDesc": "Extra environment variables handed to the omp process, for example the API key an MCP server needs. One KEY=VALUE per line; # comments and blank lines are ignored.", "settingsConfig.agentEnvNote": "Saved values are injected when a session starts. Sessions that are already running keep the environment they started with, so restart them to pick up the new values. Variables omp-web needs itself (PATH, HOME, PI_CODING_AGENT_DIR, OMP_WEB_*, and similar) cannot be set here.", diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index ad392fcb6..8691d071f 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; -import { mkdtempSync, rmSync } from "node:fs"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; @@ -1792,3 +1792,61 @@ test("skill diagnostics cross the wrapper only as parsed public DTOs", async (t) "invalid control data must not reach OMP", ); }); + +test("server agent tools are answered by the server, not the browser (#275)", async (t) => { + // Enable the off-by-default gate via the isolated settings file, and + // drop the cached settings so this test's gate value is actually read. + globalThis.__ompWebSettingsCache = undefined; + const settingsPath = join(isolatedAgentDir, "omp-web-settings.json"); + writeFileSync(settingsPath, JSON.stringify({ agentToolsEnabled: true, agentEnv: {} })); + t.after(() => { + globalThis.__ompWebSettingsCache = undefined; + try { rmSync(settingsPath); } catch { /* already gone */ } + }); + + const sentCommands = []; + const { wrapper, emit, sentFrames } = snapshotSession( + t, + async (command) => { sentCommands.push(command); return {}; }, + SnapshotWrapper, + "agent-source", + ); + // A UI registration must not drop the server tools (send() merges them). + await wrapper.send({ type: "set_host_tools", tools: [{ name: "open_url" }] }); + const registration = sentCommands.find((c) => c.type === "set_host_tools"); + assert.ok(registration.tools.some((tool) => tool.name === "list_sessions")); + assert.ok(registration.tools.some((tool) => tool.name === "send_to_session")); + + // A tab watching this session must NOT receive the call: the server + // answers it itself, with no browser involved. + const own = []; + const detach = wrapper.onEvent((event) => own.push(event)); + emit({ type: "host_tool_call", id: "list-1", toolName: "list_sessions", arguments: {} }); + await new Promise((resolve) => setTimeout(resolve, 100)); + assert.equal(own.some((event) => event.type === "host_tool_call"), false); + assert.equal(sentFrames.length, 1); + assert.equal(sentFrames[0].id, "list-1"); + assert.equal(sentFrames[0].isError, false); + assert.deepEqual(JSON.parse(sentFrames[0].result.content[0].text), { sessions: [] }); + detach(); +}); + +test("server agent tools are rejected when the gate is off (#275)", async (t) => { + globalThis.__ompWebSettingsCache = undefined; + t.after(() => { globalThis.__ompWebSettingsCache = undefined; }); + const { emit, sentFrames } = snapshotSession(t, undefined, SnapshotWrapper, "agent-source-off"); + emit({ type: "host_tool_call", id: "off-1", toolName: "list_sessions", arguments: {} }); + assert.deepEqual(sentFrames.map((f) => [f.id, f.isError]), [["off-1", true]]); + assert.match(sentFrames[0].result.content[0].text, /disabled/); +}); + +test("waitForTurnEnd resolves on terminal agent_end and rejects on timeout (#275)", async (t) => { + const { wrapper, emit } = snapshotSession(t, undefined, SnapshotWrapper, "waiter"); + const done = wrapper.waitForTurnEnd(1000); + emit({ type: "agent_end", isTerminal: true }); + await done; + await assert.rejects(() => wrapper.waitForTurnEnd(20), /Timed out/); + const promptDone = wrapper.waitForTurnEnd(1000); + emit({ type: "prompt_result" }); + await promptDone; +}); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index a0bf9e130..90541921b 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -12,9 +12,20 @@ import { invalidateSessionEntriesCache, invalidateSessionListCache, invalidateSessionListMeta, + listAllSessions, readSessionHeader, resolveSessionPath, } from "./session-reader"; +import { allowFileRoot } from "./file-access"; +import { loadWebServerSettings } from "./web-settings"; +import { + AGENT_TOOL_DEFINITIONS, + AGENT_TOOL_NAMES, + AgentToolGuard, + executeAgentTool, + type AgentToolDeliverResult, + type AgentToolSessionOps, +} from "./agent-tools"; import { markShuttingDown, recordRunningSessions, RESUME_PROMPT, takeInterruptedSessions } from "./session-resume"; import { PRESET_FULL } from "./tool-presets"; import { comparableProjectPath } from "./comparable-path"; @@ -818,6 +829,28 @@ export class AgentSessionWrapper { case "host_tool_call": { const id = typeof event.id === "string" ? event.id : ""; const toolName = typeof event.toolName === "string" ? event.toolName : ""; + // Server-side agent tools (#275) are answered here, before any + // browser routing, so they work with no tab open. A disabled gate + // is an explicit error, not a silent hang and not a browser call. + if (id && toolName && AGENT_TOOL_NAMES.has(toolName)) { + if (loadWebServerSettings().agentToolsEnabled) { + void this.answerServerAgentTool(event); + } else { + this.proc.sendFrame({ + type: "host_tool_result", + id, + isError: true, + result: { + content: [{ + type: "text", + text: "Agent tools are disabled. Enable \"Agent tools\" in omp-web Settings (System & Updates) first.", + }], + }, + }); + this.emit({ type: "notice", level: "warning", message: `Rejected disabled agent tool: ${toolName}` }); + } + return; + } // Route REGISTERED host tools to an attached UI (the browser answers // via host_tool_result). With no tab on this session, hand the call to // any open omp-web tab (the user switched sessions mid-run). Otherwise @@ -1196,6 +1229,73 @@ export class AgentSessionWrapper { this.onDestroyCallback = cb; } + /** + * Wait for the next `terminalEndsNeeded` terminal turn ends after this + * call (terminal agent_end, prompt_result, or prompt_error). The caller + * registers the waiter BEFORE sending the prompt/steer/follow_up, so a + * fast turn cannot end before the waiter exists. Rejects on timeout; + * the target is left running (never aborted by a waiter timeout). + * A follow_up sent to a running target needs two ends: the running + * turn ends first, then the queued message's own turn ends. + */ + waitForTurnEnd(timeoutMs: number, terminalEndsNeeded = 1): Promise { + return new Promise((resolve, reject) => { + let done = false; + let endsSeen = 0; + const timer = setTimeout(() => finish(new Error("Timed out waiting for the target session's response.")), timeoutMs); + timer.unref?.(); + const detach = this.onEvent((event) => { + if (event.type === "agent_end" && event.isTerminal === false) return; + if (event.type === "agent_end" || event.type === "prompt_result") { + endsSeen += 1; + if (endsSeen >= terminalEndsNeeded) finish(null); + } else if (event.type === "prompt_error") { + finish(new Error(typeof event.errorMessage === "string" ? event.errorMessage : "Target session turn failed.")); + } + }); + const finish = (error: Error | null) => { + if (done) return; + done = true; + clearTimeout(timer); + detach(); + if (error) reject(error); + else resolve(); + }; + }); + } + + /** + * Answer a server-side agent tool call (#275) from this wrapper's child. + * Runs on the server, with no browser involved, and answers directly + * with host_tool_result — never via pendingHostTools, so a later tab + * disconnect cannot settle it as a UI call. + */ + private async answerServerAgentTool(event: UnsequencedAgentEvent): Promise { + const id = typeof event.id === "string" ? event.id : ""; + const toolName = typeof event.toolName === "string" ? event.toolName : ""; + if (!id) return; + const sendResult = (text: string, isError = false) => { + this.proc.sendFrame({ + type: "host_tool_result", + id, + isError, + result: { content: [{ type: "text", text }] }, + }); + }; + try { + const args = event.arguments && typeof event.arguments === "object" ? event.arguments as Record : {}; + const result = await executeAgentTool(toolName, args, createAgentToolOps(), { + sourceSessionId: this.sessionId, + sourceCwd: this.cwd, + enabled: loadWebServerSettings().agentToolsEnabled, + guard: getAgentToolGuard(), + }); + sendResult(typeof result === "string" ? result : JSON.stringify(result)); + } catch (error) { + sendResult(error instanceof Error ? error.message : String(error), true); + } + } + /** Called when a session-changing command re-keyed this wrapper (branch/new_session/switch_session). */ onIdentityChange(cb: (oldId: string, newId: string, options?: IdentityChangeOptions) => void): void { this.onIdentityChangeCallback = cb; @@ -1795,8 +1895,16 @@ export class AgentSessionWrapper { case "set_host_tools": { const tools = Array.isArray(command.tools) ? command.tools as Array<{ name?: unknown; [key: string]: unknown }> : []; const valid = tools.filter((t) => typeof t.name === "string" && t.name); - this.hostToolNames = new Set(valid.map((t) => t.name as string)); - await this.proc.sendCommand({ type: "set_host_tools", tools: valid }); + // Merge the server agent tools (#275) into every registration when + // the gate is on, so a later UI registration cannot drop them and + // a no-tab session keeps them after its startup registration. + // With the gate off the registration is exactly what the caller + // asked for, so existing behavior and tests are unchanged. + const merged = loadWebServerSettings().agentToolsEnabled + ? [...valid, ...AGENT_TOOL_DEFINITIONS.filter((t) => !valid.some((v) => v.name === t.name))] + : valid; + this.hostToolNames = new Set(merged.map((t) => t.name as string)); + await this.proc.sendCommand({ type: "set_host_tools", tools: merged }); return null; } @@ -2122,6 +2230,94 @@ function launchConfigForCwd(cwd: string): ProjectLaunchConfig | undefined { * Pass toolNames to pre-configure the builtin toolset of a NEW session * (empty array = all tools disabled); ignored when resuming. */ +declare global { + var __ompAgentToolGuard: AgentToolGuard | undefined; +} + +/** Process-wide loop/spam guard for server agent tools (#275). Stored on + * globalThis like the session registry so a hot reload does not silently + * reset the chain depths mid-loop. */ +function getAgentToolGuard(): AgentToolGuard { + if (!globalThis.__ompAgentToolGuard) globalThis.__ompAgentToolGuard = new AgentToolGuard(); + return globalThis.__ompAgentToolGuard; +} + +/** + * Real session operations behind lib/agent-tools executeAgentTool. + * Reuses the existing spawn/resume and message-send paths (startRpcSession, + * wrapper.send) instead of a second session engine. Delivery rules, kept + * explicit because omp's commands do not all make sense in every state: + * - prompt: only when the target is idle (starts a new turn); + * - steer: only when the target is running (steers that turn); + * - followUp: any state (queues behind a running turn, or starts one + * when idle — omp owns the queue, as with the UI's follow-ups). + * A waited delivery registers its turn-end waiter BEFORE sending, then + * reads the turn's final text with get_last_assistant_text. + */ +function createAgentToolOps(): AgentToolSessionOps { + return { + async listSessions() { + const running = new Set(getRunningRpcSessionIds()); + const sessions = await listAllSessions(); + return sessions.map((s) => ({ id: s.id, name: s.name, cwd: s.cwd, running: running.has(s.id) })); + }, + + async createSession(input) { + if (!existsSync(input.cwd)) throw new Error(`Directory does not exist: ${input.cwd}`); + const tempKey = `__new__${randomUUID()}`; + const { session, realSessionId } = await startRpcSession(tempKey, "", input.cwd, undefined, undefined); + allowFileRoot(input.cwd); + invalidateSessionListCache(); + try { + if (input.provider && input.modelId) { + await session.send({ type: "set_model", provider: input.provider, modelId: input.modelId }); + } + if (input.name) await session.send({ type: "set_session_name", name: input.name }); + if (input.prompt) await session.send({ type: "prompt", message: input.prompt }); + } catch (error) { + await session.destroyAndWait(); + throw error; + } + return { sessionId: realSessionId }; + }, + + async deliver(input): Promise { + const live = getRpcSession(input.sessionId); + let wrapper = live?.isAlive() ? live : undefined; + if (!wrapper) { + const filePath = await resolveSessionPath(input.sessionId); + if (!filePath) throw new Error(`Session not found: ${input.sessionId}`); + const header = readSessionHeader(filePath); + const { cwd } = resolveSpawnCwdResult(header?.cwd); + const started = await startRpcSession(input.sessionId, filePath, cwd, undefined, undefined, header?.cwd); + wrapper = started.session; + } + const wasRunning = wrapper.isRunning(); + if (input.delivery === "prompt" && wasRunning) { + throw new Error("Target session is running; use delivery \"steer\" or \"followUp\" for a running target."); + } + if (input.delivery === "steer" && !wasRunning) { + throw new Error("Target session is not running; use delivery \"prompt\" to start a turn."); + } + const terminalEndsNeeded = input.delivery === "followUp" && wasRunning ? 2 : 1; + const waiter = input.wait ? wrapper.waitForTurnEnd(input.waitTimeoutMs, terminalEndsNeeded) : null; + await wrapper.send({ type: input.delivery, message: input.message }); + if (!input.wait || !waiter) { + return { accepted: true, targetSessionId: input.sessionId, delivery: input.delivery, waited: false, responseText: null }; + } + await waiter; + const last = (await wrapper.send({ type: "get_last_assistant_text" })) as { text?: unknown } | null; + return { + accepted: true, + targetSessionId: input.sessionId, + delivery: input.delivery, + waited: true, + responseText: typeof last?.text === "string" ? last.text : null, + }; + }, + }; +} + export async function startRpcSession( sessionId: string, sessionFile: string, @@ -2219,6 +2415,15 @@ export async function startRpcSession( if (!sessionFile && created.sessionFile && existsSync(created.sessionFile)) { await created.send({ type: "new_session" }); } + // Register server agent tools (#275) at startup when the gate is on, + // so a session works for agent-to-agent calls even when no browser + // tab ever registers host tools for it. send() merges these with any + // later UI registration, so this never drops the UI tools. Older omp + // builds without host tools simply reject the registration; ignore + // that the way the UI registration does. + if (loadWebServerSettings().agentToolsEnabled) { + await created.send({ type: "set_host_tools", tools: AGENT_TOOL_DEFINITIONS }).catch(() => {}); + } } catch (error) { // Await the child's full exit before the `finally` releases the startup // lock: a fire-and-forget destroy() would let a retry spawn a second diff --git a/lib/web-settings.test.mjs b/lib/web-settings.test.mjs index bb680a34e..7828be1b7 100644 --- a/lib/web-settings.test.mjs +++ b/lib/web-settings.test.mjs @@ -24,7 +24,7 @@ function withAgentDir(run) { test("defaults apply when no settings file exists yet", () => { withAgentDir(() => { - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentEnv: {} }); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, agentEnv: {} }); }); }); @@ -40,7 +40,7 @@ test("agentEnv round-trips through the settings file", () => { delete globalThis.__ompWebSettingsCache; process.env.PI_CODING_AGENT_DIR = fresh; try { - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentEnv: { OBSIDIAN_API_KEY: "secret" } }); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, agentEnv: { OBSIDIAN_API_KEY: "secret" } }); } finally { rmSync(fresh, { recursive: true, force: true }); } @@ -51,14 +51,25 @@ test("a patch leaves the other keys untouched", () => { withAgentDir(() => { saveWebServerSettings({ autoResumeSessions: true, agentEnv: { A: "1" } }); saveWebServerSettings({ agentEnv: { B: "2" } }); - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: true, agentEnv: { B: "2" } }); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: true, agentToolsEnabled: false, agentEnv: { B: "2" } }); }); }); test("corrupt files fall back to defaults instead of throwing", () => { withAgentDir((dir) => { writeFileSync(join(dir, "omp-web-settings.json"), "{ not json", "utf8"); - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentEnv: {} }); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, agentEnv: {} }); + }); +}); + +test("agentToolsEnabled round-trips, and a non-boolean value falls back to false (#275)", () => { + withAgentDir(() => { + saveWebServerSettings({ agentToolsEnabled: true }); + assert.equal(loadWebServerSettings().agentToolsEnabled, true); + }); + withAgentDir((dir) => { + writeFileSync(join(dir, "omp-web-settings.json"), JSON.stringify({ agentToolsEnabled: "yes" }), "utf8"); + assert.equal(loadWebServerSettings().agentToolsEnabled, false); }); }); @@ -69,7 +80,7 @@ test("only string-valued agentEnv entries are kept", () => { JSON.stringify({ autoResumeSessions: "yes", agentEnv: { GOOD: "1", BAD: 2, WORSE: null, NESTED: { a: 1 } } }), "utf8", ); - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentEnv: { GOOD: "1" } }); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, agentEnv: { GOOD: "1" } }); }); }); diff --git a/lib/web-settings.ts b/lib/web-settings.ts index b108b8af9..f1ffa3cab 100644 --- a/lib/web-settings.ts +++ b/lib/web-settings.ts @@ -7,6 +7,14 @@ import { isRecord } from "./type-guards"; export interface WebServerSettings { /** Resume sessions that were mid-run when omp-web stopped. */ autoResumeSessions: boolean; + /** + * Server-side agent tools (issue #275: list_sessions / new_session / + * send_to_session). OFF by default: when on, any agent session may call + * them to reach other sessions, with no browser tab required. Sessions + * pick the tools up on their next host-tool registration (session start + * or SSE reconnect). + */ + agentToolsEnabled: boolean; /** * Environment variables merged into the `omp` child process (issue #104). * Stored as a validated record; lib/omp/agent-env.ts owns the policy and @@ -15,7 +23,7 @@ export interface WebServerSettings { agentEnv: Record; } -const DEFAULTS: WebServerSettings = { autoResumeSessions: false, agentEnv: {} }; +const DEFAULTS: WebServerSettings = { autoResumeSessions: false, agentToolsEnabled: false, agentEnv: {} }; /** String-valued entries only — the allow-list lives in lib/omp/agent-env.ts. */ function readAgentEnvRecord(value: unknown): Record { @@ -47,6 +55,7 @@ export function loadWebServerSettings(): WebServerSettings { if (isRecord(raw)) { settings = { autoResumeSessions: raw.autoResumeSessions === true, + agentToolsEnabled: raw.agentToolsEnabled === true, agentEnv: readAgentEnvRecord(raw.agentEnv), }; }