Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
import { isSdkRecord } from "../ProtocolJson.ts";
import * as Predicate from "effect/Predicate";
/**
* ClaudeAdapterLive - Scoped live implementation for the Claude Agent provider adapter.
*
* Wraps `@anthropic-ai/claude-agent-sdk` query sessions behind the generic
* provider adapter contract and emits canonical runtime events.
*
* @module ClaudeAdapterLive
*/
import { type SDKMessage } from "@anthropic-ai/claude-agent-sdk";
import { EventId, type ProviderRuntimeEvent } from "@akeru/contracts";
import * as Effect from "effect/Effect";
import { ProviderAdapterRequestError } from "../../Errors.ts";
import {
PROVIDER,
type AssistantTextBlockState,
type ToolInFlight,
type ClaudeSessionContext,
} from "./ClaudeAdapterState.ts";
import {
asRuntimeItemId,
asCanonicalTurnId,
classifyToolItemType,
summarizeToolRequest,
titleForTool,
streamKindFromDeltaType,
nativeProviderRefs,
extractAssistantTextBlocks,
extractContentBlockText,
tryParseJsonRecord,
toolInputFingerprint,
} from "./ClaudeProtocolValues.ts";
import {
isTodoTool,
extractPlanStepsFromTodoInput,
agentIdForParentToolUse,
} from "./ClaudeTasks.ts";
import { normalizeClaudeActiveTokenUsage } from "./ClaudeUsage.ts";
export function createClaudeTextStreams(deps: {
readonly randomUUIDv4: Effect.Effect<string, ProviderAdapterRequestError, never>;
readonly makeEventStamp: () => Effect.Effect<
{ eventId: EventId; createdAt: string },
ProviderAdapterRequestError,
never
>;
readonly offerRuntimeEvent: (event: ProviderRuntimeEvent) => Effect.Effect<void>;
readonly emitThreadTokenUsage: (
context: ClaudeSessionContext,
usage:
| {
readonly usedTokens: number;
readonly totalProcessedTokens?: number | undefined;
readonly maxTokens?: number | undefined;
readonly inputTokens?: number | undefined;
readonly cachedInputTokens?: number | undefined;
readonly cacheCreationTokens?: number | undefined;
readonly outputTokens?: number | undefined;
readonly reasoningOutputTokens?: number | undefined;
readonly lastUsedTokens?: number | undefined;
readonly lastInputTokens?: number | undefined;
readonly lastCachedInputTokens?: number | undefined;
readonly lastCacheCreationTokens?: number | undefined;
readonly lastOutputTokens?: number | undefined;
readonly lastReasoningOutputTokens?: number | undefined;
readonly toolUses?: number | undefined;
readonly durationMs?: number | undefined;
readonly compactsAutomatically?: boolean | undefined;
readonly autoCompactThreshold?: number | undefined;
}
| undefined,
options?: { readonly rawMethod?: string; readonly rawPayload?: unknown } | undefined,
) => Effect.Effect<void, ProviderAdapterRequestError, never>;
}) {
const ensureAssistantTextBlock = Effect.fn("ensureAssistantTextBlock")(function* (
context: ClaudeSessionContext,
blockIndex: number,
options?: {
readonly fallbackText?: string;
readonly streamClosed?: boolean;
},
) {
const turnState = context.turnState;
if (!turnState) {
return undefined;
}
const existing = turnState.assistantTextBlocks.get(blockIndex);
if (existing && !existing.completionEmitted) {
if (existing.fallbackText.length === 0 && options?.fallbackText) {
existing.fallbackText = options.fallbackText;
}
if (options?.streamClosed) {
existing.streamClosed = true;
}
return { blockIndex, block: existing };
}
const block: AssistantTextBlockState = {
itemId: yield* deps.randomUUIDv4,
blockIndex,
emittedTextDelta: false,
fallbackText: options?.fallbackText ?? "",
streamClosed: options?.streamClosed ?? false,
completionEmitted: false,
};
turnState.assistantTextBlocks.set(blockIndex, block);
turnState.assistantTextBlockOrder.push(block);
return { blockIndex, block };
});
const createSyntheticAssistantTextBlock = Effect.fn("createSyntheticAssistantTextBlock")(
function* (context: ClaudeSessionContext, fallbackText: string) {
const turnState = context.turnState;
if (!turnState) {
return undefined;
}
const blockIndex = turnState.nextSyntheticAssistantBlockIndex;
turnState.nextSyntheticAssistantBlockIndex -= 1;
return yield* ensureAssistantTextBlock(context, blockIndex, {
fallbackText,
streamClosed: true,
});
},
);
const completeAssistantTextBlock = Effect.fn("completeAssistantTextBlock")(function* (
context: ClaudeSessionContext,
block: AssistantTextBlockState,
options?: {
readonly force?: boolean;
readonly rawMethod?: string;
readonly rawPayload?: unknown;
},
) {
const turnState = context.turnState;
if (!turnState || block.completionEmitted) {
return;
}
if (!options?.force && !block.streamClosed) {
return;
}
if (!block.emittedTextDelta && block.fallbackText.length > 0) {
const deltaStamp = yield* deps.makeEventStamp();
yield* deps.offerRuntimeEvent({
type: "content.delta",
eventId: deltaStamp.eventId,
provider: PROVIDER,
createdAt: deltaStamp.createdAt,
threadId: context.session.threadId,
turnId: turnState.turnId,
itemId: asRuntimeItemId(block.itemId),
payload: {
streamKind: "assistant_text",
delta: block.fallbackText,
},
providerRefs: nativeProviderRefs(context),
...(options?.rawMethod || options?.rawPayload
? {
raw: {
source: "claude.sdk.message" as const,
...(options.rawMethod ? { method: options.rawMethod } : {}),
payload: options?.rawPayload,
},
}
: {}),
});
}
block.completionEmitted = true;
if (turnState.assistantTextBlocks.get(block.blockIndex) === block) {
turnState.assistantTextBlocks.delete(block.blockIndex);
}
const stamp = yield* deps.makeEventStamp();
yield* deps.offerRuntimeEvent({
type: "item.completed",
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
itemId: asRuntimeItemId(block.itemId),
threadId: context.session.threadId,
turnId: turnState.turnId,
payload: {
itemType: "assistant_message",
status: "completed",
title: "Assistant message",
...(block.fallbackText.length > 0 ? { detail: block.fallbackText } : {}),
},
providerRefs: nativeProviderRefs(context),
...(options?.rawMethod || options?.rawPayload
? {
raw: {
source: "claude.sdk.message" as const,
...(options.rawMethod ? { method: options.rawMethod } : {}),
payload: options?.rawPayload,
},
}
: {}),
});
});
const backfillAssistantTextBlocksFromSnapshot = Effect.fn(
"backfillAssistantTextBlocksFromSnapshot",
)(function* (context: ClaudeSessionContext, message: SDKMessage) {
const turnState = context.turnState;
if (!turnState) {
return;
}
const snapshotTextBlocks = extractAssistantTextBlocks(message);
if (snapshotTextBlocks.length === 0) {
return;
}
const orderedBlocks = turnState.assistantTextBlockOrder.map((block) => ({
blockIndex: block.blockIndex,
block,
}));
for (const [position, text] of snapshotTextBlocks.entries()) {
const existingEntry = orderedBlocks[position];
const entry =
existingEntry ??
(yield* createSyntheticAssistantTextBlock(context, text).pipe(
Effect.map((created) => {
if (!created) {
return undefined;
}
orderedBlocks.push(created);
return created;
}),
));
if (!entry) {
continue;
}
if (entry.block.fallbackText.length === 0) {
entry.block.fallbackText = text;
}
if (entry.block.streamClosed && !entry.block.completionEmitted) {
yield* completeAssistantTextBlock(context, entry.block, {
rawMethod: "claude/assistant",
rawPayload: message,
});
}
}
});
const handleStreamEvent = Effect.fn("handleStreamEvent")(function* (
context: ClaudeSessionContext,
message: SDKMessage,
) {
if (message.type !== "stream_event") {
return;
}
const { event } = message;
// Subagent-owned stream traffic (parent_tool_use_id set) must not write
// into the parent transcript: with forwardSubagentText off the SDK still
// forwards subagent tool_use/tool_result blocks and their wrapping
// text/thinking deltas, and emitting them interleaved N subagents'
// narration into the chat (live-test finding). Their results reach the
// UI via the task.* lifecycle; their tool blocks are attributed and
// re-homed by the quiet-timeline filter.
const streamParentToolUseId = message.parent_tool_use_id;
if (streamParentToolUseId !== null && streamParentToolUseId !== undefined) {
// Drop only the subagent's narration (text/thinking); tool_use blocks
// and their input_json_delta frames must flow so attributed tool items
// keep their inputs (review finding: dropping deltas emptied inputs).
const dropStart =
event.type === "content_block_start" &&
event.content_block.type !== "tool_use" &&
event.content_block.type !== "server_tool_use" &&
event.content_block.type !== "mcp_tool_use";
const dropDelta =
event.type === "content_block_delta" &&
(event.delta.type === "text_delta" || event.delta.type === "thinking_delta");
if (dropStart || dropDelta) {
return;
}
}
if (event.type === "message_delta") {
if (message.parent_tool_use_id !== null && message.parent_tool_use_id !== undefined) {
return;
}
const snapshot = normalizeClaudeActiveTokenUsage(
event.usage,
context.lastKnownContextWindow,
context.lastKnownTotalProcessedTokens,
);
yield* deps.emitThreadTokenUsage(context, snapshot, {
rawMethod: "claude/stream_event/message_delta",
rawPayload: message,
});
return;
}
if (event.type === "content_block_delta") {
if (
(event.delta.type === "text_delta" || event.delta.type === "thinking_delta") &&
context.turnState
) {
const deltaText =
event.delta.type === "text_delta"
? event.delta.text
: Predicate.isString(event.delta.thinking)
? event.delta.thinking
: "";
if (deltaText.length === 0) {
return;
}
const streamKind = streamKindFromDeltaType(event.delta.type);
const assistantBlockEntry =
event.delta.type === "text_delta"
? yield* ensureAssistantTextBlock(context, event.index)
: context.turnState.assistantTextBlocks.get(event.index)
? {
blockIndex: event.index,
block: context.turnState.assistantTextBlocks.get(event.index),
}
: undefined;
if (assistantBlockEntry?.block && event.delta.type === "text_delta") {
assistantBlockEntry.block.emittedTextDelta = true;
}
const stamp = yield* deps.makeEventStamp();
yield* deps.offerRuntimeEvent({
type: "content.delta",
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
turnId: context.turnState.turnId,
...(assistantBlockEntry?.block
? {
itemId: asRuntimeItemId(assistantBlockEntry.block.itemId),
}
: {}),
payload: {
streamKind,
delta: deltaText,
},
providerRefs: nativeProviderRefs(context),
raw: {
source: "claude.sdk.message",
method: "claude/stream_event/content_block_delta",
payload: message,
},
});
return;
}
if (event.delta.type === "input_json_delta") {
const tool = context.inFlightTools.get(event.index);
if (!tool || !Predicate.isString(event.delta.partial_json)) {
return;
}
const partialInputJson = tool.partialInputJson + event.delta.partial_json;
const parsedInput = tryParseJsonRecord(partialInputJson);
const detail = parsedInput ? summarizeToolRequest(tool.toolName, parsedInput) : tool.detail;
let nextTool: ToolInFlight = {
...tool,
partialInputJson,
...(parsedInput ? { input: parsedInput } : {}),
...(detail ? { detail } : {}),
};
const nextFingerprint =
parsedInput && Object.keys(parsedInput).length > 0
? toolInputFingerprint(parsedInput)
: undefined;
context.inFlightTools.set(event.index, nextTool);
if (
!parsedInput ||
!nextFingerprint ||
tool.lastEmittedInputFingerprint === nextFingerprint
) {
return;
}
nextTool = {
...nextTool,
lastEmittedInputFingerprint: nextFingerprint,
};
context.inFlightTools.set(event.index, nextTool);
const stamp = yield* deps.makeEventStamp();
yield* deps.offerRuntimeEvent({
type: "item.updated",
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
itemId: asRuntimeItemId(nextTool.itemId),
payload: {
itemType: nextTool.itemType,
status: "inProgress",
title: nextTool.title,
...(nextTool.detail ? { detail: nextTool.detail } : {}),
...(nextTool.agentId ? { agentId: nextTool.agentId } : {}),
...(nextTool.parentToolUseId ? { parentToolUseId: nextTool.parentToolUseId } : {}),
data: {
toolName: nextTool.toolName,
input: nextTool.input,
},
},
providerRefs: nativeProviderRefs(context, {
providerItemId: nextTool.itemId,
}),
raw: {
source: "claude.sdk.message",
method: "claude/stream_event/content_block_delta/input_json_delta",
payload: message,
},
});
// Emit plan update when TodoWrite input is parsed
if (parsedInput && isTodoTool(nextTool.toolName)) {
const planSteps = extractPlanStepsFromTodoInput(parsedInput);
if (planSteps && planSteps.length > 0) {
const planStamp = yield* deps.makeEventStamp();
yield* deps.offerRuntimeEvent({
type: "turn.plan.updated",
eventId: planStamp.eventId,
provider: PROVIDER,
createdAt: planStamp.createdAt,
threadId: context.session.threadId,
...(context.turnState
? {
turnId: asCanonicalTurnId(context.turnState.turnId),
}
: {}),
payload: {
plan: planSteps,
},
providerRefs: nativeProviderRefs(context),
});
}
}
}
return;
}
if (event.type === "content_block_start") {
const { index, content_block: block } = event;
if (block.type === "text") {
yield* ensureAssistantTextBlock(context, index, {
fallbackText: extractContentBlockText(block),
});
return;
}
if (
block.type !== "tool_use" &&
block.type !== "server_tool_use" &&
block.type !== "mcp_tool_use"
) {
return;
}
const toolName = block.name;
const itemType = classifyToolItemType(toolName);
const toolInput = isSdkRecord(block.input) && block.input !== null ? block.input : {};
const itemId = block.id;
const detail = summarizeToolRequest(toolName, toolInput);
const inputFingerprint =
Object.keys(toolInput).length > 0 ? toolInputFingerprint(toolInput) : undefined;
// Attribute tools that ran inside a subagent to their owning agent so
// clients can re-home them out of the main timeline (quiet-timeline
// guarantee): the SDK forwards subagent tool_use blocks tagged with the
// spawning Task tool's id as parent_tool_use_id.
const parentToolUseId = message.parent_tool_use_id ?? undefined;
const owningAgentId = agentIdForParentToolUse(context.taskAgents, parentToolUseId);
const tool: ToolInFlight = {
itemId,
itemType,
toolName,
title: titleForTool(itemType),
detail,
input: toolInput,
partialInputJson: "",
...(inputFingerprint ? { lastEmittedInputFingerprint: inputFingerprint } : {}),
...(owningAgentId ? { agentId: owningAgentId } : {}),
...(parentToolUseId ? { parentToolUseId } : {}),
};
context.inFlightTools.set(index, tool);
const stamp = yield* deps.makeEventStamp();
yield* deps.offerRuntimeEvent({
type: "item.started",
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
itemId: asRuntimeItemId(tool.itemId),
payload: {
itemType: tool.itemType,
status: "inProgress",
title: tool.title,
...(tool.detail ? { detail: tool.detail } : {}),
...(tool.agentId ? { agentId: tool.agentId } : {}),
...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),
data: {
toolName: tool.toolName,
input: toolInput,
},
},
providerRefs: nativeProviderRefs(context, {
providerItemId: tool.itemId,
}),
raw: {
source: "claude.sdk.message",
method: "claude/stream_event/content_block_start",
payload: message,
},
});
return;
}
if (event.type === "content_block_stop") {
const { index } = event;
const assistantBlock = context.turnState?.assistantTextBlocks.get(index);
if (assistantBlock) {
assistantBlock.streamClosed = true;
yield* completeAssistantTextBlock(context, assistantBlock, {
rawMethod: "claude/stream_event/content_block_stop",
rawPayload: message,
});
return;
}
const tool = context.inFlightTools.get(index);
if (!tool) {
return;
}
}
});
return {
ensureAssistantTextBlock,
createSyntheticAssistantTextBlock,
completeAssistantTextBlock,
backfillAssistantTextBlocksFromSnapshot,
handleStreamEvent,
};
}