Official

acp

ACP agents from the ACP registry (Gemini, Cursor, Droid, Kilo, pi, ...), Oh My Pi, and your own entries (custom.json in the plugin's data folder). Agents are discovered at runtime.

The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/acp@0.2.4

Permissions in 0.2.4

Take care. This plugin asks for permissions that can do anything your account can. The app asks you to hold Enable for two seconds or to type the plugin's name before it turns on.
  • Run any command process.anyDangerousStarts any program or shell command. This is as strong as your own account.Start the ACP agents, which the registry launches by path or through package runners such as npx and uvx, and run the terminal commands an agent asks for
  • Provide agents agents.provideMediumAdds agents to the app.Provide the agents of the ACP registry, and serve plugin tools to them through the host's loopback MCP server
  • Network access netMediumConnects to the listed hosts.Download the ACP registry and the agents' marks once a dayHosts: cdn.agentclientprotocol.com
  • Read files fs.readMediumReads files in the listed places.Read the files an agent asks for (ACP fs/read_text_file), only inside the chat's workspace, and your own agents from custom.json in this plugin's data folderPlaces: the open workspaceits own data folder
  • Write files fs.writeMediumCreates, changes and deletes files in the listed places.Write the files an agent asks to write (ACP fs/write_text_file), only inside the chat's workspace, and move the custom agents of the old ACP plugin into custom.json oncePlaces: the open workspaceits own data folder
  • Environment variables envMediumReads the listed environment variables.Sign Grok in with your xAI API key when you set one, and tell which Windows build of an agent to runVariables: XAI_API_KEYPROCESSOR_ARCHITECTURE

Files

v2.ts18.9 KB
// ACP v2 2.0.0-alpha.16 owns its wire shapes and ID-addressed projection here.
import * as z from "zod";
import type { AgentEventKind, Plan, ToolCall, ToolContent, TranscriptItem } from "divergence/protocol";
import { Entities, array, notice, patch, record, textOf } from "./entities.ts";
import type { RecordValue } from "./entities.ts";
import * as map from "./map.ts";
import * as wire from "./wire.ts";
import { embeddedApps } from "./apps.ts";
import type { Capabilities } from "./types.ts";

const object = z.looseObject({});
const config = z.looseObject({ configId: z.string(), name: z.string(), type: z.string() });
const command = z.looseObject({ type: z.string(), name: z.string(), description: z.string() });
export const setup = z.looseObject({
  sessionId: z.string().optional(),
  configOptions: z.array(config).optional(),
  availableCommands: z.array(command).optional(),
});
export const initialize = z.looseObject({
  protocolVersion: z.literal(2),
  info: z.looseObject({ name: z.string(), version: z.string(), title: z.string().nullish() }),
  capabilities: object.optional(),
  authMethods: z.array(z.looseObject({ methodId: z.string(), type: z.string(), name: z.string() })).optional(),
});

export function capabilities(value: unknown, authenticated: boolean): Capabilities {
  const caps = record(value);
  const session = record(caps.session);
  const prompt = record(session.prompt);
  const mcp = record(session.mcp);
  return {
    loadSession: caps.session != null,
    promptCapabilities: {
      image: prompt.image != null,
      audio: prompt.audio != null,
      embeddedContext: prompt.embeddedContext != null,
    },
    mcpCapabilities: { http: mcp.http != null, stdio: mcp.stdio != null },
    auth: { ...record(caps.auth), logout: authenticated ? {} : undefined },
    sessionCapabilities: caps.session != null ? { ...session, list: {}, resume: {}, close: {} } : {},
  };
}

export function configs(value: unknown): RecordValue[] {
  return array(value)
    .map(record)
    .map((option) => ({
      ...option,
      id: option.configId,
      options: array(option.options).map((value) => {
        const group = record(value);
        return typeof group.groupId === "string" ? { ...group, group: group.groupId } : group;
      }),
    }));
}

export function commands(value: unknown) {
  return map.commands({
    availableCommands: array(value)
      .map(record)
      .filter((entry) => entry.type === "command")
      .map((entry) => ({ ...entry, input: record(entry.input).type === "text" ? entry.input : null })),
  });
}

export function sessionResponse(value: unknown): wire.Response<"session/new"> {
  const response = setup.parse(value);
  return {
    ...response,
    configOptions: configs(response.configOptions),
    availableCommands: response.availableCommands ?? [],
  };
}

export function requestShape(method: keyof typeof wire.responses, params: unknown) {
  const body = record(params);
  switch (method) {
    case "authenticate":
      return { method: "auth/login", params: body };
    case "logout":
      return { method: "auth/logout", params: body };
    case "session/load":
      return { method: "session/resume", params: { ...body, replayFrom: { type: "start" } } };
    case "session/set_config_option":
      return { method, params: { ...body, type: typeof body.value === "boolean" ? "boolean" : "id" } };
    case "session/set_mode":
    case "session/set_model":
      throw new Error(`${method} is not available in ACP v2.`);
    default:
      return { method, params: body };
  }
}

export function responseSchema<M extends keyof typeof wire.responses>(method: M): z.ZodType<wire.Response<M>> {
  switch (method) {
    case "session/new":
    case "session/load":
    case "session/resume":
    case "session/fork":
    case "session/options":
    case "session/set_config_option":
      return setup.transform(sessionResponse) as unknown as z.ZodType<wire.Response<M>>;
    case "session/prompt":
      return z.looseObject({ messageId: z.string() }) as unknown as z.ZodType<wire.Response<M>>;
    default:
      return wire.responses[method];
  }
}

export function toolContent(value: unknown, terminals: ReadonlyMap<unknown, map.TerminalView>): ToolContent[] {
  return array(value).flatMap<ToolContent>((value) => {
    const item = record(value);
    if (item.type !== "diff") return map.toolContent([item], terminals);
    const changes = array(item.changes).map(record);
    const nativePatch = record(item.patch);
    const text =
      nativePatch.format === "git_patch" && typeof nativePatch.text === "string" ? nativePatch.text : undefined;
    return changes
      .filter((change) => typeof change.path === "string")
      .map((change) => ({
        type: "diff" as const,
        path: String(change.path),
        ...(text !== undefined ? { diff: text } : {}),
      }));
  });
}

function planEntries(plan: RecordValue): NonNullable<Plan["entries"]> {
  if (plan.type !== "items") return [];
  return array(plan.entries)
    .map(record)
    .filter((entry) => typeof entry.content === "string")
    .map((entry) => ({
      content: String(entry.content),
      status:
        entry.status === "pending" ||
        entry.status === "in_progress" ||
        entry.status === "completed" ||
        entry.status === "cancelled"
          ? entry.status
          : undefined,
      priority:
        entry.priority === "high" || entry.priority === "medium" || entry.priority === "low"
          ? entry.priority
          : undefined,
    }));
}

export class Session {
  readonly mcpApps: boolean;
  constructor(mcpApps = false) {
    this.mcpApps = mcpApps;
  }
  readonly entities = new Entities(2);
  readonly items = new Map<string, TranscriptItem>();
  readonly tools = new Map<string, RecordValue>();
  readonly messages = new Map<string, RecordValue>();
  readonly terminals = new Map<string, RecordValue>();
  readonly terminalViews = new Map<string, map.TerminalView>();
  readonly plans = new Map<string, RecordValue>();
  state: RecordValue = { state: "idle" };
  active = false;

  push(update: wire.Message): AgentEventKind[] {
    const persistent = this.entities.push(update);
    if (persistent !== null) {
      for (const [id, item] of this.entities.items) this.items.set(id, item);
      return persistent;
    }
    switch (update.sessionUpdate) {
      case "user_message":
      case "user_message_chunk":
      case "agent_message":
      case "agent_message_chunk":
      case "agent_thought":
      case "agent_thought_chunk":
        return this.message(update);
      case "tool_call_update":
      case "tool_call_content_chunk":
        return this.tool(update);
      case "terminal_update":
      case "terminal_output_chunk":
        return this.terminal(update);
      case "plan_update":
        return this.plan(update);
      case "state_update":
        this.state = update;
        if (update.state === "running" || update.state === "requires_action") this.active = true;
        else if (update.state === "idle") this.active = false;
        return [];
      case "notice":
        return [notice(update)];
      default:
        return [];
    }
  }

  private message(update: wire.Message): AgentEventKind[] {
    if (typeof update.messageId !== "string") return [];
    const type = String(update.sessionUpdate).replace(/_chunk$/, "");
    const id = `${type}:${update.messageId}`;
    const state = this.messages.get(id) ?? {};
    const chunk = update.sessionUpdate?.endsWith("_chunk");
    if (chunk) state.content = [...array(state.content), update.content];
    else patch(state, update);
    this.messages.set(id, state);
    if (type === "user_message") {
      this.items.set(id, { id: update.messageId, role: "user", blocks: array(state.content).map(map.userBlock) });
      return [];
    }
    const text = textOf(state.content);
    const thought = type === "agent_thought";
    this.items.set(id, { id, role: thought ? "reasoning" : "assistant", text });
    return [
      {
        event: thought ? "reasoning_delta" : "text_delta",
        itemId: id,
        text: chunk ? map.contentText(update.content) : text,
        mode: chunk ? "append" : "replace",
      },
    ];
  }

  private tool(update: wire.Message): AgentEventKind[] {
    if (typeof update.toolCallId !== "string") return [];
    const id = update.toolCallId;
    const first = !this.tools.has(id);
    const state = this.tools.get(id) ?? {};
    if (update.sessionUpdate === "tool_call_content_chunk") state.content = [...array(state.content), update.content];
    else patch(state, update);
    this.tools.set(id, state);
    const call: ToolCall = {
      id,
      name: typeof state.name === "string" ? state.name : "",
      title: typeof state.title === "string" ? state.title : "",
      kind: map.toolKind(state.kind),
      status:
        state.status === "cancelled"
          ? "cancelled"
          : state.status === "paused"
            ? "pending"
            : state.status == null || state.status === "pending"
              ? "pending"
              : state.status === "completed" || state.status === "failed"
                ? state.status
                : "running",
      input: state.rawInput ?? null,
      output: state.rawOutput ?? null,
      content: this.mcpApps
        ? embeddedApps(state, toolContent(state.content, this.terminalViews))
        : toolContent(state.content, this.terminalViews),
      locations: map.locations(state.locations),
    };
    this.items.set(`tool:${id}`, { id, role: "tool", call });
    for (const item of array(state.content)) {
      const terminalId = record(item).terminalId;
      if (typeof terminalId === "string") {
        const terminal = this.items.get(`terminal:${terminalId}`);
        if (terminal?.role === "task") terminal.task.toolCallId = id;
      }
    }
    return [first ? { event: "tool_call_started", ...call } : { event: "tool_call_updated", ...call }];
  }

  private terminal(update: wire.Message): AgentEventKind[] {
    if (typeof update.terminalId !== "string") return [];
    const id = update.terminalId;
    const state: RecordValue = this.terminals.get(id) ?? { bytes: new Uint8Array(0) };
    if (update.sessionUpdate === "terminal_output_chunk") this.appendBytes(state, update.data, false);
    else {
      const { output, ...rest } = update;
      patch(state, rest);
      if (output === null) state.bytes = new Uint8Array(0);
      else if (output !== undefined) this.appendBytes(state, record(output).data, true);
    }
    this.terminals.set(id, state);
    const exit = record(state.exitStatus);
    const output = new TextDecoder().decode(state.bytes as Uint8Array, { stream: state.exitStatus == null });
    this.terminalViews.set(id, {
      command: typeof state.command === "string" ? state.command : "",
      cwd: typeof state.cwd === "string" ? state.cwd : null,
      output,
      exitCode: typeof exit.exitCode === "number" ? exit.exitCode : null,
    });
    const task = {
      id: `terminal:${id}`,
      kind: "terminal" as const,
      title: typeof state.command === "string" ? state.command : id,
      command: typeof state.command === "string" ? state.command : undefined,
      output,
      status:
        state.exitStatus == null
          ? ("running" as const)
          : exit.signal != null
            ? ("cancelled" as const)
            : typeof exit.exitCode === "number" && exit.exitCode !== 0
              ? ("failed" as const)
              : ("completed" as const),
    };
    this.items.set(`terminal:${id}`, { id: `terminal:${id}`, role: "task", task });
    const events: AgentEventKind[] = [{ event: "task", ...task }];
    for (const [toolCallId, call] of this.tools)
      if (array(call.content).some((item) => record(item).terminalId === id))
        events.push(...this.tool({ sessionUpdate: "tool_call_update", toolCallId }));
    return events;
  }

  private appendBytes(state: RecordValue, data: unknown, replace: boolean): void {
    if (typeof data !== "string" || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data))
      return;
    const bytes = Uint8Array.from(atob(data), (character) => character.charCodeAt(0));
    const previous = replace ? new Uint8Array(0) : (state.bytes as Uint8Array);
    const output = new Uint8Array(previous.length + bytes.length);
    output.set(previous);
    output.set(bytes, previous.length);
    let start = Math.max(0, output.length - 262144);
    while (start < output.length && ((output[start] ?? 0) & 0xc0) === 0x80) start++;
    state.bytes = output.subarray(start);
  }

  private plan(update: wire.Message): AgentEventKind[] {
    const plan = record(update.plan);
    if (typeof plan.planId !== "string") return [];
    const mapped = { entries: planEntries(plan) };
    this.plans.set(plan.planId, plan);
    this.items.set(`plan:${plan.planId}`, { id: `plan:${plan.planId}`, role: "plan", plan: mapped });
    return [{ event: "plan", entries: [...this.plans.values()].flatMap(planEntries) }];
  }

  finish(): TranscriptItem[] {
    return [...this.items.values()];
  }
}

import type { AcpAgent } from "./agent.ts";
import { newId } from "../sdk/agent.ts";

// The v2 lifecycle is independent of the prompt acknowledgement and replay snapshots.
export function applyUpdate(this: AcpAgent, session: string, live: string, update: wire.Message): void {
  let projection = this.projections.get(live);
  if (!projection) this.projections.set(live, (projection = new Session(this.hostFeatures.includes("mcpApps"))));
  const wasActive = projection.active;
  const events = projection.push(update);
  const child = this.subagents.children.has(live);
  switch (update.sessionUpdate) {
    case "config_option_update":
      this.stateOf(session).config = configs(update.configOptions);
      this.publishOptions(session);
      return;
    case "available_commands_update": {
      const available = commands(update.availableCommands);
      this.stateOf(session).commands = available;
      this.emitFor(session, { event: "commands", commands: available });
      return;
    }
    case "session_info_update":
      if (typeof update.title === "string") this.emitFor(session, { event: "session_info", title: update.title });
      return;
    case "usage_update": {
      const old = this.stateOf(session).context;
      const usage = {
        ...map.contextUsage(update),
        ...(update.cost === undefined && typeof old?.costUsd === "number" ? { costUsd: old.costUsd } : {}),
      };
      this.stateOf(session).context = usage;
      this.emitFor(session, { event: "usage", ...usage });
      return;
    }
    case "state_update": {
      if (child) return;
      const state = this.stateOf(session);
      if ((update.state === "running" || update.state === "requires_action") && !state.run) {
        state.run = newId("acp-run");
        this.emitFor(session, { event: "run_started" });
      }
      // Initial/resume idle snapshots and repeated idle states are not completions.
      if (update.state === "idle" && wasActive) {
        const completed = this.prompts.get(session);
        if (completed) completed(wire.responses["session/prompt"].parse(update));
        else
          this.finishRun(
            session,
            update.stopReason === "error"
              ? {
                  status: "failed",
                  message:
                    typeof record(update.error).message === "string"
                      ? String(record(update.error).message)
                      : "The agent failed while answering.",
                }
              : map.stopReason(update.stopReason),
          );
      }
      return;
    }
  }
  for (const event of events) this.emitFor(session, event);
}

// Permission copy is separate from tool state in v2; command subjects are display-only.
export function permission(request: wire.Message): {
  request: wire.Message;
  subject: RecordValue;
  title: string | null;
  warning: string | null;
} {
  const subject = record(request.subject);
  return {
    request: { ...request, toolCall: subject.type === "tool_call" ? record(subject.toolCall) : null },
    subject,
    title: typeof request.title === "string" ? request.title : null,
    warning:
      [request.description, subject.type === "command" ? `${String(subject.command)}\n${String(subject.cwd)}` : null]
        .filter((part) => typeof part === "string")
        .join("\n\n") || null,
  };
}

const contentBlock = z.looseObject({ type: z.string() });
const idMessage = wire.message.extend({ messageId: z.string() });
const chunkMessage = idMessage.extend({ content: contentBlock });
const updates: Record<string, z.ZodType<wire.Message>> = {
  user_message: idMessage,
  agent_message: idMessage,
  agent_thought: idMessage,
  user_message_chunk: chunkMessage,
  agent_message_chunk: chunkMessage,
  agent_thought_chunk: chunkMessage,
  session_message: idMessage,
  session_message_chunk: chunkMessage,
  tool_call_update: wire.message.extend({ toolCallId: z.string() }),
  tool_call_content_chunk: wire.message.extend({ toolCallId: z.string(), content: contentBlock }),
  terminal_update: wire.message.extend({ terminalId: z.string() }),
  terminal_output_chunk: wire.message.extend({ terminalId: z.string(), data: z.string() }),
  compaction_update: wire.message.extend({ compactionId: z.string(), status: z.string() }),
  compaction_summary_chunk: wire.message.extend({ compactionId: z.string(), content: contentBlock }),
  subagent_update: wire.message.extend({ sessionId: z.string() }),
  state_update: wire.message.extend({ state: z.string() }),
  notice: wire.message.extend({ severity: z.string(), title: z.string() }),
  plan_update: wire.message.extend({ plan: z.looseObject({ type: z.string(), planId: z.string() }) }),
};
export function readUpdate(update: wire.Message): wire.Message | null {
  const parsed = (updates[String(update.sessionUpdate)] ?? wire.message).safeParse(update);
  if (parsed.success) return parsed.data;
  console.warn(`acp: ignored malformed v2 ${update.sessionUpdate} update: ${parsed.error.message}`);
  return null;
}

const permissionRequest = wire.message.extend({
  sessionId: z.string(),
  title: z.string(),
  options: z.array(object).min(1),
});
const elicitationRequest = wire.message
  .extend({ mode: z.string(), message: z.string(), requestId: z.union([z.string(), z.number().int()]).optional() })
  .refine(
    (value) => (typeof value.sessionId === "string") !== (value.requestId !== undefined),
    "An elicitation needs exactly one sessionId or requestId.",
  );
export function clientSchema(method: string): z.ZodType<wire.Message> {
  if (method === "session/request_permission") return permissionRequest;
  if (method === "elicitation/create") return elicitationRequest;
  return wire.message;
}

export function mcpServers(values: unknown[], caps: Capabilities): unknown[] {
  return values.map((value) => {
    const server = z.looseObject({ type: z.string().optional(), name: z.string() }).parse(value);
    const type = server.type ?? "stdio";
    if ((type !== "http" && type !== "stdio") || !caps.mcpCapabilities?.[type])
      throw new Error(`The agent does not advertise the ${type} MCP transport.`);
    return { ...server, type };
  });
}

Versions

VersionPublishedPlugin APISizePermissionsStatus
0.2.5latestNov 21, 2026>=5 <6134 KB6 permissionsListed
0.2.4Nov 16, 2026>=5 <6132.8 KB6 permissionsListed
0.2.3Nov 11, 2026>=5 <6108.9 KB6 permissionsListed
0.2.2Nov 9, 2026>=5 <6105.6 KB6 permissionsListed
0.2.1Oct 27, 2026>=2 <4105.3 KB6 permissionsListed

Reviews and comments

0 threads · 0 reviews

No comments yet.