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

environment.ts

510 lines18.5 KB

1// @effect-diagnostics nodeBuiltinImport:off globalTimers:off - the eval owns a server subprocess and a scratch workspace.
2/**
3 * An isolated T3 server for one device run. Its only provider is `evalbot`, an Fx instance
4 * backed by `fake-fx.ts`, so every reply is scripted. State lives under the run's `--out`.
5 */
6import * as NodeChildProcess from "node:child_process";
7import * as NodeFS from "node:fs";
8import * as NodeNet from "node:net";
9import * as NodePath from "node:path";
10import * as NodeWS from "@effect/platform-node/NodeWS";
11import {
12 CommandId,
13 EnvironmentId,
14 ExecutionEnvironmentDescriptor,
15 MessageId,
16 ORCHESTRATION_PROTOCOL_HEADER,
17 ORCHESTRATION_PROTOCOL_VERSION,
18 OrchestrationV2ShellSnapshot,
19 ProjectId,
20 ProviderInstanceId,
21 ThreadId,
22 WsRpcGroup,
23 type OrchestrationV2ThreadProjection,
24} from "@t3tools/contracts";
25import * as SecureRandom from "effect/crypto/SecureRandom";
26import * as Effect from "effect/Effect";
27import * as FileSystem from "effect/FileSystem";
28import * as Layer from "effect/Layer";
29import * as Option from "effect/Option";
30import * as Schema from "effect/Schema";
31import * as Scope from "effect/Scope";
32import * as Stream from "effect/Stream";
33import { ChildProcess, ChildProcessSpawner } from "effect/process";
34import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
35import { RpcClient, RpcSerialization } from "effect/rpc";
36import { Socket } from "effect/socket";
37​
38const REPO_ROOT = NodePath.resolve(import.meta.dirname, "../..");
39export const EVAL_INSTANCE = ProviderInstanceId.make("evalbot");
40export const EVAL_MODEL = "eval/scripted";
41​
42export const uuid = Effect.flatMap(SecureRandom.SecureRandom, (random) => random.uuidV4());
43​
44export class EnvironmentError extends Schema.TaggedError<EnvironmentError>()("EnvironmentError", {
45 message: Schema.String,
46 cause: Schema.optional(Schema.Defect()),
47}) {}
48​
49/**
50 * Spawns `command` with its stdout and stderr written to `logPath`. The log keeps draining until
51 * the process has stopped, so its shutdown output is kept.
52 */
53export const spawnLogged = Effect.fn("environment.spawnLogged")(function* (
54 command: ChildProcess.Command,
55 logPath: string,
56) {
57 const fs = yield* FileSystem.FileSystem;
58 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
59 // Closes after the process's own finalizer, which was registered later.
60 const logs = yield* Scope.fork(yield* Effect.scope);
61 const handle = yield* spawner.spawn(command);
62 yield* handle.all.pipe(Stream.run(fs.sink(logPath)), Effect.ignore, Effect.forkIn(logs));
63 return handle;
64});
65​
66export const freePort = () =>
67 Effect.callback<number>((resume) => {
68 const server = NodeNet.createServer();
69 server.listen(0, () => {
70 const address = server.address();
71 server.close(() =>
72 resume(Effect.succeed(typeof address === "object" && address ? address.port : 0)),
73 );
74 });
75 });
76​
77const waitForPort = Effect.fn("environment.waitForPort")(function* (port: number) {
78 for (let attempt = 0; attempt < 120; attempt++) {
79 const open = yield* Effect.callback<boolean>((resume) => {
80 const socket = NodeNet.connect(port, "127.0.0.1");
81 socket.once("connect", () => (socket.destroy(), resume(Effect.succeed(true))));
82 socket.once("error", () => resume(Effect.succeed(false)));
83 });
84 if (open) return;
85 yield* Effect.sleep("500 millis");
86 }
87 return yield* new EnvironmentError({ message: `The server never listened on ${port}.` });
88});
89​
90/** Runs a server CLI command and returns both output streams. */
91const runCli = (args: ReadonlyArray<string>) =>
92 Effect.try({
93 try: () => {
94 const result = NodeChildProcess.spawnSync("node", ["apps/server/src/bin.ts", ...args], {
95 cwd: REPO_ROOT,
96 encoding: "utf8",
97 });
98 if (result.status !== 0) throw new Error(result.stderr);
99 return { stdout: result.stdout, stderr: result.stderr };
100 },
101 catch: (cause) =>
102 new EnvironmentError({ message: `bin.ts ${args.join(" ")} failed: ${cause}` }),
103 });
104​
105function writeScratch(baseDir: string) {
106 const workspace = NodePath.join(baseDir, "workspace/acme-app");
107 const control = NodePath.join(baseDir, "control");
108 NodeFS.mkdirSync(NodePath.join(baseDir, "userdata"), { recursive: true });
109 NodeFS.mkdirSync(control, { recursive: true });
110 NodeFS.mkdirSync(workspace, { recursive: true });
111 NodeFS.writeFileSync(NodePath.join(workspace, "README.md"), "# acme app\n");
112 // The / menu's pickable row; without it, fx finds only skills in folders above `--out`.
113 const skill = NodePath.join(workspace, ".fx/skills/eval-notes");
114 NodeFS.mkdirSync(skill, { recursive: true });
115 NodeFS.writeFileSync(
116 NodePath.join(skill, "SKILL.md"),
117 "---\nname: eval-notes\ndescription: Takes notes for the eval.\n---\nTake notes.\n",
118 );
119 const git = (...args: string[]) =>
120 NodeChildProcess.execFileSync("git", ["-C", workspace, ...args], { stdio: "ignore" });
121 git("init", "-q");
122 git("add", "-A");
123 git("-c", "user.name=eval", "-c", "user.email=eval@example.com", "commit", "-qm", "init");
124 const launcher = NodePath.join(baseDir, "fx");
125 NodeFS.writeFileSync(
126 launcher,
127 `#!/bin/sh\nexec node ${JSON.stringify(NodePath.join(import.meta.dirname, "fake-fx.ts"))} "$@"\n`,
128 { mode: 0o755 },
129 );
130 NodeFS.writeFileSync(
131 NodePath.join(baseDir, "userdata/settings.json"),
132 JSON.stringify({
133 providerInstances: {
134 [EVAL_INSTANCE]: {
135 driver: "fx",
136 displayName: "Eval Bot",
137 environment: [{ name: "T3_EVAL_FX_CONTROL_DIR", value: control }],
138 config: { enabled: true, binaryPath: launcher },
139 },
140 },
141 }),
142 );
143 return { workspace, control };
145​
146/** Extras a caller layers on the scratch workspace, such as mobile:metrics' fake GitHub. */
147export interface EnvironmentOptions {
148 /** Runs on the committed scratch repository before the server starts. */
149 readonly prepareWorkspace?: (
150 workspace: string,
151 ) => Effect.Effect<void, { readonly message: string }>;
152 readonly serverEnv?: Readonly<Record<string, string>>;
154​
155/** Starts the server in the caller's scope; the scope's end stops it. */
156export const startEnvironment = Effect.fn("environment.start")(function* (
157 input: {
158 readonly baseDir: string;
159 /** Origin the device uses to reach this machine, without a port. */
160 readonly deviceHost: string;
161 } & EnvironmentOptions,
162) {
163 NodeFS.rmSync(input.baseDir, { recursive: true, force: true });
164 const { workspace, control } = writeScratch(input.baseDir);
165 if (input.prepareWorkspace)
166 yield* input
167 .prepareWorkspace(workspace)
168 .pipe(
169 Effect.mapError(
170 (cause) =>
171 new EnvironmentError({ message: `Preparing the workspace failed: ${cause.message}` }),
172 ),
173 );
174 const home = NodePath.join(input.baseDir, "home");
175 NodeFS.mkdirSync(home, { recursive: true });
176 const port = yield* freePort();
177 yield* spawnLogged(
178 ChildProcess.make(
179 "node",
180 [
181 "apps/server/src/bin.ts",
182 "serve",
183 "--host",
184 "0.0.0.0",
185 "--port",
186 String(port),
187 "--base-dir",
188 input.baseDir,
189 "--no-browser",
190 "--log-level",
191 "warn",
192 workspace,
193 ],
194 // A scratch HOME keeps the user's own skills and config out of the app under test.
195 {
196 cwd: REPO_ROOT,
197 stdin: "ignore",
198 extendEnv: true,
199 env: { ...input.serverEnv, HOME: home },
200 forceKillAfter: "10 seconds",
201 },
202 ),
203 NodePath.join(input.baseDir, "server.log"),
204 ).pipe(
205 Effect.mapError(
206 (cause) => new EnvironmentError({ message: "Starting the server failed.", cause }),
207 ),
208 );
209 yield* waitForPort(port);
210 const origin = `http://127.0.0.1:${port}`;
211 const issued = yield* runCli([
212 "auth",
213 "session",
214 "issue",
215 "--base-dir",
216 input.baseDir,
217 "--token-only",
218 ]);
219 // The token is the last line of stdout; stderr is only a fallback.
220 const lastLine = (text: string) =>
221 text
222 .split("\n")
223 .filter((line) => line.trim())
224 .at(-1)
225 ?.trim();
226 const token = lastLine(issued.stdout) ?? lastLine(issued.stderr) ?? "";
227 const http = (yield* HttpClient.HttpClient).pipe(
228 HttpClient.mapRequest((request) =>
229 request.pipe(
230 HttpClientRequest.bearerToken(token),
231 HttpClientRequest.setHeader(
232 ORCHESTRATION_PROTOCOL_HEADER,
233 String(ORCHESTRATION_PROTOCOL_VERSION),
234 ),
235 ),
236 ),
237 HttpClient.filterStatusOk,
238 );
239 const descriptor = yield* http
240 .get(`${origin}/.well-known/t3/environment`)
241 .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)));
242 const shell = () =>
243 http
244 .get(`${origin}/api/orchestration/shell`)
245 .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(OrchestrationV2ShellSnapshot)));
246 const createProject = Effect.fn("environment.createProject")(function* (
247 title: string,
248 workspaceRoot: string,
249 ) {
250 const projectId = ProjectId.make(yield* uuid);
251 yield* http.execute(
252 HttpClientRequest.post(`${origin}/api/projects/mutate`).pipe(
253 HttpClientRequest.bodyJsonUnsafe({
254 type: "project.create",
255 commandId: yield* uuid,
256 projectId,
257 title,
258 workspaceRoot,
259 }),
260 ),
261 );
262 return projectId;
263 });
264 const projectId = yield* createProject("acme-app", workspace);
265 const ticket = yield* http
266 .execute(HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`))
267 .pipe(
268 Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))),
269 );
270 // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns.
271 const protocol = yield* Layer.build(
272 RpcClient.layerProtocolSocket().pipe(
273 Layer.provide(
274 Socket.layerWebSocket(
275 `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket.ticket)}`,
276 ),
277 ),
278 Layer.provide(RpcSerialization.layerJson),
279 Layer.provide(NodeWS.layerWebSocketConstructor),
280 ),
281 );
282 const client = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
283 const environmentId = EnvironmentId.make(descriptor.environmentId);
284​
285 const command = Effect.map(uuid, CommandId.make);
286 const projection = (threadId: ThreadId) =>
287 client["orchestration.getThreadProjection"]({ threadId });
288​
289 const create = Effect.fn("environment.create")(function* (
290 title: string,
291 prompt?: string,
292 project: ProjectId = projectId,
293 ) {
294 const threadId = ThreadId.make(yield* uuid);
295 yield* client["orchestration.launchThread"]({
296 commandId: yield* command,
297 threadId,
298 projectId: project,
299 title,
300 modelSelection: { instanceId: EVAL_INSTANCE, model: EVAL_MODEL },
301 runtimeMode: "full-access",
302 interactionMode: "default",
303 workspaceStrategy: { type: "root" },
304 ...(prompt === undefined ? {} : { initialMessage: { text: prompt, attachments: [] } }),
305 });
306 return threadId;
307 });
308​
309 /** Starts a thread whose first reply follows `prompt`'s `[[eval:…]]` script. */
310 const launch = (title: string, prompt: string) => create(title, prompt);
311​
312 const until = Effect.fn("environment.until")(function* <A>(
313 description: string,
314 threadId: ThreadId,
315 pick: (value: OrchestrationV2ThreadProjection) => A | undefined,
316 ) {
317 for (let attempt = 0; attempt < 150; attempt++) {
318 const found = pick(yield* projection(threadId));
319 if (found !== undefined) return found;
320 yield* Effect.sleep("200 millis");
321 }
322 return yield* new EnvironmentError({ message: `Thread ${threadId} never had ${description}.` });
323 });
324​
325 const send = Effect.fn("environment.send")(function* (threadId: ThreadId, text: string) {
326 yield* client["orchestration.dispatchCommand"]({
327 type: "message.dispatch",
328 commandId: yield* command,
329 threadId,
330 messageId: MessageId.make(yield* uuid),
331 text,
332 attachments: [],
333 dispatchMode: { type: "queue_after_active" },
334 createdBy: "user",
335 creationSource: "server",
336 });
337 });
338​
339 const isSettled = (value: OrchestrationV2ThreadProjection) =>
340 value.runs.length > 0 &&
341 value.runs.every((run) =>
342 ["completed", "failed", "interrupted", "cancelled"].includes(run.status),
343 );
344​
345 /** Waits until every run of the thread has ended. */
346 const settled = Effect.fn("environment.settled")(function* (threadId: ThreadId) {
347 for (let attempt = 0; attempt < 600; attempt++) {
348 const value = yield* projection(threadId);
349 if (isSettled(value)) return value;
350 yield* Effect.sleep("200 millis");
351 }
352 return yield* new EnvironmentError({ message: `Thread ${threadId} never settled.` });
353 });
354​
355 /** Whether a message with `text` is persisted in the thread; false when none lands in 30 seconds. */
356 const delivered = Effect.fn("environment.delivered")(function* (
357 threadId: ThreadId,
358 text: string,
359 ) {
360 const head = yield* client["orchestration.subscribeThread"]({ threadId }).pipe(
361 Stream.filter((item) =>
362 item.kind === "snapshot"
363 ? item.projection.messages.some((message) => message.text === text)
364 : item.kind === "event" &&
365 item.event.type === "message.updated" &&
366 item.event.payload.text === text,
367 ),
368 Stream.runHead,
369 Effect.timeoutOption("30 seconds"),
370 );
371 return Option.isSome(Option.flatten(head));
372 });
373​
374 /** A settled thread of `turns` request and reply pairs, for scroll and jank cases. */
375 const longThread = Effect.fn("environment.longThread")(function* (title: string, turns: number) {
376 const threadId = yield* launch(title, "Summarize the module. [[eval:stream:400:0]]");
377 yield* settled(threadId);
378 for (let turn = 1; turn < turns; turn++) {
379 const text = `Next part ${turn}. [[eval:stream:${turn % 3 === 0 ? 900 : 300}:0]]`;
380 yield* send(threadId, text);
381 // The message and its run land in one command, so once it shows, `settled` sees the run.
382 yield* until("its next message", threadId, (value) =>
383 value.messages.some((message) => message.text === text) ? true : undefined,
384 );
385 yield* settled(threadId);
386 }
387 return threadId;
388 });
389​
390 return {
391 /** An empty thread in its own project; `lock` then disables `evalbot` there, so sends are rejected. */
392 launchLockable: Effect.fn("environment.launchLockable")(function* (title: string) {
393 const root = NodePath.join(input.baseDir, `workspace/locked-${(yield* uuid).slice(0, 6)}`);
394 NodeFS.mkdirSync(root, { recursive: true });
395 const project = yield* createProject("locked", root);
396 const threadId = yield* create(title, undefined, project);
397 const lock = client["server.updateSettings"]({
398 patch: {
399 projectSettingsOverrides: {
400 [project]: { providerInstances: { [EVAL_INSTANCE]: { enabled: false } } },
401 },
402 },
403 });
404 return { threadId, lock };
405 }),
406 /** Archives every thread but `keep`, so earlier samples' rows never crowd Home. */
407 archiveAllExcept: Effect.fn("environment.archiveAllExcept")(function* (keep: ThreadId) {
408 for (const thread of (yield* shell()).threads) {
409 if (thread.id === keep) continue;
410 yield* client["orchestration.dispatchCommand"]({
411 type: "thread.archive",
412 commandId: yield* command,
413 threadId: thread.id,
414 });
415 }
416 }),
417 /** Stops every unfinished run, so one sample's held turns never leak into the next. */
418 interruptAll: Effect.fn("environment.interruptAll")(function* () {
419 const threads = (yield* shell()).threads;
420 for (const thread of threads)
421 for (const run of (yield* projection(thread.id)).runs) {
422 if (["completed", "failed", "interrupted", "cancelled"].includes(run.status)) continue;
423 yield* client["orchestration.dispatchCommand"]({
424 type: "run.interrupt",
425 commandId: yield* command,
426 threadId: thread.id,
427 runId: run.id,
428 });
429 }
430 for (const thread of threads)
431 if ((yield* projection(thread.id)).runs.length) yield* settled(thread.id);
432 }),
433 createEmptyThread: (title: string) => create(title),
434 delivered,
435 waitForPendingInput: (threadId: ThreadId) =>
436 until("a pending question", threadId, (value) =>
437 value.runtimeRequests.find((request) => request.status === "pending"),
438 ),
439 waitForSubagents: (threadId: ThreadId) =>
440 until("running subagents", threadId, (value) =>
441 value.subagents.length >= 2 ? value.subagents : undefined,
442 ),
443 origin,
444 environmentId,
445 archive: (threadId: ThreadId) =>
446 command.pipe(
447 Effect.flatMap((commandId) =>
448 client["orchestration.dispatchCommand"]({ type: "thread.archive", commandId, threadId }),
449 ),
450 Effect.asVoid,
451 ),
452 unpin: (threadId: ThreadId) =>
453 command.pipe(
454 Effect.flatMap((commandId) =>
455 client["orchestration.dispatchCommand"]({ type: "thread.unpin", commandId, threadId }),
456 ),
457 Effect.asVoid,
458 ),
459 /** A side chat forked from `source`'s latest settled point, as the app's own command does. */
460 forkSideChat: Effect.fn("environment.forkSideChat")(function* (
461 source: ThreadId,
462 title: string,
463 ) {
464 const targetThreadId = ThreadId.make(yield* uuid);
465 yield* client["orchestration.dispatchCommand"]({
466 type: "thread.fork",
467 commandId: yield* command,
468 createdBy: "user",
469 creationSource: "server",
470 sourceThreadId: source,
471 targetThreadId,
472 sourcePoint: { type: "latest_stable" },
473 sideChat: true,
474 title,
475 });
476 return targetThreadId;
477 }),
478 projection,
479 launch,
480 send,
481 settled,
482 longThread,
483 shell,
484 release: (key: string) =>
485 Effect.sync(() => NodeFS.writeFileSync(NodePath.join(control, `release-${key}`), "")),
486 pairingUrl: () =>
487 runCli([
488 "auth",
489 "pairing",
490 "create",
491 "--base-dir",
492 input.baseDir,
493 "--base-url",
494 `http://${input.deviceHost}:${port}`,
495 "--ttl",
496 "15m",
497 "--label",
498 "mobile-behavior-eval",
499 ]).pipe(
500 Effect.flatMap((out) => {
501 const url = /Pair URL:\s*(\S+)/.exec(`${out.stdout}\n${out.stderr}`)?.[1];
502 return url
503 ? Effect.succeed(url)
504 : Effect.fail(new EnvironmentError({ message: "No pairing URL in CLI output." }));
505 }),
506 ),
507 };
508}, Effect.provide(FetchHttpClient.layer));
509​
510export type EvalEnvironment = Effect.Success<ReturnType<typeof startEnvironment>>;