Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

workflowAgent.ts

663 lines25.7 KB

1// The steps that involve someone else: an agent that returns data, and a person who answers.
2import * as Clock from "effect/Clock";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import { identity } from "effect/Function";
6import * as Option from "effect/Option";
7import * as Result from "effect/Result";
8import * as Schema from "effect/Schema";
9import { Activity, DurableDeferred } from "effect/workflow";
10​
11import { checkOptions } from "./options.ts";
12import { stepReferences } from "./runReferences.ts";
13import {
14 claim,
15 type InRun,
16 journaled,
17 jsonSchemaOf,
18 type StepFailed,
19 text,
20 waitAs,
21 wakeOf,
22} from "./workflow.ts";
23import type { IssueAddress } from "./WorkflowForge.ts";
24import {
25 type AgentLaunch,
26 type AgentModel,
27 AgentResult,
28 AgentTurn,
29 WorkflowAgents,
30} from "./WorkflowAgents.ts";
31import * as WorkflowStore from "./WorkflowStore.ts";
32​
33/** A thread an agent step ran in, to hand to a later step that should continue it. */
34export interface AgentThread {
35 readonly threadId: string;
36 /** The linked environment it is in. Absent for this one. */
37 readonly environment?: string | undefined;
39​
40const CORRECTIONS = 2;
41​
42export interface AgentOptions<A, I> extends AgentLaunch {
43 readonly brief: string;
44 /** The new thread's title. `<workflow>: <step>` by default. */
45 readonly title?: string;
46 readonly returns?: Schema.Codec<A, I>;
47 readonly model?: AgentModel;
48 readonly project?: string;
49 readonly environment?: string;
50 readonly thread?: AgentThread;
51 /**
52 * The issue this job is about. Its thread shows the issue, and the issue's page lists the
53 * thread. Only for a thread on this server, not one in a linked `environment`.
54 */
55 readonly issue?: IssueAddress;
56 /** How long the agent has. Past it the thread is stopped and the step has failed. */
57 readonly timeout?: Duration.Input;
58 /**
59 * Let the agent end a turn without its `returns` and answer from a later one, as an agent does
60 * that waits to be woken: by a pull request it watches, by work it left running. Only when
61 * its thread has done nothing for this long is it asked for the result. Without it, a turn
62 * that ends without the result is asked at once.
63 */
64 readonly quiet?: Duration.Input;
66​
67type Attempt<A> =
68 | { readonly outcome: "done"; readonly value: A; readonly thread: AgentThread }
69 | { readonly outcome: "failed"; readonly reason: string; readonly thread?: AgentThread };
70​
71const AGENT_OPTIONS = [
72 "brief",
73 "returns",
74 "model",
75 "project",
76 "environment",
77 "thread",
78 "issue",
79 "timeout",
80 "quiet",
81 "title",
82 "workspace",
83 "runtimeMode",
84 "interactionMode",
85];
86​
87// What only shapes a new thread: a continued one keeps its project, machine, model and modes.
88const NEW_THREAD_OPTIONS = [
89 "project",
90 "environment",
91 "model",
92 "title",
93 "workspace",
94 "runtimeMode",
95 "interactionMode",
96] as const;
97​
98/** What the engine needs to see one turn of an agent step through to its end. */
99export const TurnWatch = Schema.Struct({
100 agent: Schema.Struct({
101 step: Schema.String,
102 turn: AgentTurn,
103 startedAt: Schema.optional(Schema.Number),
104 timeoutMs: Schema.optional(Schema.Number),
105 quietMs: Schema.optional(Schema.Number),
106 owesOutput: Schema.Boolean,
107 onFailure: Schema.Literals(["pause", "return"]),
108 }),
109});
110export type TurnWatch = typeof TurnWatch.Type;
111​
112/** How a watched turn ended: its result, or why it could not be read, which pauses the run. */
113export const TurnEnd = Schema.Union([
114 Schema.Struct({ result: AgentResult }),
115 Schema.Struct({ lost: Schema.String }),
116]);
117export type TurnEnd = typeof TurnEnd.Type;
118​
119/** The turn's result, or its thread stopped when the step's time is up. */
120export const settleTurn = Effect.fn("workflow.agent.settle")(function* ({
121 agent: watch,
122}: TurnWatch): Effect.fn.Return<TurnEnd, never, WorkflowAgents> {
123 const agents = yield* WorkflowAgents;
124 const { turn, startedAt } = watch;
125 const threadOf = { threadId: turn.threadId, environment: turn.environment };
126 const resultOf = (quiet: number | undefined) =>
127 agents
128 .result(turn, { quiet: quiet === undefined ? undefined : Duration.millis(quiet) })
129 .pipe(
130 watch.onFailure === "pause"
131 ? identity
132 : Effect.catch((error) =>
133 Effect.succeed<AgentResult>({ ending: "failed", detail: text(error), reply: "" }),
134 ),
135 );
136 const settled = Effect.gen(function* () {
137 if (watch.timeoutMs === undefined || startedAt === undefined) {
138 return yield* resultOf(watch.quietMs);
139 }
140 const limit = Duration.millis(watch.timeoutMs);
141 const left = startedAt + watch.timeoutMs - (yield* Clock.currentTimeMillis);
142 const result = yield* resultOf(watch.quietMs).pipe(
143 Effect.timeoutOption(Duration.millis(Math.max(0, left))),
144 );
145 if (Option.isSome(result)) return result.value;
146 // A stop that still fails pauses the run, so resuming tries the stop again. A step that
147 // returns its failure says the turn may still be running.
148 const stopping = agents
149 .interrupt({ ...threadOf, turnId: turn.turnId })
150 .pipe(Effect.retry({ times: 2 }));
151 const stop: "stopped" | "ended" | "failed" = yield* watch.onFailure === "pause"
152 ? stopping
153 : stopping.pipe(Effect.orElseSucceed(() => "failed" as const));
154 const late = `it was not done after ${Duration.format(limit)}`;
155 if (stop === "ended") {
156 // The turn ended before it could be stopped, maybe long ago, as a run that resumes late
157 // finds it. What it left is the answer when it is one.
158 const ended = yield* resultOf(undefined);
159 if (ended.ending !== "completed" || !watch.owesOutput || ended.output !== undefined) {
160 return ended;
161 }
162 // Stopping the later turn it may answer from could stop someone else's.
163 return {
164 ending: "stopped" as const,
165 detail: `${late}: its turn ended without its result, and the agent may still be at work on its thread`,
166 reply: "",
167 };
168 }
169 return {
170 ending: "stopped" as const,
171 detail: `${late}${stop === "stopped" ? "" : ", and its turn could not be stopped"}`,
172 reply: "",
173 };
174 });
175 return yield* settled.pipe(
176 Effect.map((result): TurnEnd => ({ result })),
177 Effect.catch((error) => Effect.succeed<TurnEnd>({ lost: text(error) })),
178 );
179});
180​
181// An agent turn's wait takes no signal from outside: only the engine's watch ends it.
182const NOTHING_FITS = WorkflowStore.jsonText({ not: {} });
183// A result journaled when the wait for a turn still ran inside its activity, which kept the
184// engine from stopping, and every workflow call with it, until the turn ended.
185const Opened = Schema.Union([AgentResult, Schema.Struct({ ending: Schema.Literal("watching") })]);
186const decodeTurnEnd = Schema.decodeUnknownEffect(Schema.toCodecJson(TurnEnd));
187const encodeWatch = Schema.encodeEffect(Schema.toCodecJson(TurnWatch));
188​
189const attempt = Effect.fn("workflow.agent")(function* <A, I>(
190 name: string,
191 options: AgentOptions<A, I>,
192 /** What a failure does: pause the run at this step, or come back as the step's answer. */
193 onFailure: "pause" | "return",
194): Effect.fn.Return<Attempt<A>, StepFailed, InRun> {
195 checkOptions(`agent("${name}")`, options, AGENT_OPTIONS);
196 if (options.thread !== undefined) {
197 const shaping = NEW_THREAD_OPTIONS.filter((key) => options[key] !== undefined);
198 if (shaping.length > 0) {
199 return yield* Effect.die(
200 new Error(
201 `agent("${name}") continues \`thread\`, which keeps how it started. Drop ${shaping.map((key) => `\`${key}\``).join(", ")}.`,
202 ),
203 );
204 }
205 }
206 const run = yield* claim(name);
207 const agents = yield* WorkflowAgents;
208 const outputSchema =
209 options.returns === undefined ? undefined : jsonSchemaOf(options.returns, true);
210 // Only a turn asked for a result can owe one from a later turn.
211 const quiet =
212 options.quiet === undefined || outputSchema === undefined
213 ? undefined
214 : Duration.fromInputUnsafe(options.quiet);
215 const outputCodec =
216 options.returns === undefined ? undefined : Schema.toCodecJson(options.returns);
217 const decodeOutput = outputCodec === undefined ? undefined : Schema.decodeEffect(outputCodec);
218 const timeoutMs =
219 options.timeout === undefined
220 ? undefined
221 : Duration.toMillis(Duration.fromInputUnsafe(options.timeout));
222 const threadOf = (turn: AgentTurn): AgentThread => ({
223 threadId: turn.threadId,
224 ...(turn.environment === undefined ? {} : { environment: turn.environment }),
225 });
226 const launch: AgentLaunch | undefined =
227 options.workspace === undefined &&
228 options.runtimeMode === undefined &&
229 options.interactionMode === undefined
230 ? undefined
231 : {
232 workspace: options.workspace,
233 runtimeMode: options.runtimeMode,
234 interactionMode: options.interactionMode,
235 };
236 // What the agent's thread touches, its issue and the pull requests it links, is this step's.
237 const touches = stepReferences(run.store, run.runId, name);
238 const start = (key: string, prompt: string, thread: AgentThread | undefined) =>
239 agents
240 .start({
241 key: `${run.runId}/${name}/${key}`,
242 origin: { runId: run.runId, workflow: run.workflow, step: name },
243 title: options.title ?? `${run.workflow}: ${name}`,
244 // Only the step's own `thread` is refused them; a correction on the thread it made is not.
245 launch: thread === undefined || thread === options.thread ? launch : undefined,
246 prompt,
247 outputSchema,
248 model: options.model,
249 project: options.project,
250 environment: thread === undefined ? options.environment : thread.environment,
251 thread: thread?.threadId,
252 issue: options.issue,
253 })
254 .pipe(
255 Effect.provideContext(touches),
256 Effect.tap((turn) =>
257 run.store.stepThread(
258 run.runId,
259 name,
260 turn.threadId,
261 turn.environment ?? null,
262 turn.turnId,
263 ),
264 ),
265 Effect.flatMap((turn) =>
266 Effect.map(Clock.currentTimeMillis, (startedAt): AgentTurn => ({ ...turn, startedAt })),
267 ),
268 // No machine, no project, no link: for a step that takes failure as an answer, that is one.
269 onFailure === "pause"
270 ? identity
271 : Effect.catch((error) =>
272 Effect.succeed<AgentTurn>({ threadId: "", turnId: "", failed: text(error) }),
273 ),
274 );
275 /**
276 * The turn's result. The engine watches the turn outside the run and wakes the run once it
277 * ends, so an engine that stops while an agent works is not held up by it.
278 */
279 const ended = Effect.fn("workflow.agent.ended")(function* (
280 turn: AgentTurn,
281 startedAt: number | undefined,
282 round: number,
283 correction: number,
284 ) {
285 const watch = WorkflowStore.jsonText(
286 yield* encodeWatch({
287 agent: {
288 step: name,
289 turn,
290 startedAt,
291 timeoutMs,
292 quietMs: quiet === undefined ? undefined : Duration.toMillis(quiet),
293 owesOutput: outputSchema !== undefined,
294 onFailure,
295 },
296 }).pipe(Effect.orDie),
297 );
298 const first = `agent/${name}/${round}/result/${correction}`;
299 for (let lost = 0; ; lost++) {
300 const at = lost === 0 ? first : `${first}/again/${lost}`;
301 const wake = wakeOf(at);
302 const token = yield* DurableDeferred.token(wake);
303 const opened = yield* journaled(
304 run,
305 name,
306 at,
307 Opened,
308 Effect.gen(function* () {
309 yield* run.store.runStatus(run.runId, "waiting", `agent ${name}`);
310 yield* run.store.waitOpened({
311 runId: run.runId,
312 name: at,
313 workflow: run.workflow,
314 key: undefined,
315 token,
316 schemaJson: NOTHING_FITS,
317 requestJson: null,
318 watchJson: watch,
319 deadline: null,
320 });
321 yield* run.watchTurn(at);
322 return { ending: "watching" as const };
323 }),
324 );
325 if (opened.ending !== "watching") return opened;
326 const woke = yield* DurableDeferred.await(wake);
327 const end = yield* Effect.orDie(decodeTurnEnd(woke.value));
328 yield* Activity.make({ name: `${at}/close`, execute: run.store.waitClosed(run.runId, at) });
329 if ("result" in end) return end.result;
330 // Fails the first time it is reached, which pauses the run here. Resuming the run reaches
331 // it again, and the turn is watched once more.
332 yield* journaled(
333 run,
334 name,
335 `${at}/lost`,
336 Schema.Void,
337 Effect.flatMap(run.store.mark(run.runId, `${at}/lost`), (arrivals) =>
338 arrivals > 1 ? Effect.void : Effect.fail(end.lost),
339 ),
340 );
341 }
342 });
343 const done = (round: number, produced: Schema.Json, said?: string) =>
344 journaled(
345 run,
346 name,
347 `agent/${name}/${round}/done`,
348 Schema.Void,
349 Effect.all(
350 [
351 run.store.stepEnded(run.runId, name, "completed", null),
352 run.store.stepResult(run.runId, name, produced, said),
353 run.store.runResumed(run.runId),
354 ],
355 { discard: true },
356 ),
357 );
358​
359 for (let round = 0; ; round++) {
360 let turn = yield* journaled(
361 run,
362 name,
363 `agent/${name}/${round}/start`,
364 AgentTurn,
365 Effect.andThen(
366 run.store.stepStarted(run.runId, name, "agent"),
367 start(`${round}`, options.brief, options.thread),
368 ),
369 );
370 // Counted from the step's first turn, so corrections do not buy more time.
371 const startedAt = turn.startedAt;
372 let problem = turn.failed === undefined ? "" : `the agent could not be started: ${turn.failed}`;
373 let stopped = false;
374 let died = false;
375 for (let correction = 0; turn.failed === undefined; correction++) {
376 const result = yield* ended(turn, startedAt, round, correction);
377 if (result.ending !== "completed") {
378 stopped = result.ending === "stopped";
379 died = result.ending === "failed";
380 problem = `the agent's turn was ${stopped ? "stopped" : "cut short"}: ${result.detail}`;
381 break;
382 }
383 if (decodeOutput === undefined) {
384 yield* done(round, result.reply);
385 return { outcome: "done", value: result.reply as A, thread: threadOf(turn) };
386 }
387 // What the submitted result got wrong; undefined when nothing was submitted.
388 let misfit: string | undefined;
389 if (result.output !== undefined) {
390 const decoded = yield* Effect.result(decodeOutput(result.output));
391 if (Result.isSuccess(decoded)) {
392 yield* done(round, result.output, result.reply);
393 return { outcome: "done", value: decoded.success, thread: threadOf(turn) };
394 }
395 misfit = text(decoded.failure);
396 }
397 problem =
398 misfit === undefined
399 ? "the agent did not return a result: its turn ended with none accepted"
400 : `the agent's result did not fit: ${misfit}`;
401 if (correction >= CORRECTIONS) break;
402 // Back to the same thread: it has the context and only owes the result.
403 const corrected = yield* journaled(
404 run,
405 name,
406 `agent/${name}/${round}/correct/${correction}`,
407 AgentTurn,
408 start(
409 `${round}/correct/${correction}`,
410 misfit === undefined
411 ? "Your turn ended without an accepted result. Do not redo the work: call `t3_submit_output` now with the result of what you did."
412 : `The result you submitted does not fit: ${misfit}\nDo not redo the work: call \`t3_submit_output\` again with a corrected result.`,
413 threadOf(turn),
414 ),
415 );
416 if (corrected.failed !== undefined) {
417 problem = `${problem}, and it could not be asked again: ${corrected.failed}`;
418 break;
419 }
420 turn = corrected;
421 }
422 // The turn may only be out of sight, not dead: it is stopped before another does its work again.
423 // A stop that does not get through pauses the run unrecorded, or gives up a step that returns.
424 let lingers = false;
425 if (died && turn.failed === undefined) {
426 const lost = turn;
427 lingers = !(yield* journaled(
428 run,
429 name,
430 `agent/${name}/${round}/stop`,
431 Schema.Boolean,
432 agents
433 .interrupt({ ...threadOf(lost), turnId: lost.turnId })
434 .pipe(
435 Effect.retry({ times: 2 }),
436 Effect.as(true),
437 onFailure === "pause" ? identity : Effect.catch(() => Effect.succeed(false)),
438 ),
439 ));
440 if (lingers) problem = `${problem}; its turn could not be stopped`;
441 }
442 // A turn that died is not the job's fault the first time: once more, on a thread of its own,
443 // or on the same thread for a step that continues one, since only that thread has its project.
444 // Anything else is not tried again behind a person's back: one they stopped, one that never
445 // started, or one that did its work and would not give its result, which may have acted.
446 if (round % 2 === 0 && died && !lingers) continue;
447 if (onFailure === "return") {
448 yield* journaled(
449 run,
450 name,
451 `agent/${name}/${round}/failed`,
452 Schema.Void,
453 Effect.andThen(
454 run.store.stepEnded(run.runId, name, "failed", problem),
455 run.store.runResumed(run.runId),
456 ),
457 );
458 return {
459 outcome: "failed",
460 reason: problem,
461 ...(turn.failed === undefined ? { thread: threadOf(turn) } : {}),
462 };
463 }
464 // Fails the first time it is reached, which pauses the run here. Resuming the run reaches it
465 // again, and the next round starts.
466 yield* journaled(
467 run,
468 name,
469 `agent/${name}/${round}/pause`,
470 Schema.Void,
471 Effect.flatMap(run.store.mark(run.runId, `${name}/pause/${round}`), (arrivals) =>
472 arrivals > 1 ? Effect.void : Effect.fail(problem),
473 ),
474 // Resuming starts the agent's job again from the top, which is a person's call.
475 true,
476 );
477 }
478});
479​
480const orPause = <A = string, I = string>(
481 name: string,
482 options: AgentOptions<A, I>,
483): Effect.Effect<{ readonly value: A; readonly thread: AgentThread }, never, InRun> =>
484 Effect.flatMap(Effect.orDie(attempt(name, options, "pause")), (result) =>
485 result.outcome === "done"
486 ? Effect.succeed({ value: result.value, thread: result.thread })
487 : // `pause` never returns a failure: the step fails first, which pauses the run.
488 Effect.die(new Error(`Agent step ${name} failed without pausing: ${result.reason}`)),
489 );
490​
491/**
492 * An agent doing one job in a thread a person can open. It returns data checked against `returns`,
493 * or its last message without one. It starts a thread in `project`, in the linked `environment`
494 * when one is named, or continues `thread` where that is. Past `timeout` it is stopped. A turn
495 * that dies is tried once more, then the run pauses at this step.
496 */
497export const agent = Object.assign(orPause, {
498 /**
499 * For a workflow that decides for itself what a failed agent means: another model, another
500 * machine, or stop. An agent that could not be started, died twice, ran out of time or never
501 * gave its result comes back as `failed` with the reason, and the run goes on.
502 */
503 try: <A = string, I = string>(
504 name: string,
505 options: AgentOptions<A, I>,
506 ): Effect.Effect<Attempt<A>, never, InRun> => Effect.orDie(attempt(name, options, "return")),
507});
508​
509/** A choice that says what picking it does, or that takes an answer only with a reason. */
510// Types, not interfaces, so a question's request and its answer are still JSON.
511export type AskChoice<Value extends string = string> = {
512 readonly value: Value;
513 readonly description?: string;
514 readonly requireReason?: boolean;
515};
516​
517/** Something to look at before answering, shown on the question. */
518export type AskLink = {
519 readonly label: string;
520 readonly url: string;
521};
522​
523type ChoiceValue<C> = C extends string ? C : C extends AskChoice<infer Value> ? Value : never;
524​
525/** What a person answered, and who and when as the server saw it. */
526export type AskAnswer<Choice extends string> = {
527 readonly choice: Choice;
528 readonly reason?: string;
529 /** The name of the client, tool or agent thread that sent the answer. */
530 readonly answeredBy?: string;
531 /** The client session that sent it, for an answer given in the app. */
532 readonly answeredBySession?: string;
533 readonly answeredAt?: string;
534};
535​
536const ASK_OPTIONS = ["title", "choices", "kind", "data", "links", "timeout"];
537const ASK_CHOICE_OPTIONS = ["value", "description", "requireReason"];
538const ASK_LINK_OPTIONS = ["label", "url"];
539​
540const answeredFields = {
541 answeredBy: Schema.optional(Schema.String),
542 answeredBySession: Schema.optional(Schema.String),
543 answeredAt: Schema.optional(Schema.String),
544};
545const givenReason = Schema.String.check(Schema.isPattern(/\S/));
546​
547const readChoice = (name: string, choice: unknown): AskChoice => {
548 if (typeof choice === "string") return { value: choice };
549 if (typeof choice !== "object" || choice === null) {
550 throw new Error(
551 `ask("${name}")'s choices are text or \`{ value, description?, requireReason? }\`.`,
552 );
553 }
554 checkOptions(`ask("${name}")'s choice`, choice, ASK_CHOICE_OPTIONS);
555 const { value, description, requireReason } = choice as Record<string, unknown>;
556 if (
557 typeof value !== "string" ||
558 (description !== undefined && typeof description !== "string") ||
559 (requireReason !== undefined && typeof requireReason !== "boolean")
560 ) {
561 throw new Error(
562 `ask("${name}")'s choice takes \`value\` and \`description\` as text and \`requireReason\` as true or false.`,
563 );
564 }
565 return {
566 value,
567 ...(description === undefined || description.trim() === "" ? {} : { description }),
568 ...(requireReason === true ? { requireReason } : {}),
569 };
570};
571​
572const readLink = (name: string, link: unknown): AskLink => {
573 if (typeof link === "object" && link !== null) {
574 checkOptions(`ask("${name}")'s link`, link, ASK_LINK_OPTIONS);
575 const { label, url } = link as Record<string, unknown>;
576 if (typeof label === "string" && label.trim() !== "" && typeof url === "string") {
577 const protocol = URL.parse(url)?.protocol;
578 if (protocol === "https:" || protocol === "http:") return { label, url };
579 }
580 }
581 throw new Error(`ask("${name}")'s links are \`{ label, url }\`, each with an http or https url.`);
582};
583​
584/**
585 * A question a person answers with one of `choices`; `None` when the timeout passes first. `data`
586 * is the same facts as the title, for whatever lays the question out. `kind` is one of the
587 * workflow's `asks`, which lists filter by; any other kind is asked the same and listed as Other.
588 */
589export const ask = <const Choices extends ReadonlyArray<string | AskChoice>>(
590 name: string,
591 options: {
592 readonly title: string;
593 readonly choices: Choices;
594 readonly kind?: string;
595 readonly data?: Schema.Json;
596 readonly links?: ReadonlyArray<AskLink>;
597 readonly timeout?: Parameters<typeof waitAs>[2]["timeout"];
598 },
599): Effect.Effect<Option.Option<AskAnswer<ChoiceValue<Choices[number]>>>, never, InRun> =>
600 Effect.suspend(() => {
601 checkOptions(`ask("${name}")`, options, ASK_OPTIONS);
602 const kind = options.kind;
603 if (kind !== undefined && typeof kind !== "string") {
604 throw new Error(
605 `ask("${name}")'s kind is the name of one of the workflow's \`asks\`, as text.`,
606 );
607 }
608 if (options.links !== undefined && !Array.isArray(options.links)) {
609 throw new Error(`ask("${name}")'s links are a list of \`{ label, url }\`.`);
610 }
611 const choices = options.choices.map((choice) => readChoice(name, choice));
612 const links = (options.links ?? []).map((link) => readLink(name, link));
613 const values = choices.map((choice) => choice.value);
614 const needReason = choices.filter((choice) => choice.requireReason).map((c) => c.value);
615 const free = values.filter((value) => !needReason.includes(value));
616 const answer = (picks: ReadonlyArray<string>, reason: Schema.Top) =>
617 Schema.Struct({ choice: Schema.Literals(picks), reason, ...answeredFields });
618 const optionalReason = answer(free, Schema.optional(Schema.String));
619 const requiredReason = answer(needReason, givenReason);
620 const returns =
621 needReason.length === 0
622 ? optionalReason
623 : free.length === 0
624 ? requiredReason
625 : Schema.Union([optionalReason, requiredReason]);
626 const described = choices.filter(
627 (choice) => choice.description !== undefined || choice.requireReason,
628 );
629 return Effect.orDie(
630 waitAs("ask", name, {
631 returns: returns as unknown as Schema.Codec<AskAnswer<ChoiceValue<Choices[number]>>>,
632 timeout: options.timeout,
633 request: {
634 title: options.title,
635 // Plain values, so a client that knows no `choiceDetails` still offers every choice.
636 choices: values,
637 ...(described.length === 0 ? {} : { choiceDetails: described }),
638 ...(links.length === 0 ? {} : { links }),
639 ...(kind === undefined ? {} : { kind }),
640 ...(options.data === undefined ? {} : { data: options.data }),
641 },
642 }),
643 );
644 });
645​
646/**
647 * Why `value` does not answer a question asked with `request`, in words that name the choice, or
648 * undefined when nothing in it is missing. The wait's schema refuses it as well, in less plain words.
649 */
650export const answerProblem = (request: unknown, value: unknown): string | undefined => {
651 const field = (from: unknown, key: string): unknown =>
652 typeof from === "object" && from !== null ? (from as Record<string, unknown>)[key] : undefined;
653 const choice = field(value, "choice");
654 const reason = field(value, "reason");
655 const details = field(request, "choiceDetails");
656 if (typeof choice !== "string" || !Array.isArray(details)) return undefined;
657 const needed = details.some(
658 (detail) => field(detail, "value") === choice && field(detail, "requireReason") === true,
659 );
660 return needed && (typeof reason !== "string" || reason.trim() === "")
661 ? `"${choice}" needs a reason. Send one with the answer.`
662 : undefined;
663};