@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
292 lines • 16.4 kB
JavaScript
import { createHash } from "node:crypto";
import { CredentialStoreBusyError } from "../../../lockfile-policy.js";
import { emitProviderAccountFailover, emitProviderAccountsChanged } from "./account-events.js";
import { ANTHROPIC_SUBSCRIPTION_PROVIDER_ID } from "./account-management.js";
import { emptyCredential, envSlotToken, listAccounts, unusableStoredSlotCount, } from "./accounts.js";
import { isBlockedFor, selectAccount } from "./affinity.js";
import { createAttemptMessages } from "./auth-attempt.js";
import { recoverAuthBlockedSlots } from "./auth-block-recovery.js";
import { activeBoundary } from "./auth-lane-boundary.js";
import { hasRequestOauthToken, mergeRequestAuthEnvironment, stripManagedAuthEnvironment } from "./auth-environment.js";
import { accountDirFor, claudeCliSharedRoot, ensureAccountDir } from "./claude-cli-account-dir.js";
import { buildClaudeCliEnvironment } from "./claude-cli-environment.js";
import { profileChanged, verifyClaudeCliInitialization } from "./claude-cli-token-source.js";
import { writeConfigDirCredential } from "./config-dir-credentials.js";
import { asksLegacyLongContext, CLAUDE_CODE_DEFAULT_CONTEXT_WINDOW, claudeCodeMaxContextTokens, } from "./context-window.js";
import { isExtraUsageExhausted } from "./errors.js";
import { runFailover } from "./failover.js";
import { logContinuityEvent } from "./session-observability.js";
import { markLongContextRefused } from "./long-context.js";
import { classifyForRequest, retryAtStandardWindowOnce, sdkFailure, visibleSdkMessage } from "./long-context-retry.js";
import { refreshFailure } from "./refresh-failure.js";
import { ClaudeSignInRequiredError, isServableAccountSlot, signInRequiredAccounts } from "./sign-in-again.js";
export { ANTHROPIC_SUBSCRIPTION_PROVIDER_ID } from "./account-management.js";
export { overrideAuthLaneBoundary, resetAuthLaneBoundary } from "./auth-lane-boundary.js";
const DEFAULT_FALLBACK_OUTPUT_TOKENS = 32_000;
const MIN_FALLBACK_OUTPUT_TOKENS = 8_192;
/** A managed lane with an empty pool must refuse rather than spawn the SDK against ambient host credentials. */
const NO_MANAGED_ACCOUNTS_ERROR = "authentication_failed: No Anthropic Subscription accounts configured for the managed lane; " +
"run /login anthropic-subscription or set CLAUDE_CODE_OAUTH_TOKEN";
/**
* A stored account that names no account cannot be selected, signed into, or affinity-routed, and its seat digest would
* hash an undefined name. Refusing here keeps the turn from silently falling back to ambient host credentials
* (oh-my-openagent#12228).
*/
const UNUSABLE_STORED_ACCOUNT_ERROR = "claude_account_unusable: a stored Claude account has no name, so no turn can use it; " +
"run /login anthropic-subscription to add a named account";
export function resolveEffectiveLane(settings, accounts) {
return settings.tokenInjection ?? (accounts.length > 0 ? "oauth-slots" : "ambient");
}
async function managedPool(settings, requestEnvironment) {
const store = activeBoundary.createStore();
let credential = await store.read(ANTHROPIC_SUBSCRIPTION_PROVIDER_ID);
const environment = mergeRequestAuthEnvironment(activeBoundary.env(), requestEnvironment);
let accounts = listAccounts(credential ?? emptyCredential(), (name) => environment[name]);
if (!credential && accounts.length > 0) {
credential = await store.modify(ANTHROPIC_SUBSCRIPTION_PROVIDER_ID, async () => emptyCredential());
accounts = listAccounts(credential ?? emptyCredential(), (name) => environment[name]);
}
const configuredLane = resolveEffectiveLane(settings, accounts);
const lane = configuredLane === "config-dir" && hasRequestOauthToken(requestEnvironment) ? "oauth-slots" : configuredLane;
const unusableStoredAccounts = unusableStoredSlotCount(credential);
if (lane === "ambient") {
// An ambient lane the user configured explicitly is their choice and is never overridden (omo#6784); a lane that
// defaulted to ambient only because every stored account was dropped names the real cause instead.
if (settings.tokenInjection === "ambient" || unusableStoredAccounts === 0)
return undefined;
throw new Error(UNUSABLE_STORED_ACCOUNT_ERROR);
}
if (accounts.length === 0)
throw new Error(NO_MANAGED_ACCOUNTS_ERROR);
const stored = credential?.type === "oauth" ? credential : undefined;
return {
accounts,
environment,
lane,
pinnedAccount: settings.pinnedAccount ?? stored?.pinned,
...(settings.pinnedAccount !== undefined
? { pinSource: "settings" }
: stored?.pinned !== undefined
? { pinSource: "stored" }
: {}),
...(stored?.order === undefined ? {} : { accountOrder: stored.order }),
store,
};
}
function storedAccounts(credential, pool) {
const stored = credential?.type === "oauth" ? credential : undefined;
return listAccounts(stored ?? emptyCredential(), (key) => pool.environment[key]);
}
function laneFor(pool, slot) {
return slot.store === "claude-cli" ? "claude-cli" : pool.lane;
}
/**
* A claude-cli account turn: no token, only the account's own config dir (its links repaired first, so the
* transcript lands in the shared root). Every inherited auth variable is stripped, so the CLI can only use
* the login in its own store.
*/
function prepareClaudeCliSlot(pool, slot) {
const accountDir = ensureAccountDir({
agentDir: activeBoundary.getAgentDir(),
dirId: slot.dirId,
sharedRoot: claudeCliSharedRoot(pool.environment),
});
const env = buildClaudeCliEnvironment(pool.environment, { configDir: accountDir });
return { env, credentialDigest: createHash("sha256").update(`claude-cli\0${accountDir}`).digest("hex") };
}
/**
* Fails the attempt closed on an inherited credential. Only after the check passed is the profile the CLI reported
* stored when it changed; that write is bookkeeping, so a busy or failing store is logged and never fails the turn.
*/
function claudeCliInitializationCheck(pool, slot) {
return async (initialization) => {
const reported = verifyClaudeCliInitialization(initialization);
if (!profileChanged(slot.profile, reported))
return;
const profile = { ...reported, checkedAt: activeBoundary.now() };
slot.profile = profile;
try {
await pool.store.modify(ANTHROPIC_SUBSCRIPTION_PROVIDER_ID, async (current) => {
if (current?.type !== "oauth")
return current;
const credential = current;
return {
...credential,
accounts: (credential.accounts ?? []).map((candidate) => candidate.name === slot.name && candidate.store === "claude-cli"
? { ...candidate, profile }
: candidate),
};
});
}
catch (error) {
logContinuityEvent("claude_cli_profile_write_failed", {
accountName: slot.name,
reason: error instanceof CredentialStoreBusyError ? "store_busy" : "store_error",
});
}
};
}
/** An env token account's turn: the token goes to the SDK child, or into a per-account config dir on that lane. */
function prepareEnvSlot(pool, slot) {
const environment = pool.environment;
const access = envSlotToken((name) => environment[name], slot.name);
if (!access)
throw new Error("authentication_failed: selected OAuth token is unavailable");
const childEnvironment = stripManagedAuthEnvironment(environment);
const credentialDigest = createHash("sha256").update(access).digest("hex");
if (pool.lane === "oauth-slots") {
return { env: { ...childEnvironment, CLAUDE_CODE_OAUTH_TOKEN: access }, credentialDigest };
}
const directory = writeConfigDirCredential(activeBoundary.getAgentDir(), slot, access);
return { env: { ...childEnvironment, CLAUDE_CONFIG_DIR: directory }, credentialDigest };
}
/** Resolves managed OAuth immediately before each subprocess spawn and retries only pre-delta failures. */
export async function* queryWithAuthLane(input) {
const signal = input.signal ?? new AbortController().signal;
const pool = await managedPool(input.providerSettings, input.env);
let standardWindow = false;
let retryAccountName;
let outputReserveTokens = input.outputReserveTokens ?? DEFAULT_FALLBACK_OUTPUT_TOKENS;
const buildOptions = (lane) => {
const options = input.buildOptions(lane);
if (standardWindow) {
options.model = options.model?.replace(/\[1m\]$/, "");
options.env = {
...options.env,
// Claude Code then refuses only past the 200k window itself; the prompt-plus-output check below keeps the fit.
CLAUDE_CODE_MAX_CONTEXT_TOKENS: String(claudeCodeMaxContextTokens(CLAUDE_CODE_DEFAULT_CONTEXT_WINDOW, outputReserveTokens)),
// Reserve and request the same output budget, not the model catalog's ceiling.
CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(outputReserveTokens),
};
}
return options;
};
const onLongContextRefused = (error) => {
if (isExtraUsageExhausted(error)) {
// The full estimate already includes the preamble margin when no billed prefix exists.
const contextTokens = input.contextTokens?.() ?? 0;
outputReserveTokens =
input.outputReserveTokens ??
Math.max(MIN_FALLBACK_OUTPUT_TOKENS, Math.min(DEFAULT_FALLBACK_OUTPUT_TOKENS, CLAUDE_CODE_DEFAULT_CONTEXT_WINDOW - contextTokens));
if (contextTokens > CLAUDE_CODE_DEFAULT_CONTEXT_WINDOW - outputReserveTokens) {
const reason = error instanceof Error ? error.message : String(error);
throw new Error(`${reason} The prompt plus ${outputReserveTokens} output tokens cannot fit the 200k retry. Top up extra usage to keep the 1M window, or start a new session or compact this session before retrying.`);
}
// Exhausted balance is not an entitlement verdict: only this request uses 200k.
standardWindow = true;
}
else {
markLongContextRefused();
}
input.onLongContextFallback?.();
};
if (!pool) {
const parentEnvironment = mergeRequestAuthEnvironment(activeBoundary.env(), input.env);
const ambientEnvironment = { ...parentEnvironment };
for (const name of Object.keys(ambientEnvironment)) {
if (name.startsWith("SENPI_"))
delete ambientEnvironment[name];
}
// Lane-owned variables from buildOptions (the compaction-owner overlay) win over the host.
let askedLegacyLongContext = false;
const ambientAttempt = async () => {
const options = buildOptions("ambient");
askedLegacyLongContext = asksLegacyLongContext(options.model);
options.env = { ...ambientEnvironment, ...options.env };
return createAttemptMessages(input, { accountName: "ambient", accounts: [], authLane: "ambient", options });
};
yield* retryAtStandardWindowOnce(ambientAttempt, () => askedLegacyLongContext, onLongContextRefused);
return;
}
if (input.probe === true) {
const probed = pool.accounts.find((account) => account.name === input.pinnedAccount);
if (probed === undefined)
throw new Error(`authentication_failed: no stored account named ${input.pinnedAccount}`);
const { blockedUntil: _until, blockReason: _reason, blockedAt: _at, modelBlocks: _model, ...unblocked } = probed;
pool.accounts = [unblocked];
}
else {
pool.accounts = await recoverAuthBlockedSlots({
store: pool.store,
providerId: ANTHROPIC_SUBSCRIPTION_PROVIDER_ID,
accounts: pool.accounts,
signal,
reload: async () => storedAccounts(await pool.store.read(ANTHROPIC_SUBSCRIPTION_PROVIDER_ID), pool),
isUsable: (account) => !isBlockedFor(account, activeBoundary.now(), input.model),
now: activeBoundary.now(),
transientError: (error) => (error instanceof CredentialStoreBusyError ? error : refreshFailure(error)),
claudeCliStatus: async (slot) => {
const configDir = accountDirFor(activeBoundary.getAgentDir(), slot.dirId);
return (await activeBoundary.claudeCliAuthStatus(configDir, pool.environment)).state;
},
});
}
// A slot that must sign in again is never selected, like a removed one, and neither is a stored CLI slot whose
// account dir id is unusable: that slot carries no readable login and preparing it would fail with an internal
// error before the first model call (omo#12228). With none left the turn names them.
const signedOut = signInRequiredAccounts(pool.accounts);
pool.accounts = pool.accounts.filter(isServableAccountSlot);
if (pool.accounts.length === 0)
throw new ClaudeSignInRequiredError(signedOut);
let askedLegacyLongContext = false;
yield* runFailover({
accounts: pool.accounts,
recheckedAccounts: input.probe === true ? undefined : input.recheckedAccounts,
accountFallback: input.providerSettings.accountFallback,
selectFn: (accounts) => selectAccount(accounts, {
sessionId: input.sessionId,
pinnedAccount: input.pinnedAccount ?? pool.pinnedAccount,
...(input.pinnedAccount !== undefined
? { pinSource: "cli" }
: pool.pinSource === undefined
? {}
: { pinSource: pool.pinSource }),
accountFallback: input.providerSettings.accountFallback,
accountStrategy: input.providerSettings.accountStrategy,
...(pool.accountOrder === undefined ? {} : { accountOrder: pool.accountOrder }),
...(input.preferredAccount === undefined ? {} : { preferredAccount: input.preferredAccount }),
now: activeBoundary.now(),
...(input.model === undefined ? {} : { model: input.model }),
}),
runAttempt: async (slot) => {
if (retryAccountName !== slot.name)
standardWindow = false;
retryAccountName = slot.name;
const authLane = laneFor(pool, slot);
const options = buildOptions(authLane);
askedLegacyLongContext = asksLegacyLongContext(options.model);
const accounts = pool.accounts.map((account) => ({ ...account }));
const prepared = slot.store === "claude-cli" ? prepareClaudeCliSlot(pool, slot) : prepareEnvSlot(pool, slot);
options.env = { ...prepared.env, ...options.env };
return createAttemptMessages(input, {
accountName: slot.name,
accounts,
authLane,
pinSource: input.pinnedAccount !== undefined ? "cli" : pool.pinSource,
options,
credentialDigest: prepared.credentialDigest,
...(slot.store === "claude-cli" ? { verifyInitialization: claudeCliInitializationCheck(pool, slot) } : {}),
});
},
classify: (error) => classifyForRequest(error, askedLegacyLongContext),
...(input.sessionId === undefined ? {} : { sessionKey: input.sessionId }),
onLongContextRefused,
store: pool.store,
providerId: ANTHROPIC_SUBSCRIPTION_PROVIDER_ID,
...(input.model === undefined ? {} : { model: input.model }),
now: activeBoundary.now,
errorFromEvent: sdkFailure,
isVisibleDelta: visibleSdkMessage,
signal,
...(input.probe === true ? { persistBlocks: false } : {}),
onFailover: ({ account, nextAccount, classification }) => {
if (input.probe === true)
return;
emitProviderAccountsChanged(ANTHROPIC_SUBSCRIPTION_PROVIDER_ID);
if (nextAccount) {
emitProviderAccountFailover(ANTHROPIC_SUBSCRIPTION_PROVIDER_ID, account.name, nextAccount.name, classification.kind);
}
},
});
}
//# sourceMappingURL=auth-lane.js.map