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

session.ts65.2 KB
// One `claude` process per session, driven over its headless `stream-json`
// protocol (the Rust `session.rs`).
//
// stdin carries user messages and `control_request` envelopes; stdout
// carries the transcript, `control_response` envelopes for our requests
// and `control_request` envelopes for the CLI's permission prompts and its
// talk to the plugin tool server.
import * as Queue from "effect/Queue";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as Semaphore from "effect/Semaphore";
import * as Result from "effect/Result";
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
import * as wire from "./wire.ts";
import * as Effect from "effect/Effect";
import { Fs, Plugin, parse } from "divergence/effect";
import type { PluginServices } from "divergence/effect";
import { ProviderError } from "./errors.ts";
import { callHostToolEffect } from "../sdk/effect.ts";
import type { ProcessReport } from "../sdk/agent.ts";
import type { TransportError } from "../sdk/effect.ts";
import type { Files } from "./files.ts";
import type { SessionStore } from "./state.ts";
import type { Instance } from "./instances.ts";
import type { Launch } from "./config.ts";
import type {
  AgentEvent,
  AgentEventKind,
  Emission,
  Values,
  RunOutcome,
  Skill,
} from "./types.ts";
import { errorMessage } from "../sdk/errors.ts";
import {
  agentEvent,
  consumedInput,
  newId,
  outcome,
  permissionMode,
  rejectedInput,
  QUEUED_INPUT_HELD,
} from "../sdk/agent.ts";
import { contextText, retainIngress } from "../sdk/context.ts";
import { handleMcp, MCP_SERVER } from "../sdk/mcp.ts";
import { spawn, stop } from "./transport.ts";
import type { LineProcess, ProcessExit } from "../sdk/process.ts";
import { childEnv, configDirOf, emptyLaunch, launchArgs, workflowSettings } from "./config.ts";
import { join, readJson } from "./files.ts";
import { recordsAfter, sessionFile, turnFromElsewhere } from "./history.ts";
import { fromUsageResponse, fromRateLimitInfo } from "./limits.ts";
import { probeAccount, recoveryIdentity } from "./account.ts";
import { Mapper, contextContents, failureMessage } from "./map.ts";
import {
  Catalog,
  EFFORT,
  FAST_MODE,
  MODEL,
  ULTRACODE,
  permissionFlag,
  selected,
  toggle,
} from "./options.ts";
import { listSkills } from "./skills.ts";
import { emptyState } from "./state.ts";
import { DISMISSED, answeredInput, approvalDecision, approvalRequest, questionRequest } from "./approvals.ts";
import { Tail } from "./workflow.ts";
import { peerMessage } from "./records.ts";
import { readAgent } from "./subagents.ts";
import { cancel, setOption, sessionUpdate } from "./control.ts";
import { elicitationQuestion, elicitationResult } from "./elicitation.ts";
import { TASK_OUTPUT_LIMIT, taskOutput } from "../sdk/tasks.ts";
import type { HostFeature } from "divergence/protocol";
import { capabilitiesFor, loadApps, refreshApps, refreshAppsLater, saveApps, supportsApps } from "./mcp.ts";

export type Job = Effect.Effect<unknown, unknown, PluginServices>;
export interface SessionContext {
  files: Files;
  store: SessionStore;
  instance: Instance;
  env: Record<string, string>;
  agentId: string;
  emit: (event: AgentEvent) => void;
  report: (report: ProcessReport) => void;
  scope: Scope.Scope;
  jobs: Queue.Queue<Job>;
  hostFeatures?: ReadonlySet<HostFeature>;
}
export type Start =
  { kind: "new" | "resume" } | { kind: "resumeAt"; at: string } | { kind: "fork"; origin: string; at?: string };
export interface Additions {
  tools?: { name: string; description?: string; inputSchema?: unknown }[];
  instructions?: string | null;
}
export interface SessionOptions {
  id: string;
  cli?: string | null;
  workspace: string;
  values?: Values;
  start?: Start;
  probe?: boolean;
  launch?: Launch | null;
  additions?: Additions;
  sent?: Record<string, number | string>;
  rewound?: string | null;
}
export interface Prompt {
  itemId?: string;
  delivery?: import("divergence/protocol").PromptDelivery;
  context?: import("divergence/protocol").ContextPacket;
  blocks?: {
    type: string;
    text?: string;
    path?: string;
    mimeType?: string;
    data?: string;
    name?: string;
    input?: string;
  }[];
}
export interface Answer {
  values?: Record<string, unknown>;
  cancelled?: boolean;
}
type Pending = { task: string | null } & (
  | { kind: "approval"; toolName: string; suggestions: unknown; suppressAlways: boolean }
  | { kind: "question"; input: wire.Input | null }
  | { kind: "elicitation"; request: wire.ControlRequest }
);
type SessionError = TransportError | ProviderError;

/// How long the CLI may take to answer a control request.
export const CONTROL_TIMEOUT = 60_000;
/// How long the CLI waits for one plugin tool call, in milliseconds. A tool
/// can run for minutes (code mode's `execute` calls other tools), so the
/// CLI's own MCP timeout must not cut it off.
export const TOOL_TIMEOUT_MS = 60 * 60 * 1000;
export { CANCEL_TIMEOUT } from "./control.ts";
/// How often, and how many times, a command the CLI took in on its own is
/// looked for in its file: the CLI writes the record without waiting.
export const INBOX_POLL = 25;
export const INBOX_ATTEMPTS = 40;
/// How often, and how far apart, the record a workflow wrote when it ended
/// is looked for: the CLI writes it without waiting.
const OUTPUT_ATTEMPTS = 10;
const OUTPUT_RETRY = 300;

/// Separates the session from the CLI request id inside an approval or
/// question id, so the host can answer without a second index.
const ID_SEPARATOR = "::";

export function splitId(id: string): [string, string] | null {
  const at = String(id).indexOf(ID_SEPARATOR);
  return at < 0 ? null : [id.slice(0, at), id.slice(at + ID_SEPARATOR.length)];
}

/// How a session's process attaches to a conversation: `new` (under the
/// session's CLI id), `resume`, `resumeAt` (dropping everything recorded
/// after `at`), or `fork` (copying `origin` into the session's id, up to
/// `at` when it is given).
export const starts = {
  new: (): Start => ({ kind: "new" }),
  resume: (): Start => ({ kind: "resume" }),
  resumeAt: (at: string): Start => ({ kind: "resumeAt", at }),
  fork: (origin: string, at?: string): Start =>
    at === undefined ? { kind: "fork", origin } : { kind: "fork", origin, at },
};

/// A signal that is already given.
function given() {
  const deferred = Deferred.makeUnsafe<void>();
  Deferred.doneUnsafe(deferred, Effect.void);
  return deferred;
}

export class Session {
  ctx: SessionContext;
  files: Files;
  id: string;
  cli: string;
  workspace: string;
  values: Values;
  startMode: Start;
  probe: boolean;
  launch: Launch;
  additions: Required<Additions>;
  sent: Record<string, number | string>;
  /// The record the conversation was rewound to, until a prompt follows it
  /// (`SessionState.rewound`).
  rewound: string | null;
  catalog: Catalog;
  mapper: Mapper;
  proc: LineProcess | null;
  starting: Effect.Effect<void, SessionError, PluginServices> | null;
  launched: boolean;
  run: string | null;
  cancelled: boolean;
  skills: Skill[] | null;
  controlRequests: Map<string, { resolve: (value: unknown) => void; reject: (error: ProviderError) => void }>;
  pending: Map<string, Pending>;
  capabilities: Set<string> | null = null;
  nextControl: number;
  lines: Promise<void>;
  reader: Queue.Queue<Job> | null;
  tails: Map<string, Tail>;
  tailLock = Semaphore.makeUnsafe(1);
  terminalLock = Semaphore.makeUnsafe(1);
  followingTerminals = false;
  promptLock = Semaphore.makeUnsafe(1);
  /// A Stop that came while a prompt was still being admitted (the CLI
  /// starting), before its run existed: the run is interrupted once sent.
  stopBeforeRun = false;
  inputs = new Map<
    string,
    {
      delivery?: import("divergence/protocol").PromptDelivery;
      contextId?: string;
      runId: string;
      consumed: boolean;
      answered: boolean;
    }
  >();
  finishedRuns = new Set<string>();
  /// The inputs the CLI's latest request carried. A steer taken mid-turn
  /// is named only on that request's status line; the replies to it carry
  /// no input ids.
  requested: string[] = [];
  results = new Set<string>();
  identity: string | null = null;
  /// Done unless the identity of the running process is still being read.
  identityKnown = given();
  /// The last `rate_limit_event` seen while the identity was being read.
  heldLimit: { info: unknown; run: string | null; blocked: boolean } | null = null;
  missingResume: string | null = null;
  /// The replies this session's processes streamed, by record uuid, and
  /// how far the session's file has been read for turns another program
  /// ran (`continuedElsewhere`).
  replies = new Set<string>();
  read: { path: string; offset: number } | null = null;
  /// The commands the CLI took in on its own, read from the file
  /// (`received`): how far it was read, the messages from other sessions by
  /// id, and the ids of every other command, which need nothing shown.
  inbox = {
    offset: 0,
    heard: new Map<string, NonNullable<ReturnType<typeof peerMessage>>>(),
    other: new Set<string>(),
  };

  /// `ctx`: `{ api, files, store, instance, env, agentId, emit }`.
  constructor(
    ctx: SessionContext,
    {
      id,
      cli,
      workspace,
      values = {},
      start = starts.new(),
      probe = false,
      launch = null,
      additions = {},
      sent = {},
      rewound = null,
    }: SessionOptions,
  ) {
    this.ctx = ctx;
    this.files = ctx.files;
    this.id = id;
    this.cli = cli ?? id;
    this.workspace = workspace;
    this.values = { ...values };
    this.startMode = start;
    this.probe = probe;
    this.launch = launch ?? emptyLaunch();
    this.additions = {
      tools: Array.isArray(additions.tools) ? additions.tools : [],
      instructions: additions.instructions ?? null,
    };
    this.sent = { ...sent };
    this.rewound = rewound;
    this.catalog = new Catalog();
    this.mapper = new Mapper();
    this.mapper.mcp.enabled = ctx.hostFeatures?.has("mcpApps") ?? false;
    this.proc = null;
    this.starting = null;
    this.launched = false;
    this.run = null;
    this.cancelled = false;
    this.skills = null;
    this.controlRequests = new Map();
    this.pending = new Map();
    this.nextControl = 1;
    this.lines = Promise.resolve();
    this.tails = new Map();
    this.reader = null;
  }

  /// Builds a session and its CLI id. Starting over on a conversation the
  /// CLI already holds needs a new CLI id: the CLI will not reuse one, so
  /// the fresh conversation gets its own and the host's id stays the
  /// alias, for this launch and every later one.
  static create = Effect.fn("Claude.create")(function* (ctx: SessionContext, options: SessionOptions) {
    const { id, workspace, probe = false } = options;
    let start = options.start ?? starts.new();
    let state = probe ? emptyState() : yield* ctx.store.load(id);
    let cli = state.cli ?? id;
    if (!probe && start.kind === "new") {
      const file = sessionFile(configDirOf(ctx.instance, ctx.env), workspace, cli);
      if (file && (yield* ctx.files.stat(file))) {
        cli = crypto.randomUUID();
        state = { cli, sent: {}, rewound: null };
        yield* ctx.store.save(id, state);
      }
    }
    // The host has a chat for this session already; its new file must not
    // be listed as another one. Kept again at each open for an alias
    // older than the note.
    if (!probe && cli !== id) yield* ctx.store.keepAlias(cli, id);
    // The CLI writes nothing at a rewind: until the next prompt its file
    // ends with the dropped turns, and a later launch must go back again.
    if (!probe && start.kind === "resumeAt" && state.rewound !== start.at) {
      state = { ...state, rewound: start.at };
      yield* ctx.store.save(id, state);
    }
    // The CLI writes a fork's file at its first prompt. A fork stopped
    // before that (the pool put it to sleep, or the app quit) has no file
    // to resume, so it forks its origin again.
    if (!probe && start.kind === "fork") {
      state = { ...state, fork: start.at === undefined ? { origin: start.origin } : { origin: start.origin, at: start.at } };
      yield* ctx.store.save(id, state);
    } else if (!probe && start.kind === "resume" && state.fork) {
      const file = sessionFile(configDirOf(ctx.instance, ctx.env), workspace, cli);
      if (file && !(yield* ctx.files.stat(file))) start = starts.fork(state.fork.origin, state.fork.at);
    }
    if (start.kind === "resume" && state.rewound) start = starts.resumeAt(state.rewound);
    return new Session(ctx, { ...options, start, cli, sent: state.sent, rewound: state.rewound });
  });

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

  // --- events ---------------------------------------------------------------

  emitEvent(kind: AgentEventKind, task: string | null = null) {
    this.ctx.emit(agentEvent(this.id, kind, { runId: this.run, taskId: task }));
  }

  emitMapped({ task, kind }: Emission) {
    this.emitEvent(kind, task);
  }

  // --- launch ---------------------------------------------------------------

  /// The option values this session runs with, so a fork or a rewind can
  /// carry them into the replacement process.
  options() {
    return this.catalog.options(this.values);
  }

  commands() {
    return this.catalog.slashCommands();
  }

  /// The `initialize` control request. The plugin tools are declared as an
  /// SDK MCP server, which the CLI then talks to through `mcp_message`
  /// control requests; the text to follow goes in `appendSystemPrompt`,
  /// with the user's own (the CLI drops `--append-system-prompt` when this
  /// field is set). Both are sent at every launch. Where native system
  /// prompt snapshots are enabled, the recorded text wins on resume until
  /// compaction, even if a later launch supplies different text.
  initializeRequest() {
    const request: {
      subtype: string;
      sdkMcpServers?: string[];
      sdkMcpServerConfigs?: Record<string, { timeout: number }>;
      appendSystemPrompt?: string;
    } = { subtype: "initialize" };
    if (this.additions.tools.length) {
      request.sdkMcpServers = [MCP_SERVER];
      request.sdkMcpServerConfigs = { [MCP_SERVER]: { timeout: TOOL_TIMEOUT_MS } };
    }
    const appended = [this.launch.appendSystemPrompt, this.additions.instructions]
      .filter((text) => typeof text === "string")
      .map((text) => text.trim())
      .filter((text) => text);
    if (appended.length) request.appendSystemPrompt = appended.join("\n\n");
    return request;
  }

  /// The argument list for this session.
  args() {
    const values = this.values;
    const args = [
      "--output-format",
      "stream-json",
      "--input-format",
      "stream-json",
      "--verbose",
      "--include-partial-messages",
    ];
    // Routes the CLI's permission prompts to the control channel as
    // `can_use_tool` requests.
    args.push("--permission-prompt-tool", "stdio");
    const start = this.startMode;
    if (start.kind === "new") args.push("--session-id", this.cli);
    else if (start.kind === "resume") args.push("--resume", this.cli);
    // The CLI keeps the named message and drops everything after it, so
    // the caller passes the message to rewind *to*.
    else if (start.kind === "resumeAt") args.push("--resume", this.cli, "--resume-session-at", start.at);
    // `--session-id` with `--resume` needs `--fork-session`, which is what
    // makes the new id ours to pick.
    else if (start.kind === "fork") {
      args.push("--resume", start.origin, "--fork-session", "--session-id", this.cli);
      if (start.at !== undefined) args.push("--resume-session-at", start.at);
    }
    // Without this the CLI hides a subagent's work behind its parent tool
    // call, so a task would have no transcript.
    if (!this.probe) args.push("--forward-subagent-text");
    const model = selected(values, MODEL);
    if (model !== null) args.push("--model", model);
    const effort = selected(values, EFFORT);
    if (effort !== null) args.push("--effort", effort);
    if (!this.probe) {
      args.push("--permission-mode", permissionFlag(permissionMode.selected(values, true)));
      // The CLI refuses `bypassPermissions` unless the caller also accepts
      // the risk, and only at launch: without this a session could never be
      // switched to Full access later. The flag alone changes nothing.
      args.push("--allow-dangerously-skip-permissions");
      // Under stream-json the CLI leaves thinking to the API, which omits
      // its text; summaries must be asked for.
      args.push("--thinking-display", "summarized");
    }
    const settings = this.settingsLayer();
    if (settings !== null) args.push("--settings", settings);
    // Reading the catalog is a health check: it must not start MCP servers.
    if (this.probe) args.push("--strict-mcp-config");
    else args.push(...launchArgs(this.launch, this.workspace));
    return args;
  }

  /// The extra settings layer, as the CLI's `--settings` JSON. A health
  /// check must not fire the user's `SessionStart` hooks.
  settingsLayer() {
    if (this.probe) return JSON.stringify({ disableAllHooks: true });
    const layer = { ...(toggle(this.values, FAST_MODE, false) && { fastMode: true }), ...(this.ultracode() && { ultracode: true }) };
    return Object.keys(layer).length ? JSON.stringify(layer) : null;
  }

  /// Starts the CLI if it is not running and completes the `initialize`
  /// handshake. Concurrent callers share one start.
  start = Effect.fn("Claude.start")(function* (this: Session) {
    if (this.proc?.alive) return;
    if (!this.starting)
      this.starting = yield* Effect.cached(
        this.launchProcess().pipe(
          Effect.ensuring(
            Effect.sync(() => {
              this.starting = null;
            }),
          ),
        ),
      );
    yield* this.starting;
  });

  launchProcess = Effect.fn("Claude.launchProcess")(function* (this: Session) {
    this.capabilities = null;
    // A process that exited after it attached is started again on the
    // conversation it left, never as a new one under a used id.
    if (this.launched && this.startMode.kind !== "resume") {
      const file = sessionFile(this.configDir, this.workspace, this.cli);
      if (file && (yield* this.files.stat(file)))
        this.startMode = this.rewound ? starts.resumeAt(this.rewound) : starts.resume();
    }
    const env = {
      ...childEnv(this.ctx.instance, this.ctx.env),
      CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS: "1",
      // Claude creates this private directory itself. Its output is covered
      // by the provider's existing data read grant rather than a temp glob.
      CLAUDE_CODE_TMPDIR: `${(yield* Plugin).api.paths.data}/tmp`,
    };
    if (!this.reader) {
      this.reader = yield* Queue.make<Job>();
      yield* Stream.runForEach(Stream.fromQueue(this.reader), (job) => job).pipe(Effect.forkIn(this.ctx.scope));
    }
    const handle: { proc: LineProcess | null; processId: string | null } = { proc: null, processId: null };
    const spawned = yield* Effect.result(
      spawn(this.args(), {
        cwd: this.workspace,
        env,
        name: "claude",
        onLine: (line) => this.queue(this.onLine(line)),
        onExit: (status, tail) =>
          this.queue(
            Effect.sync(() => {
              if (handle.processId) this.reportProcess(handle.processId, "stopped");
              this.onExit(handle.proc, status, tail);
            }),
          ),
      }).pipe(Effect.provideService(Scope.Scope, this.ctx.scope)),
    );
    if (Result.isFailure(spawned)) {
      // A program started in a folder that is gone fails as if the program
      // were missing (`os error 2`).
      const folder = yield* Effect.result((yield* Fs).stat(this.workspace));
      const gone = Result.isFailure(folder) && folder.failure._tag !== "PermissionNotGranted";
      return yield* new ProviderError({
        message: gone
          ? `the workspace folder ${this.workspace} no longer exists`
          : `the claude CLI could not be started (it must be on the login PATH): ${spawned.failure.message}`,
      });
    }
    const proc = spawned.success;
    handle.proc = proc;
    this.proc = proc;
    yield* Scope.addFinalizer(this.ctx.scope, this.shutdown().pipe(Effect.orDie));
    // The CLI opens its MCP server before answering initialization; the
    // line reader already handles that server's requests.
    const initialized = yield* Effect.result(this.controlRequest(this.initializeRequest()));
    if (Result.isFailure(initialized)) {
      const tail = proc.stderrTail().slice(-5).join("\n");
      yield* stop(proc, 500).pipe(Effect.ignore);
      if (this.proc === proc) this.proc = null;
      return yield* new ProviderError({
        message: this.missingResume ?? `claude did not start: ${initialized.failure.message}${tail ? `\n${tail}` : ""}`,
        ...(this.missingResume ? { sessionUnavailable: true } : {}),
      });
    }
    // One pool slot per session process, once it answered; the probe is a
    // short helper.
    if (!this.probe && proc.alive) {
      handle.processId = newId("claude-process");
      this.reportProcess(handle.processId, "started");
    }
    const response = yield* parse("Claude initialization", wire.catalog, initialized.success ?? {});
    this.capabilities = new Set([...(this.capabilities ?? []), ...(response.capabilities ?? [])]);
    const appsEnabled = this.ctx.hostFeatures?.has("mcpApps") ?? false;
    if (appsEnabled)
      yield* capabilitiesFor(this, typeof response.claude_code_version === "string" ? response.claude_code_version : null);
    this.mapper.mcp = yield* loadApps(this.id, appsEnabled && supportsApps(this.capabilities));
    yield* refreshApps(this);
    this.launched = true;
    // What the file holds now is what this process took over.
    const file = this.probe ? null : sessionFile(this.configDir, this.workspace, this.cli);
    this.read = file ? { path: file, offset: (yield* this.files.stat(file))?.size ?? 0 } : null;
    this.inbox = { offset: this.read?.offset ?? 0, heard: new Map(), other: new Set() };
    this.identity = null;
    const catalog = Catalog.fromResponse(response);
    this.catalog = catalog;
    this.emitEvent({ event: "commands", commands: catalog.slashCommands() });
    this.emitEvent({ event: "config_options", options: this.options() });
    const account = wire.objectOf(response.account);
    // A rate limit that arrives before the identity waits for it.
    this.heldLimit = null;
    this.identityKnown = this.reconciles(account) ? Deferred.makeUnsafe<void>() : given();
    // The session is ready now. What only adds to it (who is signed in,
    // the user's settings, the skills, whether ultracode holds) arrives
    // after, each as it is known. A health check has no user waiting and
    // reads both the identity and the catalog, so it waits.
    const metadata = this.loadMetadata(proc, this.identityKnown, catalog, account, env);
    if (this.probe) yield* metadata;
    else yield* metadata.pipe(Effect.forkIn(this.ctx.scope));
  });

  /// The four reads that follow `initialize`, side by side. A failure is a
  /// notice; a result for a process that is no longer the session's is
  /// dropped.
  loadMetadata = Effect.fn("Claude.loadMetadata")(function* (
    this: Session,
    proc: LineProcess,
    known: Deferred.Deferred<void>,
    catalog: Catalog,
    account: ReturnType<typeof wire.objectOf>,
    env: Record<string, string>,
  ) {
    const notice = (what: string) =>
      Effect.catchCause((cause: Cause.Cause<unknown>) =>
        Effect.sync(() => {
          if (this.proc === proc)
            this.emitEvent({
              event: "notice",
              level: "warning",
              message: `${what}: ${errorMessage(Cause.squash(cause))}`,
            });
        }),
      );
    yield* Effect.all(
      [
        this.reconciles(account)
          ? this.loadIdentity(proc, account, env).pipe(Effect.ensuring(Deferred.succeed(known, undefined)))
          : Effect.void,
        this.workflowSettings().pipe(
          Effect.map(({ enabled }) => {
            if (this.proc !== proc || catalog.workflowsOff === !enabled) return;
            catalog.workflowsOff = !enabled;
            this.emitEvent({ event: "config_options", options: this.options() });
          }),
          notice("Claude's settings could not be read"),
        ),
        this.refreshSkills().pipe(notice("Claude's skills could not be read")),
        !this.probe && this.ultracode() ? this.checkUltracode() : Effect.void,
        this.probe ? Effect.void : this.readContext(),
      ],
      { concurrency: "unbounded", discard: true },
    );
  });

  /// The identity automatic usage-limit recovery is keyed by. Custom CLI
  /// flags can change credentials/settings outside auth status's view, so
  /// only the supported native subscription configuration is reconciled.
  reconciles(account: ReturnType<typeof wire.objectOf>) {
    return (
      !!account.email &&
      account.apiProvider === "firstParty" &&
      !this.launch.extraArgs.length &&
      !this.launch.settingSources
    );
  }

  /// Reads the identity, then reports again the rate limit seen while it
  /// was being read.
  loadIdentity = Effect.fn("Claude.loadIdentity")(function* (
    this: Session,
    proc: LineProcess,
    account: ReturnType<typeof wire.objectOf>,
    env: Record<string, string>,
  ) {
    const auth = yield* Effect.result(Effect.scoped(probeAccount(env, this.workspace)));
    if (this.proc !== proc) return;
    if (Result.isSuccess(auth)) this.identity = recoveryIdentity(account, auth.success, this.configDir);
    else {
      console.debug(`claude: recovery identity could not be established: ${auth.failure.message}`);
      this.emitEvent({
        event: "notice",
        level: "warning",
        message: `Automatic recovery from usage limits is off for this session: ${auth.failure.message}`,
      });
    }
    const held = this.heldLimit;
    this.heldLimit = null;
    if (held && this.identity) this.reportLimits(held.info, held.run);
  });

  /// Reports the limits of one `rate_limit_event`. A rejection belongs to
  /// the run it arrived in, and only while that run is open.
  reportLimits(info: unknown, run: string | null) {
    const limits = fromRateLimitInfo(info, this.identity);
    if (!limits) return false;
    if (run && run === this.run && limits.recovery?.availability === "blocked")
      this.emitEvent({ event: "usage_blocked", recovery: limits.recovery });
    this.emitEvent({ event: "usage_limits", ...limits });
    return limits.recovery?.availability === "blocked";
  }

  workflowSettings = Effect.fn("Claude.workflowSettings")(function* (this: Session) {
    const dir = this.configDir;
    return workflowSettings(dir ? yield* readJson(this.files, join(dir, "settings.json")) : null);
  });

  ultracode() {
    return toggle(this.values, ULTRACODE, false);
  }

  /// Ultracode needs dynamic workflows and a model that supports it. The
  /// CLI takes it either way and quietly runs without, so the session asks
  /// what is in force and says so when it is not.
  checkUltracode = Effect.fn("Claude.checkUltracode")(function* (this: Session) {
    const response = yield* Effect.result(this.controlRequest({ subtype: "get_settings" }));
    if (Result.isFailure(response)) return;
    const settings = response.success;
    if (wire.objectOf(wire.objectOf(settings).applied).ultracode === false) {
      this.emitEvent({
        event: "notice",
        level: "warning",
        message: "Ultracode is off in this session: it needs dynamic workflows and a model that supports it.",
      });
    }
  });

  /// Reads the context window the CLI holds for the session's model and
  /// what fills it, so the meter shows from the start and moves within a
  /// turn. The window is otherwise only known from a finished turn. After
  /// a turn (`totals` false) the tokens in use stay the turn's own and
  /// only what fills them is read; after a compaction that did not say
  /// what it left, they are read too.
  readContext = Effect.fn("Claude.readContext")(function* (this: Session, totals = true) {
    const proc = this.proc;
    const response = yield* Effect.result(this.controlRequest({ subtype: "get_context_usage" }));
    if (Result.isFailure(response)) {
      console.debug(`claude: the context window could not be read: ${response.failure.message}`);
      return;
    }
    const reading = wire.objectOf(response.success);
    const { totalTokens, maxTokens } = reading;
    if (this.proc !== proc || typeof maxTokens !== "number" || typeof totalTokens !== "number") return;
    this.mapper.window = maxTokens;
    const { categories: _, autoCompactAt: __, ...reported } = this.mapper.reported ?? {};
    this.mapper.reported = {
      ...reported,
      ...(totals || !this.mapper.reported ? { usedTokens: totalTokens } : {}),
      contextWindow: maxTokens,
      ...contextContents(reading),
    };
    this.emitEvent({ event: "usage", ...this.mapper.reported });
  });

  /// Reads the workspace's skills and reports them when they changed. The
  /// list is read at startup, after each run and on commands_changed.
  refreshSkills = Effect.fn("Claude.refreshSkills")(function* (this: Session) {
    if (this.probe) return;
    const skills = yield* listSkills(this.files, this.workspace, this.configDir, this.catalog.commands);
    if (this.skills !== null && JSON.stringify(this.skills) === JSON.stringify(skills)) return;
    this.skills = skills;
    this.emitEvent({ event: "skills", skills });
  });

  // --- the wire -------------------------------------------------------------

  /// Runs `work` after everything queued before it: the CLI's lines are
  /// handled one at a time, in order, the process's end after its last
  /// line.
  queue(work: Job) {
    let done: () => void = () => {};
    this.lines = new Promise<void>((resolve) => {
      done = resolve;
    });
    if (this.reader)
      Queue.offerUnsafe(
        this.reader,
        work.pipe(
          // A malformed line must not prevent later CLI lines or its exit.
          Effect.catchCause((cause) =>
            Effect.sync(() => console.warn(`claude: handling its output failed: ${String(cause)}`)),
          ),
          Effect.ensuring(Effect.sync(done)),
        ),
      );
    return this.lines;
  }

  send(message: unknown) {
    if (!this.proc || !this.proc.alive) throw new Error("the claude process is not running");
    this.proc.send(message);
  }

  /// Sends a control request and waits for its response.
  controlRequest = Effect.fn("Claude.controlRequest")(function* (
    this: Session,
    request: unknown,
    timeout = CONTROL_TIMEOUT,
  ) {
    const id = `req-${this.nextControl++}`;
    return yield* Effect.callback<unknown, ProviderError>((resume) => {
      this.controlRequests.set(id, {
        resolve: (value) => resume(Effect.succeed(value)),
        reject: (error) => resume(Effect.fail(error)),
      });
      try {
        this.send({ type: "control_request", request_id: id, request });
      } catch (error) {
        resume(Effect.fail(new ProviderError({ message: errorMessage(error) })));
      }
    }).pipe(
      Effect.timeoutOrElse({
        duration: timeout,
        orElse: () => Effect.fail(new ProviderError({ message: "the claude process did not answer in time" })),
      }),
      Effect.ensuring(
        Effect.sync(() => {
          this.controlRequests.delete(id);
        }),
      ),
    );
  });

  respondControl(requestId: string, result: unknown, error: string | null = null) {
    const response =
      error !== null
        ? { subtype: "error", request_id: requestId, error }
        : { subtype: "success", request_id: requestId, response: result };
    try {
      this.send({ type: "control_response", response });
    } catch (failure) {
      console.warn(`claude: could not answer a control request: ${errorMessage(failure)}`);
    }
  }

  onLine = Effect.fn("Claude.onLine")(function* (this: Session, line: string) {
    if (!line.trim()) return;
    let json: unknown;
    try {
      json = JSON.parse(line);
    } catch {
      console.debug(`claude: ignoring output that is not JSON: ${line.slice(0, 200)}`);
      return;
    }
    // A field in a shape the plugin does not expect is left out, never the
    // whole line; say so, rather than pass it over as noise.
    const read = wire.readRecord(json);
    if (read === null) {
      console.warn(`claude: a CLI line that is not an object was skipped: ${line.slice(0, 200)}`);
      return;
    }
    if (read.dropped.length)
      console.warn(`claude: left out fields of a CLI line in an unexpected shape: ${read.dropped.join(", ")}`);
    const message = read.record;
    if (message.type === "assistant" && !message.parent_tool_use_id && typeof message.uuid === "string")
      this.replies.add(message.uuid);
    if (yield* sessionUpdate(this, message)) return;
    // Native startup diagnostics are distinct from arbitrary model/tool text.
    // Preserve them even when initialization has not opened a run yet.
    if (
      this.startMode.kind === "resume" &&
      message.type === "result" &&
      message.is_error === true &&
      message.subtype === "error_during_execution" &&
      message.num_turns === 0 &&
      message.errors?.includes(`No conversation found with session ID: ${this.cli}`)
    )
      this.missingResume = `No conversation found with session ID: ${this.cli}`;
    switch (message?.type) {
      case "control_response":
        this.onControlResponse(message);
        return;
      case "control_request":
        yield* this.onControlRequest(message);
        return;
      case "control_cancel_request":
        if (typeof message.request_id === "string") this.withdraw(`${this.id}${ID_SEPARATOR}${message.request_id}`);
        return;
      case "keep_alive":
        return;
      default:
        break;
    }
    if (message.type === "system" && message.subtype === "session_state_changed") {
      if (message.state === "running") this.beginOwnRun();
      return;
    }
    // A message another session sent arrives without a prompt from here,
    // and the stream only says that a command started.
    if (message.type === "command_lifecycle") {
      const id = message.command_uuid;
      if (message.state === "cancelled" && typeof id === "string") {
        const input = this.inputs.get(id);
        if (input) input.answered = true;
      }
      if (message.state === "started" && typeof id === "string" && !this.inputs.has(id)) yield* this.received(id);
      return;
    }
    // Every turn opens with `init`. The state line is not enough: while a
    // background task still runs, the CLI stays "running" after a turn's
    // `result`, so the turn that answers the task sends no new state line.
    if (message.type === "system" && message.subtype === "init") this.beginOwnRun();
    if (message.type === "result" && message.uuid && this.results.has(message.uuid)) return;
    const attributed = this.attributeInput(message);
    if (attributed && attributed !== this.run) return;
    if (message.type === "rate_limit_event") {
      const blocked = this.reportLimits(message.rate_limit_info, this.run);
      if (!Deferred.isDoneUnsafe(this.identityKnown))
        this.heldLimit = { info: message.rate_limit_info, run: this.run, blocked };
      return;
    }
    const resumed = this.mapper.resumedUnknown(message);
    if (resumed !== null) yield* this.adoptAgent(resumed);
    for (const emission of this.mapper.handle(message)) this.emitMapped(emission);
    if (this.mapper.mcp.dirty) yield* saveApps(this);
    if (this.mapper.mcp.stale) {
      this.mapper.mcp.stale = false;
      yield* refreshAppsLater(this);
    }
    // A workflow's frames say its agents moved, and a tool result can name
    // where they write.
    if (message.type === "system" || message.type === "user") yield* this.followWorkflows();
    if (this.mapper.terminalOutputs.size) {
      yield* this.readTerminals();
      if (
        !this.followingTerminals &&
        [...this.mapper.terminalOutputs.keys()].some((id) => !this.mapper.tasks.get(id)?.done)
      ) {
        this.followingTerminals = true;
        yield* Effect.gen({ self: this }, function* () {
          while (
            this.proc?.alive &&
            [...this.mapper.terminalOutputs.keys()].some((id) => !this.mapper.tasks.get(id)?.done)
          ) {
            yield* Effect.sleep(500);
            yield* this.readTerminals();
          }
        }).pipe(
          Effect.ensuring(
            Effect.sync(() => {
              this.followingTerminals = false;
            }),
          ),
          Effect.forkIn(this.ctx.scope),
        );
      }
    }
    if (message.type === "result") {
      if (message.uuid) this.results.add(message.uuid);
      // A rejection seen before the identity was known is reported again
      // with it, and only an open run takes it.
      if (this.heldLimit?.blocked && this.heldLimit.run === this.run) yield* Deferred.await(this.identityKnown);
      const cancelled = this.cancelled;
      this.cancelled = false;
      this.finishRun(runOutcome(message, cancelled));
    }
  });

  /// Echoed user UUIDs on native replies/results identify picked-up inputs,
  /// including merged steers. A replayed user line is admission/history only.
  /// Keep completed aliases so a delayed result cannot end a successor run.
  /// An agent the CLI resumes that this process never saw start is taken up
  /// from its own files, so its new run goes on in its row.
  adoptAgent = Effect.fn("Claude.adoptAgent")(function* (this: Session, cliId: string) {
    const file = sessionFile(this.configDir, this.workspace, this.cli);
    const info = file ? yield* readAgent(this.files, file.replace(/\.jsonl$/, ""), cliId) : null;
    if (info) this.mapper.adopt(cliId, info);
  });

  attributeInput(message: wire.Record): string | null {
    if (message.parent_tool_use_id) return null;
    if (message.type === "system" && message.subtype === "status" && message.status === "requesting") {
      this.requested = message.user_message_uuids ?? [];
      return null;
    }
    const thinking = message.type === "system" && message.subtype === "thinking_tokens";
    if (!thinking && !["assistant", "stream_event", "result"].includes(message.type ?? "")) return null;
    const ids = [
      ...new Set([
        ...(message.user_message_uuids ?? (message.user_message_uuid ? [message.user_message_uuid] : [])),
        ...this.requested,
      ]),
    ];
    if (message.type === "result") this.requested = [];
    const inputs = ids.flatMap((id) => {
      const input = this.inputs.get(id);
      return input ? [{ id, input }] : [];
    });
    if (!inputs.length) return null;
    const observed =
      !message.error &&
      (message.type === "assistant" ||
        thinking ||
        (message.type === "stream_event" && message.event?.type !== "ping" && message.event?.type !== "error") ||
        (message.type === "result" &&
          ((message.num_turns ?? 0) > 0 ||
            (failureMessage(message) === null &&
              (typeof message.request_sent_wall_ms === "number" || typeof message.local_command === "string")))));
    for (const { id, input } of inputs) {
      if (!input.answered) {
        // Only an input not yet picked up can move to a continuation.
        // Consumed aliases stay on the finished run even when its result
        // named just the last input rather than every merged contribution.
        if (!input.consumed && this.finishedRuns.has(input.runId) && (observed || message.type === "result")) {
          this.beginOwnRun();
          if (this.run) input.runId = this.run;
        }
        if (observed && !input.consumed) {
          input.consumed = true;
          if (input.delivery)
            for (const event of consumedInput(input.delivery, input.contextId, id))
              this.ctx.emit(agentEvent(this.id, event, { runId: input.runId }));
        }
        if (message.type === "result") input.answered = true;
      }
    }
    // A merged result may contain old aliases as well as the live input.
    // Its list order is not authority to terminate a different run.
    return inputs.find(({ input }) => input.runId === this.run)?.input.runId ?? inputs[0]?.input.runId ?? null;
  }

  onControlResponse(message: wire.Record) {
    const response = message.response;
    const id = response?.request_id;
    const entry = typeof id === "string" ? this.controlRequests.get(id) : undefined;
    if (!entry) return;
    this.controlRequests.delete(id!); // Found by this id above.
    if (response?.subtype === "error")
      entry.reject(
        new ProviderError({ message: typeof response?.error === "string" ? response.error : "control request failed" }),
      );
    else entry.resolve(response?.response ?? null);
  }

  /// The CLI asks for permission, or talks to the plugin tool server.
  /// `AskUserQuestion` is the agent asking the user something, so it
  /// becomes a question rather than an approval.
  onControlRequest = Effect.fn("Claude.onControlRequest")(function* (this: Session, message: wire.Record) {
    const request = message.request;
    const requestId = message.request_id;
    if (!request || typeof requestId !== "string") return;
    if (request.subtype === "mcp_message" && request.server_name === MCP_SERVER) {
      yield* this.onMcpMessage(requestId, request.message ?? null);
      return;
    }
    if (request.subtype === "elicitation") {
      const id = `${this.id}${ID_SEPARATOR}${requestId}`;
      try {
        const question = elicitationQuestion(id, request);
        if (!this.mapper.mcp.calling) this.beginOwnRun();
        this.pending.set(id, { kind: "elicitation", task: null, request });
        this.emitEvent({ event: "question", ...question });
      } catch (error) {
        this.respondControl(requestId, null, errorMessage(error));
        this.emitEvent({ event: "notice", level: "error", message: errorMessage(error) });
      }
      return;
    }
    if (request.subtype !== "can_use_tool") {
      // Nothing else is enabled for this client, but the CLI expects an
      // answer to every request it sends.
      this.respondControl(requestId, null, "this client supports no such control request");
      return;
    }
    const toolName = typeof request.tool_name === "string" ? request.tool_name : "";
    const input = request.input ?? null;
    const toolUseId = typeof request.tool_use_id === "string" ? request.tool_use_id : "";
    // A background subagent can ask after the turn's `result`. The CLI is
    // working and waits on the user, so this is a run Stop reaches.
    if (!this.mapper.mcp.calling) this.beginOwnRun();
    const id = `${this.id}${ID_SEPARATOR}${requestId}`;
    // A subagent's request names it by the CLI's own id; the card and the
    // subagent's row show it under the published one.
    const task = this.mapper.taskOfAgent(
      typeof request.agent_id === "string" ? request.agent_id : null,
      toolUseId || null,
    );
    const question = toolName === "AskUserQuestion";
    this.pending.set(id, question
      ? { kind: "question", input, task }
      : {
          kind: "approval", toolName, task,
          suggestions: request.permission_suggestions ?? null,
          suppressAlways: request.suppress_always_allow_rule === true,
        });
    let kind: AgentEventKind;
    if (question) {
      kind = { event: "question", ...questionRequest(id, input) };
    } else {
      if (toolUseId) this.mapper.rememberTool(toolUseId, toolName, input);
      kind = { event: "approval", ...approvalRequest(id, request) };
    }
    this.emitEvent(kind, task);
    if (task !== null) for (const emission of this.mapper.ask(task)) this.emitMapped(emission);
  });

  /// A request left the pending list: its subagent, if any, may run on.
  settled(pending: Pending | undefined) {
    if (!pending?.task) return;
    for (const emission of this.mapper.answered(pending.task)) this.emitMapped(emission);
  }

  /// The CLI gave up a request it had asked, or the plugin answered it
  /// with `decision` on its own: the card goes.
  withdraw(id: string, decision?: unknown) {
    const pending = this.pending.get(id);
    if (!pending) return;
    if (decision) this.respondControl(splitId(id)?.[1] ?? id, pending.kind === "elicitation" ? { action: "cancel" } : decision);
    this.pending.delete(id);
    this.emitEvent({ event: pending.kind === "approval" ? "approval_resolved" : "question_resolved", id }, pending.task);
    this.settled(pending);
  }

  /// Answers one MCP message for the plugin tool server. A tool call can
  /// take minutes, so it runs by itself: the reader keeps going. A
  /// notification has no MCP answer, but the control request still needs
  /// one.
  onMcpMessage = Effect.fn("Claude.onMcpMessage")(function* (this: Session, requestId: string, message: unknown) {
    // Claude Code names its tool-use id in the `_meta` of each MCP call.
    const scope = {
      agentId: this.ctx.agentId,
      sessionId: this.id,
      tools: this.additions.tools,
      callIdMeta: "claudecode/toolUseId",
    };
    // The shared MCP dispatcher is Promise-based. Its host calls are queued
    // into the provider scope so the dispatcher still uses the SDK Effect path.
    const api = {
      host: {
        tools: {
          call: (call: import("../sdk/agent.ts").HostToolCall) =>
            new Promise<unknown>((resolve) => {
              Queue.offerUnsafe(this.ctx.jobs, callHostToolEffect(call).pipe(Effect.map(resolve)));
            }),
        },
      },
    };
    yield* Effect.tryPromise({
      try: () => handleMcp(api, scope, message),
      catch: (cause) => new ProviderError({ message: errorMessage(cause) }),
    }).pipe(
      Effect.match({
        onSuccess: (answer) =>
          this.respondControl(requestId, { mcp_response: answer ?? { jsonrpc: "2.0", result: {}, id: 0 } }),
        onFailure: (error) => this.respondControl(requestId, null, error.message),
      }),
      Effect.forkIn(this.ctx.scope),
    );
  });

  /** False when the approval no longer waits (withdrawn or the turn ended). */
  respondToApproval(id: string, optionId: string): boolean {
    const pending = this.pending.get(id);
    if (!pending || pending.kind !== "approval") return false;
    this.pending.delete(id);
    const requestId = splitId(id)?.[1] ?? id;
    this.respondControl(requestId, approvalDecision(optionId, pending.toolName, pending.suggestions, pending.suppressAlways));
    this.settled(pending);
    return true;
  }

  /** False when the question no longer waits (dismissed by a steer or ended with its turn). */
  respondToQuestion(id: string, answer: Answer): boolean {
    const pending = this.pending.get(id);
    if (!pending || pending.kind === "approval") return false;
    const decision = pending.kind === "elicitation"
      ? elicitationResult(pending.request, answer)
      : answer?.cancelled
        ? DISMISSED
        : { behavior: "allow", updatedInput: answeredInput(pending.input, answer ?? { values: {} }) };
    this.pending.delete(id);
    const requestId = splitId(id)?.[1] ?? id;
    this.respondControl(requestId, decision);
    this.settled(pending);
    return true;
  }

  // --- workflows ------------------------------------------------------------

  readTerminals = Effect.fn("Claude.readTerminals")(function* (this: Session) {
    yield* this.terminalLock.withPermit(
      Effect.gen({ self: this }, function* () {
        for (const [id, path] of this.mapper.terminalOutputs) {
          const stat = yield* this.files.stat(path);
          if (!stat) continue;
          const bytes = yield* this.files.range(path, Math.max(0, stat.size - TASK_OUTPUT_LIMIT), TASK_OUTPUT_LIMIT);
          if (bytes === null) continue;
          let start = Math.max(0, bytes.length - TASK_OUTPUT_LIMIT);
          while (start < bytes.length && ((bytes[start] ?? 0) & 0xc0) === 0x80) start++;
          const output = taskOutput(new TextDecoder().decode(bytes.subarray(start), { stream: true }));
          for (const emission of this.mapper.update(id, (task) => {
            task.info.output = output;
          }))
            this.emitMapped(emission);
          if (this.mapper.tasks.get(id)?.done) this.mapper.terminalOutputs.delete(id);
        }
      }),
    );
  });

  /// Reads what the workflow agents wrote since the last look, and
  /// finishes every run whose end was reported.
  followWorkflows = Effect.fn("Claude.followWorkflows")(function* (this: Session) {
    const follows = this.mapper.workflowTranscripts();
    const ended = this.mapper.takeWorkflowOutputs();
    if (follows.length) yield* this.readTranscripts(follows);
    for (const [id, path, runId] of ended) {
      yield* this.finishWorkflow(id, path, runId).pipe(
        Effect.catchCause((cause) =>
          Effect.sync(() => console.warn(`claude: finishing workflow ${id} failed: ${String(cause)}`)),
        ),
        Effect.forkIn(this.ctx.scope),
      );
    }
  });

  /// Reads the transcripts, one reader at a time, so two readers cannot
  /// emit one file's records out of order.
  readTranscripts = Effect.fn("Claude.readTranscripts")(function* (
    this: Session,
    follows: { task: string; path: string }[],
  ) {
    yield* this.tailLock.withPermit(
      Effect.gen({ self: this }, function* () {
        for (const follow of follows) {
          const tail = this.tails.get(follow.path) ?? new Tail(this.files, follow.path);
          this.tails.set(follow.path, tail);
          const records = yield* tail.read();
          for (const emission of this.mapper.workflowRecords(follow.task, records)) this.emitMapped(emission);
        }
      }),
    );
  });

  /// The places the record of a run can be read from: the notification's
  /// `output_file` (in the CLI's temporary folder, readable when a grant
  /// covers it), then the copy the CLI keeps with the session,
  /// `<session dir>/workflows/<runId>.json`, found from the run's
  /// transcript folder `<session dir>/subagents/workflows/<runId>`.
  recordPaths(id: string, path: string, runId: string | null) {
    const paths = [path];
    const dir = this.mapper.workflowDirs.get(id);
    if (runId && typeof dir === "string") {
      const suffix = `/subagents/workflows/${runId}`;
      const trimmed = dir.replace(/\/+$/, "");
      if (trimmed.endsWith(suffix)) paths.push(`${trimmed.slice(0, -suffix.length)}/workflows/${runId}.json`);
    }
    if (runId && this.configDir) {
      const file = sessionFile(this.configDir, this.workspace, this.cli);
      if (file) paths.push(`${file.replace(/\.jsonl$/, "")}/workflows/${runId}.json`);
    }
    return [...new Set(paths)];
  }

  /// A run ended: its record gives the script's result and the final state
  /// of every agent, and each agent's transcript is read one last time,
  /// since an agent can write its last lines after its end was reported.
  finishWorkflow = Effect.fn("Claude.finishWorkflow")(function* (
    this: Session,
    id: string,
    path: string,
    runId: string | null,
  ) {
    const paths = this.recordPaths(id, path, runId);
    let output = null;
    for (let attempt = 0; attempt < OUTPUT_ATTEMPTS && output === null; attempt += 1) {
      for (const candidate of paths) {
        output = yield* readJson(this.files, candidate);
        if (output !== null) break;
      }
      if (output === null && attempt + 1 < OUTPUT_ATTEMPTS) yield* Effect.sleep(OUTPUT_RETRY);
    }
    if (output !== null) {
      const record = yield* parse("Claude workflow output", wire.workflowOutput, output);
      for (const emission of this.mapper.workflowOutput(id, record)) this.emitMapped(emission);
    } else {
      console.warn(`claude: the record of workflow ${id} never appeared (${paths.join(", ")})`);
    }
    const prefix = `${id}/`;
    const follows = this.mapper.workflowTranscripts().filter((follow) => follow.task.startsWith(prefix));
    yield* this.readTranscripts(follows);
    this.mapper.drained(id);
    for (const follow of follows) this.tails.delete(follow.path);
  });

  // --- the host's calls -----------------------------------------------------

  setOption = setOption;

  /// The account's subscription limits, as the CLI reports them now. The
  /// behaviour scan reads every transcript of the last week, and nothing
  /// here shows it.
  usageLimits = Effect.fn("Claude.usageLimits")(function* (this: Session) {
    const limits = fromUsageResponse(yield* this.controlRequest({ subtype: "get_usage", skip_behaviors: true }), this.identity);
    if (limits) return limits;
    return yield* new ProviderError({
      message: "Claude's usage service did not return the limits; it may be refusing requests for a while",
    });
  });

  /// The index of the user record a host message became, when this
  /// session sent it.
  sentAs(itemId: string) {
    return Object.hasOwn(this.sent, itemId) ? (this.sent[itemId] ?? null) : null;
  }

  prompt = Effect.fn("Claude.prompt")((input: Prompt) => this.promptLock.withPermit(this.sendPrompt(input)));

  sendPrompt = Effect.fn("Claude.sendPrompt")(function* (this: Session, input: Prompt) {
    if (input.delivery?.intent === "queue") {
      for (const event of rejectedInput(input, QUEUED_INPUT_HELD)) this.emitEvent(event);
      return yield* new ProviderError({ message: QUEUED_INPUT_HELD });
    }
    this.stopBeforeRun = false;
    // A process keeps the conversation in memory: one that does not know a
    // turn run elsewhere since it started would answer as if it never
    // happened. It starts again on the file, which has that turn. Work
    // still running in the background would be cut off, so it waits.
    if (!this.run && this.proc?.alive && ![...this.mapper.tasks.values()].some((task) => !task.done))
      if (yield* this.continuedElsewhere()) yield* this.shutdown();
    yield* this.start();
    const active = this.run;
    const runId = active ?? newId("claude-run");
    if (!active) {
      this.run = runId;
      this.cancelled = false;
    }
    // Legacy Alpha prompts have no delivery metadata, but still need native
    // UUID aliases to fence old results from later runs.
    const uuid = crypto.randomUUID();
    yield* Effect.gen({ self: this }, function* () {
      // Kept by the uuid the CLI records the prompt under: counting the
      // records before it read the whole file at every prompt, which in a
      // long conversation held each prompt back for half a minute. A prompt
      // also settles a pending rewind: it follows the record the rewind
      // went back to, so the conversation goes on from it.
      if (typeof input.itemId === "string" || this.rewound) {
        if (typeof input.itemId === "string") this.sent[input.itemId] = uuid;
        this.rewound = null;
        yield* this.ctx.store.save(this.id, { cli: this.cli, sent: this.sent, rewound: null });
      }
      if (input.context && input.delivery)
        yield* retainIngress(this.ctx.agentId, this.id, uuid, input.delivery, input.context);
      this.inputs.set(uuid, {
        delivery: input.delivery,
        contextId: input.context?.id,
        runId,
        consumed: false,
        answered: false,
      });
      const blocks = contentBlocks(input.blocks ?? []);
      if (input.context) blocks.unshift({ type: "text", text: contextText(input.context) });
      yield* Effect.try({
        try: () =>
          this.send({
            type: "user",
            uuid,
            ...(active ? { priority: "next" } : {}),
            message: { role: "user", content: blocks },
          }),
        catch: (error) => new ProviderError({ message: errorMessage(error) }),
      });
      // The CLI takes a steer in only once the question it waits on is
      // answered. As in Claude's own app, a prompt typed instead of an
      // answer dismisses the question; it goes after the prompt, so the
      // turn the dismissal resumes already has the prompt queued. A host
      // that dismisses it as well finds it gone, which is not an error.
      if (active) for (const [id, pending] of this.pending) if (pending.kind !== "approval") this.withdraw(id, DISMISSED);
    }).pipe(
      Effect.tapError((error) =>
        Effect.sync(() => {
          if (!active && this.run === runId) this.finishRun(outcome.failed(error.message));
        }),
      ),
    );
    if (!active && this.stopBeforeRun) yield* this.cancel();
    // The SDK's ordered writer only buffers this line; it gives no write
    // acknowledgement. Do not claim local_write, admission or consumption.
    return { runId };
  });

  /// Whether another program ran a turn on this conversation since the
  /// file was last read here: the file then holds a prompt this session did
  /// not send and a reply its processes did not stream.
  continuedElsewhere = Effect.fn("Claude.continuedElsewhere")(function* (this: Session) {
    const read = this.read;
    if (!read) return false;
    const after = yield* recordsAfter(this.files, read.path, read.offset);
    this.read = { path: read.path, offset: after.offset };
    return turnFromElsewhere(after.records, this.inputs, this.replies);
  });

  /// Asks the CLI to summarize the conversation. `/compact` is a slash
  /// command, so compaction is an ordinary turn whose result is a
  /// `compacted` event.
  compact() {
    return this.prompt({ blocks: [{ type: "text", text: "/compact" }] });
  }

  cancel = cancel;

  /// Stops one subagent and leaves the run going. The CLI answers with a
  /// `task_notification` of status `stopped`, which ends the task as
  /// cancelled.
  cancelTask = Effect.fn("Claude.cancelTask")(function* (this: Session, taskId: string) {
    // The CLI runs a workflow's agents inside the workflow's own task;
    // there is none of theirs to stop.
    if (this.mapper.isWorkflowAgent(taskId))
      return yield* new ProviderError({
        message: "an agent of a workflow stops with its workflow: stop the workflow instead",
      });
    const cli = this.mapper.cliTaskId(taskId);
    if (cli === null)
      return yield* new ProviderError({ message: `the subagent ${taskId} has not started in this session` });
    yield* this.controlRequest(stopTaskRequest(cli));
  });

  /// Takes back a steer the CLI still holds in its command queue. False
  /// once a turn took it in: then it goes on and is answered.
  withdrawInput = Effect.fn("Claude.withdrawInput")(function* (this: Session, inputId: string) {
    const uuid = [...this.inputs].find(([, input]) => input.delivery?.inputId === inputId && !input.consumed)?.[0];
    if (uuid === undefined) return false;
    const response = yield* this.controlRequest({ subtype: "cancel_async_message", message_uuid: uuid });
    const withdrawn = wire.objectOf(response).cancelled === true;
    if (withdrawn) this.inputs.delete(uuid);
    return withdrawn;
  });

  /// Shows the message another session sent as the command `id`, before
  /// the reply to it streams. What it says and who sent it are only in
  /// the session's file, which the CLI writes without waiting.
  received = Effect.fn("Claude.received")(function* (this: Session, id: string) {
    const path = this.read?.path;
    if (!path) return;
    for (let attempt = 0; attempt < INBOX_ATTEMPTS; attempt++) {
      const after = yield* recordsAfter(this.files, path, this.inbox.offset);
      this.inbox.offset = after.offset;
      for (const record of after.records) {
        const peer = peerMessage(record);
        if (peer) {
          if (peer.address) this.mapper.peers.set(peer.address, peer.from);
          this.inbox.heard.set(peer.id, peer);
          // A command the CLI took in on its own (the end of a background
          // task) says where it came from.
        } else if (record?.origin && typeof record.uuid === "string") this.inbox.other.add(record.uuid);
        else if (record?.attachment?.origin && typeof record.attachment.source_uuid === "string")
          this.inbox.other.add(record.attachment.source_uuid);
      }
      const peer = this.inbox.heard.get(id);
      if (peer) {
        this.inbox.heard.delete(id);
        const senders = peer.sender ? [{ id: peer.id, ...peer.sender }] : [];
        const session = (yield* this.ctx.store.senders(this.files, this.configDir, senders)).get(peer.id);
        this.emitEvent({
          event: "message_received",
          itemId: id,
          from: peer.from,
          ...(session && { fromSession: session }),
          blocks: [{ type: "text", text: peer.text }],
        });
        return;
      }
      if (this.inbox.other.delete(id)) return;
      yield* Effect.sleep(INBOX_POLL);
    }
  });

  /// Opens a run for a turn the CLI began without a prompt, such as the
  /// answer to a background task that ended. A prompted turn already has
  /// its run.
  beginOwnRun() {
    if (this.run) return;
    const runId = newId("claude-run");
    this.run = runId;
    this.cancelled = false;
    this.ctx.emit({ sessionId: this.id, runId, event: "run_started" });
  }

  /// Ends the active run once. Later calls for the same run do nothing.
  finishRun(result: RunOutcome) {
    const runId = this.run;
    if (!runId) return;
    this.run = null;
    this.finishedRuns.add(runId);
    for (const input of this.inputs.values()) {
      if (input.runId === runId && (input.consumed || result.status === "cancelled")) input.answered = true;
    }
    this.ctx.emit({ sessionId: this.id, runId, event: "run_finished", outcome: result });
    // A turn can have written a skill file.
    const warn = (message: string) => Effect.ignore({ log: "Warn", message: `claude: could not read ${message}` });
    Queue.offerUnsafe(this.ctx.jobs, this.refreshSkills().pipe(warn("the skills again")));
    // The tokens in use are the turn's own, unless a compaction left them unknown.
    if (!this.probe)
      Queue.offerUnsafe(this.ctx.jobs, this.readContext(this.mapper.context === null).pipe(warn("the context window")));
  }

  reportProcess(processId: string, state: ProcessReport["state"]) {
    this.ctx.report({
      processId,
      state,
      sessions: state === "stopped" ? [] : [this.id],
      shared: false,
      external: false,
    });
  }

  onExit(proc: LineProcess | null, status: ProcessExit | null, tail: string[]) {
    if (this.proc !== proc) return;
    this.proc = null;
    for (const [id, task] of this.mapper.tasks) {
      if (task.info.kind !== "terminal" || task.done) continue;
      for (const emission of this.mapper.update(id, (task) => {
        task.done = true;
        task.info.status = "cancelled";
        task.info.endedAt = new Date().toISOString();
      }))
        this.emitMapped(emission);
    }
    this.mapper.terminalOutputs.clear();
    this.mapper.bashTasks.clear();
    const diagnostic = `No conversation found with session ID: ${this.cli}`;
    if (this.startMode.kind === "resume" && status?.code === 1 && tail.includes(diagnostic))
      this.missingResume = diagnostic;
    for (const [, entry] of this.controlRequests) {
      entry.reject(
        new ProviderError({
          message: this.missingResume ?? "the claude process exited",
          ...(this.missingResume ? { sessionUnavailable: true } : {}),
        }),
      );
    }
    this.controlRequests.clear();
    this.pending.clear();
    let message = "the claude process exited";
    if (status && status.code !== 0 && status.code !== null) message += ` with code ${status.code}`;
    else if (status && status.signal) message += ` with signal ${status.signal}`;
    const detail = (tail ?? []).slice(-3).join(" | ");
    if (detail && status?.code !== 0) message += `: ${detail}`;
    if (this.run) {
      this.emitEvent({ event: "notice", level: "error", message });
      this.finishRun(outcome.failed(message));
    }
  }

  shutdown = Effect.fn("Claude.shutdown")(function* (this: Session) {
    const proc = this.proc;
    if (proc) yield* stop(proc, 1000).pipe(Effect.ignore);
    yield* Effect.promise(() => this.lines);
  });
}

/// Turns prompt blocks into Anthropic content blocks. The CLI expands a
/// skill only when the message's **last** content block is text that
/// starts with `/`, and only for the first such command: so the skill
/// becomes the closing text block, images come before it, and an earlier
/// skill stays inline as text for the model to start through its own tool.
export function contentBlocks(blocks: NonNullable<Prompt["blocks"]>) {
  const images: unknown[] = [];
  let text = "";
  let command = null;
  for (const block of blocks) {
    switch (block?.type) {
      case "text":
        text += block.text ?? "";
        break;
      case "file_ref":
        text += `@${block.path}`;
        break;
      case "image":
        images.push({ type: "image", source: { type: "base64", media_type: block.mimeType, data: block.data } });
        break;
      case "skill": {
        const earlier = command;
        command = block.input ? `/${block.name} ${block.input}` : `/${block.name}`;
        if (earlier !== null) text += `${earlier} `;
        break;
      }
      // Claude reads files itself, so a carried file becomes labelled text
      // rather than a second copy on disk.
      case "resource":
        text += `${block.path}:\n${block.text ?? ""}`;
        break;
      // The CLI takes no audio content block.
      case "audio":
        text += "[audio is not supported by Claude Code]";
        break;
      default:
        break;
    }
  }
  const out: unknown[] = [];
  let closing = text;
  if (command !== null) {
    if (text.trim()) out.push({ type: "text", text: text.replace(/\s+$/, "") });
    closing = command;
  }
  out.push(...images);
  if (closing || !out.length) out.push({ type: "text", text: closing });
  return out;
}

/// How a run ended, from the CLI's `result` message. After the user
/// pressed Stop the CLI reports the cut-off turn as
/// `error_during_execution`; that is the stop the user asked for.
export function runOutcome(result: wire.Record, cancelled: boolean) {
  if (cancelled) return outcome.cancelled();
  const failure = failureMessage(result);
  return failure === null ? outcome.completed() : outcome.failed(failure);
}

/// The control request that stops one task, named by the CLI's own id.
export function stopTaskRequest(cliTaskId: string) {
  return { subtype: "stop_task", task_id: cliTaskId };
}

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.