@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
198 lines • 10.3 kB
JavaScript
import { AgentBusyError } from "../../core/agent-busy-error.js";
import { clientMessageIdentity } from "../../core/client-message-identity.js";
import { ModelNotReadyError } from "../../core/model-not-ready-error.js";
import { SessionMovedAwayError } from "../../core/session-move/ownership.js";
import { TurnConflictError } from "../../core/turn-conflict.js";
import { UNKNOWN_COMMAND_CONFIRM_HINT, UnknownCommandError } from "../../core/unknown-command.js";
import { ClientMessageIdConflict, } from "./client-admission-record.js";
import { admitInputChain } from "./chain-admission.js";
import { ClientAdmissions } from "./client-admissions.js";
import { clientInputContext } from "./client-message-events.js";
import { RPC_ERROR_NO_MODEL_SELECTED, RPC_ERROR_TURN_CONFLICT, RPC_ERROR_PROVIDER_CREDENTIALS_EXPIRED, RPC_ERROR_PROVIDER_CREDENTIALS_MISSING, RPC_ERROR_UNKNOWN_COMMAND, } from "./rpc-types.js";
class ChainRefusedError extends Error {
constructor(refusal) {
super(refusal.message);
this.name = "ChainRefusedError";
this.refusal = refusal;
}
}
/** The `prompt` refusal's `errorCode` for each reason a turn cannot start. */
const MODEL_NOT_READY_ERROR_CODES = {
provider_credentials_missing: RPC_ERROR_PROVIDER_CREDENTIALS_MISSING,
provider_credentials_expired: RPC_ERROR_PROVIDER_CREDENTIALS_EXPIRED,
no_model_selected: RPC_ERROR_NO_MODEL_SELECTED,
};
/** The same admission path serves classic stdio, shared sessions, and worker sessions. */
export async function handleClientInput(session, command, io, client = { interactiveUser: false }) {
try {
// A thread call from another session is admitted against the user's count limit before anything of it is recorded.
const admittedChain = admitInputChain(command.chainCount, session.settingsManager);
if (admittedChain.kind === "refused")
throw new ChainRefusedError(admittedChain.refusal);
const chain = admittedChain.chainCount === undefined ? {} : { chainCount: admittedChain.chainCount };
const admissions = ClientAdmissions.forSession(session);
let disposition;
let turnId;
let responded = false;
const respond = (admission) => {
responded = true;
const finalDisposition = admission?.disposition ?? disposition;
const admittedTurnId = admission?.turnId ?? turnId;
io.output({
id: command.id,
type: "response",
command: command.type,
success: true,
data: {
disposition: finalDisposition,
...(admittedTurnId === undefined ? {} : { turnId: admittedTurnId }),
...clientMessageIdentity(command),
...(admission ? { admission } : {}),
...(command.type === "prompt" && command.toolBarrier !== undefined
? { toolBarrier: finalDisposition === "started" ? "armed" : "ignored" }
: {}),
},
});
};
const admission = await clientInputContext.run(clientMessageIdentity(command), () => admissions.admit(command, async (hooks) => {
// A sealed file would refuse this input only when the turn writes it, after `prompt` was accepted (senpi#5889).
const ownership = session.sessionManager.getOwnership();
if (!ownership.writable)
throw new SessionMovedAwayError(session.sessionManager.getSessionFile() ?? "", ownership);
// `prompt` and `steer`/`follow_up { whenIdle: "start" }` share one path: the session decides
// atomically whether the input starts a turn or joins the running one.
const promptPath = (options) => {
const accepted = Promise.withResolvers();
let preflightSucceeded = false;
let acceptedAdmission;
const call = session
.prompt(command.message, {
...clientMessageIdentity(command),
images: command.images,
...options,
source: "rpc",
interactiveUser: client.interactiveUser,
...(client.connectionOrigin === undefined ? {} : { connectionOrigin: client.connectionOrigin }),
...chain,
onQueuedInput: hooks.queued,
promptDisposition: (next) => {
disposition = next;
if (next !== "started")
acceptedAdmission = hooks.accepted(next);
},
preflightResult: (succeeded) => {
if (succeeded && disposition !== undefined && disposition !== "started") {
preflightSucceeded = true;
accepted.resolve(disposition);
respond(acceptedAdmission);
}
},
onTurnAdmitted: () => {
// The epoch exists here, before agent.prompt emits the user message.
turnId = session.currentTurnId;
acceptedAdmission = hooks.accepted("started", turnId);
preflightSucceeded = true;
accepted.resolve("started");
respond(acceptedAdmission);
},
})
.catch((error) => {
if (!preflightSucceeded)
accepted.reject(error);
});
io.promptCalls.add(call);
void call.finally(() => io.promptCalls.delete(call));
return accepted.promise;
};
switch (command.type) {
case "prompt": {
if (command.thinkingLevel !== undefined &&
session.isStreaming &&
command.streamingBehavior !== undefined) {
throw new Error("Cannot set thinkingLevel on a queued prompt; set it after the current turn completes.");
}
return promptPath({
streamingBehavior: command.streamingBehavior,
// The session checks it where the steer enters the queue, in the same step (senpi#5776).
expectedTurnId: command.expectedTurnId,
thinkingLevel: command.thinkingLevel,
sessionTitlePrompt: command.sessionTitlePrompt,
expandPromptTemplates: command.expandPromptTemplates,
unknownCommandAsText: command.unknownCommandAsText,
toolBarrier: command.toolBarrier,
});
}
case "steer":
case "follow_up": {
if (command.whenIdle === "start")
return promptPath({
streamingBehavior: command.type === "steer" ? "steer" : "followUp",
enqueueOrder: command.enqueueOrder,
expectedTurnId: command.expectedTurnId,
});
const options = {
...clientMessageIdentity(hooks.identity),
enqueueOrder: command.enqueueOrder,
// Checked where the input enters the queue, in the same step (senpi#5776).
expectedTurnId: command.expectedTurnId,
source: "rpc",
interactiveUser: client.interactiveUser,
...(client.connectionOrigin === undefined ? {} : { connectionOrigin: client.connectionOrigin }),
...chain,
onQueuedInput: hooks.queued,
};
disposition =
command.type === "steer"
? await session.steer(command.message, command.images, options)
: await session.followUp(command.message, command.images, options);
hooks.accepted(disposition);
return disposition;
}
}
}));
if (!responded)
respond(admission);
}
catch (error) {
const unknownCommand = error instanceof UnknownCommandError;
io.output({
id: command.id,
type: "response",
command: command.type,
success: false,
error: unknownCommand
? `${error.message} ${UNKNOWN_COMMAND_CONFIRM_HINT}`
: error instanceof Error
? error.message
: String(error),
...(error instanceof ClientMessageIdConflict || error instanceof AgentBusyError
? { errorCode: error.code }
: {}),
...(error instanceof ModelNotReadyError
? {
errorCode: MODEL_NOT_READY_ERROR_CODES[error.code],
...(error.provider === undefined ? {} : { errorData: { provider: error.provider } }),
}
: {}),
...(error instanceof SessionMovedAwayError
? { errorCode: error.code, errorData: { state: error.ownership.state } }
: {}),
...(error instanceof TurnConflictError
? {
errorCode: RPC_ERROR_TURN_CONFLICT,
...(error.currentTurnId === undefined ? {} : { errorData: { currentTurnId: error.currentTurnId } }),
}
: {}),
...(error instanceof ChainRefusedError
? { errorCode: error.refusal.errorCode, errorData: error.refusal.errorData }
: {}),
...(unknownCommand
? {
errorCode: RPC_ERROR_UNKNOWN_COMMAND,
errorData: { command: error.command, suggestions: error.suggestions, reason: error.reason },
}
: {}),
});
}
}
//# sourceMappingURL=client-input-handler.js.map