@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
225 lines • 11.1 kB
JavaScript
import { userWordBlocks } from "../../../tool-result-user-words.js";
import { DEFAULT_ASK_USER_TIMEOUT_MS, } from "./schema.js";
import { INLINE_WORDS, readUserWordBlocks, resolveUserWordReferences, separatedWords, } from "./user-words.js";
function headerFor(id, questions) {
return questions.find((question) => question.id === id)?.header ?? id;
}
function questionTextFor(id, questions) {
return questions.find((question) => question.id === id)?.question ?? id;
}
function typedText(answer) {
if (answer.selected.length > 0)
return undefined;
const text = answer.text?.trim();
return text === undefined || text.length === 0 ? undefined : text;
}
/** A typed text that repeats an offered label (clients that report picks as text) is not the user's own words. */
function answerBody(answer, header, words = INLINE_WORDS, offered = []) {
if (!answer)
return undefined;
if (answer.selected.length > 0)
return answer.selected.join(", ");
const text = typedText(answer);
if (text === undefined)
return undefined;
return offered.some((option) => option.label === text) ? text : words.typed(header, text);
}
function answeredLines(response, questions, words) {
const lines = [];
const seen = new Set();
for (const question of questions) {
const body = answerBody(response.answers[question.id], question.header, words, question.options);
if (body !== undefined) {
lines.push(`${question.header}: ${body}`);
seen.add(question.id);
}
}
for (const [id, answer] of Object.entries(response.answers)) {
if (seen.has(id))
continue;
const header = headerFor(id, questions);
const body = answerBody(answer, header, words);
if (body !== undefined)
lines.push(`${header}: ${body}`);
}
return lines;
}
function unansweredLine(response, questions) {
const unanswered = response.unanswered.map((id) => headerFor(id, questions));
return unanswered.length > 0 ? [`Unanswered: ${unanswered.join(", ")}`] : [];
}
const CANCELLED_BY_USER = "The user cancelled the question after answering part of it.";
const CANCELLED_AFTER_ANSWERS = "The question was cancelled after part of it was answered.";
/** Whether a line opens the partial answers of a cancelled question. */
export function isCancelledWithAnswersLine(line) {
return line === CANCELLED_BY_USER || line === CANCELLED_AFTER_ANSWERS;
}
/**
* The one rule for a cancelled question's partial answers (sisyphuslabs/omo-desktop-app#4042): a cancel
* the user chose, or a failing question UI, shows the model what was already answered. Every lifecycle
* cancel (a turn abort, the session closing, ask-user disabled, a closed RPC connection) stays silent.
*/
export function showsPartialAnswers(response) {
if (response.status !== "cancelled")
return false;
if (response.cancelOrigin !== "user" && response.cancelOrigin !== "ui_failure")
return false;
return Object.values(response.answers).some((answer) => answerBody(answer, "") !== undefined);
}
function selectedBlock(prefix, selected) {
return selected.length === 1 ? [`${prefix} ${selected[0]}`] : [prefix, ...selected];
}
const GATED_NO_ANSWER = "No answer: do not take the action it gates. Keep that action pending and end the turn.";
/** A required question gates an action, so every settlement without an answer refuses that action (senpi#2949). */
function formatGatedNoAnswer(response, questions, words, cancellationReason) {
const reason = cancellationReason ??
(response.status === "timed_out"
? `The user did not answer within ${Math.round((response.autoResolvedAfterMs ?? DEFAULT_ASK_USER_TIMEOUT_MS) / 60_000)} minutes. (사용자가 답변을 안하고 timeout 으로 종료됨)`
: response.status === "cancelled"
? "The user dismissed the question."
: response.status === "orphaned-after-restart"
? "The pending question could not be resumed after a restart."
: "This session has no user attached (subagent or headless).");
const lines = [reason];
const selected = answeredLines(response, questions, words);
if (selected.length > 0)
lines.push(...selectedBlock("Before going idle the user had selected (not an answer):", selected));
lines.push(GATED_NO_ANSWER);
return lines.join("\n");
}
/**
* A required question cancelled with a reason (a UI failure): the reason stands in for the status line,
* a draft the user typed is named and marked not an answer, and the action is refused (senpi#2949).
*/
export function formatGatedCancellation(reason, response, requestId, questions) {
return formatGatedNoAnswer(response, questions, separatedWords(requestId), reason);
}
function formatBody(response, questions, words, required = false) {
if (required && response.status !== "answered" && response.status !== "comment-submitted") {
return formatGatedNoAnswer(response, questions, words);
}
switch (response.status) {
case "answered":
return [...answeredLines(response, questions, words), ...unansweredLine(response, questions)].join("\n");
case "comment-submitted": {
const comment = response.comment?.trim() ?? "";
const lines = [
`The user responded: ${comment.length > 0 ? words.comment(comment) : ""}`,
...answeredLines(response, questions, words),
...unansweredLine(response, questions),
];
return lines.join("\n");
}
case "timed_out": {
const minutes = Math.round((response.autoResolvedAfterMs ?? DEFAULT_ASK_USER_TIMEOUT_MS) / 60_000);
const lines = [
`The user did not answer within ${minutes} minutes. (사용자가 답변을 안하고 timeout 으로 종료됨)`,
];
const selected = answeredLines(response, questions, words);
if (selected.length > 0) {
lines.push(...selectedBlock("Before going idle the user had selected:", selected), ...unansweredLine(response, questions));
}
lines.push("Continue the work to completion on your best judgment; do not ask this question again this turn.");
return lines.join("\n");
}
case "cancelled": {
if (!showsPartialAnswers(response))
return "The user dismissed the question.";
// A UI failure names itself; only a cancel the user chose says the user cancelled.
const reason = response.cancelOrigin === "ui_failure" ? response.comment?.trim() : undefined;
return [
...(reason ? [reason] : []),
response.cancelOrigin === "user" ? CANCELLED_BY_USER : CANCELLED_AFTER_ANSWERS,
...answeredLines(response, questions, words),
...unansweredLine(response, questions),
].join("\n");
}
case "orphaned-after-restart":
return "The pending question could not be resumed after a restart; continue on best judgment.";
case "unavailable":
return "This session has no user attached (subagent or headless); decide on best judgment.";
}
}
/** The answer as a person reads it, with the user's words inline (hooks, the transcript card). */
export function formatResultText(_variant, response, questions = [], required = false) {
return formatBody(response, questions, INLINE_WORDS, required);
}
/**
* The answer as the model receives it: `text` holds only the structure and the options the model
* offered; each of the user's own words is a `words` entry that `text` names by its label.
*/
export function formatModelAnswer(response, requestId, questions = [], required = false) {
const placement = separatedWords(requestId);
return { text: formatBody(response, questions, placement, required), words: placement.words };
}
/**
* The framed user message for a later answer: the `[Answer to question <id>]` frame with the
* structure, then each of the user's words after its own label block. An answer with no typed
* words stays the single framed string it always was.
*/
export function formatUserMessage(response, requestId, questions = [], required = false) {
const answer = formatModelAnswer(response, requestId, questions, required);
const frame = `[Answer to question ${requestId}]\n${answer.text}`;
if (answer.words.length === 0)
return frame;
return [{ type: "text", text: frame }, ...userWordBlocks(answer.words)];
}
/** Display text of a framed answer whose words travel as labelled blocks; undefined otherwise. */
export function askUserAnswerDisplayText(content) {
if (typeof content === "string")
return undefined;
const [first, ...rest] = content;
if (first?.type !== "text" || rest.length === 0 || !parseAskUserAnswerFrame(first.text))
return undefined;
const words = readUserWordBlocks(rest);
return words ? resolveUserWordReferences(first.text, words) : undefined;
}
export function parseAskUserAnswerFrame(text) {
const match = /^\[Answer to question ([^\]\r\n]+)\]\r?\n([\s\S]*)$/.exec(text);
return match ? { requestId: match[1], body: match[2] } : undefined;
}
function selectedAnswers(answer) {
if (answer.selected.length > 0)
return answer.selected;
const text = answer.text?.trim();
return text === undefined || text.length === 0 ? [] : [text];
}
export function formatResultDetails(variant, response, requestId, questions = [], required = false) {
const { words } = formatModelAnswer(response, requestId, questions, required);
if (variant === "codex") {
const answers = {};
for (const [id, answer] of Object.entries(response.answers)) {
answers[id] = { answers: selectedAnswers(answer) };
}
const details = {
...(response.resolvedBy !== undefined ? { resolvedBy: response.resolvedBy } : {}),
answers,
unanswered: response.unanswered,
status: response.status,
};
if (response.comment !== undefined)
details.comment = response.comment;
if (words.length > 0)
details.userWords = words;
return details;
}
const answers = {};
for (const [id, answer] of Object.entries(response.answers)) {
const body = answerBody(answer, headerFor(id, questions));
if (body !== undefined)
answers[questionTextFor(id, questions)] = body;
}
const details = {
...(response.resolvedBy !== undefined ? { resolvedBy: response.resolvedBy } : {}),
questions,
answers,
unanswered: response.unanswered.map((id) => questionTextFor(id, questions)),
status: response.status,
};
if (response.comment !== undefined)
details.freeText = response.comment;
if (words.length > 0)
details.userWords = words;
return details;
}
//# sourceMappingURL=format.js.map