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

workflowAgent.ts

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