Official

claude

Claude Code agent provider: runs the Claude Code CLI headless for each account.

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/claude@0.2.6

Permissions in 0.2.6

  • Provide agents agents.provideMediumAdds agents to the app.Provide the Claude Code agent and pass its tool calls to plugin tools
  • Run named programs processMediumStarts the listed programs.Run the Claude Code CLI (sessions, sign-in, `claude update`), and ask the npm installation that owns it about a newer versionPrograms: claudenpm
  • Read files fs.readMediumReads files in the listed places.Read Claude Code's sessions, settings and skills (in ~/.claude, other accounts' ~/.claude-* folders, the shared skills and the folder you choose in Settings), the project's .claude folder, the administrator's skill policy, and once, what the previous provider keptPlaces: ~/.claude/**~/.claude*/**~/.agents/skills/**the open workspaceits own data folder/Library/Application Support/ClaudeCode/managed-settings.json/etc/claude-code/managed-settings.json${settings.configDir}
  • Environment variables envMediumReads the listed environment variables.Find Claude Code's configuration directory, and the launch settings you set in CLAUDE_* variables (extra arguments, MCP servers, setting sources, appended system prompt, extra folders)Variables: HOMECLAUDE_CONFIG_DIRCLAUDE_EXTRA_ARGSCLAUDE_MCP_CONFIGCLAUDE_STRICT_MCP_CONFIGCLAUDE_SETTING_SOURCESCLAUDE_APPEND_SYSTEM_PROMPTCLAUDE_ADD_DIRS

Files

agent.ts34.5 KB
// The Claude Code provider: one `claude` process per session, run headless
// over its `stream-json` protocol (the Rust `agent.rs`). See NOTES.md for
// the protocol facts behind every choice here.
import * as Scope from "effect/Scope";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import * as Result from "effect/Result";
import * as Effect from "effect/Effect";
import * as Semaphore from "effect/Semaphore";
import { Fs } from "divergence/effect";
import type { EffectAgent, PluginServices } from "divergence/effect";
import type { AgentInfo, AgentEvent, Values } from "./types.ts";
import type { Files } from "./files.ts";
import type { Instance } from "./instances.ts";
import type { Catalog } from "./options.ts";
import type { SessionContext, Start, Additions, Prompt, Answer, Job } from "./session.ts";
import { ProviderError } from "./errors.ts";
import { runProcess } from "../sdk/effect.ts";
import {
  which,
  accountSummary,
  installedVersion,
  maintenance,
  messageOf,
  probeAccount,
  signedOutMessage,
  update,
} from "./account.ts";
import {
  chosenConfigDir,
  childEnv,
  configDirOf,
  continuationKey,
  launchFromEnv,
  loginEnv,
  workflowSettings,
} from "./config.ts";
import { apiFiles, join, readJson } from "./files.ts";
import type { Fingerprint } from "./fingerprint.ts";
import { recordReads, unchanged } from "./fingerprint.ts";
import {
  listSessions,
  readSessionFile,
  rewindTarget,
  rewindTargetAt,
  sessionFile,
  Tails,
  transcriptSession,
} from "./history.ts";
import type { ScanStore } from "./history.ts";
import { ICON } from "./icon.ts";
import { agentId, displayName } from "./instances.ts";
import { ULTRACODE } from "./options.ts";
import { sendersOf, sentAliases, streamedAliases } from "./records.ts";
import { Session, splitId, starts } from "./session.ts";
import { listSkills, skillRoots } from "./skills.ts";
import { SessionStore, storedScans } from "./state.ts";
import { ingressEchoes } from "../sdk/context.ts";
import type { ProcessReport } from "../sdk/agent.ts";
import { SessionWatch } from "../sdk/sessions.ts";
import { errorMessage } from "../sdk/errors.ts";
import type { AgentInitializeParams, HostFeature, McpCallToolParams, McpReadResourceParams } from "divergence/protocol";
import { callTool, loadApps, readResource, supportsApps } from "./mcp.ts";

interface SessionParams {
  sessionId: string;
  requireResume?: boolean;
  workspace?: string;
  options?: Values;
  tools?: Additions["tools"];
  instructions?: string;
}

export const FAMILY = "claude";
const DESCRIPTION = "Anthropic's coding agent, run headless over its stream-json protocol.";

/// Raised when the transcript reads a record differently, so a session read
/// before is read again once (images were left out before 2).
const HISTORY_FORMAT = 3;

/// A `read_session` version this plugin answered: the transcript path and
/// the fingerprint of the read (`fingerprint.ts`).
function parseVersion(version: string | undefined, apps: boolean): { path: string; fingerprint: Fingerprint } | undefined {
  if (!version) return undefined;
  try {
    const value: unknown = JSON.parse(version);
    if (typeof value !== "object" || value === null) return undefined;
    const { path, fingerprint, format, mcpApps } = value as {
      path?: unknown;
      fingerprint?: { probes?: unknown };
      format?: unknown;
      mcpApps?: unknown;
    };
    return format === HISTORY_FORMAT && (mcpApps === true) === apps && typeof path === "string" && Array.isArray(fingerprint?.probes)
      ? { path, fingerprint: fingerprint as Fingerprint }
      : undefined;
  } catch {
    return undefined;
  }
}

export class ClaudeAgent {
  instance: Instance;
  emit: (event: AgentEvent) => void;
  /// Sends a process report (`agent/process`) to the host's process pool.
  report: (report: ProcessReport) => void;
  files: Files;
  store: SessionStore;
  /// What listing read of each transcript (`listSessions`).
  scans: ScanStore;
  id: string;
  name: string;
  sessions: Map<string, Session>;
  catalog: Catalog | null;
  probing: Effect.Effect<Catalog, unknown, PluginServices> | null;
  usageWorkspace: string | null = null;
  /// What the last complete history read of each host session saw, and the
  /// full reads of each session under way, `unsure` when the host may not
  /// keep what they answer (`readSession`).
  seen = new Map<string, { path: string; fingerprint: Fingerprint }>();
  /// The records of the sessions' transcripts read most recently, so the
  /// next read takes only what the CLI appended (`readRecords`).
  tails = new Tails();
  reading = new Map<string, { running: number; unsure: boolean }>();
  /// One history read at a time: two long transcripts parsed at once hold
  /// both in memory together.
  readLock = Semaphore.makeUnsafe(1);
  env: Record<string, string>;
  /// Skill folders watched, so a skill installed or removed later shows in
  /// the app: the CLI has no event for it.
  watchedSkills = new Set<string>();
  /// Tells the host about sessions started in Claude Code itself.
  sessionWatch: SessionWatch;
  scope: Scope.Scope;
  jobs: Queue.Queue<Job>;
  hostFeatures = new Set<HostFeature>();
  catalogCapabilities: Set<string> | null = null;

  /// `api`: the plugin API. `instance`: the account. `emit`: sends an agent
  /// event and `report` a process report (both set once the agent is
  /// registered). `files` and `store` are the
  /// plugin's file reads and session state, replaceable in tests.
  constructor({
    instance,
    scope,
    jobs,
    emit = () => {},
    report = () => {},
    files = null,
    store = null,
    scans = null,
  }: {
    instance: Instance;
    scope: Scope.Scope;
    jobs: Queue.Queue<Job>;
    emit?: (event: AgentEvent) => void;
    report?: (report: ProcessReport) => void;
    files?: Files | null;
    store?: SessionStore | null;
    scans?: ScanStore | null;
  }) {
    this.scope = scope;
    this.jobs = jobs;
    this.instance = instance;
    this.emit = emit;
    this.report = report;
    this.files = files ?? apiFiles();
    this.store = store ?? new SessionStore();
    this.scans = scans ?? storedScans();
    this.id = agentId(instance);
    this.name = displayName(instance);
    this.sessions = new Map();
    /// The model and command catalog, read once from a short-lived CLI
    /// process so `list_options` works before any session exists.
    this.catalog = null;
    this.probing = null;
    /// The login environment last read (`config.ts`).
    this.env = {};
    this.sessionWatch = new SessionWatch({
      session: transcriptSession,
      own: (session) => this.sessions.has(session) || [...this.sessions.values()].some((live) => live.cli === session),
      report: (workspace) => this.emit({ sessionId: "", event: "sessions_changed", workspace }),
      run: (work) => Queue.offerUnsafe(this.jobs, work),
    });
  }

  /// The handlers the host calls, by `agent/<method>` name.
  definition(): EffectAgent {
    const handlers: EffectAgent = {
      id: this.id,
      name: this.name,
      icon: ICON,
      initialize: this.initialize.bind(this),
      list_options: this.listOptions.bind(this),
      list_commands: this.listCommands.bind(this),
      list_sessions: this.listSessions.bind(this),
      read_session: this.readSession.bind(this),
      list_skills: this.listSkills.bind(this),
      create_session: this.createSession.bind(this),
      resume_session: this.resumeSession.bind(this),
      close_session: this.closeSession.bind(this),
      fork_session: this.forkSession.bind(this),
      prompt: this.prompt.bind(this),
      cancel: this.cancel.bind(this),
      cancel_task: this.cancelTask.bind(this),
      withdraw: this.withdraw.bind(this),
      set_option: this.setOption.bind(this),
      respond_to_approval: this.respondToApproval.bind(this),
      respond_to_question: this.respondToQuestion.bind(this),
      rollback: this.rollback.bind(this),
      compact: this.compact.bind(this),
      usage_limits: this.usageLimits.bind(this),
      update: this.update.bind(this),
      authenticate: this.authenticate.bind(this),
      logout: this.logout.bind(this),
    };
    // The process pool's call (`agent-protocol.md`, "Processes"), which the
    // API's agent types do not list yet. Claude runs no shared server, so
    // there is no `stop_process`.
    return Object.assign(handlers, {
      suspend_session: this.suspendSession.bind(this),
      mcp_read_resource: (params: McpReadResourceParams) => readResource(this.session(params.sessionId), params),
      mcp_call_tool: (params: McpCallToolParams) => callTool(this.session(params.sessionId), params),
    });
  }

  background = Effect.fn("Claude.background")(function* (this: ClaudeAgent) {
    yield* Stream.runForEach(Stream.fromQueue(this.jobs), (job) => job.pipe(Effect.forkIn(this.scope))).pipe(
      Effect.forkIn(this.scope),
    );
    yield* Effect.addFinalizer(() => this.shutdown().pipe(Effect.orDie));
  });

  /// Reads the login environment again: the launch knobs apply to the
  /// next session without a restart.
  refreshEnv = Effect.fn("Claude.refreshEnv")(function* (this: ClaudeAgent) {
    this.env = yield* loginEnv();
    return this.env;
  });

  configDir() {
    return configDirOf(this.instance, this.env);
  }

  /// The configuration folder, once it is sure the plugin may read it. A
  /// folder no grant covers (an account's own folder outside `~/.claude*`,
  /// or `CLAUDE_CONFIG_DIR` from the login environment with the setting
  /// empty) would read as an empty history: no sessions, nothing to rewind
  /// to. Say so instead.
  readableConfigDir = Effect.fn("Claude.readableConfigDir")(function* (this: ClaudeAgent) {
    const dir = this.configDir();
    if (!dir) return dir;
    const read = yield* Effect.result((yield* Fs).stat(join(dir, "projects")));
    if (Result.isFailure(read) && read.failure._tag === "PermissionNotGranted") {
      const account = this.instance.id ? `the ${this.instance.id} account` : "the default account";
      return yield* new ProviderError({
        message: `Claude Code keeps ${account}'s sessions in ${dir}, which this plugin may not read: choose that folder as the Configuration folder in Settings > Claude Code, or keep the account in a folder whose name starts with ~/.claude (as ~/.claude-work)`,
      });
    }
    // A missing projects folder means the CLI has not written history yet.
    return dir;
  });

  /// What a session needs from its agent.
  context(emit: (event: AgentEvent) => void = (event) => this.emit(event)): SessionContext {
    return {
      scope: this.scope,
      jobs: this.jobs,
      files: this.files,
      store: this.store,
      instance: this.instance,
      env: this.env,
      agentId: this.id,
      emit,
      report: (report) => this.report(report),
      hostFeatures: this.hostFeatures,
    };
  }

  session(id: string) {
    const session = this.sessions.get(id);
    if (!session) throw new Error(`unknown session ${id}`);
    return session;
  }

  /// Reads the catalog with a throwaway session that is never prompted. It
  /// does not ask for the subscription limits: the host decides when those
  /// are read (`agent/usage_limits`), and a read here on every plugin start
  /// or reload would hit Anthropic's rate-limited usage service behind the
  /// host's back.
  loadCatalog = Effect.fn("Claude.loadCatalog")(function* (this: ClaudeAgent, workspace: string) {
    this.usageWorkspace = workspace;
    if (this.catalog) return this.catalog;
    if (!this.probing)
      this.probing = yield* Effect.cached(
        Effect.gen({ self: this }, function* () {
          yield* this.refreshEnv();
          const probe = yield* Session.create(
            this.context(() => {}),
            { id: crypto.randomUUID(), workspace, probe: true, launch: launchFromEnv(this.env) },
          );
          return yield* Effect.gen({ self: this }, function* () {
            yield* probe.start();
            this.catalog = probe.catalog;
            this.catalogCapabilities = probe.capabilities;
            return probe.catalog;
          }).pipe(Effect.ensuring(probe.shutdown().pipe(Effect.orDie)));
        }).pipe(
          Effect.ensuring(
            Effect.sync(() => {
              this.probing = null;
            }),
          ),
        ),
      );
    return yield* this.probing;
  });

  /// Starts a session's process and keeps it. The old process of the same
  /// session is stopped first: two processes writing one conversation file
  /// would race over the transcript.
  open = Effect.fn("Claude.open")(function* (
    this: ClaudeAgent,
    id: string,
    workspace: string,
    values: Values,
    start: Start,
    additions: Additions,
  ) {
    this.usageWorkspace = workspace;
    const previous = this.sessions.get(id);
    if (previous) {
      this.sessions.delete(id);
      yield* previous.shutdown();
    }
    yield* this.refreshEnv();
    const session = yield* Session.create(this.context(), {
      id,
      workspace,
      values,
      start,
      launch: launchFromEnv(this.env),
      additions,
    });
    this.sessions.set(id, session);
    yield* session.start().pipe(
      Effect.onError(() =>
        Effect.sync(() => {
          if (this.sessions.get(id) === session) this.sessions.delete(id);
        }),
      ),
    );
    return session;
  });

  // --- agent methods ----------------------------------------------------------

  initialize = Effect.fn("Claude.initialize")(function* (this: ClaudeAgent, params: AgentInitializeParams = {}) {
    this.hostFeatures.clear();
    for (const feature of params.hostFeatures ?? []) this.hostFeatures.add(feature);
    for (const session of this.sessions.values())
      session.mapper.mcp.enabled = this.hostFeatures.has("mcpApps") && supportsApps(session.capabilities);
    this.seen.clear();
    yield* this.refreshEnv();
    yield* this.watchSkills(null);
    const info = (
      status: AgentInfo["status"],
      version: string | null,
      description: string,
      maintained: AgentInfo["maintenance"] | null,
    ): AgentInfo => {
      const out: AgentInfo = {
        id: this.id,
        name: this.name,
        description,
        icon: ICON,
        capabilities: {
          reasoning: true,
          images: true,
          approvals: true,
          questions: true,
          sessionList: true,
          sessionHistory: true,
          resume: true,
          slashCommands: true,
          // Streaming `priority: next` is native non-interrupting pickup.
          steer: true,
          cancel: true,
          skills: true,
          rollback: true,
          fork: true,
          forkAt: true,
          compact: true,
          usageLimits: true,
          subagents: true,
          // `stop_task` stops one subagent; the parent's Stop still stops
          // them all.
          cancelTask: true,
          // `cancel_async_message` drops a steer the CLI has not taken in.
          withdraw: true,
          context: { labelled: true, ordinaryFiles: true, commands: true },
          ...(this.hostFeatures.has("mcpApps") && (
            supportsApps(this.catalogCapabilities) || [...this.sessions.values()].some((session) => supportsApps(session.capabilities))
          ) ? { mcpApps: true } : {}),
        },
        // The CLI owns the browser flow; Divergence starts it so the user
        // never has to find a terminal.
        authMethods: [
          {
            id: "anthropic",
            name: "Sign in to Anthropic",
            description: "Runs `claude auth login` for this configuration directory",
          },
        ],
        status,
        family: FAMILY,
        continuationKey: continuationKey(this.instance, this.env),
      };
      if (version) out.version = version;
      if (maintained) out.maintenance = maintained;
      return out;
    };
    const keywords = yield* this.promptKeywords();
    const withKeywords = (out: AgentInfo) => (keywords.length ? { ...out, promptKeywords: keywords } : out);
    const found = yield* which();
    if (!found.path)
      return withKeywords(
        info({ state: "unavailable", message: "the claude CLI is not on PATH" }, null, DESCRIPTION, null),
      );
    const version = yield* Effect.scoped(installedVersion());
    const maintained = (yield* Effect.scoped(maintenance(version))).out;
    // The plugin drives this same binary, so an `auth status` that cannot
    // run means a session would not run either.
    const probe = yield* Effect.result(Effect.scoped(probeAccount(childEnv(this.instance, this.env))));
    if (Result.isFailure(probe))
      return withKeywords(
        info({ state: "unavailable", message: probe.failure.message }, version, DESCRIPTION, maintained),
      );
    const account = probe.success;
    const status: AgentInfo["status"] = account.loggedIn
      ? { state: "ready" }
      : { state: "auth_required", message: signedOutMessage(chosenConfigDir(this.instance, this.env)) };
    const summary = accountSummary(account);
    if (account.loggedIn && this.hostFeatures.has("mcpApps"))
      yield* this.loadCatalog(this.usageWorkspace ?? this.env.HOME ?? "");
    return withKeywords(info(status, version, summary ? `${DESCRIPTION} ${summary}` : DESCRIPTION, maintained));
  });

  /// The CLI finds the word itself and turns that one turn into a
  /// workflow; the composer only tells the user it will.
  promptKeywords = Effect.fn("Claude.promptKeywords")(function* (this: ClaudeAgent) {
    const dir = this.configDir();
    const settings = workflowSettings(dir ? yield* readJson(this.files, join(dir, "settings.json")) : null);
    return settings.keyword
      ? [{ word: ULTRACODE, label: "Ultracode", description: "Activates dynamic workflows for this turn." }]
      : [];
  });

  listOptions = Effect.fn("Claude.listOptions")(function* (this: ClaudeAgent, { workspace }: { workspace?: string }) {
    return { options: (yield* this.loadCatalog(String(workspace ?? ""))).options({}) };
  });

  listCommands = Effect.fn("Claude.listCommands")(function* (this: ClaudeAgent, { sessionId }: { sessionId: string }) {
    return { commands: this.session(sessionId).commands() };
  });

  /// The sessions of the CLI's own files, but for a file that continues a
  /// session the host has a chat for already (a start over after a rewind,
  /// `Session.create`). The first listing starts watching the account's
  /// transcripts, so a session started in Claude Code itself is reported.
  listSessions = Effect.fn("Claude.listSessions")(function* (this: ClaudeAgent, { workspace }: { workspace?: string }) {
    yield* this.refreshEnv();
    const dir = yield* this.readableConfigDir();
    const sessions = yield* listSessions(this.files, dir, String(workspace ?? ""), this.scans);
    this.sessionWatch.know(sessions.map((session) => session.id));
    if (dir) yield* this.sessionWatch.watch(join(dir, "projects"), this.scope);
    const aliases = yield* this.store.aliases(sessions.map((session) => session.id));
    return { sessions: sessions.filter((session) => !aliases.has(session.id)) };
  });

  /// The host reads a chat's history on almost every switch to it, and a
  /// full read of a long session takes seconds of this plugin's only
  /// thread. So a session whose files look as they did at this plugin's
  /// last complete read of it answers with nothing at once, which the host
  /// takes as "nothing new" and leaves the chat as it is
  /// (`Host::load_history`). "Unchanged" means: the same transcript path
  /// (configuration folder, workspace and the CLI's id for the session, so
  /// an alias after a rewind or another folder is another path), and every
  /// file that read used with the same kind, size and modification time,
  /// every folder it listed with the same entries, and every path it found
  /// missing still missing (`fingerprint.ts`). The read maps exactly those
  /// files, and an echo is stored before its record is written, so it
  /// would answer what the host already took. The first read after a load,
  /// a read whose metadata proves nothing, two full reads of a session at
  /// once (the host may apply the older answer last) and a read the session
  /// was closed during leave nothing to skip with; `closeSession` forgets
  /// the session, so a chat made again for it reads it whole.
  readSession = Effect.fn("Claude.readSession")(function* (
    this: ClaudeAgent,
    {
      workspace,
      sessionId,
      version,
      tasks,
    }: { workspace?: string; sessionId: string; version?: string; tasks?: readonly string[] },
  ) {
    yield* this.refreshEnv();
    const live = this.sessions.get(sessionId);
    const state = live ? { cli: live.cli, rewound: live.rewound, sent: live.sent } : yield* this.store.load(sessionId);
    const cli = state.cli ?? sessionId;
    const dir = yield* this.readableConfigDir();
    const path = sessionFile(dir, String(workspace ?? live?.workspace ?? ""), cli);
    // The host passes back the fingerprint of the last read it reconciled,
    // so a session unchanged since then is not read after a restart either.
    const known = this.seen.get(sessionId) ?? parseVersion(version, this.hostFeatures.has("mcpApps"));
    if (!tasks?.length && (!path || (known?.path === path && (yield* unchanged(this.files, known.fingerprint)))))
      return { items: [], echoes: [], ...(version ? { version } : {}) };
    if (!path) return { items: [], echoes: [] };
    const flight = this.reading.get(sessionId) ?? { running: 0, unsure: false };
    flight.unsure ||= flight.running > 0;
    flight.running += 1;
    this.reading.set(sessionId, flight);
    const reads = recordReads(this.files);
    const answer = yield* this.readLock
      .withPermit(
        Effect.gen({ self: this }, function* () {
          const read = yield* readSessionFile(reads.files, path, {
            tail: this.tails.get(sessionId),
            tasks: new Set(tasks ?? []),
            rewound: state.rewound,
            mcp: yield* loadApps(sessionId, this.hostFeatures.has("mcpApps")),
          });
          if (read.tail) this.tails.set(sessionId, read.tail);
          else this.tails.delete(sessionId);
          const received = sendersOf(read.items);
          const senders = yield* this.store.senders(this.files, dir, received.map(({ sender }) => sender));
          for (const { item, sender } of received) {
            const session = senders.get(sender.id);
            if (session && item.role === "user") item.fromSession = session;
          }
          const echoes = yield* ingressEchoes(this.id, sessionId, read.items);
          return {
            items: read.items,
            aliases: sentAliases(state.sent, read.items, echoes),
            echoes,
            streamed: streamedAliases(read.items),
            ...(read.omitted.length ? { omittedTasks: read.omitted } : {}),
          };
        }),
      )
      .pipe(
        Effect.ensuring(
          Effect.sync(() => {
            flight.running -= 1;
            if (!flight.running) this.reading.delete(sessionId);
          }),
        ),
      );
    const fingerprint = flight.unsure ? null : reads.fingerprint(path);
    if (fingerprint) this.seen.set(sessionId, { path, fingerprint });
    else this.seen.delete(sessionId);
    return fingerprint ? { ...answer, version: JSON.stringify({ path, fingerprint, format: HISTORY_FORMAT, mcpApps: this.hostFeatures.has("mcpApps") }) } : answer;
  });

  listSkills = Effect.fn("Claude.listSkills")(function* (this: ClaudeAgent, { workspace }: { workspace?: string }) {
    yield* this.refreshEnv();
    yield* this.watchSkills(String(workspace ?? ""));
    const commands = this.catalog ? this.catalog.commands : [];
    return { skills: yield* listSkills(this.files, String(workspace ?? ""), this.configDir(), commands) };
  });

  /// Watches the account's skill folder and, given one, the workspace's,
  /// each once; a change tells the host to list the skills again. A folder
  /// that does not exist yet cannot be watched and is tried again at the
  /// next list.
  watchSkills = Effect.fn("Claude.watchSkills")(function* (this: ClaudeAgent, workspace: string | null) {
    const fs = yield* Fs;
    for (const { source, root } of skillRoots(workspace ?? "", this.configDir())) {
      if ((source === "project" && workspace === null) || this.watchedSkills.has(root)) continue;
      this.watchedSkills.add(root);
      const watched = yield* Effect.result(
        fs
          .watch(root, () => this.emit({ sessionId: "", event: "skills_changed" }))
          .pipe(Effect.provideService(Scope.Scope, this.scope)),
      );
      if (Result.isFailure(watched)) {
        this.watchedSkills.delete(root);
        console.debug(`claude: the skills in ${root} are not watched: ${watched.failure.message}`);
      }
    }
  });

  createSession = Effect.fn("Claude.createSession")(function* (
    this: ClaudeAgent,
    params: Omit<SessionParams, "sessionId">,
  ) {
    const id = crypto.randomUUID();
    yield* this.open(id, String(params.workspace ?? ""), params.options ?? {}, starts.new(), {
      tools: params.tools,
      instructions: params.instructions,
    });
    return { sessionId: id };
  });

  resumeSession = Effect.fn("Claude.resumeSession")(function* (this: ClaudeAgent, params: SessionParams) {
    const resumed = yield* Effect.result(
      this.open(params.sessionId, String(params.workspace ?? ""), params.options ?? {}, starts.resume(), {
        tools: params.tools,
        instructions: params.instructions,
      }),
    );
    if (Result.isFailure(resumed)) {
      if (params.requireResume && resumed.failure._tag === "ProviderError" && resumed.failure.sessionUnavailable)
        return { unavailable: resumed.failure.message };
      return yield* Effect.fail(resumed.failure);
    }
    return {};
  });

  closeSession = Effect.fn("Claude.closeSession")(function* (this: ClaudeAgent, { sessionId }: { sessionId: string }) {
    // The host closes the session of a chat it deletes; a chat imported
    // again for it starts empty and must get the whole history.
    this.seen.delete(sessionId);
    this.tails.delete(sessionId);
    const flight = this.reading.get(sessionId);
    if (flight) flight.unsure = true;
    const session = this.sessions.get(sessionId);
    if (session) {
      this.sessions.delete(sessionId);
      yield* session.shutdown();
    }
    return {};
  });

  /// Stops the session's CLI for the host's process pool and keeps what a
  /// resume needs: the saved state and CLI id (`SessionStore`), and what the
  /// last history read saw, so the next read of an unchanged session still
  /// answers at once. Unlike `closeSession` nothing is forgotten; the next
  /// `resume_session` starts the CLI again on the same conversation.
  suspendSession = Effect.fn("Claude.suspendSession")(function* (
    this: ClaudeAgent,
    { sessionId }: { sessionId: string },
  ) {
    const session = this.sessions.get(sessionId);
    if (session) {
      this.sessions.delete(sessionId);
      yield* session.shutdown();
    }
    return {};
  });

  prompt = Effect.fn("Claude.prompt")(function* (
    this: ClaudeAgent,
    { sessionId, input }: { sessionId: string; input?: Prompt },
  ) {
    return yield* this.session(sessionId).prompt(input ?? {});
  });

  cancel = Effect.fn("Claude.cancel")(function* (this: ClaudeAgent, { sessionId }: { sessionId: string }) {
    yield* this.session(sessionId).cancel();
    return {};
  });

  cancelTask = Effect.fn("Claude.cancelTask")(function* (
    this: ClaudeAgent,
    { sessionId, taskId }: { sessionId: string; taskId: string },
  ) {
    yield* this.session(sessionId).cancelTask(taskId);
    return {};
  });

  withdraw = Effect.fn("Claude.withdraw")(function* (
    this: ClaudeAgent,
    { sessionId, inputId }: { sessionId: string; inputId: string },
  ) {
    return { withdrawn: yield* this.session(sessionId).withdrawInput(inputId) };
  });

  setOption = Effect.fn("Claude.setOption")(function* (
    this: ClaudeAgent,
    { sessionId, optionId, value }: { sessionId: string; optionId: string; value: unknown },
  ) {
    return { options: yield* this.session(sessionId).setOption(optionId, value) };
  });

  respondToApproval = Effect.fn("Claude.respondToApproval")(function* (
    this: ClaudeAgent,
    { approvalId, optionId }: { approvalId: string; optionId: string },
  ) {
    const parts = splitId(approvalId);
    if (!parts) return yield* new ProviderError({ message: "malformed approval id" });
    // Settled before the answer came: nothing waits for it, which the host
    // shows as answered.
    return this.session(parts[0]).respondToApproval(approvalId, optionId) ? {} : { notPending: true as const };
  });

  respondToQuestion = Effect.fn("Claude.respondToQuestion")(function* (
    this: ClaudeAgent,
    { questionId, answer }: { questionId: string; answer?: Answer },
  ) {
    const parts = splitId(questionId);
    if (!parts) return yield* new ProviderError({ message: "malformed question id" });
    const answered = yield* Effect.try({
      try: () => this.session(parts[0]).respondToQuestion(questionId, answer ?? { values: {}, cancelled: false }),
      catch: (cause) => new ProviderError({ message: errorMessage(cause) }),
    });
    return answered ? {} : { notPending: true as const };
  });

  /// Rewinds the conversation so `itemId` and everything after it is
  /// forgotten: the session's process starts again with
  /// `--resume-session-at` the record before it, or, when nothing came
  /// before it, on a fresh conversation. The host's own id is found by the
  /// user record its prompt became; an id from the CLI's file (a resumed
  /// conversation) by its uuid.
  rollback = Effect.fn("Claude.rollback")(function* (
    this: ClaudeAgent,
    { sessionId, itemId }: { sessionId: string; itemId: string },
  ) {
    const current = this.session(sessionId);
    const rewind = yield* this.rewindPoint(current.workspace, current.cli, current.sentAs(itemId), itemId);
    if (!rewind)
      return yield* new ProviderError({
        message: `the conversation has nothing recorded before ${itemId}, so it cannot be rewound to that point`,
      });
    const start = "fresh" in rewind ? starts.new() : starts.resumeAt(rewind.at);
    yield* this.open(sessionId, current.workspace, current.values, start, current.additions);
    return {};
  });

  /// Where the CLI's file `cli` must be resumed so that the user message
  /// `itemId` (found as this plugin sent it, when it did) and everything
  /// after it are left out.
  rewindPoint = Effect.fn("Claude.rewindPoint")(function* (
    this: ClaudeAgent,
    workspace: string,
    cli: string,
    sent: number | string | null,
    itemId: string,
  ) {
    const dir = yield* this.readableConfigDir();
    const rewind = sent !== null ? yield* rewindTargetAt(this.files, dir, workspace, cli, sent) : null;
    if (rewind) return rewind;
    const at = yield* rewindTarget(this.files, dir, workspace, cli, itemId);
    return at === null ? null : { at };
  });

  /// A fork keeps the original's settings, because it is the same
  /// conversation taken in another direction; the tools and instructions
  /// are the ones the host sent for the copy. With `itemId` the copy
  /// stops before that user message, found as a rewind finds it.
  forkSession = Effect.fn("Claude.forkSession")(function* (
    this: ClaudeAgent,
    params: SessionParams & { itemId?: string },
  ) {
    const origin = this.sessions.get(params.sessionId);
    const values = origin ? origin.values : (params.options ?? {});
    const workspace = String(params.workspace ?? "");
    const state = origin ? null : yield* this.store.load(params.sessionId);
    const from = origin ? origin.cli : (state?.cli ?? params.sessionId);
    let at: string | undefined;
    if (params.itemId !== undefined) {
      const sent = origin ? origin.sentAs(params.itemId) : (state?.sent[params.itemId] ?? null);
      const rewind = yield* this.rewindPoint(workspace, from, sent, params.itemId);
      if (!rewind || "fresh" in rewind)
        return yield* new ProviderError({
          message: `the conversation has nothing recorded before ${params.itemId}, so it cannot be forked there`,
        });
      at = rewind.at;
    }
    const id = crypto.randomUUID();
    yield* this.open(id, workspace, values, starts.fork(from, at), {
      tools: params.tools,
      instructions: params.instructions,
    });
    return { sessionId: id };
  });

  compact = Effect.fn("Claude.compact")(function* (this: ClaudeAgent, { sessionId }: { sessionId: string }) {
    yield* this.session(sessionId).compact();
    return {};
  });

  /// Re-initialize a prompt-free process with the current configuration. An
  /// existing process's account snapshot may predate login/config changes;
  /// relabelling its cached permission with today's auth identity is unsafe.
  usageLimits = Effect.fn("Claude.usageLimits")(function* (this: ClaudeAgent) {
    if (this.usageWorkspace === null) return { limits: null };
    yield* this.refreshEnv();
    const probe = yield* Session.create(
      this.context(() => {}),
      {
        id: crypto.randomUUID(),
        workspace: this.usageWorkspace,
        probe: true,
        launch: launchFromEnv(this.env),
      },
    );
    return yield* Effect.gen({ self: this }, function* () {
      yield* probe.start();
      return { limits: yield* probe.usageLimits() };
    }).pipe(Effect.ensuring(probe.shutdown().pipe(Effect.orDie)));
  });

  /// Runs the CLI's own sign-in for this configuration directory. It opens
  /// a browser and waits, so it gets no timeout: running it here rather
  /// than in a terminal is the point, since a second account has its own
  /// directory and a login typed in the wrong shell lands in the wrong one.
  authenticate = Effect.fn("Claude.authenticate")(function* (this: ClaudeAgent) {
    yield* this.refreshEnv();
    const result = yield* Effect.scoped(
      runProcess("claude", ["auth", "login"], { env: childEnv(this.instance, this.env) }),
    );
    if (result.code !== 0) return yield* new ProviderError({ message: messageOf(result) });
    this.catalog = null;
    return {};
  });

  logout = Effect.fn("Claude.logout")(function* (this: ClaudeAgent) {
    yield* this.refreshEnv();
    // Stop every session first: a resumed one would keep using the account
    // that was just signed out.
    yield* this.shutdown();
    const result = yield* Effect.scoped(
      runProcess("claude", ["auth", "logout"], { env: childEnv(this.instance, this.env) }),
    );
    if (result.code !== 0) return yield* new ProviderError({ message: messageOf(result) });
    this.catalog = null;
    return {};
  });

  update = Effect.fn("Claude.update")(function* (this: ClaudeAgent) {
    yield* this.refreshEnv();
    yield* Effect.scoped(update(childEnv(this.instance, this.env)));
    return {};
  });

  shutdown = Effect.fn("Claude.shutdown")(function* (this: ClaudeAgent) {
    const sessions = [...this.sessions.values()];
    this.sessions.clear();
    yield* Effect.all(
      sessions.map((session) => session.shutdown()),
      { concurrency: "unbounded" },
    );
  });
}

Versions

VersionPublishedPlugin APISizePermissionsStatus
0.2.7latestNov 21, 2026>=5 <6207.5 KB4 permissionsListed
0.2.6Nov 16, 2026>=5 <6206 KB4 permissionsListed
0.2.5Nov 11, 2026>=5 <6168.3 KB4 permissionsListed
0.2.4Nov 9, 2026>=5 <6166.1 KB4 permissionsListed
0.2.3Oct 27, 2026>=2 <4151.6 KB4 permissionsListed

Reviews and comments

0 threads · 0 reviews

No comments yet.