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

Permissions in 0.2.7

  • 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.ts26 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 type { PluginServices } from "divergence/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, isLocalCommandOutput, recordsToItems, timestamp } from "./records.ts";
import { attachSubagents } from "./subagents.ts";
import { attachWorkflows } from "./workflow.ts";
import type { McpApps } from "./mcp.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;
}

/// The session whose transcript `path` is, for a path of the form
/// `<config dir>/projects/<workspace folder>/<session>.jsonl`, else `null`
/// (a subagent's file is a folder deeper).
export function transcriptSession(path: string) {
  const parts = path.split("/");
  const name = parts.at(-1) ?? "";
  return parts.at(-3) === "projects" && name.endsWith(".jsonl") ? name.slice(0, -".jsonl".length) : null;
}

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

/// What a `Summary` has taken from the records so far, small enough to
/// keep for every transcript between listings (`Scans`).
export interface SummaryState {
  records: number;
  title: string | null;
  custom: string | null;
  /// The first line of the first prompt, already cut to a title's length.
  prompt: string | null;
  createdAt: string | null;
  updatedAt: string | 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;
}

/// Title, first and last activity of a transcript, taken a record at a
/// time.
class Summary {
  state: SummaryState;
  constructor(state?: SummaryState) {
    this.state = state
      ? { ...state }
      : { records: 0, title: null, custom: null, prompt: null, createdAt: null, updatedAt: null, first: null };
  }

  get first() {
    return this.state.first;
  }

  add(record: wire.Record) {
    const state = this.state;
    state.records += 1;
    if (
      state.first === null &&
      (record?.type === "user" || record?.type === "assistant") &&
      record.isSidechain !== true &&
      typeof record.uuid === "string"
    )
      state.first = record.uuid;
    if (record?.type === "custom-title" && typeof record.customTitle === "string") state.custom = record.customTitle;
    else if (record?.type === "ai-title" && typeof record.aiTitle === "string") state.title = record.aiTitle;
    else if (record?.type === "user" && state.prompt === null && record.isSidechain !== true) {
      const text = firstText(record.message?.content);
      if (text !== null) {
        const chars = [...(text.split("\n").find((line) => line.trim()) ?? "").trim()];
        state.prompt = chars.length > 80 ? `${chars.slice(0, 80).join("")}…` : chars.join("");
      }
    }
    const time = timestamp(record);
    if (time !== null) {
      state.createdAt ??= time;
      state.updatedAt = time;
    }
  }

  result(id: string) {
    const state = this.state;
    if (!state.records) return null;
    const chosen = state.custom ?? state.title ?? state.prompt;
    const out: SessionSummary = { id };
    if (chosen !== null) out.title = chosen;
    if (state.createdAt !== null) out.createdAt = state.createdAt;
    if (state.updatedAt !== null) out.updatedAt = state.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 };
});

/// What listing took from one transcript: the summary of its whole lines
/// and the byte where they end.
export interface Scan {
  end: number;
  summary: SummaryState;
}

/// The scans of one workspace folder's transcripts, by file name.
export type Scans = Record<string, Scan>;

/// Where listings keep their scans, so the next one, in this launch or a
/// later one, reads only what the CLI appended since. A folder can hold
/// gigabytes of transcripts, and reading them all again took seconds of
/// this plugin's only thread at every listing.
export interface ScanStore {
  load(dir: string): Effect.Effect<Scans, never, PluginServices>;
  save(dir: string, scans: Scans): Effect.Effect<void, never, PluginServices>;
}

/// Scans kept for this plugin's life only, which tests use.
export function memoryScans(): ScanStore {
  const kept = new Map<string, Scans>();
  return {
    load: (dir) => Effect.sync(() => kept.get(dir) ?? {}),
    save: (dir, scans) => Effect.sync(() => void kept.set(dir, scans)),
  };
}

/// `summarize` of the transcript at `path` of `size` bytes, read a piece
/// at a time: a transcript can be hundreds of megabytes, and listing a
/// workspace reads several at once. `kept`, the scan of an earlier
/// listing, is carried on from where it ended; the CLI only appends, so a
/// file shorter than that is read again whole.
const summarizeFile = Effect.fn("Claude.summarizeFile")(function* (
  files: Files,
  path: string,
  id: string,
  size: number,
  kept: Scan | undefined,
) {
  const from = kept && kept.end <= size ? kept : undefined;
  const summary = new Summary(from?.summary);
  let scan: Scan = from ?? { end: 0, summary: summary.state };
  if (scan.end < size || !from) {
    const { end, rest } = yield* forEachRecord(files, path, scan.end, size, (record) => summary.add(record));
    if (end !== from?.end) scan = { end, summary: { ...summary.state } };
    // A line still being written counts now and is read again next time.
    for (const record of parseLines(decoder.decode(rest))) summary.add(record);
  }
  const result = summary.result(id);
  return { scan, listed: 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. `scans`
/// keeps what each listing read, for the next.
export const listSessions = Effect.fn("Claude.listSessions")(function* (
  files: Files,
  configDir: string | null,
  workspace: string,
  scans: ScanStore = memoryScans(),
) {
  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 kept = yield* scans.load(dir);
  const read = yield* mapLimit(transcripts, 8, ({ name, size }) =>
    summarizeFile(files, join(dir, name), name.slice(0, -".jsonl".length), size, kept[name]).pipe(
      Effect.map((file) => ({ ...file, name })),
    ),
  );
  const next: Scans = Object.fromEntries(read.map(({ name, scan }) => [name, scan]));
  const names = Object.keys(next);
  if (names.length !== Object.keys(kept).length || names.some((name) => next[name] !== kept[name]))
    yield* scans.save(dir, next);
  const sessions = read.flatMap(({ listed }) => (listed ? [listed] : []));
  return nameForks(sessions).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);
});

type Linked = wire.Record & { uuid: string };

/// The records that hold the conversation together: each names the one
/// before it (`parentUuid`).
function linked(record: wire.Record): record is Linked {
  const type = record?.type;
  return (
    typeof record?.uuid === "string" &&
    (type === "user" || type === "assistant" || type === "attachment" || type === "system" || type === "progress")
  );
}

/// The record before `record`. A compaction starts the chain again (its
/// `parentUuid` is null) and names the record it followed as its
/// `logicalParentUuid`: the chat still shows what came before it.
function previous(record: wire.Record) {
  return record.parentUuid ?? record.logicalParentUuid ?? null;
}

function isToolResult(record: wire.Record) {
  const content = record.message?.content;
  return record.type === "user" && Array.isArray(content) && content.some((block) => block?.type === "tool_result");
}

/// Where the CLI resumes a conversation: each record nothing follows ends
/// under the user or assistant record nearest above it, and the latest of
/// those not written by the CLI itself (`isMeta`) or a team member wins.
function latestEnd(chain: Linked[], byUuid: Map<string, { record: Linked; at: number }>) {
  const parents = new Set(chain.map((record) => record.parentUuid));
  let latest: { record: Linked; at: number } | undefined;
  let latestTyped: typeof latest;
  for (const record of chain) {
    if (parents.has(record.uuid)) continue;
    const seen = new Set<string>();
    let entry = byUuid.get(record.uuid);
    while (entry && !seen.has(entry.record.uuid) && entry.record.type !== "user" && entry.record.type !== "assistant") {
      seen.add(entry.record.uuid);
      entry = entry.record.parentUuid ? byUuid.get(entry.record.parentUuid) : undefined;
    }
    if (!entry || seen.has(entry.record.uuid)) continue;
    if (!latest || entry.at > latest.at) latest = entry;
    if (entry.record.isMeta !== true && !entry.record.teamName && (!latestTyped || entry.at > latestTyped.at))
      latestTyped = entry;
  }
  return latestTyped ?? latest;
}

/// The records of the conversation the CLI goes on with, in file order.
/// The file keeps every branch: a rewind (`--resume-session-at`) writes the
/// next turn under an earlier record and leaves the turns it dropped where
/// they were. The CLI resumes, as the Agent SDK's `getSessionMessages`
/// reads, from its latest record (`latestEnd`) back along `parentUuid`,
/// with the other records of each assistant message on that chain and the
/// tool results that answer them (parallel tool calls hang off the chain
/// beside it). `rewound` is a rewind no prompt has followed yet: the CLI
/// wrote nothing at it, so the file still ends with the turns it dropped,
/// and the conversation ends at it instead. A record that hangs off the
/// chain without being on it is a dropped turn and is left out; one not
/// linked to the chain at all is kept.
export function liveRecords(records: wire.Record[], rewound: string | null = null) {
  const chain = records.filter(linked);
  const byUuid = new Map(chain.map((record, at) => [record.uuid, { record, at }]));
  const pending = rewound !== null && byUuid.has(rewound) ? rewound : null;
  const end = pending === null ? latestEnd(chain, byUuid) : undefined;
  const from = pending ?? end?.record.uuid;
  if (from === undefined) return records;
  const live = new Set<string>();
  const follow = (uuid: string) => {
    for (let entry = byUuid.get(uuid); entry && !live.has(entry.record.uuid);) {
      live.add(entry.record.uuid);
      const parent = previous(entry.record);
      entry = parent ? byUuid.get(parent) : undefined;
    }
  };
  follow(from);
  // What the CLI wrote after the latest reply, such as how long the turn took.
  if (end)
    for (const record of chain.slice(end.at + 1))
      if (record.parentUuid && live.has(record.parentUuid)) live.add(record.uuid);
  const messages = new Map<string, Linked[]>();
  const results = new Map<string, Linked[]>();
  const add = (map: Map<string, Linked[]>, key: string, record: Linked) => {
    const list = map.get(key);
    if (list) list.push(record);
    else map.set(key, [record]);
  };
  for (const record of chain) {
    if (record.type === "assistant" && record.message?.id) add(messages, record.message.id, record);
    else if (record.parentUuid && isToolResult(record)) add(results, record.parentUuid, record);
  }
  for (const uuid of [...live]) {
    const record = byUuid.get(uuid)!.record;
    if (record.type !== "assistant" || !record.message?.id) continue;
    for (const sibling of messages.get(record.message.id) ?? []) {
      live.add(sibling.uuid);
      for (const result of results.get(sibling.uuid) ?? []) live.add(result.uuid);
    }
  }
  // Whether each record off the chain hangs off it, worked out once each.
  const hangs = new Map<string, boolean>();
  const hangsOff = (record: Linked) => {
    const path = new Set<string>();
    let answer = false;
    for (let entry = byUuid.get(record.uuid); entry;) {
      const uuid = entry.record.uuid;
      if (live.has(uuid)) {
        answer = true;
        break;
      }
      if (hangs.has(uuid) || path.has(uuid)) {
        answer = hangs.get(uuid) ?? false;
        break;
      }
      path.add(uuid);
      const parent = previous(entry.record);
      entry = parent ? byUuid.get(parent) : undefined;
    }
    for (const uuid of path) hangs.set(uuid, answer);
    return answer;
  };
  return records.filter((record) => !linked(record) || live.has(record.uuid) || !hangsOff(record));
}

/// `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`. `rewound` is as in `liveRecords`.
export const readSessionFile = Effect.fn("Claude.readSessionFile")(function* (
  files: Files,
  path: string,
  options: { tail?: Tail; tasks: ReadonlySet<string> | "all"; rewound?: string | null; mcp?: McpApps },
) {
  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 = liveRecords(
    read.records.filter((record) => record?.isSidechain !== true),
    options.rewound ?? null,
  );
  const items = recordsToItems(records, options.mcp);
  const sessionDir = path.replace(/\.jsonl$/, "");
  const omitted = yield* attachSubagents(files, items, records, sessionDir, options.tasks);
  yield* attachWorkflows(files, items, records, sessionDir);
  options.mcp?.decorateHistory(items);
  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) || isLocalCommandOutput(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.