@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
281 lines • 12.3 kB
JavaScript
import { sdkResultFailure } from "./errors.js";
import { refusalError } from "./refusal.js";
import { evaluateAbortOutcome } from "./session-reattach.js";
import { createSessionUuid, } from "./session-registry.js";
import { transitionToIdleSynced, transitionToTurnResultSeen, transitionToTurnSent, transitionToTurnStreaming, transitionToTurnWaiting, } from "./session-registry-state.js";
import { bufferBeforeReplay, claimTurn, deliver, endForeignTurnBeforeReplay, isForeignResult, isReplayFor, resultMatchesTurn, } from "./session-turn-claim.js";
import { SessionTurnAttributionError } from "./session-turn-types.js";
export const DEFAULT_PRE_REPLAY_MAX_MESSAGES = 64;
export const DEFAULT_PRE_REPLAY_MAX_BYTES = 256 * 1024;
export const SESSION_TURN_ABORT_GRACE_MS = 1_000;
/**
* How long a turn submitted while the previous turn of the same session is still active waits for that turn to
* settle before the submission is refused. The common case settles within the abort grace above: the agent loop
* starts the next turn (a steer, a follow-up, a monitor notification) right after it interrupted or finished
* consuming the previous one, while the pump still waits for the SDK's terminal result of that turn.
*/
export const SESSION_TURN_ADMISSION_WAIT_MS = 10_000;
export class ConcurrentSessionTurnAdmissionError extends Error {
constructor(sessionId) {
super(`Concurrent Anthropic Subscription turn admission for session ${sessionId}`);
this.code = "claude_sdk_oauth_concurrent_turn_admission";
this.name = "ConcurrentSessionTurnAdmissionError";
}
}
function currentTurn(entry) {
return entry.activeTurn;
}
function scheduleAbort(callback, delayMs) {
const timer = setTimeout(callback, delayMs);
timer.unref();
return () => clearTimeout(timer);
}
function removeAbortListener(turn) {
turn.signal?.removeEventListener("abort", turn.onAbort);
turn.cancelAbort?.();
turn.cancelAbort = undefined;
}
function failTurn(registry, entry, error) {
const turn = currentTurn(entry);
if (turn) {
removeAbortListener(turn);
entry.activeTurn = null;
turn.reject(error);
}
if (registry.isCurrentGeneration(entry.senpiSessionId, entry.generation)) {
registry.closeSession(entry.senpiSessionId, error.message);
}
}
/**
* An interrupt that never produces a terminal result still ends the user's turn:
* settle it as aborted and close only the query, so the binding survives and the
* next turn reattaches. Rejecting here would drop the turn's continuity
* observation and hand the following turn two.
*/
function abortTurn(registry, entry, turn, _error) {
if (currentTurn(entry) !== turn || !registry.isCurrentGeneration(entry.senpiSessionId, turn.generation))
return;
removeAbortListener(turn);
entry.activeTurn = null;
registry.closeSession(entry.senpiSessionId, "abort_uncertain");
turn.resolve({ uuid: turn.uuid, messages: turn.messages, aborted: true });
}
function finishTurn(registry, entry, turn, message) {
if (!resultMatchesTurn(message, turn)) {
throw new SessionTurnAttributionError("Anthropic Subscription result user_message_uuid did not match the active turn");
}
if (entry.state === "TURN_CLAIMED")
transitionToTurnStreaming(entry);
if (!turn.aborted)
deliver(entry, turn, message);
transitionToTurnResultSeen(entry);
removeAbortListener(turn);
entry.activeTurn = null;
if (!turn.aborted || evaluateAbortOutcome(turn.interruptReceipt) === "keep")
transitionToIdleSynced(entry);
else
registry.closeSession(entry.senpiSessionId, "abort_uncertain");
turn.resolve({ uuid: turn.uuid, messages: turn.messages, aborted: turn.aborted });
}
function handleMessage(registry, entry, message) {
// A forked query mints a NEW session id (forkSession: true + resume): the
// init message carries it, and it must be persisted BEFORE any turn-state
// guard — otherwise subsequent reattach targets the original session and
// the fork's content is lost.
if (message.type === "system" && message.subtype === "init" && typeof message.session_id === "string") {
if (message.session_id !== entry.sdkSessionId)
entry.sdkSessionId = message.session_id;
entry.sdkSessionIdConfirmed = true;
}
const turn = currentTurn(entry);
if (!turn || !registry.isCurrentGeneration(entry.senpiSessionId, turn.generation))
return false;
if (!turn.claimed) {
if (isReplayFor(message, turn.uuid)) {
entry.sdkSessionIdConfirmed = true;
for (const buffered of claimTurn(entry, turn)) {
if (buffered.type === "result")
finishTurn(registry, entry, turn, buffered);
else
deliver(entry, turn, buffered);
}
}
else if (message.type === "stream_event")
bufferBeforeReplay(registry, entry, turn, message);
else if (message.type === "result" && resultMatchesTurn(message, turn)) {
const failure = sdkResultFailure(message);
if (failure)
throw failure;
for (const buffered of claimTurn(entry, turn))
deliver(entry, turn, buffered);
finishTurn(registry, entry, turn, message);
return false;
}
else if (message.type === "result" && isForeignResult(message, turn)) {
endForeignTurnBeforeReplay(turn);
}
else if (message.type === "result") {
// A result that fails before the SDK ever echoed our user message (a
// 400 version floor, a session limit) must surface as that failure so
// failover can classify and rotate; only a genuine success-before-claim
// is an attribution error.
throw (sdkResultFailure(message) ??
new SessionTurnAttributionError("Anthropic Subscription result arrived before replay claim"));
}
return false;
}
if (message.type === "user" && "isReplay" in message && message.isReplay === true)
return false;
const refusal = refusalError(message);
if (refusal) {
failTurn(registry, entry, refusal);
return true;
}
if (message.type === "result") {
const failure = sdkResultFailure(message);
if (failure) {
failTurn(registry, entry, failure);
return true;
}
finishTurn(registry, entry, turn, message);
}
else
deliver(entry, turn, message);
return false;
}
async function runPump(registry, entry) {
const iterator = entry.query[Symbol.asyncIterator]();
try {
while (true) {
const { value, done } = await iterator.next();
if (done) {
failTurn(registry, entry, new Error("Anthropic Subscription query ended before the active turn completed"));
return;
}
if (handleMessage(registry, entry, value))
return;
await currentTurn(entry)?.writable?.();
}
}
catch (error) {
failTurn(registry, entry, error instanceof Error ? error : new Error(String(error)));
}
}
/**
* Waits for `settled`, bounded by SESSION_TURN_ADMISSION_WAIT_MS: "admitted" once it settles, "aborted" when
* `signal` aborts first, and a ConcurrentSessionTurnAdmissionError when the bound passes, so a stuck pump cannot
* hold the session's callers forever.
*/
export function waitForTurnAdmission(sessionId, settled, signal, schedule = scheduleAbort) {
return new Promise((resolve, reject) => {
let done = false;
let cancelTimer;
const finish = (run) => {
if (done)
return;
done = true;
cancelTimer?.();
signal?.removeEventListener("abort", onAbort);
run();
};
const onAbort = () => finish(() => resolve("aborted"));
if (signal?.aborted) {
onAbort();
return;
}
// The scheduler may fire synchronously (tests inject one); `done` then stops every later step.
cancelTimer = schedule(() => finish(() => reject(new ConcurrentSessionTurnAdmissionError(sessionId))), SESSION_TURN_ADMISSION_WAIT_MS);
if (done)
return;
signal?.addEventListener("abort", onAbort, { once: true });
const admitted = () => finish(() => resolve("admitted"));
void settled.then(admitted, admitted);
});
}
/**
* A turn submitted while the session's previous turn is still active waits for that turn to settle, bounded by
* SESSION_TURN_ADMISSION_WAIT_MS, then submits. One SDK session runs one turn at a time, so the second request is
* logically after the first; refusing it (the behavior before this guard) surfaced as a provider failure and moved
* the session to a fallback model for no reason of the provider's. An abort of the waiting request resolves it as
* an aborted turn; a previous turn that does not settle in time keeps the refusal.
*/
async function admitAfter(registry, entry, active, settled, request, limits) {
const generation = entry.generation;
const outcome = await waitForTurnAdmission(entry.senpiSessionId, settled, request.signal, request.scheduleAbort);
if (outcome === "aborted")
return { uuid: createSessionUuid(), messages: [], aborted: true };
if (!registry.isCurrentGeneration(entry.senpiSessionId, generation)) {
throw new Error("Anthropic Subscription session closed while a turn waited for admission");
}
if (currentTurn(entry) === active)
entry.activeTurn = null;
return submitSessionTurn(registry, entry, request, limits);
}
export function submitSessionTurn(registry, entry, request, limits = {
maxMessages: DEFAULT_PRE_REPLAY_MAX_MESSAGES,
maxBytes: DEFAULT_PRE_REPLAY_MAX_BYTES,
}) {
const active = currentTurn(entry);
if (active) {
if (!active.settled)
throw new ConcurrentSessionTurnAdmissionError(entry.senpiSessionId);
return admitAfter(registry, entry, active, active.settled, request, limits);
}
if (entry.state === "STARTING")
transitionToIdleSynced(entry);
transitionToTurnWaiting(entry);
const uuid = createSessionUuid();
let turn;
const promise = new Promise((resolve, reject) => {
const onAbort = () => {
if (turn.aborted)
return;
turn.aborted = true;
turn.cancelAbort = (request.scheduleAbort ?? scheduleAbort)(() => abortTurn(registry, entry, turn, new Error("Anthropic Subscription interrupted turn did not terminate")), SESSION_TURN_ABORT_GRACE_MS);
void entry.query
.interrupt()
.then((receipt) => {
turn.interruptReceipt = receipt;
})
.catch((error) => {
const detail = error instanceof Error ? error.message : String(error);
abortTurn(registry, entry, turn, new Error(`Anthropic Subscription query interrupt failed: ${detail}`));
});
};
turn = {
uuid,
generation: entry.generation,
messages: [],
preReplay: [],
preReplayBytes: 0,
preReplayOverflowed: false,
claimed: false,
aborted: false,
onMessage: request.onMessage,
writable: request.writable,
signal: request.signal,
onAbort,
resolve,
reject,
limits,
};
});
turn.settled = promise.then(() => undefined, () => undefined);
entry.activeTurn = turn;
if (!entry.pumpTask)
entry.pumpTask = runPump(registry, entry);
entry.inputController.push({
type: "user",
message: request.message,
parent_tool_use_id: null,
uuid,
session_id: entry.sdkSessionId,
});
transitionToTurnSent(entry);
if (request.signal?.aborted)
turn.onAbort();
else
request.signal?.addEventListener("abort", turn.onAbort, { once: true });
return promise;
}
//# sourceMappingURL=session-registry-pump.js.map