The Open Framework for Building Agents
feat(eve): add editable setup questions (#1896)
OwenKepharta56e0174bed1
diff --git a/packages/eve/src/setup/ask-editable.ts b/packages/eve/src/setup/ask-editable.tsnew file mode 100644index 000000000..2cf4b2b96--- /dev/null+++ b/packages/eve/src/setup/ask-editable.ts@@ -0,0 +1,84 @@+import type { Prompter } from "./prompter.js";+import { optionById, requiredOptionId } from "./question-options.js";+import type { SelectOption } from "./ask.js";++export interface EditableSelectQuestion<T> {+ key: string;+ message: string;+ options: readonly SelectOption<T>[];+ recommended?: T;+ required?: boolean;+ editable: {+ key: string;+ value: T;+ label: string;+ recommended: string;+ validate?: (raw: string) => string | null;+ };+}++export interface EditableSelectAnswer<T> {+ value: T;+ text?: string;+}++function selectedValue<T>(question: EditableSelectQuestion<T>, id: unknown): T {+ const match = optionById(question, id);+ if (match !== undefined) return match.value;+ const ids = question.options.map((option) => option.id).join(", ");+ throw new Error(`Invalid answer for "${question.key}": ${String(id)}. Expected one of: ${ids}.`);+}++/** Renders the specialized one-row editable select through a terminal prompter. */+export async function renderEditableQuestion<T>(+ prompter: Prompter,+ question: EditableSelectQuestion<T>,+): Promise<EditableSelectAnswer<T>> {+ const editableOptionId = requiredOptionId(+ question,+ question.editable.value,+ "configured editable value",+ );+ const options = question.options.map((option) => ({+ value: option.id,+ label: option.label,+ hint: option.hint,+ featured: option.featured,+ }));+ const initialValue =+ question.recommended === undefined+ ? undefined+ : requiredOptionId(question, question.recommended, "recommendation");+ if (prompter.selectEditable !== undefined) {+ const result = await prompter.selectEditable({+ message: question.message,+ options,+ initialValue,+ editable: {+ value: editableOptionId,+ defaultValue: question.editable.recommended,+ formatHint: (value) => `${question.editable.label}: ${value}`,+ validate: (value) => question.editable.validate?.(value) ?? undefined,+ },+ });+ const value = selectedValue(question, result.value);+ return value === question.editable.value+ ? {+ value,+ text:+ result.kind === "edited" ? result.text.trim() : question.editable.recommended.trim(),+ }+ : { value };+ }+ const value = selectedValue(+ question,+ await prompter.select({ message: question.message, options, initialValue }),+ );+ if (value !== question.editable.value) return { value };+ const text = await prompter.text({+ message: question.editable.label,+ defaultValue: question.editable.recommended,+ validate: (raw) => question.editable.validate?.(raw) ?? undefined,+ });+ return { value, text: text.trim() };+}diff --git a/packages/eve/src/setup/ask-signals.ts b/packages/eve/src/setup/ask-signals.tsnew file mode 100644index 000000000..710fe1cad--- /dev/null+++ b/packages/eve/src/setup/ask-signals.ts@@ -0,0 +1,45 @@+import type { EditableSelectQuestion } from "./ask-editable.js";+import type { MultiSelectQuestion, Question } from "./ask.js";++/** Thrown when a skippable question is skipped, so the box can branch on it. */+export class SkippedSignal extends Error {+ readonly key: string;+ constructor(key: string) {+ super(`Skipped: ${key}`);+ this.name = "SkippedSignal";+ this.key = key;+ }+}++/** Any question the channel can carry, for signals that quote one. */+export type AnyQuestion =+ | Question<unknown>+ | EditableSelectQuestion<unknown>+ | MultiSelectQuestion<unknown>;++/**+ * Headless refusal that keeps the whole question: an agent driver can relay+ * exactly what is missing (key, message, options) instead of a bare string.+ */+export class InteractionRequired extends Error {+ readonly question: AnyQuestion;+ constructor(question: AnyQuestion) {+ super(`Interaction required for "${question.key}": ${question.message}`);+ this.name = "InteractionRequired";+ this.question = question;+ }+}++/** Thrown when a pre-supplied answer fails the question's own validation. */+export class InvalidAnswerError extends Error {+ readonly question: AnyQuestion;+ constructor(question: AnyQuestion, message: string) {+ super(message);+ this.name = "InvalidAnswerError";+ this.question = question;+ }++ get key(): string {+ return this.question.key;+ }+}diff --git a/packages/eve/src/setup/ask.test.ts b/packages/eve/src/setup/ask.test.tsindex 8e3dc2d52..2796627cc 100644--- a/packages/eve/src/setup/ask.test.ts+++ b/packages/eve/src/setup/ask.test.ts@@ -30,6 +30,9 @@ function untouchableAsker(): Asker {ask(question): Promise<never> {throw new Error(`untouchableAsker was asked "${question.key}"`);},+ askEditable(question): Promise<never> {+ throw new Error(`untouchableAsker was asked "${question.key}"`);+ },askMany(question): Promise<never> {throw new Error(`untouchableAsker was asked "${question.key}"`);},@@ -124,6 +127,74 @@ describe("interactiveAsker", () => {);});+ it("preserves an editable select as one interactive prompter control", async () => {+ const { prompter } = createFakePrompter();+ prompter.selectEditable = async <T>() => ({+ kind: "edited" as const,+ value: "red" as T,+ text: "crimson",+ });+ const editable = vi.spyOn(prompter, "selectEditable");+ const events = recordingEvents();++ const value = await interactiveAsker(prompter, events).askEditable({+ key: "color",+ message: "Pick a color",+ options: COLOR_OPTIONS,+ recommended: RED,+ required: true,+ editable: {+ key: "color-name",+ value: RED,+ label: "Name",+ recommended: "scarlet",+ },+ });++ expect(value).toEqual({ value: RED, text: "crimson" });+ expect(editable).toHaveBeenCalledWith(+ expect.objectContaining({+ message: "Pick a color",+ initialValue: "red",+ editable: expect.objectContaining({ value: "red", defaultValue: "scarlet" }),+ }),+ );+ expect(events.resolutions).toEqual([+ { key: "color", value: RED, source: "asked" },+ { key: "color-name", value: "crimson", source: "asked" },+ ]);+ });++ it("falls back to select then text when inline editing is unavailable", async () => {+ const { prompter } = createFakePrompter({+ single: () => "red",+ text: () => " crimson ",+ });++ const value = await interactiveAsker(prompter).askEditable({+ key: "color",+ message: "Pick a color",+ options: COLOR_OPTIONS,+ recommended: RED,+ editable: {+ key: "color-name",+ value: RED,+ label: "Name",+ recommended: "scarlet",+ },+ });++ expect(value).toEqual({ value: RED, text: "crimson" });+ });++ it("rejects a select recommendation that is not one of its options", async () => {+ const { prompter } = selectPrompter(() => "red");++ await expect(+ interactiveAsker(prompter).ask(colorQuestion({ recommended: { hex: "#bad" } })),+ ).rejects.toThrow('Question "color" has a recommendation that is not one of its options.');+ });+it("renders a confirm as the repo's yes/no select and returns a boolean", async () => {const { single, prompter } = selectPrompter(() => "yes");@@ -392,6 +463,45 @@ describe("withAnswers", () => {]);});+ it("resolves an editable selection and its text from separate stable keys", async () => {+ const events = recordingEvents();+ const asker = withAnswers(+ { color: "red", "color-name": "crimson" },+ events,+ )(untouchableAsker());++ const value = await asker.askEditable({+ key: "color",+ message: "Pick a color",+ options: COLOR_OPTIONS,+ required: true,+ editable: { key: "color-name", value: RED, label: "Name", recommended: "scarlet" },+ });++ expect(value).toEqual({ value: RED, text: "crimson" });+ expect(events.resolutions).toEqual([+ { key: "color", value: RED, source: "answer" },+ { key: "color-name", value: "crimson", source: "answer" },+ ]);+ });++ it("refuses the editable text before mutation when only its option is answered", async () => {+ const asker = withAnswers({ color: "red" })(headlessAsker());++ await expect(+ asker.askEditable({+ key: "color",+ message: "Pick a color",+ options: COLOR_OPTIONS,+ required: true,+ editable: { key: "color-name", value: RED, label: "Name", recommended: "scarlet" },+ }),+ ).rejects.toMatchObject({+ name: "InteractionRequired",+ question: expect.objectContaining({ key: "color-name" }),+ });+ });+it("rejects an unknown multi-select id naming the alternatives, and a non-array answer", async () => {const asker = withAnswers({ colors: ["magenta"] })(untouchableAsker());diff --git a/packages/eve/src/setup/ask.ts b/packages/eve/src/setup/ask.tsindex 2b0f90246..8e7a1b3e7 100644--- a/packages/eve/src/setup/ask.ts+++ b/packages/eve/src/setup/ask.ts@@ -15,8 +15,26 @@// which also unlocks combinations a monolithic factory could not express.import { SetupPrerequisiteRequired } from "./integrations/shared/prerequisite.js";+import {+ renderEditableQuestion,+ type EditableSelectAnswer,+ type EditableSelectQuestion,+} from "./ask-editable.js";+import {+ InteractionRequired,+ InvalidAnswerError,+ SkippedSignal,+ type AnyQuestion,+} from "./ask-signals.js";+export type { EditableSelectAnswer, EditableSelectQuestion } from "./ask-editable.js";+export {+ InteractionRequired,+ InvalidAnswerError,+ SkippedSignal,+ type AnyQuestion,+} from "./ask-signals.js";import type { Prompter } from "./prompter.js";-import { optionById, requiredOptionId } from "./question-options.js";+import { optionById, optionByValue, requiredOptionId } from "./question-options.js";/** One choice in a select question. */export interface SelectOption<T> {@@ -185,6 +203,8 @@ export function text(/** The capability boxes see. Pure and flow-agnostic: Prompter's successor. */export interface Asker {ask<T>(question: Question<T>): Promise<T>;+ /** A single choice whose one row carries an editable string value. */+ askEditable<T>(question: EditableSelectQuestion<T>): Promise<EditableSelectAnswer<T>>;/*** The multi-select channel. Paired with {@link ask} instead of being a* question kind because the answer type (`T[]`) differs from the option type@@ -203,46 +223,6 @@ export type AskerDecorator = (inner: Asker) => Asker;// interactive prompter throws and the runner folds; the channel lets it// propagate instead of introducing a second cancel signal.-/** Thrown when a skippable question is skipped, so the box can branch on it. */-export class SkippedSignal extends Error {- readonly key: string;- constructor(key: string) {- super(`Skipped: ${key}`);- this.name = "SkippedSignal";- this.key = key;- }-}--/** Any question the channel can carry, for signals that quote one. */-export type AnyQuestion = Question<unknown> | MultiSelectQuestion<unknown>;--/**- * Headless refusal that keeps the whole question: an agent driver can relay- * exactly what is missing (key, message, options) instead of a bare string.- */-export class InteractionRequired extends Error {- readonly question: AnyQuestion;- constructor(question: AnyQuestion) {- super(`Interaction required for "${question.key}": ${question.message}`);- this.name = "InteractionRequired";- this.question = question;- }-}--/** Thrown when a pre-supplied answer fails the question's own validation. */-export class InvalidAnswerError extends Error {- readonly question: AnyQuestion;- constructor(question: AnyQuestion, message: string) {- super(message);- this.name = "InvalidAnswerError";- this.question = question;- }-- get key(): string {- return this.question.key;- }-}-/** How a question got its value, so nothing is silently assumed. */export type ResolutionSource = "answer" | "detected" | "assumed" | "asked" | "skipped";@@ -463,6 +443,12 @@ export function interactiveAsker(prompter: Prompter, events?: AskerEvents): Askeif (question.internal) return value;return announce(events, question.key, value, "asked");},+ async askEditable<T>(question: EditableSelectQuestion<T>): Promise<EditableSelectAnswer<T>> {+ const result = await renderEditableQuestion(prompter, question);+ announce(events, question.key, result.value, "asked");+ if (result.text !== undefined) announce(events, question.editable.key, result.text, "asked");+ return result;+ },async askMany<T>(question: MultiSelectQuestion<T>): Promise<T[]> {const value = await renderManyQuestion(prompter, question);if (question.internal) return value;@@ -489,6 +475,9 @@ export function headlessAsker(events?: AskerEvents): Asker {async ask<T>(question: Question<T>): Promise<T> {return refuse(question);},+ async askEditable<T>(question: EditableSelectQuestion<T>): Promise<EditableSelectAnswer<T>> {+ return refuse(question);+ },async askMany<T>(question: MultiSelectQuestion<T>): Promise<T[]> {return refuse(question);},@@ -529,6 +518,42 @@ export function withAnswers(}return inner.ask(question);},+ async askEditable<T>(question: EditableSelectQuestion<T>): Promise<EditableSelectAnswer<T>> {+ if (!(question.key in answers)) return inner.askEditable(question);+ const selection = coerceAnswer(+ select({ key: question.key, message: question.message, options: question.options }),+ answers[question.key],+ );+ announce(events, question.key, selection, "answer");+ if (selection !== question.editable.value) return { value: selection };+ if (!(question.editable.key in answers)) {+ const value = await inner.ask(+ text({+ key: question.editable.key,+ message: optionByValue(question, selection)?.label ?? question.message,+ recommended: question.editable.recommended,+ required: question.required,+ validate: question.editable.validate,+ }),+ );+ return { value: selection, text: value.trim() };+ }+ const raw = String(answers[question.editable.key]);+ const problem = question.editable.validate?.(raw);+ if (problem) {+ throw new InvalidAnswerError(+ text({+ key: question.editable.key,+ message: question.editable.label,+ required: question.required,+ }),+ problem,+ );+ }+ const value = raw.trim();+ announce(events, question.editable.key, value, "answer");+ return { value: selection, text: value };+ },async askMany<T>(question: MultiSelectQuestion<T>): Promise<T[]> {if (question.key in answers) {const value = coerceManyAnswer(question, answers[question.key]);@@ -553,6 +578,13 @@ export function withRequired(keys: readonly string[]): AskerDecorator {}return inner.ask(question);},+ async askEditable<T>(question: EditableSelectQuestion<T>): Promise<EditableSelectAnswer<T>> {+ return inner.askEditable(+ !question.required && keys.includes(question.key)+ ? { ...question, required: true }+ : question,+ );+ },async askMany<T>(question: MultiSelectQuestion<T>): Promise<T[]> {if (!question.required && keys.includes(question.key)) {return inner.askMany({ ...question, required: true });@@ -608,6 +640,22 @@ export function withPolicy(policy: AnswerPolicy, events?: AskerEvents): AskerDec}return inner.ask(question);},+ async askEditable<T>(question: EditableSelectQuestion<T>): Promise<EditableSelectAnswer<T>> {+ if (policy !== "assume" || question.recommended === undefined) {+ return inner.askEditable(question);+ }+ requiredOptionId(question, question.editable.value, "configured editable value");+ requiredOptionId(question, question.recommended, "recommendation");+ const result: EditableSelectAnswer<T> =+ question.recommended === question.editable.value+ ? { value: question.recommended, text: question.editable.recommended }+ : { value: question.recommended };+ announce(events, question.key, result.value, "assumed");+ if (result.text !== undefined) {+ announce(events, question.editable.key, result.text, "assumed");+ }+ return result;+ },async askMany<T>(question: MultiSelectQuestion<T>): Promise<T[]> {if (policy === "assume") {if (question.detected !== undefined) {diff --git a/packages/eve/src/setup/boxes/select-model.test.ts b/packages/eve/src/setup/boxes/select-model.test.tsindex 145e30872..a587ed9fe 100644--- a/packages/eve/src/setup/boxes/select-model.test.ts+++ b/packages/eve/src/setup/boxes/select-model.test.ts@@ -86,6 +86,9 @@ function untouchableAsker(): Asker {ask(question): Promise<never> {throw new Error(`untouchableAsker was asked "${question.key}"`);},+ askEditable(question): Promise<never> {+ throw new Error(`untouchableAsker was asked "${question.key}"`);+ },askMany(question): Promise<never> {throw new Error(`untouchableAsker was asked "${question.key}"`);},diff --git a/packages/eve/src/setup/integrations/discord/setup.test.ts b/packages/eve/src/setup/integrations/discord/setup.test.tsindex 921f17a7c..0436bdf3f 100644--- a/packages/eve/src/setup/integrations/discord/setup.test.ts+++ b/packages/eve/src/setup/integrations/discord/setup.test.ts@@ -9,6 +9,9 @@ import { setupDiscord, type DiscordSetupDeps } from "./setup.js";function asker(answers: Record<string, string>): Asker {return {ask: async <T>(question: Question<T>) => answers[question.key] as T,+ askEditable: async () => {+ throw new Error("Unexpected editable question");+ },askMany: async () => [],};}@@ -82,6 +85,9 @@ describe("Discord setup", () => {if (question.key === "discord-bot-token") return "bot-token" as T;return question.detected as T;},+ askEditable: async () => {+ throw new Error("Unexpected editable question");+ },askMany: async () => [],},prompter: createFakePrompter().prompter,diff --git a/packages/eve/src/setup/integrations/github/setup.test.ts b/packages/eve/src/setup/integrations/github/setup.test.tsindex 5de6e97b2..e79b428ff 100644--- a/packages/eve/src/setup/integrations/github/setup.test.ts+++ b/packages/eve/src/setup/integrations/github/setup.test.ts@@ -24,6 +24,7 @@ describe("GitHub setup", () => {function asker(events = ["issue_comment", "pull_request_review_comment"]): Asker {return {ask: vi.fn(),+ askEditable: vi.fn(),askMany: vi.fn(async () => events) as Asker["askMany"],};}@@ -70,7 +71,7 @@ describe("GitHub setup", () => {appRoot: "/project",environment: integrationSetupEnvironment("authenticated", { kind: "unresolved" }),ui: createIntegrationSetupUi({- asker: { ask: vi.fn(), askMany },+ asker: { ask: vi.fn(), askEditable: vi.fn(), askMany },prompter: fake.prompter,}),},diff --git a/packages/eve/src/setup/integrations/linear/setup.test.ts b/packages/eve/src/setup/integrations/linear/setup.test.tsindex d674bf1ab..10abcd272 100644--- a/packages/eve/src/setup/integrations/linear/setup.test.ts+++ b/packages/eve/src/setup/integrations/linear/setup.test.ts@@ -20,8 +20,11 @@ function deps(): LinearSetupDeps {function recommendedAsker(): Asker {const ask = async <T>(question: Question<T>): Promise<T> => question.recommended as T;+ const askEditable: Asker["askEditable"] = async () => {+ throw new Error("Unexpected editable question");+ };const askMany: Asker["askMany"] = async () => [];- return { ask, askMany };+ return { ask, askEditable, askMany };}describe("Linear setup", () => {diff --git a/packages/eve/src/setup/integrations/photon/setup-flow.test.ts b/packages/eve/src/setup/integrations/photon/setup-flow.test.tsindex c572fff26..521ea18aa 100644--- a/packages/eve/src/setup/integrations/photon/setup-flow.test.ts+++ b/packages/eve/src/setup/integrations/photon/setup-flow.test.ts@@ -10,6 +10,9 @@ import { setupPhoton, type PhotonSetupDeps } from "./setup-flow.js";function asker(answers: Record<string, string>): Asker {return {ask: async <T>(question: Question<T>) => answers[question.key] as T,+ askEditable: async () => {+ throw new Error("Unexpected editable question");+ },askMany: async () => [],};}diff --git a/packages/eve/src/setup/integrations/registry.test.ts b/packages/eve/src/setup/integrations/registry.test.tsindex 07b0d4644..893c8dbce 100644--- a/packages/eve/src/setup/integrations/registry.test.ts+++ b/packages/eve/src/setup/integrations/registry.test.ts@@ -9,6 +9,9 @@ import { WizardCancelledError } from "../step.js";const unusedAsker: Asker = {ask: async <T>() => undefined as T,+ askEditable: async () => {+ throw new Error("Unexpected editable question");+ },askMany: async () => [],};diff --git a/packages/eve/src/setup/integrations/slack/setup.test.ts b/packages/eve/src/setup/integrations/slack/setup.test.tsindex be5007d31..cc7966238 100644--- a/packages/eve/src/setup/integrations/slack/setup.test.ts+++ b/packages/eve/src/setup/integrations/slack/setup.test.ts@@ -40,7 +40,7 @@ describe("setupSlack", () => {appRoot: "/project",environment: integrationSetupEnvironment("authenticated", { kind: "unresolved" }),ui: createIntegrationSetupUi({- asker: { ask: vi.fn(), askMany: vi.fn() },+ asker: { ask: vi.fn(), askEditable: vi.fn(), askMany: vi.fn() },prompter: fake.prompter,}),yes: true,diff --git a/packages/eve/src/setup/setup-question-wire.test.ts b/packages/eve/src/setup/setup-question-wire.test.tsindex 3adea04f3..4c6042955 100644--- a/packages/eve/src/setup/setup-question-wire.test.ts+++ b/packages/eve/src/setup/setup-question-wire.test.ts@@ -1,5 +1,11 @@import { describe, expect, it } from "vitest";-import { confirm, select, text, type MultiSelectQuestion } from "./ask.js";+import {+ confirm,+ select,+ text,+ type EditableSelectQuestion,+ type MultiSelectQuestion,+} from "./ask.js";import { setupQuestionToWire } from "./setup-question-wire.js";describe("setupQuestionToWire", () => {@@ -103,6 +109,49 @@ describe("setupQuestionToWire", () => {expect(JSON.stringify(wire)).not.toContain("internal");});+ it("projects editable selects to separate stable keys", () => {+ const custom = { internal: "custom" };+ const standard = { internal: "standard" };+ const question: EditableSelectQuestion<object> = {+ key: "project",+ message: "Project?",+ options: [+ { id: "standard", label: "Standard", value: standard },+ { id: "custom", label: "Custom", value: custom },+ ],+ recommended: custom,+ required: true,+ editable: {+ key: "project-name",+ value: custom,+ label: "Project name",+ recommended: "my-project",+ validate: () => "not serialized",+ },+ };++ const wire = setupQuestionToWire(question);++ expect(wire).toEqual({+ kind: "editable-select",+ key: "project",+ message: "Project?",+ required: true,+ recommended: "custom",+ options: [+ { id: "standard", label: "Standard" },+ { id: "custom", label: "Custom" },+ ],+ editable: {+ key: "project-name",+ optionId: "custom",+ label: "Project name",+ recommended: "my-project",+ },+ });+ expect(JSON.stringify(wire)).not.toContain("internal");+ });+it("rejects recommendations that are not represented by an option id", () => {const known = { id: "known" };const unknown = { id: "unknown" };diff --git a/packages/eve/src/setup/setup-question-wire.ts b/packages/eve/src/setup/setup-question-wire.tsindex 6f834f494..ec6655e14 100644--- a/packages/eve/src/setup/setup-question-wire.ts+++ b/packages/eve/src/setup/setup-question-wire.ts@@ -25,6 +25,12 @@ export type SetupWireQuestion =kind: "multi-select";recommended?: readonly string[];options: readonly SetupWireOption[];+ })+ | (SharedWireQuestion & {+ kind: "editable-select";+ recommended?: string;+ options: readonly SetupWireOption[];+ editable: { key: string; optionId: string; label: string; recommended: string };});function wireOptions(question: {@@ -56,6 +62,29 @@ function sharedQuestion(question: AnyQuestion): SharedWireQuestion {/** Removes runtime values and validators from one internal setup question. */export function setupQuestionToWire(question: AnyQuestion): SetupWireQuestion {const shared = sharedQuestion(question);+ if ("editable" in question) {+ const editable = question;+ const editableId = requiredOptionId(+ editable,+ editable.editable.value,+ "configured editable value",+ );+ const wire: Extract<SetupWireQuestion, { kind: "editable-select" }> = {+ ...shared,+ kind: "editable-select",+ options: wireOptions(editable),+ editable: {+ key: editable.editable.key,+ optionId: editableId,+ label: editable.editable.label,+ recommended: editable.editable.recommended,+ },+ };+ if (editable.recommended !== undefined) {+ wire.recommended = requiredOptionId(editable, editable.recommended, "recommendation");+ }+ return wire;+ }if (!("kind" in question)) {const many = question;const wire: Extract<SetupWireQuestion, { kind: "multi-select" }> = {