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.4

Permissions in 0.2.4

  • 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

history.ts17.4 KB
// Reads the transcripts Claude Code stores itself (the Rust `history.rs`).
//
// The CLI keeps one JSONL file per session under
// `<config dir>/projects/<encoded workspace>/<session id>.jsonl`, where the
// encoding replaces every character that is not a letter, a digit or a
// hyphen with a hyphen (`/private/tmp/a_b.c` becomes `-private-tmp-a-b-c`).
// The CLI records the resolved working directory; the host already names
// a workspace by its resolved path, so the path is encoded as given.
import * as Effect from "effect/Effect";
import * as wire from "./wire.ts";
import type { Files } from "./files.ts";
import type { SessionSummary } from "./types.ts";
import { CHUNK, join, mapLimit, parseLines, readLines } from "./files.ts";
import { firstText, isInterruption, recordsToItems, timestamp } from "./records.ts";
import { attachSubagents } from "./subagents.ts";
import { attachWorkflows } from "./workflow.ts";

const NEWLINE = 10;
const decoder = new TextDecoder();

/// The folder name Claude Code uses for `workspace`.
export function encodeWorkspace(workspace: string) {
  return String(workspace).replace(/[^A-Za-z0-9-]/g, "-");
}

/// The folder of one workspace's transcripts in the configuration
/// directory `configDir`.
export function workspaceDir(configDir: string | null, workspace: string) {
  return configDir ? join(configDir, "projects", encodeWorkspace(workspace)) : null;
}

export function sessionFile(configDir: string | null, workspace: string, session: string) {
  const dir = workspaceDir(configDir, workspace);
  return dir ? join(dir, `${session}.jsonl`) : null;
}

/// Title, first and last activity of a transcript, taken a record at a
/// time.
class Summary {
  private records = 0;
  private title: string | null = null;
  private custom: string | null = null;
  private firstPrompt: string | null = null;
  private createdAt: string | null = null;
  private updatedAt: string | null = null;
  /// The uuid of the conversation's first message. A fork starts with a
  /// copy of its origin's messages, so it shares this with the origin.
  first: string | null = null;

  add(record: wire.Record) {
    this.records += 1;
    if (
      this.first === null &&
      (record?.type === "user" || record?.type === "assistant") &&
      record.isSidechain !== true &&
      typeof record.uuid === "string"
    )
      this.first = record.uuid;
    if (record?.type === "custom-title" && typeof record.customTitle === "string") this.custom = record.customTitle;
    else if (record?.type === "ai-title" && typeof record.aiTitle === "string") this.title = record.aiTitle;
    else if (record?.type === "user" && this.firstPrompt === null && record.isSidechain !== true)
      this.firstPrompt = firstText(record.message?.content);
    const time = timestamp(record);
    if (time !== null) {
      this.createdAt ??= time;
      this.updatedAt = time;
    }
  }

  result(id: string) {
    if (!this.records) return null;
    let chosen = this.custom ?? this.title;
    if (chosen === null && this.firstPrompt !== null) {
      const line = (this.firstPrompt.split("\n").find((line) => line.trim()) ?? "").trim();
      const chars = [...line];
      chosen = chars.length > 80 ? `${chars.slice(0, 80).join("")}…` : line;
    }
    const out: SessionSummary = { id };
    if (chosen !== null) out.title = chosen;
    if (this.createdAt !== null) out.createdAt = this.createdAt;
    if (this.updatedAt !== null) out.updatedAt = this.updatedAt;
    return out;
  }
}

/// Title, first and last activity of one transcript's records.
export function summarize(records: wire.Record[], id: string) {
  const summary = new Summary();
  for (const record of records) summary.add(record);
  return summary.result(id);
}

/// Calls `each` with every record in the bytes of `path` from `offset` to
/// `size`, read a piece at a time so that a long transcript is never held
/// whole as bytes, text and lines at once. Answers where the last whole
/// line ends and the bytes after it, a line still being written.
const forEachRecord = Effect.fn("Claude.forEachRecord")(function* (
  files: Files,
  path: string,
  offset: number,
  size: number,
  each: (record: wire.Record) => void,
) {
  let rest = new Uint8Array(0);
  let at = offset;
  while (at < size) {
    const piece = yield* files.range(path, at, Math.min(CHUNK, size - at));
    if (!piece?.length) break;
    const joined = new Uint8Array(rest.length + piece.length);
    joined.set(rest, 0);
    joined.set(piece, rest.length);
    const end = joined.lastIndexOf(NEWLINE);
    for (const record of parseLines(decoder.decode(joined.subarray(0, end + 1)))) each(record);
    rest = joined.subarray(end + 1);
    at += piece.length;
  }
  return { end: at - rest.length, rest };
});

/// `summarize` of the transcript at `path`, read a piece at a time: a
/// transcript can be hundreds of megabytes, and listing a workspace reads
/// several at once.
const summarizeFile = Effect.fn("Claude.summarizeFile")(function* (files: Files, path: string, id: string) {
  const stat = yield* files.stat(path);
  if (!stat) return null;
  const summary = new Summary();
  const { rest } = yield* forEachRecord(files, path, 0, stat.size, (record) => summary.add(record));
  for (const record of parseLines(decoder.decode(rest))) summary.add(record);
  const result = summary.result(id);
  return result && { summary: result, first: summary.first };
});

/// Claude Code names a fork after its origin with " (fork)" on the end, but
/// only where it shows the session itself: the fork's own file keeps the
/// origin's title. A session that starts with the same message as an older
/// one, under the same title, is given the name Claude Code shows.
export function nameForks(sessions: readonly { summary: SessionSummary; first: string | null }[]) {
  const origins = new Map<string, SessionSummary>();
  for (const { summary, first } of sessions) {
    if (first === null) continue;
    const origin = origins.get(first);
    if (!origin || (summary.createdAt ?? "") < (origin.createdAt ?? "")) origins.set(first, summary);
  }
  return sessions.map(({ summary, first }) => {
    const origin = first === null ? undefined : origins.get(first);
    const fork =
      origin !== undefined &&
      origin !== summary &&
      (origin.createdAt ?? "") < (summary.createdAt ?? "") &&
      summary.title !== undefined &&
      summary.title === origin.title;
    return fork ? { ...summary, title: `${summary.title} (fork)` } : summary;
  });
}

/// Every session Claude Code stored for `workspace`, newest first.
export const listSessions = Effect.fn("Claude.listSessions")(function* (
  files: Files,
  configDir: string | null,
  workspace: string,
) {
  const dir = workspaceDir(configDir, workspace);
  if (!dir) return [];
  const entries = yield* files.list(dir);
  if (!entries) return [];
  const transcripts = entries.filter((entry) => entry.kind !== "dir" && entry.name.endsWith(".jsonl"));
  const sessions = yield* mapLimit(transcripts, 8, (entry) =>
    summarizeFile(files, join(dir, entry.name), entry.name.slice(0, -".jsonl".length)),
  );
  return nameForks(sessions.filter((session) => session !== null)).sort((a, b) =>
    (b.updatedAt ?? "") > (a.updatedAt ?? "") ? 1 : (b.updatedAt ?? "") < (a.updatedAt ?? "") ? -1 : 0,
  );
});

/// The user messages of a transcript, sidechains aside.
export function userRecords(records: wire.Record[]) {
  return records.filter(
    (record) => record?.type === "user" && record.isSidechain !== true && record.message?.content !== undefined,
  );
}


/// Where a conversation goes back to when a user message is forgotten:
/// `{ fresh: true }` for the first message (nothing came before it, so the
/// conversation starts over), else `{ at: <the record just before it> }`.
/// `--resume-session-at` keeps the message it names, so the target is the
/// message's own parent.
export function rewindBefore(record: wire.Record) {
  return typeof record?.parentUuid === "string" ? { at: record.parentUuid } : { fresh: true };
}

/// How to rewind so that a prompt this plugin sent, and everything after
/// it, are forgotten: `sent` is the uuid the prompt went under, which the
/// CLI records it by (a prompt taken mid-turn first as a queued command),
/// or, kept by an older version, the index of its user record. `null`
/// when there is no such message.
export const rewindTargetAt = Effect.fn("Claude.rewindTargetAt")(function* (
  files: Files,
  configDir: string | null,
  workspace: string,
  session: string,
  sent: number | string,
) {
  const path = sessionFile(configDir, workspace, session);
  if (!path) return null;
  const records = yield* readLines(files, path);
  const record =
    typeof sent === "number"
      ? userRecords(records)[sent]
      : (records.find((record) => record?.type === "user" && promptId(record) === sent) ??
        records.find((record) => promptId(record) === sent));
  return record ? rewindBefore(record) : null;
});

/// The record to resume at so that the item `itemId` of the CLI's own file
/// and everything after it is forgotten. Assistant items are
/// `<uuid>:<block index>`; the record is the uuid. `null` for an item with
/// no parent or none at all: the rewind is refused, not half done.
export const rewindTarget = Effect.fn("Claude.rewindTarget")(function* (
  files: Files,
  configDir: string | null,
  workspace: string,
  session: string,
  itemId: string,
) {
  const path = sessionFile(configDir, workspace, session);
  if (!path) return null;
  const uuid = String(itemId).split(":")[0];
  const record = (yield* readLines(files, path)).find((record) => record?.uuid === uuid);
  return typeof record?.parentUuid === "string" ? record.parentUuid : null;
});

/// Parses one stored transcript into items, each subagent and workflow as
/// a task item with its own transcript inside.
export const readSession = Effect.fn("Claude.readSession")(function* (
  files: Files,
  configDir: string | null,
  workspace: string,
  session: string,
) {
  const path = sessionFile(configDir, workspace, session);
  return path ? yield* readFile(files, path) : [];
});

/// Parses the transcript at `path` (`<session id>.jsonl`), with the
/// subagents from the `<session id>/` folder beside it.
export const readFile = Effect.fn("Claude.readFile")(function* (files: Files, path: string) {
  return (yield* readSessionFile(files, path, { tasks: "all" })).items;
});

/// The records of a transcript up to its last newline, and where that is,
/// so that a later read takes only what was appended (`Tail`).
export interface Tail {
  path: string;
  offset: number;
  records: wire.Record[];
}

/// How much transcript the kept tails may cover together, in bytes. Parsed
/// records take about three times the bytes they were read from, and the
/// longest transcripts run past 100 MiB, so keeping every session read
/// (and two read at once) took the runtime past its memory limit, which
/// ends it and every Claude process it started.
export const TAIL_BUDGET = 96 * 1024 * 1024;

/// The tails of the sessions read most recently, within `budget` bytes of
/// transcript; the session read last keeps its tail even past the budget.
/// A session whose tail was let go is read whole the next time its file
/// changed, and an unchanged one is not read at all (`readSession` in
/// `agent.ts`), so the budget costs time only for an old session that is
/// read again after it grew.
export class Tails {
  private kept = new Map<string, Tail>();
  private budget: number;
  constructor(budget = TAIL_BUDGET) {
    this.budget = budget;
  }

  /// The tail of `session`, which counts as read last from now.
  get(session: string) {
    const tail = this.kept.get(session);
    if (tail) {
      this.kept.delete(session);
      this.kept.set(session, tail);
    }
    return tail;
  }

  set(session: string, tail: Tail) {
    this.kept.delete(session);
    this.kept.set(session, tail);
    let total = 0;
    for (const kept of this.kept.values()) total += kept.offset;
    // Oldest first, in the order the map was filled.
    for (const [id, kept] of this.kept) {
      if (total <= this.budget || id === session) break;
      this.kept.delete(id);
      total -= kept.offset;
    }
  }

  delete(session: string) {
    this.kept.delete(session);
  }
}

/// The records of the transcript at `path`. With the tail of an earlier
/// read of the same file, only the bytes written after it are read: the
/// CLI appends. A file that shrank, or whose byte before the tail is not
/// the newline it was, is read whole; so is the answer of a host without
/// ranged reads (the whole file, not the range asked for).
export const readRecords = Effect.fn("Claude.readRecords")(function* (files: Files, path: string, tail?: Tail) {
  const stat = yield* files.stat(path);
  if (!stat) return { records: [], tail: undefined };
  const settle = (records: wire.Record[], offset: number, rest: Uint8Array) => {
    const kept: Tail = { path, offset, records };
    // A last line with no newline yet is parsed now and read again later.
    return { records: rest.length ? [...records, ...parseLines(decoder.decode(rest))] : records, tail: kept };
  };
  if (tail && tail.path === path && tail.offset > 0 && stat.size >= tail.offset) {
    const length = stat.size - tail.offset + 1;
    const bytes = yield* files.range(path, tail.offset - 1, length);
    if (bytes && bytes.length === length && bytes[0] === NEWLINE) {
      const end = bytes.lastIndexOf(NEWLINE);
      const added = end > 0 ? parseLines(decoder.decode(bytes.subarray(1, end + 1))) : [];
      return settle(
        added.length ? [...tail.records, ...added] : tail.records,
        tail.offset + end,
        bytes.subarray(end + 1),
      );
    }
  }
  const records: wire.Record[] = [];
  const { end, rest } = yield* forEachRecord(files, path, 0, stat.size, (record) => records.push(record));
  return settle(records, end, rest);
});

/// `readFile`, reading only what was appended since `tail`, and the
/// transcripts of only the subagents in `tasks` (by task id), those still
/// running, and the ones they started; the others come with no items and
/// are listed in `omitted`.
export const readSessionFile = Effect.fn("Claude.readSessionFile")(function* (
  files: Files,
  path: string,
  options: { tail?: Tail; tasks: ReadonlySet<string> | "all" },
) {
  const read = yield* readRecords(files, path, options.tail);
  // Old CLIs wrote subagents inline as sidechain records; the current one
  // writes them to their own files, read below.
  const records = read.records.filter((record) => record?.isSidechain !== true);
  const items = recordsToItems(records);
  const sessionDir = path.replace(/\.jsonl$/, "");
  const omitted = yield* attachSubagents(files, items, records, sessionDir, options.tasks);
  yield* attachWorkflows(files, items, records, sessionDir);
  return { items, tail: read.tail, omitted };
});

/// The records written to the transcript at `path` after byte `offset`, and
/// the offset just past the last whole line of them. A line being written
/// at `offset` is skipped; one being written at the end waits for a later
/// read.
export const recordsAfter = Effect.fn("Claude.recordsAfter")(function* (files: Files, path: string, offset: number) {
  const stat = yield* files.stat(path);
  if (!stat || stat.size <= offset) return { records: [], offset: stat ? stat.size : 0 };
  const from = Math.max(0, offset - 1);
  const read = yield* files.range(path, from, stat.size - from);
  // A host without ranged reads answers with the whole file.
  const bytes = read && read.length > stat.size - from ? read.subarray(from) : read;
  if (!bytes?.length) return { records: [], offset };
  const start = from === offset ? 0 : bytes.indexOf(NEWLINE) + 1;
  const end = bytes.lastIndexOf(NEWLINE) + 1;
  if (end <= start) return { records: [], offset };
  return { records: parseLines(decoder.decode(bytes.subarray(start, end))), offset: from + end };
});

/// The id a person's prompt in `record` was sent under, or `null` for any
/// other record: a reply, a tool result, what the CLI adds on its own, the
/// end of a background task and a subagent's hand-back.
export function promptId(record: wire.Record): string | null {
  if (record?.isSidechain === true) return null;
  const queued = record?.attachment;
  if (record?.type === "attachment" && queued?.type === "queued_command") {
    const origin = wire.objectOf(queued.origin).kind;
    const human = queued.commandMode !== "task-notification" && (origin === undefined || origin === "human");
    return human && typeof queued.source_uuid === "string" ? queued.source_uuid : null;
  }
  if (record?.type !== "user" || typeof record.uuid !== "string") return null;
  if (record.isMeta === true || record.isCompactSummary === true) return null;
  const origin = record.origin?.kind;
  if (origin !== undefined && origin !== "human") return null;
  const content = record.message?.content;
  if (firstText(content) === null || isInterruption(content)) return null;
  return record.uuid;
}

/// Whether `records` hold a turn another program (the CLI in a terminal,
/// Claude's desktop app) ran on the conversation: a prompt this session did
/// not send, answered by a reply its process did not stream.
export function turnFromElsewhere(
  records: wire.Record[],
  sent: { has(id: string): boolean },
  streamed: { has(id: string): boolean },
) {
  let prompt = false;
  let reply = false;
  for (const record of records) {
    if (record?.isSidechain === true) continue;
    const id = promptId(record);
    if (id !== null && !sent.has(id)) prompt = true;
    if (record?.type === "assistant" && typeof record.uuid === "string" && !streamed.has(record.uuid)) reply = true;
  }
  return prompt && reply;
}

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.