Open History to see the last commit
1// Grades a workflow file the way the server would use it: loaded by the real loader, registered
2// in the real engine on a throwaway database, and driven with a stand-in for agents.
3import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Result from "effect/Result";
12import * as Stream from "effect/Stream";
13
14import WorkflowsMigration from "../../apps/server/src/persistence/Migrations/110_Workflows.ts";
15import WorkflowRunTagsMigration from "../../apps/server/src/persistence/Migrations/115_WorkflowRunTags.ts";
16import WorkflowMailSenderMigration from "../../apps/server/src/persistence/Migrations/117_WorkflowMailSender.ts";
17import WorkflowPoolsMigration from "../../apps/server/src/persistence/Migrations/118_WorkflowPools.ts";
18import WorkflowRunSubjectMigration from "../../apps/server/src/persistence/Migrations/119_WorkflowRunSubject.ts";
19import type { WorkflowDefinition } from "../../apps/server/src/workflows/workflow.ts";
20import {
21 type AgentResult,
22 WorkflowAgents,
23} from "../../apps/server/src/workflows/WorkflowAgents.ts";
24import * as WorkflowEngine from "../../apps/server/src/workflows/WorkflowEngine.ts";
25import { loadDefinitions } from "../../apps/server/src/workflows/WorkflowRuntime.ts";
26import * as Workflows from "../../apps/server/src/workflows/Workflows.ts";
27import type { WorkflowRun } from "../../apps/server/src/workflows/WorkflowStore.ts";
28
29export type AgentTurnInput = Parameters<WorkflowAgents["Service"]["start"]>[0];
30
31/**
32 * One server holding the file's workflows. Each `server` call is one lifetime of it: the file
33 * loaded afresh and a new engine on the same database, as after a restart.
34 */
35export interface World {
36 readonly definitions: ReadonlyArray<WorkflowDefinition>;
37 /** Every agent turn the workflows asked for, in order. */
38 readonly turns: ReadonlyArray<AgentTurnInput>;
39 readonly server: <A>(
40 use: (workflows: Workflows.Workflows["Service"]) => Effect.Effect<A, Workflows.WorkflowError>,
41 ) => Effect.Effect<A, Workflows.WorkflowError>;
42 /** The run once it is in one of these states, or nothing after ten seconds. */
43 readonly reaches: (
44 workflows: Workflows.Workflows["Service"],
45 runId: string,
46 ...statuses: ReadonlyArray<WorkflowRun["status"]>
47 ) => Effect.Effect<Option.Option<WorkflowRun>>;
48 /** The name of the question the run asks a person, or nothing after ten seconds. */
49 readonly asks: (
50 workflows: Workflows.Workflows["Service"],
51 runId: string,
52 ) => Effect.Effect<Option.Option<string>>;
53}
54
55export interface Case {
56 readonly id: string;
57 readonly source: string;
58 /** What the model is asked to write. */
59 readonly task: string;
60 /** What a fake agent answers. Each scenario of the case sets its own. */
61 readonly scenarios: ReadonlyArray<{
62 readonly name: string;
63 readonly agent: (turn: AgentTurnInput) => Partial<AgentResult>;
64 /** The problems found. None is a pass. */
65 readonly check: (world: World) => Effect.Effect<ReadonlyArray<string>, Workflows.WorkflowError>;
66 }>;
67}
68
69// Across every grade in the process: a load under an address used before would get that module.
70let lifetimes = 0;
71
72const world = Effect.fn("gradeWorkflow.world")(function* (
73 file: string,
74 definitions: ReadonlyArray<WorkflowDefinition>,
75 agent: (turn: AgentTurnInput) => Partial<AgentResult>,
76) {
77 const fileSystem = yield* FileSystem.FileSystem;
78 const path = yield* Path.Path;
79 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflow-eval-" });
80 const database = NodeSqliteClient.layer({ filename: path.join(directory, "state.sqlite") });
81 yield* Effect.provide(
82 WorkflowsMigration.pipe(
83 Effect.andThen(WorkflowRunTagsMigration),
84 Effect.andThen(WorkflowMailSenderMigration),
85 Effect.andThen(WorkflowPoolsMigration),
86 Effect.andThen(WorkflowRunSubjectMigration),
87 ),
88 database,
89 );
90 const turns: Array<AgentTurnInput> = [];
91 const asked = new Map<string, AgentTurnInput>();
92 const agents = WorkflowAgents.of({
93 start: Effect.fn("gradeWorkflow.agents.start")(function* (input) {
94 if (!asked.has(input.key)) {
95 asked.set(input.key, input);
96 turns.push(input);
97 }
98 return yield* Effect.succeed({
99 threadId: input.thread ?? `thread-${input.key}`,
100 turnId: input.key,
101 });
102 }),
103 result: Effect.fn("gradeWorkflow.agents.result")(function* (turn) {
104 return yield* Effect.succeed({
105 ending: "completed" as const,
106 detail: "",
107 reply: "",
108 ...agent(asked.get(turn.turnId)!),
109 });
110 }),
111 // Every turn here has already completed, so there is nothing to stop.
112 interrupt: Effect.fn("gradeWorkflow.agents.interrupt")(function* () {
113 return yield* Effect.succeed("ended" as const);
114 }),
115 });
116 const engine = (loaded: ReadonlyArray<WorkflowDefinition>) =>
117 WorkflowEngine.layer(loaded).pipe(
118 Layer.provide(Layer.succeed(WorkflowAgents, agents)),
119 Layer.provide(database),
120 Layer.provide(NodeCrypto.layer),
121 Layer.orDie,
122 );
123 return {
124 definitions,
125 turns,
126 server: (use) =>
127 loadDefinitions(file, ++lifetimes).pipe(
128 Effect.orDie,
129 Effect.provideService(Path.Path, path),
130 Effect.flatMap((loaded) =>
131 Effect.scoped(Effect.provide(Effect.flatMap(Workflows.Workflows, use), engine(loaded))),
132 ),
133 ),
134 reaches: (workflows, runId, ...statuses) =>
135 workflows
136 .waitFor(runId, (run) => statuses.includes(run.status))
137 .pipe(Effect.timeoutOption("10 seconds")),
138 asks: (workflows, runId) =>
139 workflows.watch.pipe(
140 // A question comes in the first list, or in the update where it is asked.
141 Stream.filterMap((update) => {
142 const question = update.questions.find((asked) => asked.runId === runId);
143 return question === undefined ? Result.failVoid : Result.succeed(question.name);
144 }),
145 Stream.runHead,
146 Effect.timeoutOption("10 seconds"),
147 Effect.map(Option.flatten),
148 ),
149 } satisfies World;
150});
151
152const problemsWith = Effect.fn("gradeWorkflow.problemsWith")(function* (file: string, entry: Case) {
153 const loaded = yield* Effect.result(loadDefinitions(file));
154 if (loaded._tag === "Failure") {
155 return [`The file does not load: ${String(loaded.failure.cause)}`];
156 }
157 const problems: Array<string> = [];
158 for (const scenario of entry.scenarios) {
159 const found = yield* world(file, loaded.success, scenario.agent).pipe(
160 Effect.flatMap(scenario.check),
161 Effect.scoped,
162 Effect.catch((error) => Effect.succeed([error.message])),
163 Effect.catchDefect((defect) => Effect.succeed([`It crashed: ${String(defect)}`])),
164 );
165 problems.push(...found.map((problem) => `${scenario.name}: ${problem}`));
166 }
167 return problems;
168});
169
170/** The problems with the workflow file at `file` as an answer to `entry`. None is a pass. */
171export const grade = (file: string, entry: Case): Promise<ReadonlyArray<string>> =>
172 Effect.runPromise(Effect.provide(problemsWith(file, entry), NodeServices.layer));