@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
53 lines • 2.78 kB
JavaScript
import { join } from "node:path";
import { homedir } from "node:os";
import { CONFIG_DIR_NAME, CONFIG_FLAT_LAYOUT, getAgentDir } from "../../../../config.js";
import { brandEnvNames } from "../../../brand.js";
import { seatDigest } from "./seat-digest.js";
import { logContinuityEvent } from "./session-observability.js";
// Context follows the actual SDK event/error, not the session: overlapping turns and failover
// must never borrow another attempt's account. Weak keys retain neither completed turns nor tokens.
const contexts = new WeakMap();
export function attemptAccountContext(auth) {
return {
// Operational account names, unlike displayName, cannot contain an email or org identifier.
accountLabel: /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(auth.accountName) ? auth.accountName : "configured account",
accountSource: auth.authLane === "ambient"
? "ambient"
: (auth.accounts.find((account) => account.name === auth.accountName)?.source ?? "unknown"),
...(auth.pinSource === undefined ? {} : { pinSource: auth.pinSource }),
};
}
export function rememberAccountContext(target, context) {
if (target !== null && typeof target === "object")
contexts.set(target, context);
}
/** Keep the original SDK error and its usage/classification unchanged. */
export function inheritAccountContext(event, error) {
const context = contexts.get(event);
if (context)
contexts.set(error, context);
return error;
}
export function errorAccountContext(error) {
return error !== null && typeof error === "object" ? contexts.get(error) : undefined;
}
export function logAttemptAccount(auth, sessionId) {
const agentDir = getAgentDir();
// This is the config resolver's exact prefix order, including explicitly empty selectors.
const selector = brandEnvNames("CODING_AGENT_DIR").find((name) => process.env[name] !== undefined);
const defaultDir = CONFIG_FLAT_LAYOUT ? join(homedir(), CONFIG_DIR_NAME) : join(homedir(), CONFIG_DIR_NAME, "agent");
const agentDirSource = selector !== undefined && process.env[selector] ? selector : agentDir === defaultDir ? "default" : "project";
logContinuityEvent("claude_sdk_oauth_session_auth", {
...(sessionId === undefined ? {} : { sessionId }),
agentDir: `dir:${seatDigest(`agent-dir:${agentDir}`, agentDir)}`,
agentDirSource,
agentDirRule: selector !== undefined && process.env[selector]
? "environment"
: agentDir === defaultDir
? "home-default"
: "project-local",
seat: seatDigest(auth.accountName, agentDir),
accountSource: attemptAccountContext(auth).accountSource,
});
}
//# sourceMappingURL=account-context.js.map