@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
249 lines • 13 kB
JavaScript
import { BoundedAsyncQueue, SESSION_STREAM_QUEUE_CAPACITY } from "./bounded-queue.js";
import { sdkResultFailure } from "./errors.js";
import { logContinuityEvent } from "./session-observability.js";
import { bindingFromEntry, forgetBinding, keepBindingThenClose, rememberBinding, } from "./session-reattach.js";
import { closeSession, getSession, isCurrentGeneration, sessionRegistry, } from "./session-registry.js";
import { ConcurrentSessionTurnAdmissionError, submitSessionTurn, waitForTurnAdmission, } from "./session-registry-pump.js";
import { recordSyncedStream, sentHashPrefixDigest } from "./session-sync.js";
/** Pending while the attempt that submitted the entry's latest turn has not yet recorded what that turn sent. */
const attemptBookkeeping = new WeakMap();
/**
* Holds a new attempt until the attempt running the entry's previous turn finished and recorded the sent stream
* (`recordSyncedStream`), bounded and abortable like the pump's own admission wait. The caller decides
* continuity and the delta only after this, so the delta starts after the earlier turn's message instead of
* sending it again (senpi#5015 review).
*/
async function waitForActiveTurn(entry, signal) {
const pending = attemptBookkeeping.get(entry);
if (!pending)
return;
if ((await waitForTurnAdmission(entry.senpiSessionId, pending, signal)) === "aborted") {
throw new Error("Anthropic Subscription turn aborted while waiting for the previous turn");
}
}
/**
* Holds a new attempt until the live model switch `model_select` started has settled, so a prompt sent right after
* `set_model` runs on the selected model and continuity reads the confirmed `modelId` (senpi#6411). Bounded like
* `waitForActiveTurn`: a switch Claude Code never confirms retires that process, keeping the lineage on the selected
* model, so the turn reattaches instead of hanging. Returns the switch it waited for.
*/
async function waitForModelSwitch(entry, signal) {
const pending = entry.pendingModelSwitch;
if (!pending)
return undefined;
let outcome;
try {
outcome = await waitForTurnAdmission(entry.senpiSessionId, pending.done, signal);
}
catch (error) {
if (!(error instanceof ConcurrentSessionTurnAdmissionError))
throw error;
if (isCurrentGeneration(entry.senpiSessionId, entry.generation)) {
logContinuityEvent("claude_sdk_oauth_model_switch_timeout", { modelId: pending.modelId });
keepBindingThenClose(entry.senpiSessionId, "model_switch_timeout");
}
return pending;
}
if (outcome === "aborted")
throw new Error("Anthropic Subscription turn aborted while waiting for the model switch");
return pending;
}
/**
* Runs `admit` once the session's previous turn and pending model switch have settled. `admit` awaits, and a switch
* issued meanwhile would otherwise run while this turn does (senpi#6412 review), so admission repeats until no switch
* other than the one already awaited is pending; a switch issued after admission applies to the next turn. Each wait
* keeps its own admission bound and the abort signal.
*/
export async function admitSettledTurn(sessionId, signal, admit) {
for (;;) {
const entry = getSession(sessionId);
let awaited;
if (entry) {
await waitForActiveTurn(entry, signal);
awaited = await waitForModelSwitch(entry, signal);
}
const admitted = await admit();
const pending = getSession(sessionId)?.pendingModelSwitch;
if (pending === undefined || pending === awaited)
return admitted;
}
}
function successfulTurn(messages) {
return messages.some((message) => message.type === "result" && message.subtype === "success" && sdkResultFailure(message) === undefined);
}
function recordAssistantUuid(entry, sentCount, message) {
if (message.type === "assistant" && message.parent_tool_use_id === null) {
entry.assistantUuidByIndex.set(sentCount, message.uuid);
}
}
/**
* An attempt that pushed its user payload and then aborted or failed leaves that
* message on the lineage un-answered: `recordSyncedStream` never ran, so the
* entry still points at the PRE-TURN boundary. Remembering the binding at that
* boundary, tagged with the attempted turn's full sent-stream digest, lets the
* SAME turn's retry fork past the orphaned message instead of appending it
* twice (issue #723 retry storm). In-memory only — nothing here is persisted.
*/
/** Claude Code answered "No conversation found with session ID": the bound id is dead, never resume it again. */
const RESUME_TARGET_MISSING = /no conversation found with session id/i;
/** Claude Code's wording for a fork point absent from its transcript; the captured id is the dead one. */
export const RESUME_MESSAGE_MISSING = /no message found with message\.uuid(?:\s+of)?:\s*([0-9a-fA-F-]+)/i;
/**
* Drops only the boundary Claude Code rejected. Republishing it would make the next admission ask
* for the same dead id, fail the same way, and flatten again (senpi#1958); earlier boundaries stay
* mapped so the retry can still fork at one of them instead of re-sending the conversation.
*/
function forgetMissingAssistantUuid(entry, message) {
const missing = RESUME_MESSAGE_MISSING.exec(message)?.[1];
if (missing === undefined)
return;
for (const [index, uuid] of entry.assistantUuidByIndex) {
if (uuid === missing)
entry.assistantUuidByIndex.delete(index);
}
}
/** The same drop on a lineage this attempt forked from: the boundary was missing from that lineage's transcript. */
function withoutMissingAssistantUuid(binding, message) {
const missing = RESUME_MESSAGE_MISSING.exec(message)?.[1];
if (missing === undefined)
return binding;
return {
...binding,
lastAssistantUuid: binding.lastAssistantUuid === missing ? null : binding.lastAssistantUuid,
assistantUuidByIndex: binding.assistantUuidByIndex?.filter(([, uuid]) => uuid !== missing),
};
}
function publishBinding(entry, binding) {
rememberBinding({ ...binding, sdkSessionIdConfirmed: entry.sdkSessionIdConfirmed });
}
function rememberRetryCheckpoint(entry, hashes) {
if (entry.sentCount < 0 || entry.sentCount > hashes.length)
return;
publishBinding(entry, {
...bindingFromEntry(entry, hashes.slice(0, entry.sentCount)),
unansweredTurnDigest: sentHashPrefixDigest(hashes, hashes.length),
});
}
/**
* An unanswered attempt on an account other than the one `servedLineage` names served nothing, so the
* session's prompt cache is most likely still on that account. Once the attempt's process is gone,
* `servedLineage` stays the binding, so the next request prefers its account, forks its own lineage
* there and reads its cache, and is not reported as a seat change (senpi#4304). An attempt on that same
* account records its own retry checkpoint, as before. `servedLineage` is the last binding recorded for
* the session, not proof of the last answer: see `createSessionTurnAttempt`.
*/
function rememberUnansweredAttempt(entry, hashes, servedLineage) {
if (servedLineage !== undefined && servedLineage.accountName !== entry.accountName)
rememberBinding(servedLineage);
else
rememberRetryCheckpoint(entry, hashes);
}
export function createSessionTurnAttempt(entry, message, hashes, signal, staged,
/**
* The binding this process held for the session before this attempt (`getBinding`). It is the last
* binding recorded, which usually names the account that last answered, but not always: a retry
* checkpoint from an unanswered attempt, the entry kept when a session closes, a resumed lineage and
* a binding restored from the session file on restart are recorded the same way, so it can name an
* account whose latest attempt went unanswered. Undefined when nothing has been recorded since the
* session started, forked or lost its binding (for example on compaction or divergence).
*/
servedLineage) {
const generation = entry.generation;
// Claude Code declared the bound id dead: no later cleanup may re-publish it.
let resumeTargetMissing = false;
let servedBefore = servedLineage;
return {
messages: (async function* () {
const queue = new BoundedAsyncQueue(SESSION_STREAM_QUEUE_CAPACITY);
let markBookkept;
const bookkeeping = new Promise((resolve) => {
markBookkept = resolve;
});
attemptBookkeeping.set(entry, bookkeeping);
const bookkept = () => {
if (attemptBookkeeping.get(entry) === bookkeeping)
attemptBookkeeping.delete(entry);
markBookkept();
};
// An abort releases the pump promptly (senpi#2974): while the consumer is stalled, the pump waits
// on writable(); without this the abort grace timer fires first and the session ends as
// abort_uncertain before the interrupt receipt is read and the keep-or-close decision applies.
const abortReleased = signal === undefined
? undefined
: new Promise((resolve) => {
if (signal.aborted)
resolve();
else
signal.addEventListener("abort", () => resolve(), { once: true });
});
const completion = submitSessionTurn(sessionRegistry, entry, {
message,
signal,
onMessage: (sdkMessage) => {
recordAssistantUuid(entry, hashes.length, sdkMessage);
queue.push(sdkMessage);
},
writable: () => abortReleased === undefined ? queue.writable() : Promise.race([queue.writable(), abortReleased]),
});
void completion.then(() => queue.close(), (error) => queue.fail(error));
try {
for await (const sdkMessage of queue)
yield sdkMessage;
const turn = await completion;
if (!turn.aborted && successfulTurn(turn.messages)) {
recordSyncedStream(entry, hashes);
publishBinding(entry, bindingFromEntry(entry, hashes));
}
else if (isCurrentGeneration(entry.senpiSessionId, generation)) {
// A process kept after a clean interrupt still holds this turn: the binding stays on its lineage,
// which the live entry keeps serving.
rememberRetryCheckpoint(entry, hashes);
}
else {
rememberUnansweredAttempt(entry, hashes, servedBefore);
}
// Emit only when this attempt was consumed to completion (retained). A
// discarded attempt (failover to another account) unwinds through the
// generator's return() and never reaches here; an internally-failed
// attempt throws to the catch below. Both stay silent so the turn yields
// exactly one continuity observation - this retained attempt, or the
// single terminal observation residentSessionMessages emits when every
// attempt fails.
staged.emit();
}
catch (error) {
// The queue failed (completion rejected: pump failure, query end,
// attribution error). The payload was still pushed, so the retry needs
// the same checkpoint the aborted path records.
if (error instanceof Error && RESUME_TARGET_MISSING.test(error.message)) {
resumeTargetMissing = true;
forgetBinding(entry.senpiSessionId);
}
else {
if (error instanceof Error) {
forgetMissingAssistantUuid(entry, error.message);
if (servedBefore)
servedBefore = withoutMissingAssistantUuid(servedBefore, error.message);
}
rememberUnansweredAttempt(entry, hashes, servedBefore);
}
throw error;
}
finally {
// A consumer that stops reading early must not leave the pump waiting for room.
queue.close();
bookkept();
}
})(),
discard: () => {
if (resumeTargetMissing)
forgetBinding(entry.senpiSessionId);
else
rememberUnansweredAttempt(entry, hashes, servedBefore);
if (isCurrentGeneration(entry.senpiSessionId, generation)) {
closeSession(entry.senpiSessionId, "attempt_discarded");
}
},
};
}
//# sourceMappingURL=session-turn-attempt.js.map