diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a2cc56..fc049cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,21 @@ plugin contract. ## [Unreleased] +### Added + +- Native OpenCode shell, read, list, search, edit, write, web, todo and task + presentation for recognised ACP tool activity, with structured ACP metadata + retained on fallback cards. +- Cursor, Claude, Codex and Grok subagent activity projection, plus the shared + ACP task-shape fallback used by Hermes and custom agents. + +### Fixed + +- Preserve OpenCode provider whitelist/blacklist settings when injecting an ACP + provider, including base-ID expansion for parameterised Cursor model IDs. +- Correlate session-less Cursor task notifications by tool-call ID and suppress + redundant control-tool cards for informational task/todo extensions. + ## [0.1.0] - 2026-08-15 ### Added diff --git a/README.md b/README.md index 2304a45..8168256 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,9 @@ callbacks required for full-fidelity ACP operation. fallback. - One durable ACP conversation per OpenCode session, server and worktree. - Streaming assistant text, thought/reasoning, usage, plans and provider-owned - tool calls without re-executing those tools in OpenCode. + tool calls without re-executing those tools in OpenCode. Standard ACP tool + kinds are projected onto OpenCode's native shell, read, list, grep, glob, + edit, write, web and task cards when the agent supplies enough metadata. - OpenCode-native permission prompts with exact ACP `allow_once`, `allow_always`, `reject_once` and cancellation correlation. - Standard form elicitation and Cursor questions through OpenCode's built-in @@ -28,7 +30,10 @@ callbacks required for full-fidelity ACP operation. authentication metadata retained on the private worker event channel. - Native agent skills, rules, hooks, MCP servers, memory and subagents remain active in the ACP agent. Advertised commands and invocable skills are added - to OpenCode's startup command catalogue when available. + to OpenCode's startup command catalogue when available. Cursor task events, + Claude/Codex subagent calls and Grok subagent lifecycle notifications are + rendered as native OpenCode task activity; other agents receive the shared + ACP task-shape fallback. - Bounded, authenticated NDJSON IPC between the OpenCode plugin and a plugin-owned Node worker, including parent-death and idle cleanup. @@ -229,8 +234,9 @@ See [testing](docs/testing.md) for the complete matrix and release procedure. internal to that agent. - OpenCode-native tools are not injected into the ACP agent as MCP tools. - Rewind/fork creates a fresh binding when the selected agent cannot fork. -- Rich agent-specific timeline cards degrade to generic provider-executed tool - cards with structured metadata. +- Native timeline projection is best-effort: incomplete or unknown agent tool + shapes degrade to generic provider-executed cards with structured ACP + metadata, while the private worker channel retains the complete event. - Hermes is supported through its legacy ACP model surface; its own advertised and upstream limitations still apply. diff --git a/docs/architecture.md b/docs/architecture.md index 16e97b2..72f4b1b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -89,8 +89,19 @@ calls. The provider therefore segments one ACP turn: 6. emit the final `finish` only when ACP completes. ACP-native tool calls are marked `providerExecuted: true`; OpenCode renders but -does not execute them. Reserved interaction calls are host-executed and use -unguessable, expiring tokens bound to the OpenCode and ACP sessions. +does not execute them. A shared projector maps ACP `execute`, `read`, `search`, +`edit` and `fetch` events onto native OpenCode presentation contracts while +retaining ACP status, locations, raw input/output and content as provider +metadata. Unknown shapes keep a namespaced generic tool name. Reserved +interaction calls are host-executed and use unguessable, expiring tokens bound +to the OpenCode and ACP sessions. + +Subagent activity follows the same rule. Standard task-shaped calls cover +Claude, Codex and compatible agents. Cursor's session-less `cursor/task` +notification is correlated back to the active turn by its ACP tool-call ID; +Grok's spawn/progress/finish notifications maintain one synthetic native task +lifecycle. ACP child identifiers remain metadata because they are not OpenCode +child-session identifiers and must not become broken UI links. ## Discovery diff --git a/docs/compatibility.md b/docs/compatibility.md index 2219907..90af483 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -6,21 +6,22 @@ default. ## Shared feature mapping -| ACP feature | OpenCode representation | -| ----------------------------------------- | -------------------------------------------------------------------- | -| Model config option or legacy model state | Provider model catalogue | -| Model parameters and thought level | Model options/variants and session config | -| Agent mode | Session control and configured default | -| Agent text | Assistant text | -| Agent thought | Reasoning | -| Agent-native tool | Provider-executed dynamic tool | -| Plan | ACP update retained on the private worker event channel | -| Permission request | Reserved plugin tool and OpenCode permission UI | -| Form or URL elicitation | Question/control tool when representable; otherwise cancel | -| Available command | Startup OpenCode command snapshot | -| Agent-native skill | Remains available inside the agent | -| Session lifecycle | Persistent Acpx binding with capability-gated load/resume/close/fork | -| MCP server | ACP session MCP definition, capability-gated by transport | +| ACP feature | OpenCode representation | +| ----------------------------------------- | ------------------------------------------------------------------------- | +| Model config option or legacy model state | Provider model catalogue | +| Model parameters and thought level | Model options/variants and session config | +| Agent mode | Session control and configured default | +| Agent text | Assistant text | +| Agent thought | Reasoning | +| Agent-native tool | Provider-executed native OpenCode card where recognised; generic fallback | +| Subagent activity | Native OpenCode task card where standard/vendor metadata permits | +| Plan | ACP update retained on the private worker event channel | +| Permission request | Reserved plugin tool and OpenCode permission UI | +| Form or URL elicitation | Question/control tool when representable; otherwise cancel | +| Available command | Startup OpenCode command snapshot | +| Agent-native skill | Remains available inside the agent | +| Session lifecycle | Persistent Acpx binding with capability-gated load/resume/close/fork | +| MCP server | ACP session MCP definition, capability-gated by transport | ACP v1 has no global model or skill catalogue. Discovery is session-scoped and dynamic. Catalogue entries are therefore per-instance snapshots; @@ -41,6 +42,9 @@ re-authentication or an agent update may require an OpenCode reload. - Native rules, skills, commands, plugins, hooks, MCP, code index and subagents remain active. Advertised commands are surfaced where OpenCode permits. - Cursor ask/plan/todo/task/image extension methods are version-gated. +- Standard task tool calls and `cursor/task` completion notifications are + correlated into one native OpenCode task card without inventing a host child + session link. ### Claude Agent ACP @@ -51,6 +55,8 @@ re-authentication or an agent update may require an OpenCode reload. - AskUserQuestion requires form elicitation; device/remote login may require URL elicitation or a terminal-auth action. - Native Claude commands and skills arrive through available-command updates. +- Claude Task/Agent calls with prompt, description and subagent type metadata + are projected as native OpenCode task cards. ### Codex ACP @@ -62,6 +68,8 @@ re-authentication or an agent update may require an OpenCode reload. - Codex slash commands and `$skill` entries are surfaced from runtime updates. - Standard form/URL elicitation covers request-user-input and device auth where advertised. +- Codex collaboration and sub-agent activity calls are projected as native + OpenCode task cards while preserving thread identifiers in ACP metadata. ### Grok Build @@ -71,6 +79,8 @@ re-authentication or an agent update may require an OpenCode reload. applied before the first prompt. - Native skills, workflows, plugins, hooks, memory, MCP and subagents remain in Grok. `x.ai/*` extensions are handled only when their schemas are recognised. +- Recognised `subagent_spawned`, `subagent_progress` and `subagent_finished` + notifications produce one running native task card and its final result. - The current CLI remains alpha; every exact build receives a capability fingerprint and newer builds warn until tested. @@ -84,6 +94,8 @@ re-authentication or an agent update may require an OpenCode reload. - Modes: `default`, `accept_edits`, `dont_ask` when advertised. - Native tools, memory and skills remain active, but installed skills are not individually advertised as ACP commands in Hermes 0.20.1. +- Hermes subagent-like calls use the shared ACP task-shape detector; the current + adapter does not advertise a separate subagent lifecycle extension. - The current agent accepts session MCP servers without advertising MCP capabilities; this is reported as a compatibility warning. diff --git a/docs/configuration.md b/docs/configuration.md index c6d22cb..9e87899 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -105,6 +105,27 @@ identifiers or vendor-qualified IDs. A zero limit means unknown and disables OpenCode context-overflow handling; the ACP agent remains responsible for its own context. +### OpenCode model filters + +Normal OpenCode provider filters apply after ACP discovery: + +```jsonc +{ + "provider": { + "acp.cursor": { + "whitelist": ["grok-4.6"], + }, + }, +} +``` + +The plugin preserves both `whitelist` and `blacklist`. An exact opaque model ID +is used unchanged. A convenient base ID such as `grok-4.6` expands to currently +discovered parameterised IDs such as +`grok-4.6[effort=high,fast=true]`; it does not act as a substring match. This +keeps the filter usable across Cursor catalogue refreshes without discarding +the exact ID that ACP needs for selection. + ### MCP servers Stdio: diff --git a/docs/testing.md b/docs/testing.md index 2bcd8c3..47beac7 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -35,6 +35,8 @@ Unit tests cover: - prompt extraction and attachment validation; - balanced AI SDK text/reasoning events; - provider-executed ACP tool lifecycles; +- native shell/read/search/edit/web projection with generic fallbacks; +- Cursor, Claude, Codex and Grok subagent task projection and de-duplication; - finish reason and usage mapping; - interaction segmentation and cursor replay; - exact permission/question correlation; diff --git a/src/provider.ts b/src/provider.ts index d35f1a2..2b7e0e1 100644 --- a/src/provider.ts +++ b/src/provider.ts @@ -79,7 +79,7 @@ interface TurnState { interface RuntimeHub { turns: Map; - orphans: Map; + orphans: Map; unsubscribe: () => void; } @@ -128,7 +128,8 @@ function runtimeHub(runtime: ProviderRuntime): RuntimeHub { hub.unsubscribe = runtime.client.subscribe((event) => { if ( (event.type !== "interaction.elicitation" && - event.type !== "interaction.extension") || + event.type !== "interaction.extension" && + event.type !== "extension.notification") || event.turnId === undefined ) { return; @@ -385,6 +386,12 @@ function failClosedGenericInteraction( }); } +function isInformationalCursorExtension(event: ExtensionInteraction): boolean { + return ( + event.method === "cursor/task" || event.method === "cursor/update_todos" + ); +} + function updateState( state: TurnState, event: RuntimeWorkerEvent, @@ -470,6 +477,27 @@ function streamTurn( event.type === "interaction.elicitation" || event.type === "interaction.extension" ) { + if ( + event.type === "interaction.extension" && + isInformationalCursorExtension(event) + ) { + for (const part of translator.extensionNotification({ + type: "extension.notification", + serverId: event.serverId, + ...(event.sessionKey === undefined + ? {} + : { sessionKey: event.sessionKey }), + ...(event.turnId === undefined ? {} : { turnId: event.turnId }), + method: event.method, + params: event.params, + })) + controller.enqueue(part); + await runtime.client.respondExtension({ + interactionId: event.interactionId, + result: {}, + }); + continue; + } const projection = translator.interaction(event); if (projection === undefined) { await failClosedGenericInteraction(runtime, event); @@ -486,6 +514,11 @@ function streamTurn( controller.close(); return; } + if (event.type === "extension.notification") { + for (const part of translator.extensionNotification(event)) + controller.enqueue(part); + continue; + } if (event.type === "turn.result") { for (const part of translator.terminal(event.result)) controller.enqueue(part); diff --git a/src/server.ts b/src/server.ts index 04cb697..1c63b5c 100644 --- a/src/server.ts +++ b/src/server.ts @@ -328,11 +328,24 @@ function injectConfiguration( if (!server.enabled) continue; const id = providerId(serverId); addedProviderIds.push(id); + const existing = config.provider[id]; + const models = buildProviderModels( + serverId, + server, + catalogues.get(serverId), + ); config.provider[id] = { + ...existing, name: `${resolvePreset(server)?.title ?? serverId} through ACP`, npm: providerUrl.href, - options: { pluginInstanceId, serverId }, - models: buildProviderModels(serverId, server, catalogues.get(serverId)), + options: { ...existing?.options, pluginInstanceId, serverId }, + models, + ...(existing?.whitelist === undefined + ? {} + : { whitelist: expandModelFilter(existing.whitelist, models) }), + ...(existing?.blacklist === undefined + ? {} + : { blacklist: expandModelFilter(existing.blacklist, models) }), }; const commandName = `acp-${serverId}`; config.command[commandName] ??= { @@ -471,6 +484,22 @@ function unique(values: string[]): string[] { return [...new Set(values)]; } +function expandModelFilter( + configured: string[], + models: Record, +): string[] { + const modelIds = Object.keys(models); + return unique( + configured.flatMap((configuredId) => { + if (models[configuredId] !== undefined) return [configuredId]; + const parameterised = modelIds.filter((modelId) => + modelId.startsWith(`${configuredId}[`), + ); + return parameterised.length === 0 ? [configuredId] : parameterised; + }), + ); +} + function serverWorkingDirectory( server: ServerConfig, fallback: string, diff --git a/src/translate/stream.ts b/src/translate/stream.ts index fcb8b7e..14f38c8 100644 --- a/src/translate/stream.ts +++ b/src/translate/stream.ts @@ -17,18 +17,29 @@ import { } from "../constants.js"; import type { ElicitationInteraction, + ExtensionNotificationEvent, ExtensionInteraction, PermissionInteraction, } from "../worker/messages.js"; +import { + jsonValue, + projectSubagentNotification, + projectToolCall, + projectToolResult, + type ToolProjection, +} from "./tools.js"; interface OpenBlock { kind: "text" | "reasoning"; id: string; } +type ToolEvent = Extract; interface ToolState { name: string; + projection: ToolProjection; callEmitted: boolean; finalResultEmitted: boolean; + deferredEvent?: ToolEvent; } interface QuestionInput { @@ -54,31 +65,6 @@ const terminalToolStatuses = new Set([ "cancelled", ]); -function jsonValue(value: unknown): JSONValue { - if (value === null || typeof value === "string" || typeof value === "boolean") - return value; - if (typeof value === "number") - return Number.isFinite(value) ? value : String(value); - if (Array.isArray(value)) return value.map(jsonValue); - if (typeof value === "object") { - const result: Record = {}; - for (const [key, item] of Object.entries(value)) { - if ( - item !== undefined && - typeof item !== "function" && - typeof item !== "symbol" - ) { - result[key] = jsonValue(item); - } - } - return result; - } - if (value === undefined) return "undefined"; - if (typeof value === "bigint") return value.toString(); - if (typeof value === "symbol") return value.description ?? "symbol"; - return "unsupported"; -} - function safeStringify(value: unknown): string { return JSON.stringify(jsonValue(value)); } @@ -202,12 +188,6 @@ function questionToolCallId(interactionId: string): string { return `opencode-acpx-question:${Buffer.from(interactionId, "utf8").toString("base64url")}`; } -function toolName( - event: Extract, -): string { - return `acp_${event.kind ?? "tool"}`; -} - function finishReason( result: AcpRuntimeTurnResult, ): LanguageModelV3FinishReason { @@ -280,10 +260,12 @@ export class AcpStreamTranslator { if (event.breakdown !== undefined) this.#usage = event.breakdown; return []; } - if (event.type === "text_delta") return this.#text(event); + if (event.type === "text_delta") + return [...this.#flushDeferredTools(), ...this.#text(event)]; if (event.type === "tool_call") return this.#tool(event, index); if (event.type === "error") { return [ + ...this.#flushDeferredTools(), ...this.#closeBlock(), { type: "error", error: new Error(event.message) }, ]; @@ -373,8 +355,66 @@ export class AcpStreamTranslator { }; } - terminal(result: AcpRuntimeTurnResult): LanguageModelV3StreamPart[] { + extensionNotification( + event: ExtensionNotificationEvent, + ): LanguageModelV3StreamPart[] { + const projection = projectSubagentNotification(event.method, event.params); + if (projection === undefined) return []; const parts = this.#closeBlock(); + const id = `${this.#turnId}-tool-${projection.toolCallId}`; + let state = this.#tools.get(id); + if (state !== undefined && state.name !== "task") return parts; + if (state === undefined) { + const toolProjection: ToolProjection = { + name: "task", + presentation: "task", + input: projection.input, + }; + state = { + name: "task", + projection: toolProjection, + callEmitted: false, + finalResultEmitted: false, + }; + this.#tools.set(id, state); + } else if (!state.callEmitted) { + state.projection = { + name: "task", + presentation: "task", + input: projection.input, + }; + state.name = "task"; + } + if (!state.callEmitted) { + parts.push(...this.#providerToolCall(id, state)); + state.callEmitted = true; + } + if (projection.action !== "finish" || state.finalResultEmitted) + return parts; + delete state.deferredEvent; + state.finalResultEmitted = true; + parts.push({ + type: "tool-result", + toolCallId: id, + toolName: state.name, + result: projection.result ?? { status: "completed" }, + dynamic: true, + providerMetadata: { + opencodeAcpx: { + subagent: { + method: event.method, + action: projection.action, + toolCallId: projection.toolCallId, + }, + }, + }, + ...(projection.isError === true ? { isError: true } : {}), + }); + return parts; + } + + terminal(result: AcpRuntimeTurnResult): LanguageModelV3StreamPart[] { + const parts = [...this.#flushDeferredTools(), ...this.#closeBlock()]; if (result.status === "failed") parts.push({ type: "error", error: new Error(result.error.message) }); parts.push({ @@ -409,63 +449,108 @@ export class AcpStreamTranslator { return parts; } - #tool( - event: Extract, - index: number, - ): LanguageModelV3StreamPart[] { - const parts = this.#closeBlock(); + #tool(event: ToolEvent, index: number): LanguageModelV3StreamPart[] { const id = `${this.#turnId}-tool-${event.toolCallId ?? String(index)}`; + const parts = this.#closeBlock(); + const projection = projectToolCall(event); const state = this.#tools.get(id) ?? { - name: toolName(event), + name: projection.name, + projection, callEmitted: false, finalResultEmitted: false, }; this.#tools.set(id, state); - if (!state.callEmitted) { - const input = safeStringify(event.rawInput ?? { summary: event.text }); - parts.push( - { - type: "tool-input-start", - id, - toolName: state.name, - providerExecuted: true, - dynamic: true, - ...(event.title === undefined ? {} : { title: event.title }), - }, - { type: "tool-input-delta", id, delta: input }, - { type: "tool-input-end", id }, - { - type: "tool-call", - toolCallId: id, - toolName: state.name, - input, - providerExecuted: true, - dynamic: true, - }, - ); - state.callEmitted = true; - } const terminal = event.status === undefined || terminalToolStatuses.has(event.status.toLowerCase()); + if ( + state.name === "task" && + !state.callEmitted && + state.projection.input.prompt === undefined && + state.projection.input.subagent_type === undefined + ) { + state.deferredEvent = event; + return parts; + } + if (!state.callEmitted) { + parts.push(...this.#providerToolCall(id, state, event.title)); + state.callEmitted = true; + } if (!terminal || state.finalResultEmitted) return parts; state.finalResultEmitted = true; - const output = event.rawOutput ?? event.content ?? event.text; - const translatedOutput = jsonValue(output); + parts.push(this.#providerToolResult(id, state, event)); + return parts; + } + + #flushDeferredTools(exceptId?: string): LanguageModelV3StreamPart[] { + const parts: LanguageModelV3StreamPart[] = []; + for (const [id, state] of this.#tools) { + if (id === exceptId || state.deferredEvent === undefined) continue; + const event = state.deferredEvent; + delete state.deferredEvent; + if (!state.callEmitted) { + parts.push(...this.#providerToolCall(id, state, event.title)); + state.callEmitted = true; + } + const terminal = + event.status === undefined || + terminalToolStatuses.has(event.status.toLowerCase()); + if (terminal && !state.finalResultEmitted) { + state.finalResultEmitted = true; + parts.push(this.#providerToolResult(id, state, event)); + } + } + return parts; + } + + #providerToolResult( + id: string, + state: ToolState, + event: ToolEvent, + ): LanguageModelV3StreamPart { + const output = projectToolResult(state.projection, event); const lowerStatus = event.status?.toLowerCase(); - parts.push({ + return { type: "tool-result", toolCallId: id, toolName: state.name, - result: translatedOutput ?? { value: null }, + result: output.result, dynamic: true, + providerMetadata: output.providerMetadata, ...(lowerStatus === "failed" || lowerStatus === "error" || lowerStatus === "rejected" ? { isError: true } : {}), - }); - return parts; + }; + } + + #providerToolCall( + id: string, + state: ToolState, + title?: string, + ): LanguageModelV3StreamPart[] { + const input = safeStringify(state.projection.input); + return [ + { + type: "tool-input-start", + id, + toolName: state.name, + providerExecuted: true, + dynamic: true, + ...(title === undefined ? {} : { title }), + }, + { type: "tool-input-delta", id, delta: input }, + { type: "tool-input-end", id }, + { + type: "tool-call", + toolCallId: id, + toolName: state.name, + input, + providerExecuted: true, + dynamic: true, + }, + ]; } #closeBlock(): LanguageModelV3StreamPart[] { diff --git a/src/translate/tools.ts b/src/translate/tools.ts new file mode 100644 index 0000000..6ed82be --- /dev/null +++ b/src/translate/tools.ts @@ -0,0 +1,602 @@ +import type { + JSONObject, + JSONValue, + SharedV3ProviderMetadata, +} from "@ai-sdk/provider"; +import type { AcpRuntimeEvent } from "acpx/runtime"; + +type ToolEvent = Extract; + +export type NativeToolPresentation = + | "bash" + | "edit" + | "glob" + | "grep" + | "list" + | "read" + | "skill" + | "task" + | "todowrite" + | "webfetch" + | "websearch" + | "write" + | "generic"; + +export interface ToolProjection { + name: string; + presentation: NativeToolPresentation; + input: Record; +} + +export interface ToolResultProjection { + result: NonNullable; + providerMetadata: SharedV3ProviderMetadata; +} + +export interface SubagentProjection { + action: "start" | "progress" | "finish"; + toolCallId: string; + input: Record; + result?: NonNullable; + isError?: boolean; +} + +export function jsonValue(value: unknown): JSONValue { + if (value === null || typeof value === "string" || typeof value === "boolean") + return value; + if (typeof value === "number") + return Number.isFinite(value) ? value : String(value); + if (Array.isArray(value)) return value.map(jsonValue); + if (isRecord(value)) { + const result: Record = {}; + for (const [key, item] of Object.entries(value)) { + if ( + item !== undefined && + typeof item !== "function" && + typeof item !== "symbol" + ) { + result[key] = jsonValue(item); + } + } + return result; + } + if (value === undefined) return "undefined"; + if (typeof value === "bigint") return value.toString(); + if (typeof value === "symbol") return value.description ?? "symbol"; + return "unsupported"; +} + +export function projectToolCall(event: ToolEvent): ToolProjection { + const raw = isRecord(event.rawInput) ? event.rawInput : {}; + const subagent = subagentInput(raw, event); + if (subagent !== undefined) + return { name: "task", presentation: "task", input: subagent }; + + const specialised = specialisedTool(raw, event); + if (specialised !== undefined) return specialised; + + switch (event.kind) { + case "execute": + return { + name: "bash", + presentation: "bash", + input: compact({ + command: + firstString(raw, ["command", "cmd", "script"]) ?? event.title, + description: firstString(raw, ["description"]), + }), + }; + case "read": + if (looksLikeList(raw, event)) { + return { + name: "list", + presentation: "list", + input: compact({ path: toolPath(raw, event) }), + }; + } + return { + name: "read", + presentation: "read", + input: compact({ + filePath: toolPath(raw, event), + offset: firstNumber(raw, ["offset", "line", "startLine"]), + limit: firstNumber(raw, ["limit", "lineLimit"]), + }), + }; + case "search": + return searchProjection(raw, event); + case "edit": + return editProjection(raw, event); + case "fetch": + return fetchProjection(raw, event); + default: + return { + name: `acp_${event.kind ?? "tool"}`, + presentation: "generic", + input: + Object.keys(raw).length > 0 + ? (jsonValue(raw) as Record) + : compact({ summary: event.text || event.title }), + }; + } +} + +export function projectToolResult( + projection: ToolProjection, + event: ToolEvent, +): ToolResultProjection { + const result = nativeResult(projection, event); + return { + result, + providerMetadata: { + opencodeAcpx: jsonValue({ + acp: { + kind: event.kind, + title: event.title, + status: event.status, + locations: event.locations, + rawOutput: event.rawOutput, + content: event.content, + }, + }) as JSONObject, + }, + }; +} + +export function projectSubagentNotification( + method: string, + params: unknown, +): SubagentProjection | undefined { + if (!isRecord(params)) return undefined; + if (method === "cursor/task") return cursorTask(params); + if ( + method === "x.ai/session_notification" || + method === "x.ai/session/update" + ) + return grokSubagent(params); + return undefined; +} + +function specialisedTool( + raw: Record, + event: ToolEvent, +): ToolProjection | undefined { + const nativeName = firstString(raw, ["_toolName", "toolName", "tool_name"]); + const lowered = nativeName?.toLowerCase(); + if (lowered === "updatetodos" || lowered === "todowrite") { + return { + name: "todowrite", + presentation: "todowrite", + input: compact({ todos: raw.todos }), + }; + } + if (lowered === "skill" || ("skill" in raw && event.kind === "other")) { + return { + name: "skill", + presentation: "skill", + input: compact({ name: firstString(raw, ["skill", "name"]) }), + }; + } + return undefined; +} + +function searchProjection( + raw: Record, + event: ToolEvent, +): ToolProjection { + const url = firstString(raw, ["url"]); + const webQuery = firstString(raw, ["searchTerm", "search_term"]); + if (url !== undefined || webQuery !== undefined) { + return url === undefined + ? { + name: "websearch", + presentation: "websearch", + input: compact({ query: webQuery }), + } + : { + name: "webfetch", + presentation: "webfetch", + input: compact({ url }), + }; + } + if (looksLikeList(raw, event)) { + return { + name: "list", + presentation: "list", + input: compact({ path: toolPath(raw, event) }), + }; + } + const glob = firstString(raw, ["globPattern", "glob_pattern", "glob"]); + const pattern = firstString(raw, ["pattern"]); + if (glob !== undefined || looksLikeGlob(event.title)) { + return { + name: "glob", + presentation: "glob", + input: compact({ + pattern: glob ?? pattern ?? titleSubject(event.title, ["find", "glob"]), + path: toolPath(raw, event), + }), + }; + } + return { + name: "grep", + presentation: "grep", + input: compact({ + pattern: + pattern ?? + firstString(raw, ["query", "search", "searchQuery"]) ?? + titleSubject(event.title, ["search", "grep"]), + path: toolPath(raw, event), + include: firstString(raw, ["include", "type"]), + }), + }; +} + +function editProjection( + raw: Record, + event: ToolEvent, +): ToolProjection { + const filePath = toolPath(raw, event); + const content = firstString(raw, ["content"]); + const oldString = firstString(raw, ["oldString", "old_string", "oldText"]); + const newString = firstString(raw, ["newString", "new_string", "newText"]); + const write = + (content !== undefined && oldString === undefined) || + event.title?.trim().toLowerCase().startsWith("write ") === true; + return write + ? { + name: "write", + presentation: "write", + input: compact({ filePath, content }), + } + : { + name: "edit", + presentation: "edit", + input: compact({ filePath, oldString, newString }), + }; +} + +function fetchProjection( + raw: Record, + event: ToolEvent, +): ToolProjection { + const query = firstString(raw, ["query", "searchTerm", "search_term"]); + const url = firstString(raw, ["url", "uri"]); + if (query !== undefined && url === undefined) { + return { + name: "websearch", + presentation: "websearch", + input: compact({ query }), + }; + } + return { + name: "webfetch", + presentation: "webfetch", + input: compact({ url: url ?? titleUrl(event.title) }), + }; +} + +function subagentInput( + raw: Record, + event: ToolEvent, +): Record | undefined { + const explicitName = firstString(raw, ["_toolName", "toolName", "tool_name"]); + const activity = firstString(raw, ["activityKind"]); + const agentPath = firstString(raw, ["agentPath"]); + const receivers = Array.isArray(raw.receiverThreadIds) + ? raw.receiverThreadIds + : undefined; + const prompt = firstString(raw, ["prompt", "task", "instructions"]); + const description = firstString(raw, ["description", "subject"]); + const rawType = raw.subagentType ?? raw.subagent_type ?? raw.agentType; + const subagentType = subagentTypeValue(rawType); + const recognised = + explicitName?.toLowerCase() === "task" || + (activity !== undefined && agentPath !== undefined) || + (receivers !== undefined && prompt !== undefined) || + (prompt !== undefined && + description !== undefined && + (event.kind === "think" || event.kind === "other")) || + (prompt !== undefined && subagentType !== undefined); + if (!recognised) return undefined; + return compact({ + prompt, + description: + description ?? + event.title ?? + (activity === undefined ? undefined : `${activity} subagent`), + subagent_type: + subagentType ?? + (agentPath === undefined + ? undefined + : agentPath.split("/").filter(Boolean).at(-1)) ?? + (receivers === undefined ? undefined : "collaboration"), + }); +} + +function nativeResult( + projection: ToolProjection, + event: ToolEvent, +): NonNullable { + if (projection.presentation === "bash") return shellOutput(event); + if ( + projection.presentation === "grep" || + projection.presentation === "glob" || + projection.presentation === "list" + ) { + return displayOutput(event); + } + if (projection.presentation === "edit") { + const diff = diffContent(event) ?? { + file: projection.input.filePath, + before: projection.input.oldString, + after: projection.input.newString, + }; + return nonNullJsonValue({ filediff: diff }); + } + if (projection.presentation === "read") { + const path = projection.input.filePath; + return nonNullJsonValue({ loaded: typeof path === "string" ? [path] : [] }); + } + if (projection.presentation === "task") { + return nonNullJsonValue({ + background: backgroundFlag(event.rawInput, event.rawOutput), + acp: event.rawOutput ?? displayOutput(event), + }); + } + const output = event.rawOutput ?? contentValue(event.content) ?? event.text; + return nonNullJsonValue(output); +} + +function shellOutput(event: ToolEvent): string { + if (typeof event.rawOutput === "string") return event.rawOutput; + if (isRecord(event.rawOutput)) { + const stdout = firstString(event.rawOutput, ["stdout", "output", "text"]); + const stderr = firstString(event.rawOutput, ["stderr"]); + if (stdout !== undefined || stderr !== undefined) + return [stdout, stderr] + .filter((value) => value !== undefined && value.length > 0) + .join("\n"); + } + return displayOutput(event); +} + +function displayOutput(event: ToolEvent): string { + const content = contentText(event.content); + if (content.length > 0) return content; + if (typeof event.rawOutput === "string") return event.rawOutput; + if (event.rawOutput !== undefined) + return JSON.stringify(jsonValue(event.rawOutput), null, 2); + return event.text; +} + +function contentText(value: unknown): string { + if (!Array.isArray(value)) return ""; + const result: string[] = []; + for (const item of value) { + if (!isRecord(item)) continue; + if (item.type === "content" && isRecord(item.content)) { + const text = firstString(item.content, ["text"]); + if (text !== undefined) result.push(text); + } else if (item.type === "diff") { + const path = firstString(item, ["path"]); + if (path !== undefined) result.push(`Changed ${path}`); + } + } + return result.join("\n"); +} + +function contentValue(value: unknown): unknown { + const text = contentText(value); + return text.length > 0 ? text : value; +} + +function diffContent( + event: ToolEvent, +): { file?: unknown; before?: unknown; after?: unknown } | undefined { + if (!Array.isArray(event.content)) return undefined; + for (const item of event.content) { + if (!isRecord(item) || item.type !== "diff") continue; + return { + file: item.path, + before: item.oldText, + after: item.newText, + }; + } + return undefined; +} + +function cursorTask( + params: Record, +): SubagentProjection | undefined { + const toolCallId = firstString(params, ["toolCallId"]); + if (toolCallId === undefined) return undefined; + return { + action: "finish", + toolCallId, + input: compact({ + prompt: firstString(params, ["prompt"]), + description: firstString(params, ["description"]), + subagent_type: subagentTypeValue(params.subagentType), + }), + result: nonNullJsonValue({ + model: params.model, + agentId: params.agentId, + durationMs: params.durationMs, + }), + }; +} + +function grokSubagent( + params: Record, +): SubagentProjection | undefined { + const update = isRecord(params.update) ? params.update : params; + const tag = firstString(update, ["sessionUpdate", "session_update"]); + const toolCallId = firstString(update, ["subagent_id", "subagentId"]); + if (toolCallId === undefined || tag === undefined) return undefined; + if (tag === "subagent_spawned") { + return { + action: "start", + toolCallId, + input: compact({ + description: firstString(update, ["description"]), + subagent_type: firstString(update, ["subagent_type", "subagentType"]), + prompt: firstString(update, ["description"]), + }), + }; + } + if (tag === "subagent_progress") { + return { + action: "progress", + toolCallId, + input: compact({ + description: "Subagent activity", + subagent_type: "grok", + }), + }; + } + if (tag !== "subagent_finished") return undefined; + const status = firstString(update, ["status"]); + return { + action: "finish", + toolCallId, + input: compact({ description: "Subagent activity", subagent_type: "grok" }), + result: nonNullJsonValue({ + status, + error: update.error, + output: update.output, + toolCalls: update.tool_calls ?? update.toolCalls, + turns: update.turns, + durationMs: update.duration_ms ?? update.durationMs, + tokensUsed: update.tokens_used ?? update.tokensUsed, + acpChildSessionId: update.child_session_id ?? update.childSessionId, + }), + isError: status === "failed", + }; +} + +function subagentTypeValue(value: unknown): string | undefined { + if (typeof value === "string" && value.length > 0) return value; + if (isRecord(value)) return firstString(value, ["custom", "name", "type"]); + return undefined; +} + +function backgroundFlag(...values: unknown[]): boolean | undefined { + for (const value of values) { + if (!isRecord(value)) continue; + for (const key of ["background", "isBackground", "run_in_background"]) { + if (typeof value[key] === "boolean") return value[key]; + } + } + return undefined; +} + +function toolPath( + raw: Record, + event: ToolEvent, +): string | undefined { + const direct = firstString(raw, ["filePath", "file_path", "path", "cwd"]); + if (direct !== undefined) return direct; + if (Array.isArray(event.locations)) { + for (const location of event.locations) { + if (!isRecord(location)) continue; + const path = firstString(location, ["path"]); + if (path !== undefined) return path; + } + } + return titlePath(event.title); +} + +function looksLikeList( + raw: Record, + event: ToolEvent, +): boolean { + const operation = firstString(raw, ["operation", "action", "_toolName"]); + return ( + operation?.toLowerCase() === "list" || + operation?.toLowerCase() === "ls" || + event.title?.trim().toLowerCase().startsWith("list ") === true + ); +} + +function looksLikeGlob(title: string | undefined): boolean { + const value = title?.trim().toLowerCase(); + return ( + value === "find" || + value === "glob" || + value?.startsWith("find ") === true || + value?.startsWith("glob ") === true + ); +} + +function titlePath(title: string | undefined): string | undefined { + if (title === undefined) return undefined; + const match = + /^(?:read|write|edit|list(?: files)?(?: in)?)\s+[`'"]?(.+?)[`'"]?(?:\s+\(|$)/i.exec( + title.trim(), + ); + const path = match?.[1]?.trim(); + if (path === undefined) return undefined; + if (["file", "files", "directory"].includes(path.toLowerCase())) + return undefined; + return path; +} + +function titleSubject( + title: string | undefined, + prefixes: string[], +): string | undefined { + if (title === undefined) return undefined; + const value = title.trim(); + for (const prefix of prefixes) { + const match = new RegExp( + "^" + prefix + "(?: for)?[:\\s]+[`'\"]?(.+?)[`'\"]?$", + "i", + ).exec(value); + if (match?.[1] !== undefined && match[1].toLowerCase() !== "files") + return match[1]; + } + return undefined; +} + +function titleUrl(title: string | undefined): string | undefined { + return title?.match(/https?:\/\/\S+/)?.[0]; +} + +function firstString( + value: Record, + keys: string[], +): string | undefined { + for (const key of keys) { + const item = value[key]; + if (typeof item === "string" && item.length > 0) return item; + } + return undefined; +} + +function firstNumber( + value: Record, + keys: string[], +): number | undefined { + for (const key of keys) { + const item = value[key]; + if (typeof item === "number" && Number.isFinite(item)) return item; + } + return undefined; +} + +function compact(value: Record): Record { + const result: Record = {}; + for (const [key, item] of Object.entries(value)) { + if (item !== undefined) result[key] = jsonValue(item); + } + return result; +} + +function nonNullJsonValue(value: unknown): NonNullable { + return jsonValue(value) ?? { value: null }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/src/worker/runtime-host.ts b/src/worker/runtime-host.ts index 91bd880..873797f 100644 --- a/src/worker/runtime-host.ts +++ b/src/worker/runtime-host.ts @@ -115,6 +115,7 @@ interface TurnRecord { index: number; abortController: AbortController; lastUsedAt: number; + toolCallKeys: Set; turn?: AcpRuntimeTurn; result?: AcpRuntimeTurnResult; task?: Promise; @@ -196,6 +197,7 @@ export class RuntimeHost { readonly #turns = new Map(); readonly #turnByRequest = new Map(); readonly #turnByBackendSession = new Map(); + readonly #turnByToolCall = new Map(); readonly #sessionByBackend = new Map< string, { serverId: string; sessionKey: string } @@ -332,6 +334,7 @@ export class RuntimeHost { index: 0, abortController: new AbortController(), lastUsedAt: this.#now(), + toolCallKeys: new Set(), }; this.#turns.set(params.turnId, record); this.#turnByRequest.set(requestKey, params.turnId); @@ -511,6 +514,10 @@ export class RuntimeHost { if (this.#turnByRequest.get(record.requestKey) === turnId) { this.#turnByRequest.delete(record.requestKey); } + for (const key of record.toolCallKeys) { + if (this.#turnByToolCall.get(key) === turnId) + this.#turnByToolCall.delete(key); + } } } @@ -561,6 +568,7 @@ export class RuntimeHost { this.#reverseInteractions.clear(); this.#sessionByBackend.clear(); this.#turnByBackendSession.clear(); + this.#turnByToolCall.clear(); this.#turnByRequest.clear(); this.#turns.clear(); this.#runtimes.clear(); @@ -596,6 +604,11 @@ export class RuntimeHost { record.turn = turn; try { for await (const event of turn.events) { + if (event.type === "tool_call" && event.toolCallId !== undefined) { + const key = this.#toolCallKey(params.serverId, event.toolCallId); + this.#turnByToolCall.set(key, params.turnId); + record.toolCallKeys.add(key); + } this.#emit({ type: "turn.event", turnId: params.turnId, @@ -1235,7 +1248,18 @@ export class RuntimeHost { payload: unknown, ): { sessionKey?: string; turnId?: string } { const backendSessionId = findSessionId(payload); - if (backendSessionId === undefined) return {}; + if (backendSessionId === undefined) { + const toolCallId = findToolCallId(payload); + if (toolCallId === undefined) return {}; + const turnId = this.#turnByToolCall.get( + this.#toolCallKey(serverId, toolCallId), + ); + if (turnId === undefined) return {}; + const record = this.#turns.get(turnId); + return record === undefined + ? { turnId } + : { sessionKey: record.params.sessionKey, turnId }; + } const backendKey = this.#backendSessionKey(serverId, backendSessionId); const turnId = this.#turnByBackendSession.get(backendKey); if (turnId !== undefined) { @@ -1256,6 +1280,10 @@ export class RuntimeHost { return `${serverId}\u0000${backendSessionId}`; } + #toolCallKey(serverId: string, toolCallId: string): string { + return `${serverId}\u0000${toolCallId}`; + } + #requestKey(params: TurnStartParams): string { return `${params.serverId}\u0000${params.sessionKey}\u0000${params.requestId}`; } @@ -1382,6 +1410,28 @@ function findSessionId(value: unknown, depth = 0): string | undefined { return undefined; } +function findToolCallId(value: unknown, depth = 0): string | undefined { + if (!isRecord(value) || depth > 3) return undefined; + const direct = stringField(value, [ + "toolCallId", + "tool_call_id", + "callId", + "call_id", + ]); + if (direct !== undefined) return direct; + for (const key of [ + "params", + "request", + "notification", + "message", + "update", + ]) { + const nested = findToolCallId(value[key], depth + 1); + if (nested !== undefined) return nested; + } + return undefined; +} + function isStandardPermissionKind( kind: string, ): kind is Exclude { diff --git a/test/unit/provider.test.ts b/test/unit/provider.test.ts index 7fe4dda..2d1567c 100644 --- a/test/unit/provider.test.ts +++ b/test/unit/provider.test.ts @@ -491,7 +491,7 @@ describe("OpenCode Acpx language provider", () => { expect.objectContaining({ type: "tool-call", providerExecuted: true }), expect.objectContaining({ type: "tool-result", - result: { matches: 2 }, + result: '{\n "matches": 2\n}', }), ]), ); @@ -501,4 +501,116 @@ describe("OpenCode Acpx language provider", () => { outputTokens: { total: 5, text: 3, reasoning: 2 }, }); }); + + it("routes correlated vendor subagent notifications through the provider stream", async () => { + const { client, model, providerId } = setup("acp.cursor.subagent"); + client.onStart = (params, channel) => { + channel.push({ + type: "turn.event", + turnId: params.turnId, + index: 0, + event: { + type: "tool_call", + text: "Explore", + toolCallId: "task-1", + kind: "other", + rawInput: { + _toolName: "task", + prompt: "Inspect files", + description: "Explore", + subagentType: "explore", + }, + status: "in_progress", + }, + }); + client.emit({ + type: "extension.notification", + serverId: "cursor", + sessionKey: params.sessionKey, + turnId: params.turnId, + method: "cursor/task", + params: { + toolCallId: "task-1", + description: "Explore", + prompt: "Inspect files", + subagentType: "explore", + durationMs: 100, + }, + }); + channel.push({ + type: "turn.result", + turnId: params.turnId, + index: 1, + result: { status: "completed", stopReason: "end_turn" }, + }); + }; + + const parts = await readStream( + (await model.doStream(call(providerId))).stream, + ); + expect(parts.filter((part) => part.type === "tool-call")).toHaveLength(1); + expect(parts.find((part) => part.type === "tool-call")).toMatchObject({ + toolName: "task", + providerExecuted: true, + }); + expect(parts.find((part) => part.type === "tool-result")).toMatchObject({ + toolName: "task", + result: { durationMs: 100 }, + }); + }); + + it("acknowledges Cursor activity requests without exposing control-tool cards", async () => { + const { client, model, providerId } = setup("acp.cursor.activity"); + client.onStart = (params) => { + client.emit({ + type: "interaction.extension", + turnId: params.turnId, + interactionId: "cursor-task-1", + serverId: "cursor", + sessionKey: params.sessionKey, + expiresAt: Date.now() + 60_000, + method: "cursor/task", + params: { + toolCallId: "task-1", + description: "Explore", + prompt: "Inspect the repository", + subagentType: "explore", + durationMs: 42, + }, + }); + }; + client.respondExtension.mockImplementation(() => { + const channel = [...client.channels.values()][0]; + if (channel === undefined) throw new Error("missing channel"); + channel.push({ + type: "turn.result", + turnId: channel.turnId, + index: 0, + result: { status: "completed" }, + }); + return Promise.resolve(undefined); + }); + + const parts = await readStream( + (await model.doStream(call(providerId))).stream, + ); + + expect(client.respondExtension).toHaveBeenCalledWith({ + interactionId: "cursor-task-1", + result: {}, + }); + expect(parts).toContainEqual( + expect.objectContaining({ type: "tool-call", toolName: "task" }), + ); + expect(parts).toContainEqual( + expect.objectContaining({ type: "tool-result", toolName: "task" }), + ); + expect( + parts.some( + (part) => + part.type === "tool-call" && + part.toolName === "opencode_acp_interaction", + ), + ).toBe(false); + }); }); diff --git a/test/unit/server.test.ts b/test/unit/server.test.ts index 325695f..3c99838 100644 --- a/test/unit/server.test.ts +++ b/test/unit/server.test.ts @@ -20,7 +20,13 @@ function fakeWorker() { catalogue: vi.fn(async ({ serverId }: { serverId: string }) => ({ serverId, cwd: TEST_DIRECTORY, - models: [{ id: "composer", name: "Composer" }], + models: [ + { id: "composer", name: "Composer" }, + { + id: "grok-4.6[effort=high,fast=true]", + name: "Grok 4.6", + }, + ], configOptions: [], availableCommands: [{ name: "review", description: "Review the change" }], runtimeCapabilities: { controls: [] }, @@ -94,6 +100,13 @@ describe("server plugin", () => { const hooks = await plugin(pluginInput(), options()); const config: Config & { skills?: { paths?: string[] } } = { enabled_providers: ["anthropic"], + provider: { + "acp.cursor": { + whitelist: ["grok-4.6"], + blacklist: ["default"], + options: { configuredByUser: true }, + }, + }, command: { "acp-cursor": { template: "preserve me" }, }, @@ -110,7 +123,13 @@ describe("server plugin", () => { expect(config.provider?.["acp.cursor"]).toMatchObject({ name: "Cursor Agent through ACP", npm: "file:///plugin/provider.js", - options: { pluginInstanceId: "instance-1", serverId: "cursor" }, + whitelist: ["grok-4.6[effort=high,fast=true]"], + blacklist: ["default"], + options: { + configuredByUser: true, + pluginInstanceId: "instance-1", + serverId: "cursor", + }, models: { default: { name: "Cursor Agent default", tool_call: true }, composer: { name: "Composer" }, diff --git a/test/unit/translate-stream.test.ts b/test/unit/translate-stream.test.ts index 72ff113..5de4269 100644 --- a/test/unit/translate-stream.test.ts +++ b/test/unit/translate-stream.test.ts @@ -67,13 +67,15 @@ describe("ACP stream translation", () => { expect(call).toMatchObject({ toolCallId: "turn-1-tool-remote-1", - toolName: "acp_read", + toolName: "read", providerExecuted: true, dynamic: true, }); + if (call?.type !== "tool-call") throw new Error("missing tool call"); + expect(JSON.parse(call.input)).toEqual({ filePath: "README.md" }); expect(result).toMatchObject({ toolCallId: "turn-1-tool-remote-1", - result: { text: "hello" }, + result: { loaded: ["README.md"] }, }); }); @@ -134,6 +136,189 @@ describe("ACP stream translation", () => { }); }); + it("projects Cursor task notifications as native task cards without duplicating a standard call", () => { + const translator = new AcpStreamTranslator("turn-1"); + const initial = translator.event( + { + type: "tool_call", + text: "Explore", + toolCallId: "task-1", + kind: "other", + rawInput: { + _toolName: "task", + prompt: "Inspect files", + description: "Explore", + subagentType: "explore", + }, + status: "in_progress", + }, + 0, + ); + const completed = translator.extensionNotification({ + type: "extension.notification", + serverId: "cursor", + sessionKey: "session-1", + turnId: "turn-1", + method: "cursor/task", + params: { + toolCallId: "task-1", + description: "Explore", + prompt: "Inspect files", + subagentType: "explore", + durationMs: 100, + }, + }); + + expect(initial.filter((part) => part.type === "tool-call")).toHaveLength(1); + expect(initial.find((part) => part.type === "tool-call")).toMatchObject({ + toolName: "task", + }); + expect(completed.filter((part) => part.type === "tool-call")).toHaveLength( + 0, + ); + expect(completed.find((part) => part.type === "tool-result")).toMatchObject( + { + toolName: "task", + result: { durationMs: 100 }, + }, + ); + }); + + it("enriches a completed Cursor task with request metadata before rendering it", () => { + const translator = new AcpStreamTranslator("turn-1"); + const generic = translator.event( + { + type: "tool_call", + text: "Task: Subagent task", + title: "Task: Subagent task", + toolCallId: "task-1", + kind: "other", + rawInput: { _toolName: "task" }, + status: "completed", + }, + 0, + ); + const enriched = translator.extensionNotification({ + type: "extension.notification", + serverId: "cursor", + sessionKey: "session-1", + turnId: "turn-1", + method: "cursor/task", + params: { + toolCallId: "task-1", + description: "Explore ACP runtime", + prompt: "Inspect the repository", + subagentType: "explore", + durationMs: 100, + }, + }); + + expect(generic.some((part) => part.type === "tool-call")).toBe(false); + expect(enriched.find((part) => part.type === "tool-call")).toMatchObject({ + toolName: "task", + input: JSON.stringify({ + prompt: "Inspect the repository", + description: "Explore ACP runtime", + subagent_type: "explore", + }), + }); + expect(enriched.find((part) => part.type === "tool-result")).toMatchObject({ + toolName: "task", + result: { durationMs: 100 }, + }); + }); + + it("flushes a deferred task safely when no vendor lifecycle arrives", () => { + const translator = new AcpStreamTranslator("turn-1"); + const deferred = translator.event( + { + type: "tool_call", + text: "Task: Subagent task", + toolCallId: "task-1", + kind: "other", + rawInput: { _toolName: "task" }, + status: "completed", + }, + 0, + ); + const terminal = translator.terminal({ status: "completed" }); + + expect(deferred).toEqual([]); + expect(terminal.find((part) => part.type === "tool-call")).toMatchObject({ + toolName: "task", + }); + expect(terminal.find((part) => part.type === "tool-result")).toMatchObject({ + toolName: "task", + }); + }); + + it("does not turn deferred in-progress task activity into a false result", () => { + const translator = new AcpStreamTranslator("turn-1"); + translator.event( + { + type: "tool_call", + text: "Task: Subagent task (pending)", + toolCallId: "task-1", + kind: "other", + rawInput: { _toolName: "task" }, + status: "pending", + }, + 0, + ); + const nextText = translator.event( + { type: "text_delta", text: "Continuing", stream: "output" }, + 1, + ); + + expect(nextText.find((part) => part.type === "tool-call")).toMatchObject({ + toolName: "task", + }); + expect(nextText.some((part) => part.type === "tool-result")).toBe(false); + }); + + it("keeps a Grok subagent task running from spawn until finish", () => { + const translator = new AcpStreamTranslator("turn-1"); + const spawn = translator.extensionNotification({ + type: "extension.notification", + serverId: "grok-build", + sessionKey: "session-1", + turnId: "turn-1", + method: "x.ai/session_notification", + params: { + sessionId: "parent", + update: { + sessionUpdate: "subagent_spawned", + subagent_id: "sub-1", + description: "Research", + subagent_type: "explore", + }, + }, + }); + const finish = translator.extensionNotification({ + type: "extension.notification", + serverId: "grok-build", + sessionKey: "session-1", + turnId: "turn-1", + method: "x.ai/session_notification", + params: { + sessionId: "parent", + update: { + sessionUpdate: "subagent_finished", + subagent_id: "sub-1", + status: "completed", + }, + }, + }); + + expect(spawn.find((part) => part.type === "tool-call")).toMatchObject({ + toolName: "task", + }); + expect(spawn.some((part) => part.type === "tool-result")).toBe(false); + expect(finish.find((part) => part.type === "tool-result")).toMatchObject({ + toolName: "task", + }); + }); + it("projects Cursor questions onto the built-in question tool", () => { const translator = new AcpStreamTranslator("turn-1"); const projection = translator.interaction({ diff --git a/test/unit/translate-tools.test.ts b/test/unit/translate-tools.test.ts new file mode 100644 index 0000000..e627f1e --- /dev/null +++ b/test/unit/translate-tools.test.ts @@ -0,0 +1,260 @@ +import type { AcpRuntimeEvent } from "acpx/runtime"; +import { describe, expect, it } from "vitest"; + +import { + projectSubagentNotification, + projectToolCall, + projectToolResult, +} from "../../src/translate/tools.js"; + +type ToolEvent = Extract; + +function tool(overrides: Partial): ToolEvent { + return { type: "tool_call", text: "Tool activity", ...overrides }; +} + +describe("native OpenCode tool projection", () => { + it("projects standard ACP execution as a native shell card with readable output", () => { + const start = tool({ + kind: "execute", + title: "Run tests", + rawInput: { command: "pnpm test", description: "Run the test suite" }, + }); + const projection = projectToolCall(start); + expect(projection).toEqual({ + name: "bash", + presentation: "bash", + input: { command: "pnpm test", description: "Run the test suite" }, + }); + expect( + projectToolResult(projection, { + ...start, + status: "completed", + rawOutput: { stdout: "ok", stderr: "warning", exitCode: 0 }, + }).result, + ).toBe("ok\nwarning"); + }); + + it("projects standard read, grep, glob, list, edit, write and web tools", () => { + expect( + projectToolCall( + tool({ + kind: "read", + rawInput: { file_path: "src/index.ts", offset: 4 }, + }), + ), + ).toMatchObject({ + name: "read", + input: { filePath: "src/index.ts", offset: 4 }, + }); + expect( + projectToolCall(tool({ kind: "read", title: "Read File", rawInput: {} })) + .input, + ).not.toHaveProperty("filePath"); + expect( + projectToolCall( + tool({ kind: "search", rawInput: { pattern: "TODO", path: "src" } }), + ), + ).toMatchObject({ name: "grep", input: { pattern: "TODO", path: "src" } }); + expect( + projectToolCall(tool({ kind: "search", title: "Find", rawInput: {} })), + ).toMatchObject({ name: "glob" }); + expect( + projectToolCall( + tool({ + kind: "search", + rawInput: { globPattern: "**/*.ts", path: "src" }, + }), + ), + ).toMatchObject({ + name: "glob", + input: { pattern: "**/*.ts", path: "src" }, + }); + expect( + projectToolCall( + tool({ + kind: "read", + title: "List files in src", + rawInput: { path: "src" }, + }), + ), + ).toMatchObject({ name: "list", input: { path: "src" } }); + expect( + projectToolCall( + tool({ + kind: "edit", + rawInput: { + file_path: "src/index.ts", + old_string: "old", + new_string: "new", + }, + }), + ), + ).toMatchObject({ + name: "edit", + input: { filePath: "src/index.ts", oldString: "old", newString: "new" }, + }); + expect( + projectToolCall( + tool({ + kind: "edit", + title: "Write notes.md", + rawInput: { path: "notes.md", content: "hi" }, + }), + ), + ).toMatchObject({ + name: "write", + input: { filePath: "notes.md", content: "hi" }, + }); + expect( + projectToolCall( + tool({ kind: "fetch", rawInput: { url: "https://example.com" } }), + ), + ).toMatchObject({ + name: "webfetch", + input: { url: "https://example.com" }, + }); + expect( + projectToolCall( + tool({ kind: "fetch", rawInput: { query: "ACP protocol" } }), + ), + ).toMatchObject({ name: "websearch", input: { query: "ACP protocol" } }); + }); + + it("builds OpenCode filediff metadata from ACP diff content", () => { + const event = tool({ + kind: "edit", + rawInput: { path: "src/a.ts", old_string: "a", new_string: "b" }, + content: [{ type: "diff", path: "src/a.ts", oldText: "a", newText: "b" }], + }); + const result = projectToolResult(projectToolCall(event), event); + expect(result.result).toEqual({ + filediff: { file: "src/a.ts", before: "a", after: "b" }, + }); + }); + + it("recognises Cursor, Claude, Codex and generic ACP subagent tool shapes", () => { + const cases: ToolEvent[] = [ + tool({ + kind: "other", + rawInput: { + _toolName: "task", + prompt: "Inspect the project", + description: "Explore", + subagentType: "explore", + }, + }), + tool({ + kind: "think", + rawInput: { + prompt: "Review this change", + description: "Reviewer", + subagent_type: "general-purpose", + }, + }), + tool({ + kind: "other", + title: "Start subagent explorer", + rawInput: { + agentThreadId: "thread-1", + agentPath: "agents/explorer", + activityKind: "started", + }, + }), + tool({ + kind: "other", + title: "Collaborate", + rawInput: { + prompt: "Investigate in parallel", + receiverThreadIds: ["thread-2"], + agentsStates: {}, + }, + }), + ]; + expect(cases.map((event) => projectToolCall(event).name)).toEqual([ + "task", + "task", + "task", + "task", + ]); + const cursor = cases[0]; + const codex = cases[2]; + if (cursor === undefined || codex === undefined) + throw new Error("missing subagent fixture"); + expect(projectToolCall(cursor).input).toMatchObject({ + description: "Explore", + subagent_type: "explore", + }); + expect(projectToolCall(codex).input).toMatchObject({ + subagent_type: "explorer", + }); + }); + + it("keeps unsupported standard kinds provider-executed under a safe ACP name", () => { + expect( + projectToolCall(tool({ kind: "delete", rawInput: { path: "old.txt" } })), + ).toMatchObject({ name: "acp_delete", presentation: "generic" }); + }); +}); + +describe("vendor subagent lifecycle projection", () => { + it("uses Cursor task completion metadata as a native task fallback", () => { + expect( + projectSubagentNotification("cursor/task", { + toolCallId: "task-1", + description: "Explore", + prompt: "Inspect files", + subagentType: "explore", + model: "gpt-5", + agentId: "cursor-agent-1", + durationMs: 1200, + }), + ).toMatchObject({ + action: "finish", + toolCallId: "task-1", + input: { description: "Explore", subagent_type: "explore" }, + result: { model: "gpt-5", agentId: "cursor-agent-1", durationMs: 1200 }, + }); + }); + + it("projects Grok spawn, progress and finish notifications", () => { + const spawn = projectSubagentNotification("x.ai/session_notification", { + sessionId: "parent", + update: { + sessionUpdate: "subagent_spawned", + subagent_id: "sub-1", + description: "Research", + subagent_type: "explore", + }, + }); + const progress = projectSubagentNotification("x.ai/session_notification", { + sessionId: "parent", + update: { sessionUpdate: "subagent_progress", subagent_id: "sub-1" }, + }); + const finish = projectSubagentNotification("x.ai/session_notification", { + sessionId: "parent", + update: { + sessionUpdate: "subagent_finished", + subagent_id: "sub-1", + child_session_id: "child-1", + status: "completed", + output: "Done", + tool_calls: 3, + turns: 2, + }, + }); + expect(spawn).toMatchObject({ action: "start", toolCallId: "sub-1" }); + expect(progress).toMatchObject({ action: "progress", toolCallId: "sub-1" }); + expect(finish).toMatchObject({ + action: "finish", + toolCallId: "sub-1", + result: { + status: "completed", + output: "Done", + toolCalls: 3, + turns: 2, + acpChildSessionId: "child-1", + }, + }); + }); +}); diff --git a/test/unit/worker-runtime-host.test.ts b/test/unit/worker-runtime-host.test.ts index 1348cac..2391d0e 100644 --- a/test/unit/worker-runtime-host.test.ts +++ b/test/unit/worker-runtime-host.test.ts @@ -216,4 +216,78 @@ describe("RuntimeHost", () => { await expect(extension).resolves.toEqual({ accepted: true }); await host.dispose(); }); + + it("correlates Cursor task notifications that identify only a tool call", async () => { + const fake = fakeRuntime(); + const events: Record[] = []; + let factoryInput: RuntimeFactoryInput | undefined; + let finishTurn: (() => void) | undefined; + const finished = new Promise((resolve) => { + finishTurn = resolve; + }); + fake.runtime.startTurn = vi.fn(() => ({ + requestId: "request-1", + events: { + async *[Symbol.asyncIterator]() { + yield { + type: "tool_call" as const, + text: "Explore", + toolCallId: "cursor-task-1", + kind: "other" as const, + status: "in_progress", + }; + await finished; + }, + }, + result: finished.then(() => ({ + status: "completed" as const, + stopReason: "end_turn", + })), + cancel: () => Promise.resolve(), + closeStream: () => Promise.resolve(), + })); + const host = new RuntimeHost({ + emit: (event) => events.push(event as unknown as Record), + runtimeFactory: (input) => { + factoryInput = input; + return fake.runtime; + }, + }); + await host.configure(configuration()); + await host.startTurn({ + turnId: "turn-1", + serverId: "cursor", + sessionKey: "session-1", + cwd: process.cwd(), + requestId: "request-1", + text: "Explore", + }); + await vi.waitFor(() => + expect(events).toContainEqual( + expect.objectContaining({ type: "turn.event", turnId: "turn-1" }), + ), + ); + + await factoryInput?.compatCallbacks.onExtensionNotification?.( + "cursor/task", + { toolCallId: "cursor-task-1", description: "Explore" }, + ); + + expect(events).toContainEqual( + expect.objectContaining({ + type: "extension.notification", + serverId: "cursor", + sessionKey: "session-1", + turnId: "turn-1", + method: "cursor/task", + }), + ); + finishTurn?.(); + await vi.waitFor(() => + expect(events).toContainEqual( + expect.objectContaining({ type: "turn.result", turnId: "turn-1" }), + ), + ); + await host.dispose(); + }); });