/** * One-shot Claude Code CLI subagent lifecycle: spawn `claude -p ""` * through the subprocess seam under the harness's scoped home, capture its * JSON result as the run output, and dispose to whole-tree quiescence. * Mirrors the kimi/codex providers: every accepted run is a fresh process * and a fresh claude session; there is no continuation across runs. * * The provider name `claude-local` avoids colliding with the official * `subagent-claude-code` package's provider name `claude-code` — a * composition that mounts both would fail loud with DUPLICATE_PROVIDER. The * tool row in this bundle's patch takes the official model-facing name * `subagent_claude_code` instead: the official preset row ships disabled, * and the patch disables it too (a deliberate user re-enable conflicts * loud, by design). * @module @khorsheed/dsh-local-agent-claude-code/claude-cli-provider */ import type { ContentBlock, TokenUsage } from '@deepseek-ai/dsh-llm'; import type { TodoItem } from '@deepseek-ai/dsh-tool-todo'; import { type ResolvedSubagentStartRequest, type SubagentCapabilities, type SubagentProvider, type SubagentRun, type SubagentStartRequest, type SubagentStopReason } from '@deepseek-ai/dsh-subagent'; import type { Context } from '@deepseek-ai/cordis'; import type { Session } from '@deepseek-ai/dsh-session'; import type { SubprocessHandle, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess'; import { type MirrorSource } from '@khorsheed/dsh-local-agent'; import type { DelegationExecTarget, LocalAgentToolCalls, LocalAgentToolTiming } from '@khorsheed/dsh-local-agent/types'; import type { ClaudeLiveDriver } from './live-driver.ts'; import type { ClaudeEndpointAuth } from './endpoint-auth.ts'; /** Default POSIX grace between subprocess termination tiers. */ export declare const DEFAULT_DISPOSE_GRACE_MS = 3000; /** * Auth-shaped failure signatures in claude's result error or stderr: the * endpoint rejected the credential (401/403, revoked key). Matches the CLI's * own phrasing ("Failed to authenticate. API Error: 401 …", the * `authentication_failed` error tag) plus the relay phrasings seen in the * wild ("invalid x-api-key" and friends). Narrow on purpose — matched against * provider-controlled error strings only. */ export declare const CLAUDE_AUTH_FAILURE: RegExp; /** * The MCP tool-call bound for a member's claude process (`MCP_TOOL_TIMEOUT`, * ms): a bridge call may wait up to 30 minutes for the human's answer. */ export declare const MEMBER_TOOL_TIMEOUT_MS: string; /** * Member channel registration for one claude process lifetime: mint the * per-run token and build the bridge MCP declaration for the spawn argv * (`--mcp-config ` — verified end-to-end against the real CLI). * Nothing is written to the scoped home and there is nothing to prune at * settle; `release` only invalidates the token. Returns undefined when the * mounted core predates the member channel (declare-and-degrade). The exec * driver registers per round; the live driver registers per resident * process and releases on reclaim. */ export interface ClaudeMemberRunHandle { readonly token: string; readonly mcpConfig: string; readonly allowedTool: string; release(): void; } /** Register one member run with the channel; see {@link ClaudeMemberRunHandle}. */ export declare function registerClaudeMemberRun(ctx: Context, childSessionId: string, parentSessionId: string): ClaudeMemberRunHandle | undefined; /** * The version `claude --version` reports, probed through the shared subprocess * seam against the SCOPED config directory (never the user's own * installation) and cached by the family probe against the executable's * identity. The effective-settings snapshot uses it; a settled round prefers * the version its own stream named. * @param ctx - host context carrying the subprocess seam. * @param homeDir - the harness's scoped home. * @returns the version, or undefined when the CLI cannot be asked. */ export declare function claudeCliVersion(ctx: Context, homeDir: string): Promise; export declare class ClaudeCliProvider implements SubagentProvider { private readonly ctx; private readonly permissionMode; private readonly endpoint?; private readonly live?; private readonly model?; readonly name = "claude-local"; readonly capabilities: SubagentCapabilities; readonly inheritsParentContext = false; /** * @param live - the live driver, or a resolver returning the current * generation's driver per member (the settings toggle swaps generations; * a resolver may return undefined to steer one member's round to exec * while a retiring generation still hosts it). * @param endpoint - resolver for the round's endpoint credential (endpoint-auth.ts: * the scope's endpoint-auth.json over the plugin config triple), read PER * ROUND against the round's scoped home, so a key rotation or a profile * edit takes effect on the next delegation without a reload. Absent, no * `ANTHROPIC_*` variables reach the child at all. * @param model - resolver for the member's effective model, read PER ROUND * so a settings-card write or a composer switch takes effect on the next * delegation without a reload. Receives the member (the child session id) * and the round's delegation-layer model, and answers in the family's * order — session-level override, delegation, settings. Absent (the * resolver not passed), the delegation's own model still rides, exactly * as before the key existed. */ constructor(ctx: Context, permissionMode?: 'skip' | 'normal', endpoint?: ((homeDir: string) => Promise) | undefined, live?: ClaudeLiveDriver | ((childSessionId: string) => ClaudeLiveDriver | undefined) | undefined, model?: ((childSessionId: string, delegationModel?: string) => string | undefined) | undefined); /** Resolve the live driver for one round's member, if live is on for it. */ private liveDriver; /** The round's model fragment for the exec spawn spec (see {@link resolveRoundModel}). */ private roundModel; /** Per-round member-channel registration for the exec path (see {@link registerClaudeMemberRun}). */ private memberRun; start(request: ResolvedSubagentStartRequest): Promise; /** Fresh round: record the child session, spawn `claude -p`, append after settle. */ private startClaudeFresh; /** Resume round: continue the recorded claude session inside the existing child session. */ private startClaudeResume; } /** Fully resolved inputs for one Claude CLI run. */ export interface ClaudeCliRunSpec { /** Parent Session workspace; also the claude process cwd. */ readonly cwd: string; /** * Explicit environment layered after the shared credential scrub; an * `undefined` value tombstones an inherited ambient entry, a string * restores or overrides it. */ readonly env: Readonly; /** * Run the CLI inside this container instead of on the host: the argv below * is wrapped in `docker exec` and {@link env} is forwarded through NAME-only * `-e` flags. Absent means the host spawn, unchanged. */ readonly exec?: DelegationExecTarget | undefined; /** Resolved endpoint label for diagnostics; absent means the CLI default. */ readonly endpointLabel?: string | undefined; /** Permission mode passed to `claude -p`. */ readonly permissionMode: 'skip' | 'normal'; /** * Model this round runs with, passed as `claude -p --model `. Absent * means no `--model` on the argv at all: the scoped `settings.json`'s own * `model` (or, with none, the CLI's built-in default) decides, exactly as * before the key existed. */ readonly model?: string | undefined; readonly effort?: string | undefined; readonly controlled?: boolean; /** Subprocess termination grace passed to the shared process-tree owner. */ readonly disposeGraceMs: number; /** Shared subprocess service spawn operation. */ readonly spawn: (spec: SubprocessSpawnSpec) => SubprocessHandle; /** Diagnostic sink for a post-publication error flattened into a result. */ readonly onError?: (error: Error, stopReason: SubagentStopReason) => void; /** * Called when the settled failure is auth-shaped (the endpoint rejected the * credential — a 401/403 a presence probe cannot see). The provider wires * this to the family registry's auth-failure mark. */ readonly onAuthFailure?: ((detail: string) => void) | undefined; /** * Called when the round SETTLED COMPLETED — the CLI reached its endpoint and * produced an answer, which is the only evidence a host has that the scoped * credential is live. The provider wires this to the family registry's * auth-success mark (the `verified` credential grade). */ readonly onAuthSuccess?: (() => void) | undefined; /** * The version the executable reports, resolved lazily and cached by the * family probe. Only consulted when the round's own stream named none. */ readonly cliVersion?: (() => Promise) | undefined; /** * Member channel: the bridge MCP declaration for this run, injected as * `--mcp-config ` plus a `--allowedTools` entry for the bridge's one * tool (claude `-p` auto-denies permission prompts). Absent on a core that * predates the member channel — the argv is then exactly the pre-channel * shape. */ readonly member?: { readonly mcpConfig: string; readonly allowedTool: string; } | undefined; /** dsh subagent session recording this delegation; its response is appended after settle. */ readonly childSession?: Session | undefined; /** Host context carrying session persistence. */ readonly ctx?: Context | undefined; /** * The scoped home the CLI runs against (the `CLAUDE_CONFIG_DIR` value on the * host side). With it, the member's own `Agent`/`Task` subagents are * mirrored at settle from the CLI's `subagents/` records * (subagent-mirror.ts); absent, they are not. */ readonly homeDir?: string | undefined; /** * Resume round: continue the session named by `cliSessionId` with * `claude -p --resume ` instead of a fresh `claude -p`, * appending this round into the same child session under the given turn. */ readonly resume?: { readonly cliSessionId: string; readonly turn: number; } | undefined; /** * Called after the run settles with the claude session id parsed from the * result JSON (absent when none was reported). The fresh path uses it to * record the delegation so a later resume round can continue the session. */ readonly onSessionId?: ((sessionId: string | undefined) => void) | undefined; /** * Called once per settled round, after the output stream has been fully * parsed and mirrored: the round's observed model identifier and token * usage, each absent when the stream yielded none. The provider wires this * to the registry's observation channel (`recordRoundSettled` — the * delegation record's `observedModel` merge and the `settled` run-progress * event). Fires for fresh and resume rounds alike, on every terminal state. */ readonly onRoundSettled?: ((round: { readonly observedModel?: string; readonly usage?: TokenUsage; /** The CLI's own whole-round total, when its stream reported one (never a fallback or a sum). */ readonly providerReportedUsage?: TokenUsage; readonly toolCalls?: LocalAgentToolCalls; }) => void) | undefined; } /** * Validate and join the one-shot task before crossing the process boundary. * @param prompt - task content accepted from the shared subagent service. * @returns the joined non-empty text. */ export declare function textTask(prompt: readonly ContentBlock[]): string; /** A coarse model-content interval reconstructed from consecutive CLI events. */ export interface ClaudeGenerationTiming { startedAt: number; endedAt: number; } /** One ordered transcript line from a `claude --output-format stream-json` stream. */ export type ClaudeTranscriptLine = { kind: 'think'; text: string; streamId?: string; messageId?: string; usage?: TokenUsage; generation?: ClaudeGenerationTiming; } | { kind: 'text'; text: string; streamId?: string; messageId?: string; usage?: TokenUsage; generation?: ClaudeGenerationTiming; } /** * Tool activity: one `tool_use` with its (possibly still pending) * `tool_result`. `id` is the stream's tool_use id when present, else a * synthesized position-based id — stable within a run either way, so the * child session's `tool/call`/`tool/result` events pair by it. `usage` is * the API call's own accounting (claude reports it inline on every * assistant event): it rides the call's LAST folded line — a tool-only * call's lands on the tool line's advertising message. `messageId` groups * the per-block events of ONE API call (claude emits one assistant event * per content block, each repeating the message's usage). `timing` preserves * the provider timestamps as the execution interval. */ | { kind: 'tool'; id: string; name: string; args?: string; result?: string; messageId?: string; usage?: TokenUsage; timing?: LocalAgentToolTiming; generation?: ClaudeGenerationTiming; }; /** Group the lines of one API call (consecutive lines sharing a message id). * Lines without an id stay singleton units (the pre-grouping shape). */ export declare function groupClaudeTranscriptLines(lines: readonly ClaudeTranscriptLine[]): ClaudeTranscriptLine[][]; /** Mutable fold state shared by the batch parse and the incremental parser. */ interface ClaudeStreamFoldState { readonly lines: ClaudeTranscriptLine[]; /** Timestamp of the previous CLI event, used as a coarse block boundary. */ lastEventAt: number | undefined; /** tool_use id → transcript line index, so a result pairs with its own call. */ readonly callsById: Map; /** message id → the line index its usage currently rides (per-call dedupe: * claude repeats one call's usage on EVERY per-block assistant event, and * only the call's last line may keep it). */ readonly usageStamped: Map; text: string | undefined; usage: TokenUsage | undefined; sessionId: string | undefined; /** * The model identifier the stream named: the `model` field on the * `system` init event (verified against claude 2.x stream-json) or on the * terminal `result` event. Absent when neither carries one. */ model: string | undefined; /** * The CLI's own version, from the `system` init event's * `claude_code_version` (claude 2.1.x puts its whole build-info object * there, so the `VERSION` field is read out of it; a plain string is * accepted too). Absent when the stream names none — the provider then * falls back to the family's `--version` probe. */ cliVersion: string | undefined; error: string | undefined; /** Whether the stream's terminal `result` event was folded. */ completed: boolean; /** * Subagent liveness signal: the member's `Agent`/`Task` tool_use id → how * many subagent events (`parent_tool_use_id` set) the stream carried under * it. Those events are the SUBAGENT's own conversation — they never fold * into the member's lines, final answer, usage, or tool accounting; this * count is all the fold keeps of them ("that call's subagent is alive"). */ readonly subagentEvents: Map; /** * The last TodoWrite translation (last-wins within the stream). TodoWrite * blocks are intercepted BEFORE the text fold — the member's task list * crosses as a native `todo/write` snapshot, never a `[工具 TodoWrite]` line. */ todos: TodoItem[] | undefined; /** A TodoWrite whose input missed the documented shape (degraded to the text fold). */ todoSkew: boolean; /** * Tool calls this stream made, keyed by the `tool_use` block's own `name` — * claude's vocabulary verbatim (`Bash`, `Read`, `TodoWrite`, an MCP tool's * full `mcp__server__tool`), never normalized across harnesses. Counted in * the branch that already folds the block, so no event is parsed twice. */ readonly toolCalls: Map; } /** * Fold a tool-call counter into the settled shape: `{count, byName}` with the * per-name values summing to `count`. An empty map yields undefined — a * stream that named no tool call reports nothing rather than a zero it did * not observe. * @param counts - the fold's per-name tally. * @returns the settled accounting, or undefined when nothing was counted. */ export declare function toolCallsOf(counts: ReadonlyMap): LocalAgentToolCalls | undefined; /** * Translate one TodoWrite tool input into the dsh whole-list snapshot. * Claude's documented schema is `{todos: [{content, status, activeForm}]}` * with status `pending | in_progress | completed` — dsh's TodoItem vocabulary * minus `activeForm` (display-only). Unknown statuses map to `pending`; a * shape-skewed input returns undefined and the caller degrades to the plain * text fold — shape skew must never throw into the mirror. * @param input - the tool_use block's `input` payload. * @returns the dsh todo list, or undefined on shape skew. */ export declare function todosFromTodoWrite(input: unknown): TodoItem[] | undefined; /** * The CLI version named by a `system` init event's `claude_code_version`. * claude 2.1.x serializes its whole build-info module there * (`{ VERSION, BUILD_TIME, GIT_SHA, … }`), so the version is a field of it; a * future release that emits a bare string is accepted unchanged. Anything * else yields undefined and the probe answers instead. * @param value - the event's `claude_code_version` field. * @returns the version string, or undefined. */ export declare function claudeVersionFromInit(value: unknown): string | undefined; /** * The member tool call a stream-json event belongs to when it is a subagent's * (an `assistant`/`user`/`stream_event` carrying a non-empty * `parent_tool_use_id`), else undefined — the member's own events carry * `null` or nothing there. */ export declare function claudeSubagentParentId(event: { type?: unknown; parent_tool_use_id?: unknown; }): string | undefined; /** * Incremental `claude --output-format stream-json` parser: feed stdout chunks * as they arrive and the folded transcript accumulates line by line. The last * line is volatile until the terminal `result` event — a `tool_result` merges * into a pending tool line — so live consumers hold it back (see the run's * live mirror). */ export declare class ClaudeStreamParser implements ClaudeStreamFoldState { private buffer; readonly lines: ClaudeTranscriptLine[]; lastEventAt: number | undefined; readonly callsById: Map; readonly usageStamped: Map; text: string | undefined; usage: TokenUsage | undefined; sessionId: string | undefined; model: string | undefined; cliVersion: string | undefined; error: string | undefined; completed: boolean; todos: TodoItem[] | undefined; todoSkew: boolean; readonly toolCalls: Map; readonly subagentEvents: Map; /** Fold every complete NDJSON line in the chunk; the tail stays buffered. */ push(chunk: string): void; } /** * Parse a `claude -p --verbose --output-format stream-json` NDJSON stream. * Each line is one event: `system` init (carries the session id and the * model), `assistant` (content blocks: `text`, `tool_use`, `thinking`), `user` * (a `tool_result` block), and a terminal `result` (final usage, error flag, * session id). Content blocks fold into an ordered transcript (thinking, * reply text, tool calls with results), the last assistant `text` becomes the * run output, and the `result` event's usage/session id ride the parse. The * model identifier comes from the init (or result) event's `model` field. A * malformed stream or an `is_error` result yields the error instead. * @param output - the collected stdout NDJSON text. * @returns the ordered transcript, final answer text, usage, session id, the * observed model, and the error when the run reported one. */ export declare function parseClaudeStreamJson(output: string): { lines: readonly ClaudeTranscriptLine[]; text?: string; usage?: TokenUsage; error?: string; sessionId?: string; model?: string; /** The CLI version the stream's init event named, when it carried one. */ cliVersion?: string; /** The stream's last TodoWrite translation, when one was folded. */ todos?: TodoItem[]; /** Whether a shape-skewed TodoWrite degraded to the text fold. */ todoSkew?: boolean; /** The round's tool-call accounting, absent when the stream made none. */ toolCalls?: LocalAgentToolCalls; }; /** The placeholder think line for a `redacted_thinking` block (content is server-encrypted by design). */ export declare const REDACTED_THINKING_TEXT = "\uFF08\u601D\u8003\u5185\u5BB9\u5DF2\u7531\u670D\u52A1\u7AEF\u9690\u85CF\uFF1Aredacted_thinking\uFF0C\u5185\u5BB9\u6309\u8BBE\u8BA1\u4E0D\u53EF\u89C1\uFF0C\u6B64\u884C\u4EC5\u6807\u793A\u5B83\u5B58\u5728\uFF09"; /** Render a tool_use input payload as a compact command/query line. */ export declare function inputDetail(input: unknown): string | undefined; /** * Map claude's usage payload onto the shared usage contract. Claude's * `input_tokens` is the uncached input; cache reads and cache creation are * reported separately, so each maps to its own bucket with no subtraction. * When the payload carries ANY cache field, `cacheReadTokens` is always * written (0 when the read counter is absent or zero) — a reader can then * tell "no hits" from "not reported". * @param usage - the raw claude usage object. * @returns the shared usage record. */ export declare function usageFromClaude(usage: unknown): TokenUsage; /** * Start the real `claude -p` child and publish its run. The claude * result arrives as an NDJSON event stream on stdout (`--verbose * --output-format stream-json`): assistant content blocks (text, tool_use, * thinking), user tool_result blocks, and a terminal result event carrying * usage and session id. stderr is piped for diagnostics and never folded * into the run output. A resume round spawns `claude -p --resume * ` instead, continuing the same session. The run id is the * child session id for a session-backed run. * @param request - resolved shared subagent request. * @param spec - workspace, environment, process service, and diagnostic policy. * @returns the published run after the child starts. */ export declare function startClaudeCliRun(request: SubagentStartRequest, spec: ClaudeCliRunSpec): Promise; /** * The mirror source for a message the claude route writes: the model the * round observed (the stream's init event, else the model the launch * requested), or the bare `claude` label when neither is known. */ export declare function claudeMirrorSource(model?: string): MirrorSource; /** The delta-progress text for one transcript line. */ export declare function claudeLineText(line: ClaudeTranscriptLine): string; /** * Fold one API call (a message-id group) into the child session as ONE * assistant step through the core writer: a single assistant/message carrying * the call's reasoning, text and tool-call blocks, then each call's native * lifecycle, then step/end. A line still unresulted at settle folds with the * interrupted placeholder. The call's usage rides the message once — the * group's own per-call stamp wins over the round-total fallback. */ export declare function appendClaudeTranscriptGroup(childSession: Session, turn: number, step: number, group: readonly ClaudeTranscriptLine[], usage: TokenUsage | undefined, model?: string): void; export {}; //# sourceMappingURL=claude-cli-provider.d.ts.map