UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

323 lines • 17.9 kB
import { createAssistantMessageDiagnostic, createAssistantMessageEventStream, } from "@earendil-works/pi-ai"; import { LONG_CONTEXT_FALLBACK_DIAGNOSTIC, LONG_CONTEXT_FALLBACK_NOTICE } from "../../../provider-notices.js"; import { getSessionClaudeAccountPin } from "./account-command.js"; import { queryWithAuthLane } from "./auth-lane.js"; import { markColdSeedOverflow } from "./cold-seed-budget.js"; import { CLAUDE_CODE_DEFAULT_CONTEXT_WINDOW } from "./context-window.js"; import { buildCustomToolServers } from "./custom-tools.js"; import { resolveQuerySettingsEnv } from "./claude-settings-env.js"; import { sdkAssistantFailure, sdkResultFailure, sdkResultFailureUsage } from "./errors.js"; import { defaultExecutableDeps, resolveClaudeCodeRun } from "./executable.js"; import { estimateLongContextFallbackTokens } from "./long-context-budget.js"; import { buildAnthropicSubscriptionQueryOptions } from "./options.js"; import { buildDeferredPromptStream, buildPromptBlocks } from "./prompt-bridge.js"; import { pinOneShotPromptCacheTtl } from "./prompt-cache-ttl.js"; import { dedupeUltraworkBlocks } from "./prompt-directive-dedupe.js"; import { refusalError } from "./refusal.js"; import { getSdkBoundary, loadClaudeAgentSdk } from "./sdk-boundary.js"; import { emitContinuityObservation } from "./session-observability.js"; import { forgetBinding } from "./session-reattach.js"; import { anthropicSubscriptionDiagnostic } from "./provider-diagnostic.js"; import { requireAnthropicSubscriptionCwd } from "./session-cwd.js"; import { residentSessionMessages } from "./session-stream.js"; import { loadAnthropicSubscriptionProviderSettingsFromDisk, resolveCompactionOwner, resumeModeSource, } from "./settings.js"; import { applyStreamEvent } from "./stream-events.js"; import { withAuthGuidance } from "./stream-guidance.js"; import { emptyOutput, errorMessage, mapStopReason, updateUsage } from "./stream-protocol.js"; import { toolWatch } from "./tool-watch.js"; import { resolveSdkTools } from "./tools.js"; export const NATIVE_COMPACTION_WHILE_SENPI_OWNS = 'Claude Code compacted this session natively although senpi owns compaction on this lane (compactionOwner: "senpi"); the turn was stopped so only one side compacts. Run /compact, or set anthropicSubscriptionProvider.compactionOwner to "sdk" to let Claude Code compact.'; export function streamAnthropicSubscription(model, context, options, recheckedAccounts) { const stream = createAssistantMessageEventStream(); void (async () => { const output = emptyOutput(model); const blocks = []; let sdkQuery; let closed = false; let wasAborted = false; let started = false; let sawStreamEvent = false; const onAttemptStart = () => { delete output.responseId; output.usage = emptyOutput(model).usage; sawStreamEvent = false; }; const closeQuery = () => { if (closed || !sdkQuery) return; closed = true; sdkQuery.close(); }; const requestAbort = () => { if (!sdkQuery) return; void sdkQuery .interrupt() .catch(() => { }) .finally(closeQuery); }; const onAbort = () => { wasAborted = true; requestAbort(); }; if (options?.signal?.aborted) onAbort(); else options?.signal?.addEventListener("abort", onAbort, { once: true }); let claudeCodeRun; let coldSeedAttempt = false; let coldSeedEstimate; let nativeCompactionStopped = false; try { const cwd = requireAnthropicSubscriptionCwd(options?.cwd); // Resident before the synchronous SDK member below (getSdkBoundary().query) // reads it - see sdk-boundary.lazy.ts. await loadClaudeAgentSdk(); const resolvedTools = resolveSdkTools(context); const affinityKey = options?.affinitySessionId ?? options?.sessionId; const sessionKey = options?.sessionId ? toolWatch.sessionKey(options.sessionId) : undefined; if (sessionKey) toolWatch.reconcileWithContext(sessionKey, context); const toolWatchNote = toolWatch.buildPromptNote(sessionKey, context, resolvedTools.customToolNameToSdk); const providerSettings = loadAnthropicSubscriptionProviderSettingsFromDisk(cwd); // The effective `env` block of the settings files this stream's queries load (senpi#2988 item 4): a // lifetime set there is what Claude Code will actually use, so the pin must see it. Resolved once per // stream; the pin only receives it for attempts whose settingSources are non-empty. const settingsEnv = await resolveQuerySettingsEnv(cwd, providerSettings); const senpiOwnsCompaction = resolveCompactionOwner(providerSettings) === "senpi"; const toolLessRequest = options?.toolChoice === "none"; const mcpServers = toolLessRequest ? undefined : await buildCustomToolServers(resolvedTools.customTools); claudeCodeRun = resolveClaudeCodeRun(defaultExecutableDeps()); const executable = claudeCodeRun.executable; let oneShotCacheTtl; const buildOptions = (authLane) => { const queryOptions = buildAnthropicSubscriptionQueryOptions({ model, context, streamOptions: options, cwd, providerSettings, authLane, tools: resolvedTools.sdkTools, pathToClaudeCodeExecutable: executable, sessionId: options?.sessionId, onGuidance: (text) => { output.diagnostics = [ ...(output.diagnostics ?? []), createAssistantMessageDiagnostic("claude_sdk_oauth_deprecation", text), ]; }, }); if (mcpServers) queryOptions.mcpServers = mcpServers; // The one-shot prompt is built after this, for the lane this attempt resolved (senpi#2982). if (!useResidentSession) { oneShotCacheTtl = pinOneShotPromptCacheTtl(queryOptions, authLane ?? providerSettings.tokenInjection ?? "ambient", { ...process.env, ...options?.env }, // Only the settings files this attempt loads can set its lifetime: managed lanes load // none, so nothing is passed there (senpi#2988). queryOptions.settingSources !== undefined && queryOptions.settingSources.length > 0 ? settingsEnv : undefined); } return queryOptions; }; const recordContinuity = (observation) => { // Not a failure: carry the observation as details only, with no synthesized error. output.diagnostics = [ ...(output.diagnostics ?? []), { type: "claude_sdk_oauth_session_continuity", timestamp: Date.now(), details: { ...observation }, }, ]; }; // The request keeps its model; only its window fell back, and the turn says so (senpi#4065). const recordLongContextFallback = () => { output.diagnostics = [ ...(output.diagnostics ?? []), { type: LONG_CONTEXT_FALLBACK_DIAGNOSTIC, timestamp: Date.now(), details: { contextWindow: CLAUDE_CODE_DEFAULT_CONTEXT_WINDOW, message: LONG_CONTEXT_FALLBACK_NOTICE, }, }, ]; }; const useResidentSession = options?.streamKind === "main" && providerSettings.resumeMode !== "off" && options.sessionId !== undefined; const contextTokens = () => estimateLongContextFallbackTokens(context, buildPromptBlocks(context, resolvedTools.customToolNameToSdk, toolWatchNote), options?.sessionId); const outputReserveTokens = options?.maxTokens; if (options?.streamKind === "main" && !useResidentSession) { // The reason must reflect the ACTUAL cause: resume mode "off" // disables the lane by setting, while any other mode simply has no // resident session to reuse yet. emitContinuityObservation({ kind: "disabled", reason: providerSettings.resumeMode === "off" ? "resume_mode_off" : "registry_miss", ...(providerSettings.resumeMode === "off" ? { settingSource: resumeModeSource(providerSettings) } : {}), }, options.sessionId, recordContinuity); } const messages = useResidentSession ? residentSessionMessages({ model, context, streamOptions: options, recheckedAccounts, providerSettings, pinnedAccount: getSessionClaudeAccountPin(options.sessionId), buildOptions, customToolNameToSdk: resolvedTools.customToolNameToSdk, toolWatchNote, onContinuityDecision: recordContinuity, onLongContextFallback: recordLongContextFallback, contextTokens, outputReserveTokens, onAttemptStart, onDispatchShape: (coldSeed, estimatedTokens) => { coldSeedAttempt = coldSeed; coldSeedEstimate = estimatedTokens; }, onResumeFallback: (error) => { output.diagnostics = [ ...(output.diagnostics ?? []), createAssistantMessageDiagnostic("claude_sdk_oauth_resume_fallback", error), ]; }, }) : queryWithAuthLane({ prompt: buildDeferredPromptStream(() => dedupeUltraworkBlocks(buildPromptBlocks(context, resolvedTools.customToolNameToSdk, toolWatchNote, oneShotCacheTtl === undefined ? {} : { cacheBreakpoint: oneShotCacheTtl })).blocks), query: getSdkBoundary().query, onAttemptStart, providerSettings, env: options?.env, recheckedAccounts, signal: options?.signal, sessionId: affinityKey, model: model.id, pinnedAccount: getSessionClaudeAccountPin(options?.sessionId), onQuery: (query) => { sdkQuery = query; if (wasAborted) requestAbort(); }, buildOptions, onLongContextFallback: recordLongContextFallback, contextTokens, outputReserveTokens, }); for await (const message of messages) { const refusal = refusalError(message); if (refusal) throw refusal; const failure = message.type === "assistant" ? sdkAssistantFailure(message) : message.type === "result" ? sdkResultFailure(message) : undefined; if (failure) throw failure; if (!started) { stream.push({ type: "start", partial: output }); started = true; } if (message.type === "stream_event") { sawStreamEvent = true; applyStreamEvent({ model, output, blocks, stream, customToolNameToPi: resolvedTools.customToolNameToPi }, message.event); } else if (message.type === "assistant") { // Same first-id-wins turn identity as applyStreamEvent's message_start (oh-my-openagent#10547). output.responseId ??= message.message.id || undefined; // SDK assistant snapshots have placeholder output counts. Never replace streamed usage with them. if (!sawStreamEvent && message.message.usage) { updateUsage(model, output, message.message.usage, "request-start"); } } else if (message.type === "system" && message.subtype === "compact_boundary") { // The query was started with native auto-compact off: a boundary here means Claude // Code compacted anyway. Fail the turn loudly instead of letting a second owner // rewrite the transcript behind senpi's compaction. if (senpiOwnsCompaction) { nativeCompactionStopped = true; throw new Error(NATIVE_COMPACTION_WHILE_SENPI_OWNS); } // Native compactions must reach the ledger: attach the boundary as a // diagnostic so the lane-policy collector can build a ledger entry // instead of the boundary being discarded in the stream. output.diagnostics = [ ...(output.diagnostics ?? []), { type: "claude_sdk_oauth_compact_boundary", timestamp: Date.now(), details: { boundary: { trigger: message.compact_metadata?.trigger ?? "unknown", preTokens: message.compact_metadata?.pre_tokens ?? 0, postTokens: message.compact_metadata?.post_tokens ?? 0, lineageId: message.session_id ?? "", observedAt: Date.now(), }, }, }, ]; } else if (message.type === "result" && message.subtype === "success") { // Both fields are optional on the wire, so only adopt them when present. // A terminal result must never downgrade a toolUse turn that the stream // already established, or the agent loop would stop instead of running // the tool call sitting in `output.content`. if (message.usage) updateUsage(model, output, message.usage, "query"); if (message.stop_reason != null && output.stopReason !== "toolUse") { output.stopReason = mapStopReason(message.stop_reason); } if (!sawStreamEvent) output.content.push({ type: "text", text: message.result }); } } if (wasAborted || options?.signal?.aborted) { output.stopReason = "aborted"; output.errorMessage = "Operation aborted"; stream.push({ type: "error", reason: "aborted", error: output }); } else { stream.push({ type: "done", reason: output.stopReason === "toolUse" ? "toolUse" : output.stopReason === "length" ? "length" : "stop", message: output, }); } } catch (error) { // no-excuse-ok: catch // Provider boundary converts every thrown SDK value into the stream error contract. // Unwinding the stopped attempt kept a retry checkpoint on the Claude Code session that // just compacted natively. Drop it, so the next turn rebuilds the resident session from // senpi's own history instead of resuming that rewritten transcript. if (nativeCompactionStopped && options?.sessionId) forgetBinding(options.sessionId); output.stopReason = options?.signal?.aborted ? "aborted" : "error"; // A failed result still bills its tokens; managed and resident lanes // throw before the result reaches this loop, so account for it here. const billed = sdkResultFailureUsage(error); if (billed) updateUsage(model, output, billed, "query"); output.errorMessage = withAuthGuidance(error, errorMessage(error), claudeCodeRun); const diagnostic = output.stopReason === "error" ? anthropicSubscriptionDiagnostic(error) : undefined; if (diagnostic !== undefined) output.providerDiagnostic = diagnostic; markColdSeedOverflow(output, model, coldSeedAttempt, coldSeedEstimate, options?.sessionId); stream.push({ type: "error", reason: output.stopReason, error: output }); } finally { options?.signal?.removeEventListener("abort", onAbort); closeQuery(); stream.end(); } })(); return stream; } //# sourceMappingURL=stream.js.map