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

grade.ts

182 lines8.1 KB

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