evalution 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSING.md CHANGED
@@ -52,13 +52,23 @@ permissively licensed code:
52
52
 
53
53
  - The package takes **no runtime dependency** on the AGPL core — only
54
54
  `peerDependencies` on `ai` and the `@ai-sdk/*` packages.
55
- - It does bundle one file from the core,
56
- [`src/trace/prompt-tracer.ts`](./src/trace/prompt-tracer.ts), via the build.
57
- That file is **dual-licensed `MIT OR AGPL-3.0-only`** (see its SPDX header),
55
+ - It does bundle a handful of files from the core, via the build:
56
+ [`src/trace/prompt-tracer.ts`](./src/trace/prompt-tracer.ts),
57
+ [`src/trace/trace-types.ts`](./src/trace/trace-types.ts),
58
+ [`src/trace/trace-sink.ts`](./src/trace/trace-sink.ts),
59
+ [`src/trace/trace-ingestor.ts`](./src/trace/trace-ingestor.ts), and
60
+ [`src/sdk/vercel-ai-sdk/telemetry.ts`](./src/sdk/vercel-ai-sdk/telemetry.ts).
61
+ Each is **dual-licensed `MIT OR AGPL-3.0-only`** (see its SPDX header),
58
62
  so the bytes that land in the MIT package are genuinely MIT.
59
- - `prompt-tracer.ts` must stay **self-contained** (only `@opentelemetry/api`).
60
- If it ever imports from elsewhere in the core, the bundler would pull
61
- AGPL-only code into the MIT artifact and break this guarantee.
63
+ - Those files must stay **self-contained** — only `@opentelemetry/api`, a
64
+ type-only `ai` import, and each other. If any of them ever imports from
65
+ elsewhere in the core, the bundler would pull AGPL-only code into the MIT
66
+ artifact and break this guarantee. (The AGPL-only `BaseTraceProvider`,
67
+ `OTelTraceIngestor`, `MemoryTraceProvider`, and `span-merge.ts` stay on the
68
+ core side of that boundary, even though `BaseTraceProvider` lives in the
69
+ same dual-licensed `trace-sink.ts` file as the `TraceSink` interface — it
70
+ has no AGPL-only dependencies of its own, so this holds without further
71
+ bookkeeping.)
62
72
 
63
73
  ## Contributing
64
74
 
package/dist/cli/index.js CHANGED
@@ -1,13 +1,11 @@
1
- import { a as MemoryTraceProvider, i as setupStepCommand, r as CONFIG_FILE_RELATIVE_PATH, t as VercelAISDK } from "../vercel-ai-sdk-B5BwUGKp.js";
1
+ import { g as MemoryTraceProvider, m as setupStepCommand, p as CONFIG_FILE_RELATIVE_PATH, t as VercelAISDK } from "../vercel-ai-sdk-JhQ1efcg.js";
2
2
  import module from "node:module";
3
3
  import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
6
  import { serve, upgradeWebSocket } from "@hono/node-server";
7
7
  import { serveStatic } from "@hono/node-server/serve-static";
8
- import { SpanStatusCode, context, trace } from "@opentelemetry/api";
9
- import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
10
- import { BasicTracerProvider } from "@opentelemetry/sdk-trace-base";
8
+ import { SpanStatusCode, isSpanContextValid, trace } from "@opentelemetry/api";
11
9
  import { Hono } from "hono";
12
10
  import { WebSocketServer } from "ws";
13
11
  import { streamSSE } from "hono/streaming";
@@ -99,7 +97,10 @@ function setupRoutes({ app, promptProviders, traceProviders, promptRegistry, hot
99
97
  rootPath,
100
98
  configured: hasConfig
101
99
  }));
102
- app.get("/api/setup-tasks", (c) => c.json(setupTasks ? setupTasks.resolve(rootPath) : []));
100
+ app.get("/api/setup-tasks", (c) => c.json(setupTasks ? setupTasks.resolve(rootPath) : {
101
+ agent: [],
102
+ sdk: []
103
+ }));
103
104
  app.post("/api/setup-tasks/:taskId/steps/:stepId/execute", async (c) => {
104
105
  if (!setupTasks) return c.json({ error: "Setup tasks are not available" }, 404);
105
106
  const { taskId, stepId } = c.req.param();
@@ -217,24 +218,29 @@ function setupRoutes({ app, promptProviders, traceProviders, promptRegistry, hot
217
218
  const { functionParams = [] } = await c.req.json().catch(() => ({}));
218
219
  const prompt = await provider.getPrompt(decodedId);
219
220
  if (!prompt) return c.json({ error: "Prompt not found" }, 404);
220
- const response = tracer.startActiveSpan(prompt.name, (span) => {
221
- const { traceId } = span.spanContext();
222
- provider.execute(decodedId, functionParams).then(() => {
223
- span.setStatus({ code: SpanStatusCode.OK });
224
- }, (err) => {
221
+ const response = await tracer.startActiveSpan(prompt.name, async (span) => {
222
+ const ctx = span.spanContext();
223
+ const native = !isSpanContextValid(ctx);
224
+ const traceId = native ? crypto.randomUUID() : ctx.traceId;
225
+ const rootSpanId = native ? `${traceId}:root` : ctx.spanId;
226
+ try {
227
+ await provider.execute(decodedId, functionParams, { traceId });
228
+ } catch (err) {
225
229
  console.error("prompt execution failed:", err);
226
230
  span.recordException(err);
227
231
  span.setStatus({
228
232
  code: SpanStatusCode.ERROR,
229
233
  message: err?.error ? JSON.stringify(err.error, null, 2) : err?.message ?? String(err)
230
234
  });
231
- }).finally(() => {
232
235
  span.end();
233
- });
236
+ throw err;
237
+ }
238
+ span.setStatus({ code: SpanStatusCode.OK });
239
+ span.end();
234
240
  return {
235
241
  traceId,
236
- tracerProviderId: defaultTraceProviderId,
237
- rootSpanId: span.spanContext().spanId
242
+ rootSpanId,
243
+ tracerProviderId: defaultTraceProviderId
238
244
  };
239
245
  });
240
246
  return c.json(response);
@@ -288,12 +294,12 @@ function setupRoutes({ app, promptProviders, traceProviders, promptRegistry, hot
288
294
  };
289
295
  await stream.writeSSE({ data: JSON.stringify(initial) });
290
296
  }
291
- const unsubscribe = provider.subscribeTrace(id, (event) => {
297
+ const unsubscribe = provider.subscribeTrace?.(id, (event) => {
292
298
  stream.writeSSE({ data: JSON.stringify(resolveEvent(event)) });
293
299
  });
294
300
  await new Promise((resolve) => {
295
301
  stream.onAbort(() => {
296
- unsubscribe();
302
+ unsubscribe?.();
297
303
  resolve();
298
304
  });
299
305
  });
@@ -314,6 +320,53 @@ function setupRoutes({ app, promptProviders, traceProviders, promptRegistry, hot
314
320
  }));
315
321
  }
316
322
  //#endregion
323
+ //#region src/agent/registry.ts
324
+ const AGENT_SETUP_DOMAIN = "evalut.io";
325
+ /** The prompt handed to a coding agent */
326
+ const AGENT_SETUP_PROMPT = `Follow manual setup steps from ${`https://${AGENT_SETUP_DOMAIN}/n/docs/setup.md`}`;
327
+ /**
328
+ * Every coding agent offered a one-click launcher in onboarding, in display
329
+ * order. This is the single source of truth for which agents exist and their
330
+ * task ids — each is a {@link SetupTask} whose lone {@link SetupStep} runs the
331
+ * agent's CLI with the setup prompt queued up in an interactive terminal.
332
+ *
333
+ * Mirrors {@link AI_SDK_REGISTRY} in `../sdk/registry.ts`, but agents have no
334
+ * adapter class, so they live here as plain tasks. `icon` keys into the
335
+ * client's `ProviderIcon`.
336
+ */
337
+ const AGENT_REGISTRY = [{
338
+ id: "claude-code",
339
+ label: "Claude Code",
340
+ icon: "Anthropic",
341
+ steps: [{
342
+ kind: "run_command",
343
+ id: "launch",
344
+ command: `claude "${AGENT_SETUP_PROMPT}" --allowedTools "WebFetch(domain:${AGENT_SETUP_DOMAIN})"`,
345
+ label: "Claude Code"
346
+ }]
347
+ }, {
348
+ id: "codex",
349
+ label: "Codex",
350
+ icon: "OpenAI",
351
+ steps: [{
352
+ kind: "run_command",
353
+ id: "launch",
354
+ command: `codex -c 'features.network_proxy.enabled=true' -c 'features.network_proxy.domains={ "${AGENT_SETUP_DOMAIN}" = "allow" }' -c 'sandbox_workspace_write.network_access=true' "${AGENT_SETUP_PROMPT}"`,
355
+ label: "Codex"
356
+ }]
357
+ }];
358
+ /** Look up an agent {@link SetupTask} by its id, or `undefined` if none matches. */
359
+ function findSetupTask$1(taskId) {
360
+ return AGENT_REGISTRY.find((task) => task.id === taskId);
361
+ }
362
+ /**
363
+ * Look up a step within an agent task by both ids, or `undefined` if either is
364
+ * unknown.
365
+ */
366
+ function findSetupStep$2(taskId, stepId) {
367
+ return findSetupTask$1(taskId)?.steps.find((s) => s.id === stepId);
368
+ }
369
+ //#endregion
317
370
  //#region src/sdk/registry.ts
318
371
  /**
319
372
  * Every AI SDK offered in manual onboarding, in display order. This is the
@@ -330,12 +383,19 @@ function findSetupTask(taskId) {
330
383
  * Look up a step within a task by both ids, or `undefined` if either is
331
384
  * unknown.
332
385
  */
333
- function findSetupStep(taskId, stepId) {
386
+ function findSetupStep$1(taskId, stepId) {
334
387
  return findSetupTask(taskId)?.steps.find((s) => s.id === stepId);
335
388
  }
336
389
  //#endregion
337
390
  //#region src/server/setup-tasks.ts
338
391
  /**
392
+ * Resolves a setup step across both the agent and SDK registries by its
393
+ * `taskId`/`stepId`, or `undefined` if neither knows it.
394
+ */
395
+ function findSetupStep(taskId, stepId) {
396
+ return findSetupStep$1(taskId, stepId) ?? findSetupStep$2(taskId, stepId);
397
+ }
398
+ /**
339
399
  * Thrown when a requested task or step id does not exist in the registry. The
340
400
  * route layer maps this to a 404, distinguishing it from execution failures.
341
401
  */
@@ -367,36 +427,61 @@ async function executeSetupStep(rootPath, taskId, stepId) {
367
427
  case "create_config": return { path: await writeConfigFile(rootPath, step) };
368
428
  case "run_command":
369
429
  case "install_package": throw new Error(`${step.kind} steps are not yet supported`);
430
+ default: throw new Error();
370
431
  }
371
432
  }
372
433
  /**
373
- * Returns the onboarding tasks with each step's runtime
374
- * {@link SetupStepBase.completed | completion status} resolved against the
375
- * project at `rootPath` (config file present, package installed).
434
+ * Returns the onboarding tasks — coding agents and AI SDKs — with each step's
435
+ * runtime {@link SetupStepBase.completed | completion status} resolved against
436
+ * the project at `rootPath` (config file present, package installed).
376
437
  *
377
438
  * @param rootPath - Absolute path to the project root.
378
439
  */
379
440
  function resolveSetupTasks(rootPath) {
380
- return AI_SDK_REGISTRY.map((cls) => ({
381
- ...cls.setupTask,
382
- steps: cls.setupTask.steps.map((step) => resolveStepStatus(rootPath, step))
383
- }));
441
+ const resolve = (task) => ({
442
+ ...task,
443
+ steps: task.steps.map((step) => resolveStepStatus(rootPath, step))
444
+ });
445
+ return {
446
+ agent: AGENT_REGISTRY.map(resolve),
447
+ sdk: AI_SDK_REGISTRY.map((cls) => resolve(cls.setupTask))
448
+ };
384
449
  }
385
450
  /** Adds the runtime `completed` flag to a single step where determinable. */
386
451
  function resolveStepStatus(rootPath, step) {
387
452
  switch (step.kind) {
388
- case "install_package": return {
389
- ...step,
390
- completed: isPackageInstalled(rootPath, step.package)
391
- };
392
453
  case "create_config": return {
393
454
  ...step,
394
455
  completed: fs$1.existsSync(path.join(rootPath, step.path))
395
456
  };
396
- case "run_command": return step;
457
+ case "install_package":
458
+ case "run_command": {
459
+ const result = { ...step };
460
+ if (step.kind === "install_package") result.completed = isPackageInstalled(rootPath, step.package);
461
+ const bin = setupStepCommand(step).split(/\s+/)[0];
462
+ if (bin && !isBinaryOnPath(bin)) result.disabledReason = `${bin} not found in PATH`;
463
+ return result;
464
+ }
465
+ default: throw new Error();
397
466
  }
398
467
  }
399
468
  /**
469
+ * Whether an executable named `bin` is resolvable on the current `PATH`. Used
470
+ * to disable coding-agent launchers whose CLI isn't installed. Honours
471
+ * `PATHEXT` on Windows; elsewhere it requires the file to be executable.
472
+ *
473
+ * @param bin - The bare executable name to look for, e.g. `claude`.
474
+ */
475
+ function isBinaryOnPath(bin) {
476
+ const dirs = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean);
477
+ const exts = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";") : [""];
478
+ for (const dir of dirs) for (const ext of exts) try {
479
+ fs$1.accessSync(path.join(dir, bin + ext), fs$1.constants.X_OK);
480
+ return true;
481
+ } catch {}
482
+ return false;
483
+ }
484
+ /**
400
485
  * Whether `pkg` is installed for the project at `rootPath`, walking up the
401
486
  * directory tree to honour hoisted/workspace `node_modules`.
402
487
  *
@@ -433,6 +518,12 @@ async function writeConfigFile(rootPath, step) {
433
518
  /** Shell used to run a resolved step command, so shell syntax in it works. */
434
519
  const SHELL = process.env.SHELL || (process.platform === "win32" ? "powershell.exe" : "bash");
435
520
  /**
521
+ * How long a session's PTY is kept alive after its WebSocket drops, waiting for
522
+ * the client to reconnect. Covers the brief gap while the server restarts
523
+ * itself once a config file appears, so the coding agent isn't killed mid-task.
524
+ */
525
+ const GRACE_PERIOD_MS = 1e4;
526
+ /**
436
527
  * Arguments to run `command` in {@link SHELL}, skipping the user's startup files
437
528
  * where the shell allows it. Those rc files (e.g. nvm in `~/.zshrc`) can add
438
529
  * seconds of latency before the command even begins, and they are unnecessary
@@ -465,56 +556,184 @@ function resolveTerminalCommand(taskId, stepId) {
465
556
  if (!step || step.kind === "create_config") return null;
466
557
  return setupStepCommand(step);
467
558
  }
468
- function send(ws, message) {
469
- ws.send(JSON.stringify(message));
559
+ /** Spawns a real `node-pty` PTY running the command in {@link SHELL}. */
560
+ function defaultSpawn(options) {
561
+ return pty.spawn(SHELL, shellCommandArgs(options.command), {
562
+ name: "xterm-color",
563
+ cols: options.cols || 80,
564
+ rows: options.rows || 24,
565
+ cwd: options.cwd,
566
+ env: options.env
567
+ });
568
+ }
569
+ /**
570
+ * A single onboarding terminal: one PTY plus the WebSocket currently attached to
571
+ * it. The PTY outlives any one socket so it can survive the server restart that
572
+ * happens when a config file appears — while a client is attached, output is
573
+ * streamed live; while it is detached, output is buffered and a grace timer
574
+ * reaps the PTY if no client reconnects in time.
575
+ */
576
+ var TerminalSession = class {
577
+ /** While detached: PTY output accumulated to replay on reconnect. */
578
+ buffer = null;
579
+ graceTimer;
580
+ socket = null;
581
+ exited = false;
582
+ child;
583
+ onReap;
584
+ gracePeriodMs;
585
+ /**
586
+ * @param child - The PTY this session owns.
587
+ * @param onReap - Called once the session is done (exit, grace expiry, or
588
+ * intentional kill) so the registry can drop it.
589
+ * @param gracePeriodMs - How long to keep the PTY alive after the socket drops.
590
+ */
591
+ constructor(child, onReap, gracePeriodMs = GRACE_PERIOD_MS) {
592
+ this.child = child;
593
+ this.onReap = onReap;
594
+ this.gracePeriodMs = gracePeriodMs;
595
+ child.onData((data) => this.handleData(data));
596
+ child.onExit(({ exitCode }) => this.handleExit(exitCode));
597
+ }
598
+ send(message) {
599
+ this.socket?.send(JSON.stringify(message));
600
+ }
601
+ handleData(data) {
602
+ if (this.socket) this.send({
603
+ type: "data",
604
+ data
605
+ });
606
+ else this.buffer?.push(data);
607
+ }
608
+ handleExit(code) {
609
+ this.exited = true;
610
+ this.send({
611
+ type: "exit",
612
+ code
613
+ });
614
+ this.socket?.close();
615
+ this.clearGrace();
616
+ this.onReap();
617
+ }
618
+ /**
619
+ * Attach a (re)connected socket. Replays any output buffered while detached,
620
+ * then resumes live streaming. Cancels a pending grace-period reap.
621
+ */
622
+ attach(ws) {
623
+ this.clearGrace();
624
+ this.socket = ws;
625
+ if (this.buffer) {
626
+ for (const data of this.buffer) this.send({
627
+ type: "data",
628
+ data
629
+ });
630
+ this.buffer = null;
631
+ }
632
+ }
633
+ /**
634
+ * The attached socket dropped (e.g. the server is restarting). Start buffering
635
+ * output and a grace timer; if no client reattaches in time, reap the PTY.
636
+ */
637
+ detach() {
638
+ if (this.exited || !this.socket) return;
639
+ this.socket = null;
640
+ this.buffer = [];
641
+ this.graceTimer = setTimeout(() => {
642
+ this.buffer = null;
643
+ if (!this.exited) this.child.kill();
644
+ this.onReap();
645
+ }, this.gracePeriodMs);
646
+ }
647
+ /** The client intentionally left: kill the PTY now, skipping the grace wait. */
648
+ kill() {
649
+ this.clearGrace();
650
+ this.socket = null;
651
+ this.buffer = null;
652
+ if (!this.exited) this.child.kill();
653
+ this.onReap();
654
+ }
655
+ /** Forward the user's keystrokes to the PTY. */
656
+ write(data) {
657
+ this.child.write(data);
658
+ }
659
+ /** Resize the PTY to match the client's terminal. */
660
+ resize(cols, rows) {
661
+ this.child.resize(cols || 80, rows || 24);
662
+ }
663
+ clearGrace() {
664
+ if (this.graceTimer) {
665
+ clearTimeout(this.graceTimer);
666
+ this.graceTimer = void 0;
667
+ }
668
+ }
669
+ };
670
+ /**
671
+ * Holds the live {@link TerminalSession | terminal sessions} keyed by a
672
+ * client-supplied session id. Owned by the CLI process (not by any one server
673
+ * instance) so sessions — and the PTYs they wrap — survive the server restart
674
+ * that happens when a config file appears.
675
+ */
676
+ var TerminalSessionRegistry = class {
677
+ sessions = /* @__PURE__ */ new Map();
678
+ spawn;
679
+ gracePeriodMs;
680
+ /**
681
+ * @param spawn - PTY spawner; overridable in tests.
682
+ * @param gracePeriodMs - Reconnect grace window passed to each session.
683
+ */
684
+ constructor(spawn = defaultSpawn, gracePeriodMs = GRACE_PERIOD_MS) {
685
+ this.spawn = spawn;
686
+ this.gracePeriodMs = gracePeriodMs;
687
+ }
688
+ /** The session for `id`, if one is still live. */
689
+ get(id) {
690
+ return this.sessions.get(id);
691
+ }
692
+ /** Spawn a PTY and register a new session under `id`. */
693
+ create(id, options) {
694
+ const session = new TerminalSession(this.spawn(options), () => this.sessions.delete(id), this.gracePeriodMs);
695
+ this.sessions.set(id, session);
696
+ return session;
697
+ }
698
+ };
699
+ function sendError(ws, message) {
700
+ ws.send(JSON.stringify({
701
+ type: "error",
702
+ message
703
+ }));
470
704
  }
471
705
  /**
472
706
  * Registers the interactive-terminal WebSocket route at `/api/terminal`.
473
707
  *
474
- * The client connects with `taskId` and `stepId` query params identifying a
475
- * setup step; the server resolves the actual command from its own registry
476
- * (never from the request body) and, once the client signals `start`, spawns it
477
- * in a PTY rooted at the project. Output is streamed to the client and the
478
- * client's keystrokes are written to the process, so prompts (e.g. npm's
479
- * "Ok to proceed?") work. The trust boundary mirrors the step-execute route:
480
- * the client can only ask to run a step that already exists server-side.
708
+ * The client connects with `taskId`, `stepId`, and a client-generated
709
+ * `sessionId` query param. The server resolves the actual command from its own
710
+ * registry (never from the request body). On the first connection for a session
711
+ * the client signals `start` and the server spawns the command in a PTY rooted
712
+ * at the project; output is streamed to the client and the client's keystrokes
713
+ * are written to the process, so prompts (e.g. npm's "Ok to proceed?") work.
714
+ *
715
+ * Sessions live in `sessions`, which outlives this server instance, so when the
716
+ * server restarts itself after a config file appears the PTY keeps running and a
717
+ * reconnecting client (same `sessionId`) re-attaches and replays the gap.
718
+ *
719
+ * The trust boundary mirrors the step-execute route: the client can only ask to
720
+ * run a step that already exists server-side.
481
721
  */
482
- function registerTerminalRoute(app, upgradeWebSocket, rootPath) {
722
+ function registerTerminalRoute(app, upgradeWebSocket, rootPath, sessions) {
483
723
  app.get("/api/terminal", upgradeWebSocket((c) => {
484
724
  const taskId = c.req.query("taskId");
485
725
  const stepId = c.req.query("stepId");
486
- let child;
487
- const start = (ws, cols, rows) => {
488
- if (child) return;
489
- const command = taskId && stepId ? resolveTerminalCommand(taskId, stepId) : null;
490
- if (!command) {
491
- send(ws, {
492
- type: "error",
493
- message: "Unknown or non-runnable setup step."
494
- });
495
- ws.close();
496
- return;
497
- }
498
- child = pty.spawn(SHELL, shellCommandArgs(command), {
499
- name: "xterm-color",
500
- cols: cols || 80,
501
- rows: rows || 24,
502
- cwd: rootPath,
503
- env: process.env
504
- });
505
- child.onData((data) => send(ws, {
506
- type: "data",
507
- data
508
- }));
509
- child.onExit(({ exitCode }) => {
510
- send(ws, {
511
- type: "exit",
512
- code: exitCode
513
- });
514
- ws.close();
515
- });
516
- };
726
+ const sessionId = c.req.query("sessionId") ?? `${taskId}:${stepId}`;
727
+ let session;
728
+ let leaving = false;
517
729
  return {
730
+ onOpen(_evt, ws) {
731
+ const existing = sessions.get(sessionId);
732
+ if (existing) {
733
+ session = existing;
734
+ existing.attach(ws);
735
+ }
736
+ },
518
737
  onMessage(evt, ws) {
519
738
  let msg;
520
739
  try {
@@ -523,20 +742,38 @@ function registerTerminalRoute(app, upgradeWebSocket, rootPath) {
523
742
  return;
524
743
  }
525
744
  switch (msg.type) {
526
- case "start":
527
- start(ws, msg.cols, msg.rows);
745
+ case "start": {
746
+ if (session) return;
747
+ const command = taskId && stepId ? resolveTerminalCommand(taskId, stepId) : null;
748
+ if (!command) {
749
+ sendError(ws, "Unknown or non-runnable setup step.");
750
+ ws.close();
751
+ return;
752
+ }
753
+ session = sessions.create(sessionId, {
754
+ command,
755
+ cols: msg.cols,
756
+ rows: msg.rows,
757
+ cwd: rootPath,
758
+ env: process.env
759
+ });
760
+ session.attach(ws);
528
761
  break;
762
+ }
529
763
  case "input":
530
- child?.write(msg.data);
764
+ session?.write(msg.data);
531
765
  break;
532
766
  case "resize":
533
- child?.resize(msg.cols || 80, msg.rows || 24);
767
+ session?.resize(msg.cols || 80, msg.rows || 24);
768
+ break;
769
+ case "detach":
770
+ leaving = true;
771
+ session?.kill();
534
772
  break;
535
773
  }
536
774
  },
537
775
  onClose() {
538
- child?.kill();
539
- child = void 0;
776
+ if (!leaving) session?.detach();
540
777
  }
541
778
  };
542
779
  }));
@@ -544,19 +781,15 @@ function registerTerminalRoute(app, upgradeWebSocket, rootPath) {
544
781
  //#endregion
545
782
  //#region src/server/index.ts
546
783
  async function startServer(options) {
547
- const { promptProviders, traceProviders, port, rootPath, hasConfig } = options;
784
+ const { promptProviders, traceProviders, port, rootPath, hasConfig, terminalSessions } = options;
548
785
  const promptProviderMap = new Map(promptProviders.map((p) => [p.id, p]));
549
786
  const traceProviderMap = new Map(traceProviders.map((p) => [p.id, p]));
550
787
  const promptRegistry = new PromptRegistry();
551
788
  await promptRegistry.rebuild(promptProviderMap);
552
- const tracerProvider = new BasicTracerProvider({ spanProcessors: traceProviders.filter((p) => !!p.getSpanProcessor).map((p) => p.getSpanProcessor()) });
553
- trace.setGlobalTracerProvider(tracerProvider);
554
- const contextManager = new AsyncLocalStorageContextManager();
555
- contextManager.enable();
556
- context.setGlobalContextManager(contextManager);
557
- const tracer = tracerProvider.getTracer("evalution");
558
- const defaultTraceProviderId = traceProviders.find((p) => p instanceof MemoryTraceProvider)?.id ?? traceProviders[0]?.id;
559
- if (!defaultTraceProviderId) throw new Error("At least one trace provider must be configured");
789
+ const tracer = trace.getTracer("evalution");
790
+ const defaultTraceProvider = traceProviders.find((p) => p instanceof MemoryTraceProvider) ?? traceProviders[0];
791
+ if (!defaultTraceProvider) throw new Error("At least one trace provider must be configured");
792
+ const defaultTraceProviderId = defaultTraceProvider.id;
560
793
  const app = new Hono();
561
794
  const hotReloadSubscribers = /* @__PURE__ */ new Set();
562
795
  const broadcast = (data) => {
@@ -577,7 +810,7 @@ async function startServer(options) {
577
810
  executeStep: executeSetupStep
578
811
  }
579
812
  });
580
- registerTerminalRoute(app, upgradeWebSocket, rootPath);
813
+ registerTerminalRoute(app, upgradeWebSocket, rootPath, terminalSessions);
581
814
  const clientRoot = fileURLToPath(new URL("../client/", import.meta.url));
582
815
  app.get("*", serveStatic({ root: clientRoot }));
583
816
  for (const [providerId, provider] of promptProviderMap) if (provider.watch) provider.watch(async (event) => {
@@ -613,6 +846,7 @@ async function startServer(options) {
613
846
  });
614
847
  });
615
848
  const close = () => new Promise((resolve, reject) => {
849
+ for (const ws of wss.clients) ws.close();
616
850
  if ("closeAllConnections" in server) server.closeAllConnections();
617
851
  server.close((err) => err ? reject(err) : resolve());
618
852
  });
@@ -690,7 +924,7 @@ function registerEvalutionResolver(parentURL) {
690
924
  function watchForConfigCreation(rootDir, onConfig) {
691
925
  const configPath = path.join(rootDir, CONFIG_FILE_RELATIVE_PATH);
692
926
  const configDir = path.dirname(configPath);
693
- const allowed = new Set([
927
+ const allowed = /* @__PURE__ */ new Set([
694
928
  rootDir,
695
929
  configDir,
696
930
  configPath
@@ -836,14 +1070,23 @@ function applyDotenv(rootDir) {
836
1070
  if (err?.code !== "ENOENT") console.warn(`Warning: failed to load .env from ${envPath}:`, err.message);
837
1071
  }
838
1072
  }
839
- function startConfiguredServer(rootDir, config, hasConfig, port) {
1073
+ async function startConfiguredServer(rootDir, config, hasConfig, port, terminalSessions) {
840
1074
  if (config.useDotenv !== false) applyDotenv(rootDir);
1075
+ const promptProviders = config.promptProviders ?? [];
1076
+ let traceProviders = config.traceProviders;
1077
+ if (!traceProviders) {
1078
+ const collected = (await Promise.all(promptProviders.map((p) => p.setupTraceIngestion?.()))).filter((i) => !!i);
1079
+ const ingestors = [];
1080
+ for (const ing of collected) if (!ingestors.some((kept) => kept.isRedundant?.(ing))) ingestors.push(ing);
1081
+ traceProviders = [new MemoryTraceProvider({ ingestors })];
1082
+ }
841
1083
  return startServer({
842
- promptProviders: config.promptProviders ?? [],
843
- traceProviders: config.traceProviders ?? [new MemoryTraceProvider()],
1084
+ promptProviders,
1085
+ traceProviders,
844
1086
  port,
845
1087
  rootPath: rootDir,
846
- hasConfig
1088
+ hasConfig,
1089
+ terminalSessions
847
1090
  });
848
1091
  }
849
1092
  async function main() {
@@ -858,22 +1101,25 @@ async function main() {
858
1101
  let port;
859
1102
  if (process.env.PORT) port = parseInt(process.env.PORT, 10);
860
1103
  else port = await findAvailablePort(3e3);
861
- const maybeOpen = (url) => {
862
- if (!process.env.EVALUTION_NO_OPEN) openBrowser(url);
1104
+ const maybeOpen = async (url) => {
1105
+ if (process.env.EVALUTION_NO_OPEN) return;
1106
+ await new Promise((r) => setTimeout(r, 250));
1107
+ openBrowser(url);
863
1108
  };
1109
+ const terminalSessions = new TerminalSessionRegistry();
864
1110
  if (hasConfig) {
865
- maybeOpen((await startConfiguredServer(rootDir, await loadConfig(rootDir), true, port)).url);
1111
+ await maybeOpen((await startConfiguredServer(rootDir, await loadConfig(rootDir), true, port, terminalSessions)).url);
866
1112
  return;
867
1113
  }
868
- let server = await startConfiguredServer(rootDir, {}, false, port);
869
- maybeOpen(server.url);
1114
+ let server = await startConfiguredServer(rootDir, {}, false, port, terminalSessions);
1115
+ await maybeOpen(server.url);
870
1116
  console.log(`👀 No config found; watching ${path.join(rootDir, ".evalution", "config.ts")} for creation...`);
871
1117
  const stopWatching = watchForConfigCreation(rootDir, async () => {
872
1118
  const config = await loadConfig(rootDir);
873
1119
  console.log("⚙️ Config loaded; restarting server...");
874
1120
  stopWatching();
875
1121
  await server.close();
876
- server = await startConfiguredServer(rootDir, config, true, port);
1122
+ server = await startConfiguredServer(rootDir, config, true, port, terminalSessions);
877
1123
  });
878
1124
  }
879
1125
  main().catch((error) => {