@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
120 lines • 6.09 kB
JavaScript
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { readByProviderId } from "@earendil-works/pi-ai";
import { getModels } from "@earendil-works/pi-ai/compat";
import { getAgentDir } from "../../../../config.js";
import { toBuiltinProviderContext } from "../provider-context.js";
import { registerClaudeAccountCommand } from "./account-command.js";
import { ANTHROPIC_SUBSCRIPTION_PROVIDER_ID } from "./account-management.js";
import { CLAUDE_SDK_OAUTH_API_ID } from "./api-id.js";
import { plannedContextWindow } from "./context-window.js";
import { claudeCliDefaultModel } from "./claude-cli-account-test.js";
import { longContextAvailable, onLongContextAvailabilityChange } from "./long-context.js";
import { registerLimitRecheck } from "./limit-recheck.js";
import { createOAuthConfig } from "./oauth-login.js";
import { registerSessionRegistry } from "./session-registry-wiring.js";
import { requireAnthropicSubscriptionCwd } from "./session-cwd.js";
import { loadAnthropicSubscriptionProviderSettingsFromDisk, } from "./settings.js";
import { streamAnthropicSubscription } from "./stream.js";
export { ANTHROPIC_SUBSCRIPTION_PROVIDER_ID } from "./account-management.js";
/**
* The lane's models carry the window their requests actually get, which is what compaction plans
* against: the catalog window, except a legacy long-context id at Claude Code's 200k default after the
* account refused its 1M opt-in (senpi#3408, senpi#3801).
*/
export const anthropicSubscriptionModels = (longContext = longContextAvailable()) => getModels("anthropic").map((model) => ({
id: model.id,
name: model.name,
reasoning: model.reasoning,
input: model.input,
cost: model.cost,
contextWindow: plannedContextWindow(model, longContext),
maxTokens: model.maxTokens,
thinkingLevelMap: {
...model.thinkingLevelMap,
minimal: null,
},
}));
function readStoredCredential(providerId) {
const authPath = join(getAgentDir(), "auth.json");
if (!existsSync(authPath))
return undefined;
try {
const data = JSON.parse(readFileSync(authPath, "utf8"));
// Read boundary (senpi#1989): this raw read bypasses AuthStorage, so it
// never sees the auth.json key migration. An auth.json still keyed by the
// legacy provider id would report the lane logged out with no error at
// all, so try the canonical key first and then the legacy spelling.
// `anthropic` is untouched by the rename and still resolves exactly.
return readByProviderId(data, providerId);
}
catch {
return undefined;
}
}
export function registerAnthropicSubscriptionExtension(pi, deps = {}) {
const cwd = requireAnthropicSubscriptionCwd(pi.cwd);
registerClaudeAccountCommand(pi);
registerSessionRegistry(pi);
const limitRecheck = registerLimitRecheck(pi);
// The lane re-registers whenever the 1M window is refused or offered again, so the session's current
// model, and compaction with it, plans against the window the requests get. Each registration is the
// whole config: the runtime validates a registration on its own, not merged with the previous one.
const providerConfig = (longContext) => ({
baseUrl: CLAUDE_SDK_OAUTH_API_ID,
api: CLAUDE_SDK_OAUTH_API_ID,
models: anthropicSubscriptionModels(longContext),
streamSimple: (model, context, options) => streamAnthropicSubscription(model, toBuiltinProviderContext(context), options, options?.streamKind === "main" ? limitRecheck.accounts() : undefined),
// A verbatim `enabled: false` is the kill switch: the lane cannot serve, so
// it must not consume an implicit fallback-expansion slot. An absent flag
// stays eligible - an explicit senpi-side login keeps the lane usable.
fallbackEligible: () => {
try {
const settings = deps.readSettings
? deps.readSettings()
: loadAnthropicSubscriptionProviderSettingsFromDisk(cwd);
return settings.enabled !== false;
}
catch {
return true;
}
},
// The lane selects among its accounts itself (pin, resident account, order, per-account and
// per-model limits), so the generic credential pool must not choose a second time (senpi#2081).
ownsAccountSelection: true,
// Requests run Claude Code through @anthropic-ai/claude-agent-sdk as a subprocess, under Claude logins on this machine.
localOnly: true,
oauth: createOAuthConfig({
readCurrent: async () => readStoredCredential(ANTHROPIC_SUBSCRIPTION_PROVIDER_ID),
readAmbientAuthStatus: deps.readAmbientAuthStatus,
readSettings: () => {
try {
const settings = deps.readSettings
? deps.readSettings()
: loadAnthropicSubscriptionProviderSettingsFromDisk(cwd);
return { tokenInjection: settings.tokenInjection, enabled: settings.enabled };
}
catch {
return undefined;
}
},
claudeCli: {
cwd: () => cwd,
providerSettings: () => deps.readSettings ? deps.readSettings() : loadAnthropicSubscriptionProviderSettingsFromDisk(cwd),
defaultModel: () => claudeCliDefaultModel(cwd),
},
}),
});
pi.registerProvider(ANTHROPIC_SUBSCRIPTION_PROVIDER_ID, providerConfig(longContextAvailable()));
const stopFollowingLongContext = onLongContextAvailabilityChange((available) => {
pi.registerProvider(ANTHROPIC_SUBSCRIPTION_PROVIDER_ID, providerConfig(available));
});
pi.on("session_shutdown", () => {
stopFollowingLongContext();
limitRecheck.reset();
});
}
export default function anthropicSubscriptionExtension(pi) {
registerAnthropicSubscriptionExtension(pi);
}
//# sourceMappingURL=index.js.map