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

workflowAgent.ts

442 lines16.3 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";
9​
10import { checkOptions } from "./options.ts";
11import { stepReferences } from "./runReferences.ts";
12import {
13 claim,
14 type InRun,
15 journaled,
16 jsonSchemaOf,
17 type StepFailed,
18 text,
19 waitAs,
20} from "./workflow.ts";
21import type { IssueAddress } from "./WorkflowForge.ts";
22import {
23 type AgentLaunch,
24 type AgentModel,
25 AgentResult,
26 AgentTurn,
27 WorkflowAgents,
28} from "./WorkflowAgents.ts";
29​
30/** A thread an agent step ran in, to hand to a later step that should continue it. */
31export interface AgentThread {
32 readonly threadId: string;
33 /** The linked environment it is in. Absent for this one. */
34 readonly environment?: string | undefined;
36​
37const CORRECTIONS = 2;
38​
39export interface AgentOptions<A, I> extends AgentLaunch {
40 readonly brief: string;
41 /** The new thread's title. `<workflow>: <step>` by default. */
42 readonly title?: string;
43 readonly returns?: Schema.Codec<A, I>;
44 readonly model?: AgentModel;
45 readonly project?: string;
46 readonly environment?: string;
47 readonly thread?: AgentThread;
48 /**
49 * The issue this job is about. Its thread shows the issue, and the issue's page lists the
50 * thread. Only for a thread on this server, not one in a linked `environment`.
51 */
52 readonly issue?: IssueAddress;
53 /** How long the agent has. Past it the thread is stopped and the step has failed. */
54 readonly timeout?: Duration.Input;
55 /**
56 * Let the agent end a turn without its `returns` and answer from a later one, as an agent does
57 * that waits to be woken: by a pull request it watches, by work it left running. Only when
58 * its thread has done nothing for this long is it asked for the result. Without it, a turn
59 * that ends without the result is asked at once.
60 */
61 readonly quiet?: Duration.Input;
63​
64type Attempt<A> =
65 | { readonly outcome: "done"; readonly value: A; readonly thread: AgentThread }
66 | { readonly outcome: "failed"; readonly reason: string; readonly thread?: AgentThread };
67​
68const AGENT_OPTIONS = [
69 "brief",
70 "returns",
71 "model",
72 "project",
73 "environment",
74 "thread",
75 "issue",
76 "timeout",
77 "quiet",
78 "title",
79 "workspace",
80 "runtimeMode",
81 "interactionMode",
82];
83​
84// What only shapes a new thread: a continued one keeps its project, machine, model and modes.
85const NEW_THREAD_OPTIONS = [
86 "project",
87 "environment",
88 "model",
89 "title",
90 "workspace",
91 "runtimeMode",
92 "interactionMode",
93] as const;
94​
95const attempt = Effect.fn("workflow.agent")(function* <A, I>(
96 name: string,
97 options: AgentOptions<A, I>,
98 /** What a failure does: pause the run at this step, or come back as the step's answer. */
99 onFailure: "pause" | "return",
100): Effect.fn.Return<Attempt<A>, StepFailed, InRun> {
101 checkOptions(`agent("${name}")`, options, AGENT_OPTIONS);
102 if (options.thread !== undefined) {
103 const shaping = NEW_THREAD_OPTIONS.filter((key) => options[key] !== undefined);
104 if (shaping.length > 0) {
105 return yield* Effect.die(
106 new Error(
107 `agent("${name}") continues \`thread\`, which keeps how it started. Drop ${shaping.map((key) => `\`${key}\``).join(", ")}.`,
108 ),
109 );
110 }
111 }
112 const run = yield* claim(name);
113 const agents = yield* WorkflowAgents;
114 const outputSchema =
115 options.returns === undefined ? undefined : jsonSchemaOf(options.returns, true);
116 // Only a turn asked for a result can owe one from a later turn.
117 const quiet =
118 options.quiet === undefined || outputSchema === undefined
119 ? undefined
120 : Duration.fromInputUnsafe(options.quiet);
121 const outputCodec =
122 options.returns === undefined ? undefined : Schema.toCodecJson(options.returns);
123 const decodeOutput = outputCodec === undefined ? undefined : Schema.decodeEffect(outputCodec);
124 const threadOf = (turn: AgentTurn): AgentThread => ({
125 threadId: turn.threadId,
126 ...(turn.environment === undefined ? {} : { environment: turn.environment }),
127 });
128 const launch: AgentLaunch | undefined =
129 options.workspace === undefined &&
130 options.runtimeMode === undefined &&
131 options.interactionMode === undefined
132 ? undefined
133 : {
134 workspace: options.workspace,
135 runtimeMode: options.runtimeMode,
136 interactionMode: options.interactionMode,
137 };
138 // What the agent's thread touches, its issue and the pull requests it links, is this step's.
139 const touches = stepReferences(run.store, run.runId, name);
140 const start = (key: string, prompt: string, thread: AgentThread | undefined) =>
141 agents
142 .start({
143 key: `${run.runId}/${name}/${key}`,
144 origin: { runId: run.runId, workflow: run.workflow, step: name },
145 title: options.title ?? `${run.workflow}: ${name}`,
146 // Only the step's own `thread` is refused them; a correction on the thread it made is not.
147 launch: thread === undefined || thread === options.thread ? launch : undefined,
148 prompt,
149 outputSchema,
150 model: options.model,
151 project: options.project,
152 environment: thread === undefined ? options.environment : thread.environment,
153 thread: thread?.threadId,
154 issue: options.issue,
155 })
156 .pipe(
157 Effect.provideContext(touches),
158 Effect.tap((turn) =>
159 run.store.stepThread(
160 run.runId,
161 name,
162 turn.threadId,
163 turn.environment ?? null,
164 turn.turnId,
165 ),
166 ),
167 Effect.flatMap((turn) =>
168 Effect.map(Clock.currentTimeMillis, (startedAt): AgentTurn => ({ ...turn, startedAt })),
169 ),
170 // No machine, no project, no link: for a step that takes failure as an answer, that is one.
171 onFailure === "pause"
172 ? identity
173 : Effect.catch((error) =>
174 Effect.succeed<AgentTurn>({ threadId: "", turnId: "", failed: text(error) }),
175 ),
176 );
177 const resultOf = (turn: AgentTurn, wait = { quiet }) =>
178 agents
179 .result(turn, wait)
180 .pipe(
181 Effect.provideContext(touches),
182 onFailure === "pause"
183 ? identity
184 : Effect.catch((error) =>
185 Effect.succeed<AgentResult>({ ending: "failed", detail: text(error), reply: "" }),
186 ),
187 );
188 /** The turn's result, or its thread stopped when the step's time is up. */
189 const within = Effect.fn("workflow.agent.within")(function* (
190 turn: AgentTurn,
191 startedAt: number | undefined,
192 ) {
193 if (options.timeout === undefined || startedAt === undefined) return yield* resultOf(turn);
194 const limit = Duration.fromInputUnsafe(options.timeout);
195 const left = startedAt + Duration.toMillis(limit) - (yield* Clock.currentTimeMillis);
196 const result = yield* resultOf(turn).pipe(
197 Effect.timeoutOption(Duration.millis(Math.max(0, left))),
198 );
199 if (Option.isSome(result)) return result.value;
200 // A stop that still fails pauses the run unrecorded, so resuming tries the stop again. A step
201 // that returns its failure says the turn may still be running.
202 const stopping = agents
203 .interrupt({ ...threadOf(turn), turnId: turn.turnId })
204 .pipe(Effect.retry({ times: 2 }));
205 const stop: "stopped" | "ended" | "failed" = yield* onFailure === "pause"
206 ? stopping
207 : stopping.pipe(Effect.orElseSucceed(() => "failed" as const));
208 const late = `it was not done after ${Duration.format(limit)}`;
209 if (stop === "ended") {
210 // The turn ended before it could be stopped, maybe long ago, as a run that resumes late
211 // finds it. What it left is the answer when it is one.
212 const ended = yield* resultOf(turn, { quiet: undefined });
213 if (
214 ended.ending !== "completed" ||
215 outputSchema === undefined ||
216 ended.output !== undefined
217 ) {
218 return ended;
219 }
220 // Stopping the later turn it may answer from could stop someone else's.
221 return {
222 ending: "stopped" as const,
223 detail: `${late}: its turn ended without its result, and the agent may still be at work on its thread`,
224 reply: "",
225 };
226 }
227 return {
228 ending: "stopped" as const,
229 detail: `${late}${stop === "stopped" ? "" : ", and its turn could not be stopped"}`,
230 reply: "",
231 };
232 });
233 const done = (round: number, produced: Schema.Json, said?: string) =>
234 journaled(
235 run,
236 name,
237 `agent/${name}/${round}/done`,
238 Schema.Void,
239 Effect.all(
240 [
241 run.store.stepEnded(run.runId, name, "completed", null),
242 run.store.stepResult(run.runId, name, produced, said),
243 run.store.runResumed(run.runId),
244 ],
245 { discard: true },
246 ),
247 );
248​
249 for (let round = 0; ; round++) {
250 let turn = yield* journaled(
251 run,
252 name,
253 `agent/${name}/${round}/start`,
254 AgentTurn,
255 Effect.andThen(
256 run.store.stepStarted(run.runId, name, "agent"),
257 start(`${round}`, options.brief, options.thread),
258 ),
259 );
260 // Counted from the step's first turn, so corrections do not buy more time.
261 const startedAt = turn.startedAt;
262 let problem = turn.failed === undefined ? "" : `the agent could not be started: ${turn.failed}`;
263 let stopped = false;
264 let died = false;
265 for (let correction = 0; turn.failed === undefined; correction++) {
266 const result = yield* journaled(
267 run,
268 name,
269 `agent/${name}/${round}/result/${correction}`,
270 AgentResult,
271 Effect.andThen(
272 run.store.runStatus(run.runId, "waiting", `agent ${name}`),
273 within(turn, startedAt),
274 ),
275 );
276 if (result.ending !== "completed") {
277 stopped = result.ending === "stopped";
278 died = result.ending === "failed";
279 problem = `the agent's turn was ${stopped ? "stopped" : "cut short"}: ${result.detail}`;
280 break;
281 }
282 if (decodeOutput === undefined) {
283 yield* done(round, result.reply);
284 return { outcome: "done", value: result.reply as A, thread: threadOf(turn) };
285 }
286 // What the submitted result got wrong; undefined when nothing was submitted.
287 let misfit: string | undefined;
288 if (result.output !== undefined) {
289 const decoded = yield* Effect.result(decodeOutput(result.output));
290 if (Result.isSuccess(decoded)) {
291 yield* done(round, result.output, result.reply);
292 return { outcome: "done", value: decoded.success, thread: threadOf(turn) };
293 }
294 misfit = text(decoded.failure);
295 }
296 problem =
297 misfit === undefined
298 ? "the agent did not return a result: its turn ended with none accepted"
299 : `the agent's result did not fit: ${misfit}`;
300 if (correction >= CORRECTIONS) break;
301 // Back to the same thread: it has the context and only owes the result.
302 const corrected = yield* journaled(
303 run,
304 name,
305 `agent/${name}/${round}/correct/${correction}`,
306 AgentTurn,
307 start(
308 `${round}/correct/${correction}`,
309 misfit === undefined
310 ? "Your turn ended without an accepted result. Do not redo the work: call `t3_submit_output` now with the result of what you did."
311 : `The result you submitted does not fit: ${misfit}\nDo not redo the work: call \`t3_submit_output\` again with a corrected result.`,
312 threadOf(turn),
313 ),
314 );
315 if (corrected.failed !== undefined) {
316 problem = `${problem}, and it could not be asked again: ${corrected.failed}`;
317 break;
318 }
319 turn = corrected;
320 }
321 // The turn may only be out of sight, not dead: it is stopped before another does its work again.
322 // A stop that does not get through pauses the run unrecorded, or gives up a step that returns.
323 let lingers = false;
324 if (died && turn.failed === undefined) {
325 const lost = turn;
326 lingers = !(yield* journaled(
327 run,
328 name,
329 `agent/${name}/${round}/stop`,
330 Schema.Boolean,
331 agents
332 .interrupt({ ...threadOf(lost), turnId: lost.turnId })
333 .pipe(
334 Effect.retry({ times: 2 }),
335 Effect.as(true),
336 onFailure === "pause" ? identity : Effect.catch(() => Effect.succeed(false)),
337 ),
338 ));
339 if (lingers) problem = `${problem}; its turn could not be stopped`;
340 }
341 // A turn that died is not the job's fault the first time: once more, on a thread of its own,
342 // or on the same thread for a step that continues one, since only that thread has its project.
343 // Anything else is not tried again behind a person's back: one they stopped, one that never
344 // started, or one that did its work and would not give its result, which may have acted.
345 if (round % 2 === 0 && died && !lingers) continue;
346 if (onFailure === "return") {
347 yield* journaled(
348 run,
349 name,
350 `agent/${name}/${round}/failed`,
351 Schema.Void,
352 Effect.andThen(
353 run.store.stepEnded(run.runId, name, "failed", problem),
354 run.store.runResumed(run.runId),
355 ),
356 );
357 return {
358 outcome: "failed",
359 reason: problem,
360 ...(turn.failed === undefined ? { thread: threadOf(turn) } : {}),
361 };
362 }
363 // Fails the first time it is reached, which pauses the run here. Resuming the run reaches it
364 // again, and the next round starts.
365 yield* journaled(
366 run,
367 name,
368 `agent/${name}/${round}/pause`,
369 Schema.Void,
370 Effect.flatMap(run.store.mark(run.runId, `${name}/pause/${round}`), (arrivals) =>
371 arrivals > 1 ? Effect.void : Effect.fail(problem),
372 ),
373 // Resuming starts the agent's job again from the top, which is a person's call.
374 true,
375 );
376 }
377});
378​
379const orPause = <A = string, I = string>(
380 name: string,
381 options: AgentOptions<A, I>,
382): Effect.Effect<{ readonly value: A; readonly thread: AgentThread }, never, InRun> =>
383 Effect.flatMap(Effect.orDie(attempt(name, options, "pause")), (result) =>
384 result.outcome === "done"
385 ? Effect.succeed({ value: result.value, thread: result.thread })
386 : // `pause` never returns a failure: the step fails first, which pauses the run.
387 Effect.die(new Error(`Agent step ${name} failed without pausing: ${result.reason}`)),
388 );
389​
390/**
391 * An agent doing one job in a thread a person can open. It returns data checked against `returns`,
392 * or its last message without one. It starts a thread in `project`, in the linked `environment`
393 * when one is named, or continues `thread` where that is. Past `timeout` it is stopped. A turn
394 * that dies is tried once more, then the run pauses at this step.
395 */
396export const agent = Object.assign(orPause, {
397 /**
398 * For a workflow that decides for itself what a failed agent means: another model, another
399 * machine, or stop. An agent that could not be started, died twice, ran out of time or never
400 * gave its result comes back as `failed` with the reason, and the run goes on.
401 */
402 try: <A = string, I = string>(
403 name: string,
404 options: AgentOptions<A, I>,
405 ): Effect.Effect<Attempt<A>, never, InRun> => Effect.orDie(attempt(name, options, "return")),
406});
407​
408/**
409 * A question a person answers with one of `choices`; `None` when the timeout passes first. The run
410 * holds nothing while it waits. `data` is the same facts as the title, for whatever lays the
411 * question out.
412 */
413export const ask = <const Choices extends ReadonlyArray<string>>(
414 name: string,
415 options: {
416 readonly title: string;
417 readonly choices: Choices;
418 readonly data?: Schema.Json;
419 readonly timeout?: Parameters<typeof waitAs>[2]["timeout"];
420 },
421): Effect.Effect<
422 Option.Option<{ readonly choice: Choices[number]; readonly reason?: string | undefined }>,
423 never,
424 InRun
425> =>
426 Effect.suspend(() => {
427 checkOptions(`ask("${name}")`, options, ["title", "choices", "data", "timeout"]);
428 return Effect.orDie(
429 waitAs("ask", name, {
430 returns: Schema.Struct({
431 choice: Schema.Literals(options.choices),
432 reason: Schema.optional(Schema.String),
433 }),
434 timeout: options.timeout,
435 request: {
436 title: options.title,
437 choices: [...options.choices],
438 ...(options.data === undefined ? {} : { data: options.data }),
439 },
440 }),
441 );
442 });