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

environment.ts

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