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
Files
records.ts16.4 KB
// Stored transcript records (`<session>.jsonl` and every subagent's file)
// mapped to transcript items (the record half of the Rust `history.rs`).
import * as wire from "./wire.ts";
import { userBlocksOnly } from "../sdk/context.ts";
import type { TranscriptItem } from "./types.ts";
import type { ContentBlock, HistoryAlias, NativeEcho, StreamedAlias, TaskInfo } from "divergence/protocol";
import { failedResult, resultContent, resultImages, resultText, toolCall } from "./tools.ts";
import { McpApps, callResults, mcpResult } from "./mcp.ts";
import { reviseReplies } from "./replies.ts";
/// A record's time as an ISO string, or `null`.
export function timestamp(record: wire.Record | undefined) {
if (typeof record?.timestamp !== "string") return null;
const time = Date.parse(record.timestamp);
return Number.isNaN(time) ? null : new Date(time).toISOString();
}
/// The first text of a message's content: the string itself, or the first
/// text block.
export function firstText(content: unknown): string | null {
if (typeof content === "string") return content;
if (Array.isArray(content)) {
const block = content.map(wire.objectOf).find((block) => block?.type === "text" && typeof block.text === "string");
return block && typeof block.text === "string" ? block.text : null;
}
return null;
}
/// The output of a local command (`/compact`, `/cost`), which the CLI
/// records as a user message. Nobody typed it, and a run never shows it.
export function isLocalCommandOutput(content: unknown) {
const text = firstText(content);
return text !== null && /^<local-command-(stdout|stderr)>/.test(text.trimStart());
}
/// A command as it was typed, out of the markup the CLI records it in:
/// `<command-name>/compact</command-name>…<command-args>keep it short</command-args>`
/// is `/compact keep it short`. Any other text is `null`.
export function typedCommand(text: string) {
if (!text.trimStart().startsWith("<command-")) return null;
const name = /<command-name>([^<]*)<\/command-name>/.exec(text)?.[1]?.trim();
if (!name) return null;
const args = /<command-args>([\s\S]*?)<\/command-args>/.exec(text)?.[1]?.trim();
const command = name.startsWith("/") ? name : `/${name}`;
return args ? `${command} ${args}` : command;
}
/// The marker the CLI records when the user stops a turn.
export function isInterruption(content: unknown) {
let text = null;
if (typeof content === "string") text = content;
else if (Array.isArray(content) && content.length === 1 && typeof wire.objectOf(content[0]).text === "string")
text = String(wire.objectOf(content[0]).text);
return text !== null && text.startsWith("[Request interrupted by user");
}
/// A message another session sent this one with `SendMessage`: stored as
/// a user record when it started a turn, or as a queued command when it
/// arrived during one, under the id the CLI's `command_lifecycle` names it
/// by. `address` is where a reply goes. A subagent's hand-back comes the
/// same way (with `senderTaskId`); its task shows it.
export function peerMessage(record: wire.Record) {
if (record?.isSidechain === true) return null;
const queued = record?.type === "attachment" && record.attachment?.type === "queued_command" ? record.attachment : null;
if (!queued && record?.type !== "user") return null;
const origin = wire.objectOf(queued ? queued.origin : record?.origin);
const id = queued ? queued.source_uuid : record?.uuid;
if (origin.kind !== "peer" || origin.senderTaskId != null || typeof origin.body !== "string" || typeof id !== "string")
return null;
return {
id,
from: typeof origin.name === "string" && origin.name ? origin.name : "another session",
address: typeof origin.from === "string" ? origin.from : null,
text: origin.body,
sender: sender(origin, timestamp(record)),
};
}
/// What tells which session sent a message (`SessionStore.senders`): the
/// process the CLI checked it came from, and when it arrived.
export interface Sender {
id: string;
pid: number;
at: number;
}
function sender(origin: Record<string, unknown>, at: string | null) {
const pid = origin.verifiedPeerPid;
return typeof pid === "number" && Number.isInteger(pid) && at ? { pid, at: Date.parse(at) } : null;
}
/// The messages from other sessions among `items`, with what tells who
/// sent each (`peerMessage`).
const senders = new WeakMap<TranscriptItem, Sender>();
export function sendersOf(items: readonly TranscriptItem[]) {
return items.flatMap((item) => {
const sender = senders.get(item);
return sender ? [{ item, sender }] : [];
});
}
type Body<T> = T extends { id: string } ? Omit<T, "id"> : never;
function item(id: string, createdAt: string | null, body: Body<TranscriptItem>) {
const out: { id: string; createdAt?: string } = { id };
if (createdAt) out.createdAt = createdAt;
return Object.assign(out, body);
}
/// An image the user sent, as the CLI stores it: its bytes in `source`.
function imageBlock(value: unknown): ContentBlock[] {
const block = wire.objectOf(value);
const source = wire.objectOf(block.source);
if (block.type !== "image" || source.type !== "base64" || typeof source.data !== "string") return [];
return [{ type: "image", mimeType: typeof source.media_type === "string" ? source.media_type : "image/png", data: source.data }];
}
/// The id a run streams each item under, when it is not the item's own
/// (`streamedAliases`).
const streamedIds = new WeakMap<TranscriptItem, string>();
/// What a run here showed under other ids: the live stream names a block
/// `<message id>:<block>` and a tool call by its own id (`map.ts`), the
/// file names a row by its record. Both come from the record itself.
export function streamedAliases(items: readonly TranscriptItem[]): StreamedAlias[] {
return items.flatMap((item) => {
const streamed = streamedIds.get(item);
const own = streamed ? [{ nativeItemId: item.id, streamedItemId: streamed }] : [];
return item.role === "task" ? [...own, ...streamedAliases(item.items ?? [])] : own;
});
}
/// The file reference a prompt carried, from the attachment the CLI read
/// the file in with: by the path the prompt names it with after its `@`,
/// from the session's folder or absolute, and a folder's with its slash.
/// The CLI reads in files a prompt never named too, such as memory files.
function taggedFile(attachment: Readonly<Record<string, unknown>>, prompt: string): { type: "file_ref"; path: string }[] {
if (attachment.type !== "file" && attachment.type !== "directory" && attachment.type !== "compact_file_reference") return [];
const folder = attachment.type === "directory" ? "/" : "";
const named = [attachment.displayPath, attachment.filename, attachment.path].flatMap((path) =>
typeof path === "string" && path ? [`${path}${folder}`] : [],
);
const path = named.find((path) => {
for (let at = prompt.indexOf(`@${path}`); at >= 0; at = prompt.indexOf(`@${path}`, at + 1))
if ((at === 0 || /\s/.test(prompt[at - 1]!)) && /^(?:$|[\s,.;:!?)\]])/.test(prompt.charAt(at + 1 + path.length))) return true;
return false;
});
return path ? [{ type: "file_ref", path }] : [];
}
/// The host messages this plugin sent as prompts, by the uuid it chose for
/// each and the CLI recorded the prompt under (`Session.sent`), for every
/// prompt the read holds. The host learns the pair when the CLI takes the
/// prompt in; one it never heard of, as when the app quit during the turn,
/// otherwise leaves its stored message and the CLI's record unmatched, and
/// the history cannot be brought in. A prompt sent with context is an
/// ingress echo, which names its message instead.
export function sentAliases(
sent: Readonly<Record<string, number | string>>,
items: readonly TranscriptItem[],
echoes: readonly NativeEcho[],
): HistoryAlias[] {
const users = new Set(items.filter((item) => item.role === "user").map((item) => item.id));
for (const echo of echoes) users.delete(echo.nativeItemId);
return Object.entries(sent).flatMap(([itemId, uuid]) =>
typeof uuid === "string" && users.has(uuid) ? [{ itemId, nativeItemId: uuid }] : [],
);
}
/// Maps transcript records to items. The main conversation and every
/// subagent's own file share this. Each item is one a run streams too, so
/// the host can tell the two apart from new rows: the stop and the plan,
/// which a run shows as a host notice and the plan panel, have no row.
export function recordsToItems(records: wire.Record[], mcp = new McpApps()): TranscriptItem[] {
const items: TranscriptItem[] = [];
// The sessions that wrote to this one, so a reply names its recipient.
const peers = new Map<string, string>();
// Tool calls by id, so a `tool_result` updates the call it answers.
const calls = new Map<string, number>();
// Blocks of each message so far: the CLI writes each block of a message
// as a record of its own, and a run counts them the same way.
const blocks = new Map<string, number>();
// The message and index of the thinking block that made the last row.
let thinking: string | null = null;
// The blocks of the prompt each record after a typed prompt follows, by
// the record's uuid: the CLI chains a prompt's attachments to it.
const prompts = new Map<string, ContentBlock[]>();
for (const record of records) {
const createdAt = timestamp(record);
const uuid = typeof record?.uuid === "string" ? record.uuid : "";
const peer = peerMessage(record);
if (peer) {
if (peer.address) peers.set(peer.address, peer.from);
const received = item(peer.id, createdAt, { role: "user", blocks: [{ type: "text", text: peer.text }], from: peer.from });
if (peer.sender) senders.set(received, { id: peer.id, ...peer.sender });
items.push(received);
continue;
}
// A message sent while a turn runs is queued, and stored as an
// attachment under the uuid it was sent with. The CLI queues the end of
// a background task the same way, and a subagent's hand-back (origin
// `peer`); the task item shows those, and nobody typed them.
const queued = record?.attachment;
const origin = wire.objectOf(queued?.origin).kind;
if (
record?.type === "attachment" &&
queued?.type === "queued_command" &&
queued.commandMode !== "task-notification" &&
(origin === undefined || origin === "human")
) {
const prompt = Array.isArray(queued.prompt) ? queued.prompt : [{ type: "text", text: queued.prompt }];
const typed = userBlocksOnly(
prompt.flatMap((block): ContentBlock[] =>
typeof block?.text === "string" ? [{ type: "text", text: block.text }] : imageBlock(block),
),
);
if (queued.source_uuid && typed.length)
items.push(item(queued.source_uuid, createdAt, { role: "user", blocks: typed }));
continue;
}
const prompt = prompts.get(record?.parentUuid ?? "");
if (record?.type === "attachment" && queued && prompt) {
prompts.set(uuid, prompt);
const text = prompt.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("");
for (const ref of taggedFile(queued, text))
if (!prompt.some((block) => block.type === "file_ref" && block.path === ref.path)) prompt.push(ref);
continue;
}
const content = record?.message?.content;
if (content === undefined) continue;
if (record.type === "user") {
// What the CLI adds on its own, such as the note after an image it
// read. Nobody typed it, and a run never shows it.
// The summary that starts a compacted conversation, and what a local
// command printed.
if (record.isMeta === true || record.isCompactSummary === true || isLocalCommandOutput(content)) continue;
// The CLI writes the end of a background task into the conversation
// as a user message. Nobody typed it; the task item shows it.
if (record.origin?.kind === "task-notification") continue;
if (isInterruption(content)) continue;
const blocks: ContentBlock[] = [];
for (const block of Array.isArray(content) ? content : []) {
if (block?.type === "text") {
const text = typeof block.text === "string" ? block.text : "";
blocks.push({ type: "text", text: typedCommand(text) ?? text });
} else if (block?.type === "image") {
blocks.push(...imageBlock(block));
} else if (block?.type === "tool_result") {
const at = calls.get(block.tool_use_id ?? "");
if (at === undefined) continue;
const entry = items[at];
if (entry?.role !== "tool") continue;
const call = entry.call;
const structured = wire.structuredOf(record.toolUseResult);
callResults.set(call, mcpResult(record.toolUseResult, record.mcpMeta));
call.status = block.is_error === true || failedResult(call.name, structured) ? "failed" : "completed";
call.content = mcp.content(call.name, [
...resultContent(call.name, call.input ?? null, resultText(block.content), structured),
...resultImages(block.content),
], mcpResult(record.toolUseResult, record.mcpMeta), call.id);
}
}
if (typeof content === "string") blocks.push({ type: "text", text: typedCommand(content) ?? content });
const typed = userBlocksOnly(blocks);
if (typed.length) {
items.push(item(uuid, createdAt, { role: "user", blocks: typed }));
prompts.set(uuid, typed);
}
} else if (record.type === "assistant") {
const blocksOf = Array.isArray(content) ? content : [];
const messageId = typeof record.message?.id === "string" ? record.message.id : null;
const before = messageId ? (blocks.get(messageId) ?? 0) : 0;
blocksOf.forEach((block, position) => {
const id = `${uuid}:${position}`;
// As `map.ts` places a block: older CLIs repeat the message so far.
const index = blocksOf.length === 1 ? before : position;
if (messageId) blocks.set(messageId, Math.max(blocks.get(messageId) ?? 0, index + 1));
let row: TranscriptItem | null = null;
let streamed = messageId ? `${messageId}:${index}` : null;
if (block?.type === "text") {
const text = typeof block.text === "string" ? block.text : "";
if (text) row = item(id, createdAt, { role: "assistant", text });
} else if (block?.type === "thinking") {
const text = typeof block.thinking === "string" ? block.thinking : "";
// Right after another thinking block of its message, it joins
// that block's row, as it does live.
const last = items.at(-1);
if (text && last?.role === "reasoning" && thinking === `${messageId}:${index - 1}`) {
last.text = joinThinking(last.text, text);
thinking = `${messageId}:${index}`;
return;
}
if (text) row = item(id, createdAt, { role: "reasoning", text });
} else if (block?.type === "tool_use") {
const callId = typeof block.id === "string" ? block.id : "";
const name = typeof block.name === "string" ? block.name : "";
calls.set(callId, items.length);
const call = toolCall(callId, name, block.input ?? null, "pending", peers);
const content = mcp.content(name, call.content ?? [], undefined, callId);
if (content.length) call.content = content;
row = item(id, createdAt, { role: "tool", call });
streamed = callId || null;
}
if (!row) return;
thinking = row.role === "reasoning" && messageId ? `${messageId}:${index}` : null;
if (streamed) streamedIds.set(row, streamed);
items.push(row);
});
}
}
reviseReplies(records, items, streamedIds);
return items;
}
/// The text of two thinking blocks of one message shown as one: Claude
/// often sends a second summary of its thinking right after the first,
/// before a tool call, which read as another thought, or as a reply shown
/// as thinking. They are one paragraph apart.
export function joinThinking(before: string, after: string) {
return before + thinkingBreak(before) + after;
}
/// What goes after thinking text ending in `before` to start a paragraph.
export function thinkingBreak(before: string) {
if (!before || before.endsWith("\n\n")) return "";
return before.endsWith("\n") ? "\n" : "\n\n";
}
/// A task item: the subagent's snapshot with its own items inside, under
/// the id the host gives a task it learns about live.
export function taskItem(info: TaskInfo, items: TranscriptItem[]): TranscriptItem {
return item(`task-${info.id}`, info.startedAt ?? null, { role: "task", task: info, items });
}Versions
| Version | Published | Plugin API | Size | Permissions | Status |
|---|---|---|---|---|---|
| 0.2.7latest | Nov 21, 2026 | >=5 <6 | 207.5 KB | 4 permissions | Listed |
| 0.2.6 | Nov 16, 2026 | >=5 <6 | 206 KB | 4 permissions | Listed |
| 0.2.5 | Nov 11, 2026 | >=5 <6 | 168.3 KB | 4 permissions | Listed |
| 0.2.4 | Nov 9, 2026 | >=5 <6 | 166.1 KB | 4 permissions | Listed |
| 0.2.3 | Oct 27, 2026 | >=2 <4 | 151.6 KB | 4 permissions | Listed |
No comments yet.