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