@llm4ts/shell 4.1.0 → 4.3.0

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/src/Watch.ts CHANGED
@@ -169,7 +169,7 @@ const actionWords = (run: EpicRun | undefined): string | undefined => {
169
169
  }
170
170
 
171
171
  /** The tree before any event: the epic's board, when the trace belongs to one. */
172
- const startingTree = (
172
+ export const startingTree = (
173
173
  target: WatchTarget,
174
174
  files: PlainFileStoreShape,
175
175
  idleAfterMs: number | undefined
@@ -200,9 +200,14 @@ const readInputs = (
200
200
  ): Effect.Effect<ReadonlyArray<TreeInput>, FlowError> =>
201
201
  Effect.map(readTrace(files, target.tracePath), treeInputsOfTrace)
202
202
 
203
- const pollInterval = Duration.millis(500)
203
+ /** How often a live run's trace is re-read, and its clocks move. */
204
+ export const pollInterval = Duration.millis(500)
204
205
  const replayGapCap = 2_000
205
206
 
207
+ /** A replay's wait between two inputs: their own gap, at most two seconds, sped up. */
208
+ export const replayGap = (previousAt: number, nextAt: number, speed: number): number =>
209
+ Math.max(0, Math.min(replayGapCap, nextAt - previousAt) / speed)
210
+
206
211
  const draw = (
207
212
  state: TreeState,
208
213
  view: TreeView,
@@ -346,8 +351,7 @@ export const makeWatchProgram = Effect.fn("@llm4ts/shell/Watch.make")(function*
346
351
  }
347
352
  const replaying = options.replay === true && count < current.length
348
353
  const gap = replaying
349
- ? Math.min(replayGapCap, (current[count]?.at ?? 0) - (current[count - 1]?.at ?? 0)) /
350
- speed
354
+ ? replayGap(current[count - 1]?.at ?? 0, current[count]?.at ?? 0, speed)
351
355
  : Duration.toMillis(pollInterval)
352
356
  if (yield* awaitKey(Duration.millis(Math.max(0, gap)))) {
353
357
  return
@@ -0,0 +1,145 @@
1
+ // @internal: the wire format of `llm4ts watch --web`, shared by its server and its page
2
+ import * as Schema from "effect/Schema"
3
+
4
+ /**
5
+ * What travels between `llm4ts watch --web` and its page (ADR 0051): the run
6
+ * the page first asks for, and the frames it draws. The server encodes
7
+ * through these schemas and the page decodes every response and every
8
+ * streamed frame through them. Browser-safe: this module imports only
9
+ * `effect/Schema`, so the page's bundle carries it.
10
+ */
11
+
12
+ /** How a timeline item is coloured: the tree's styles, and the node states. */
13
+ export const WebTone = Schema.Literals([
14
+ "orchestrator",
15
+ "judgment",
16
+ "judge",
17
+ "running",
18
+ "log",
19
+ "tool",
20
+ "done",
21
+ "failed",
22
+ "issue"
23
+ ])
24
+ export type WebTone = typeof WebTone.Type
25
+
26
+ export const WebChipStatus = Schema.Literals(["planned", "running", "waiting", "done", "failed"])
27
+ export type WebChipStatus = typeof WebChipStatus.Type
28
+
29
+ export const WebTimelineItem = Schema.Struct({
30
+ seq: Schema.Number,
31
+ at: Schema.Number,
32
+ who: Schema.String,
33
+ what: Schema.String,
34
+ tone: WebTone
35
+ })
36
+ export type WebTimelineItem = typeof WebTimelineItem.Type
37
+
38
+ /** A judge's verdict on a lane, with the trace seq that carried it. */
39
+ export const WebVerdict = Schema.Struct({
40
+ lane: Schema.String,
41
+ round: Schema.Number,
42
+ cleared: Schema.Boolean,
43
+ issues: Schema.Number,
44
+ dimensions: Schema.Array(
45
+ Schema.Struct({ id: Schema.String, score: Schema.Number, max: Schema.Number })
46
+ ),
47
+ seq: Schema.Number
48
+ })
49
+ export type WebVerdict = typeof WebVerdict.Type
50
+
51
+ export const WebStory = Schema.Struct({
52
+ id: Schema.String,
53
+ status: WebChipStatus,
54
+ executor: Schema.optional(Schema.String),
55
+ stage: Schema.optional(Schema.String),
56
+ startedAt: Schema.optional(Schema.Number),
57
+ endedAt: Schema.optional(Schema.Number),
58
+ tokens: Schema.Number,
59
+ prompt: Schema.Number,
60
+ completion: Schema.Number,
61
+ model: Schema.optional(Schema.String),
62
+ merged: Schema.Boolean,
63
+ failStage: Schema.optional(Schema.String),
64
+ failMessage: Schema.optional(Schema.String),
65
+ tools: Schema.Array(Schema.String),
66
+ activity: Schema.optional(Schema.Struct({ text: Schema.String, since: Schema.Number })),
67
+ note: Schema.optional(Schema.String),
68
+ tasks: Schema.Number
69
+ })
70
+ export type WebStory = typeof WebStory.Type
71
+
72
+ export const WebExecutor = Schema.Struct({
73
+ name: Schema.String,
74
+ state: Schema.Literals(["busy", "idle", "out"]),
75
+ text: Schema.String
76
+ })
77
+ export type WebExecutor = typeof WebExecutor.Type
78
+
79
+ export const WebFrame = Schema.Struct({
80
+ /** Steps folded, of `steps`; a live frame has folded them all. */
81
+ count: Schema.Number,
82
+ steps: Schema.Number,
83
+ seq: Schema.optional(Schema.Number),
84
+ lastSeq: Schema.optional(Schema.Number),
85
+ startedAt: Schema.optional(Schema.Number),
86
+ now: Schema.optional(Schema.Number),
87
+ ended: Schema.optional(Schema.String),
88
+ title: Schema.String,
89
+ action: Schema.optional(Schema.String),
90
+ stage: Schema.String,
91
+ agents: Schema.String,
92
+ counts: Schema.Struct({
93
+ planned: Schema.Number,
94
+ running: Schema.Number,
95
+ waiting: Schema.Number,
96
+ done: Schema.Number,
97
+ failed: Schema.Number,
98
+ total: Schema.Number
99
+ }),
100
+ tokens: Schema.Number,
101
+ costUsd: Schema.Number,
102
+ stories: Schema.Array(WebStory),
103
+ /** The story the detail card follows until the reader picks one. */
104
+ focus: Schema.optional(Schema.String),
105
+ judge: Schema.Struct({
106
+ executor: Schema.optional(Schema.String),
107
+ state: Schema.Literals(["idle", "waiting", "running"]),
108
+ reviews: Schema.Number,
109
+ verdicts: Schema.Number,
110
+ borrowed: Schema.Number
111
+ }),
112
+ verdicts: Schema.Array(WebVerdict),
113
+ merged: Schema.Number,
114
+ roster: Schema.Array(WebExecutor),
115
+ /** The latest items; `timelineCount` says how many there are in all. */
116
+ timeline: Schema.Array(WebTimelineItem),
117
+ timelineCount: Schema.Number,
118
+ /** The replay's wait before this frame, so the playhead moves as long. */
119
+ gapMs: Schema.Number
120
+ })
121
+ export type WebFrame = typeof WebFrame.Type
122
+
123
+ /** A step of the trace, as the scrubber places it. */
124
+ export const WebRunStep = Schema.Struct({ seq: Schema.Number, at: Schema.Number })
125
+ export type WebRunStep = typeof WebRunStep.Type
126
+
127
+ /** The run as the page first sees it: its mode, its steps, its whole timeline for the scrubber. */
128
+ export const WebRun = Schema.Struct({
129
+ mode: Schema.Literals(["live", "replay"]),
130
+ runId: Schema.optional(Schema.String),
131
+ trace: Schema.String,
132
+ speed: Schema.Number,
133
+ steps: Schema.Array(WebRunStep),
134
+ lastSeq: Schema.optional(Schema.Number),
135
+ timeline: Schema.Array(WebTimelineItem)
136
+ })
137
+ export type WebRun = typeof WebRun.Type
138
+
139
+ /**
140
+ * The bodies on the wire: JSON text, an absent value written as `null`. The
141
+ * server's `schemaJson` responses and its server-sent frames use this
142
+ * codec, and the page decodes with it.
143
+ */
144
+ export const WebFrameJson = Schema.fromJsonString(Schema.toCodecJson(WebFrame))
145
+ export const WebRunJson = Schema.fromJsonString(Schema.toCodecJson(WebRun))
@@ -0,0 +1,398 @@
1
+ // @internal: `llm4ts watch --web`, served by the shell's own CLI
2
+ import { readFileSync } from "node:fs"
3
+ import { createServer, type Server } from "node:http"
4
+ import { basename } from "node:path"
5
+ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"
6
+ import * as Clock from "effect/Clock"
7
+ import * as Duration from "effect/Duration"
8
+ import * as Effect from "effect/Effect"
9
+ import * as Layer from "effect/Layer"
10
+ import * as Schedule from "effect/Schedule"
11
+ import * as Schema from "effect/Schema"
12
+ import * as Stream from "effect/Stream"
13
+ import * as HttpRouter from "effect/http/HttpRouter"
14
+ import * as HttpServer from "effect/http/HttpServer"
15
+ import type { ServeError } from "effect/http/HttpServerError"
16
+ import * as HttpServerRequest from "effect/http/HttpServerRequest"
17
+ import * as HttpServerResponse from "effect/http/HttpServerResponse"
18
+ import type * as NetAddress from "effect/net/NetAddress"
19
+ import type { FlowError } from "@llm4ts/flow/FlowError"
20
+ import { readTrace } from "@llm4ts/flow/Replay"
21
+ import { reduceTree } from "@llm4ts/runner/AgentTree"
22
+ import {
23
+ pollInterval,
24
+ replayGap,
25
+ resolveTraceTarget,
26
+ startingTree,
27
+ type TraceSources,
28
+ type WatchOptions,
29
+ type WatchTarget,
30
+ type WatchTargetMissing
31
+ } from "./Watch.ts"
32
+ import { WebFrame, WebFrameJson, WebRun } from "./WebFrame.ts"
33
+ import {
34
+ advance,
35
+ foldSteps,
36
+ frameOf,
37
+ stepsOfTrace,
38
+ type WebFold,
39
+ type WebStep
40
+ } from "./WebWatchView.ts"
41
+
42
+ /**
43
+ * `llm4ts watch --web` (ADR 0051): the agent tree in a browser. The same
44
+ * trace `watch` reads, folded by the same `reduceTree`, served on loopback
45
+ * as a page and a stream of frames (server-sent events). A live run is
46
+ * re-read every `pollInterval`; a replay steps on `replayGap`, sped up as
47
+ * the page asks. The terminal `watch` is untouched: this runs only with
48
+ * `--web`.
49
+ */
50
+
51
+ export type WebWatchOptions = Pick<
52
+ WatchOptions,
53
+ "repo" | "trace" | "epic" | "replay" | "speed" | "idleAfterMs"
54
+ > & {
55
+ /** Loopback by default; the page shows the run to whoever can reach it. */
56
+ readonly host?: string
57
+ /** A free port when omitted. */
58
+ readonly port?: number
59
+ }
60
+
61
+ /**
62
+ * The page's files, under `packages/shell/web/`. `pnpm build` writes
63
+ * `app.js` (bundled from `web-src/`) and copies the Geist fonts and their
64
+ * licence into `fonts/` (scripts/build-web.mjs).
65
+ */
66
+ export const webAssets: ReadonlyArray<{
67
+ readonly path: HttpRouter.PathInput
68
+ readonly file: string
69
+ readonly type: string
70
+ }> = [
71
+ { path: "/", file: "index.html", type: "text/html; charset=utf-8" },
72
+ { path: "/style.css", file: "style.css", type: "text/css; charset=utf-8" },
73
+ { path: "/app.js", file: "app.js", type: "text/javascript; charset=utf-8" },
74
+ { path: "/fonts/Geist-Variable.woff2", file: "fonts/Geist-Variable.woff2", type: "font/woff2" },
75
+ {
76
+ path: "/fonts/GeistMono-Variable.woff2",
77
+ file: "fonts/GeistMono-Variable.woff2",
78
+ type: "font/woff2"
79
+ },
80
+ { path: "/fonts/OFL.txt", file: "fonts/OFL.txt", type: "text/plain; charset=utf-8" }
81
+ ]
82
+
83
+ /**
84
+ * Everything the page loads comes from this server: its script, its
85
+ * stylesheet, its fonts, its frames. Nothing inline, nothing remote.
86
+ */
87
+ export const contentSecurityPolicy =
88
+ "default-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; object-src 'none'"
89
+
90
+ export interface WebWatchDependencies extends TraceSources {
91
+ readonly write: (text: string) => Effect.Effect<void>
92
+ /** A page file's bytes. */
93
+ readonly asset: (file: string) => Uint8Array | undefined
94
+ /** Completes when the reader detaches (Ctrl-C). */
95
+ readonly detach: Effect.Effect<void>
96
+ }
97
+
98
+ const defaultSpeed = 10
99
+
100
+ /** What the page asks for: a frame after `count` steps, played at `speed`. */
101
+ const FrameQuery = Schema.Struct({
102
+ count: Schema.optional(Schema.FiniteFromString),
103
+ speed: Schema.optional(Schema.FiniteFromString)
104
+ })
105
+
106
+ interface Loaded {
107
+ readonly runId: string | undefined
108
+ readonly lastSeq: number | undefined
109
+ readonly steps: ReadonlyArray<WebStep>
110
+ }
111
+
112
+ const encodeFrame = Schema.encodeSync(WebFrameJson)
113
+
114
+ /** One server-sent event; `data` is JSON on a single line. */
115
+ const sse = (event: string, data: string): string => `event: ${event}\ndata: ${data}\n\n`
116
+
117
+ const frameEvent = (frame: WebFrame): string => sse("frame", encodeFrame(frame))
118
+ const endEvent = sse("end", "{}")
119
+
120
+ /**
121
+ * The `Host` values a request may carry: the loopback names of the port the
122
+ * server listens on. Anything else is refused, so a page on another origin
123
+ * cannot read the run by rebinding its own name to 127.0.0.1.
124
+ */
125
+ export const allowedHosts = (port: number): ReadonlySet<string> =>
126
+ new Set([`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`])
127
+
128
+ const portOf = (address: NetAddress.SocketAddress): number | undefined =>
129
+ "port" in address ? address.port : undefined
130
+
131
+ /** Refuses a foreign `Host` (403); stamps every answer as not to be sniffed or cached. */
132
+ const guard = HttpRouter.middleware(
133
+ Effect.gen(function* () {
134
+ const server = yield* HttpServer.HttpServer
135
+ const port = portOf(server.address)
136
+ const allowed = port === undefined ? new Set<string>() : allowedHosts(port)
137
+ return (app) =>
138
+ Effect.gen(function* () {
139
+ const request = yield* HttpServerRequest.HttpServerRequest
140
+ const host = request.headers["host"]
141
+ const response =
142
+ host !== undefined && allowed.has(host.toLowerCase())
143
+ ? yield* app
144
+ : HttpServerResponse.text("forbidden host", { status: 403 })
145
+ return HttpServerResponse.setHeaders(response, {
146
+ "x-content-type-options": "nosniff",
147
+ "cache-control": "no-store"
148
+ })
149
+ })
150
+ }),
151
+ { global: true }
152
+ )
153
+
154
+ /**
155
+ * The routes: the page, `/api/run`, `/api/frame?count=` (a replay's scrub),
156
+ * and `/api/stream?count=&speed=` (a replay playing, or a live run followed),
157
+ * behind the `Host` guard. Needs the `HttpServer` it is served on, for the
158
+ * port the guard allows.
159
+ */
160
+ export const webWatchApp = Effect.fn("@llm4ts/shell/WebWatch.app")(function* (
161
+ options: WebWatchOptions,
162
+ dependencies: WebWatchDependencies
163
+ ): Effect.fn.Return<
164
+ Layer.Layer<never, never, HttpRouter.HttpRouter | HttpServer.HttpServer>,
165
+ FlowError | WatchTargetMissing
166
+ > {
167
+ const target: WatchTarget = yield* resolveTraceTarget(options, dependencies)
168
+ const replay = options.replay === true
169
+ const start = yield* startingTree(target, dependencies.files, options.idleAfterMs)
170
+ const load = Effect.map(
171
+ readTrace(dependencies.files, target.tracePath),
172
+ (lines): Loaded => ({
173
+ runId: lines[0]?.runId,
174
+ lastSeq: lines.at(-1)?.seq,
175
+ steps: stepsOfTrace(lines)
176
+ })
177
+ )
178
+ // Read once up front, so a missing or unreadable trace fails before serving.
179
+ yield* load
180
+ const speedOf = (asked: number | undefined): number =>
181
+ Math.max(1, asked ?? options.speed ?? defaultSpeed)
182
+
183
+ /** A live frame: every step, the clock moved to now while the run goes on. */
184
+ const liveFrame = (loaded: Loaded): Effect.Effect<WebFrame> =>
185
+ Effect.gen(function* () {
186
+ const fold = foldSteps(start, loaded.steps)
187
+ const now = yield* Clock.currentTimeMillis
188
+ const state =
189
+ fold.state.ended === undefined
190
+ ? reduceTree(fold.state, { _tag: "Tick", at: now })
191
+ : fold.state
192
+ return frameOf({ ...fold, state }, { steps: loaded.steps.length, lastSeq: loaded.lastSeq })
193
+ })
194
+
195
+ const replayFrame = (loaded: Loaded, count: number): WebFrame =>
196
+ frameOf(foldSteps(start, loaded.steps.slice(0, count)), {
197
+ steps: loaded.steps.length,
198
+ lastSeq: loaded.lastSeq
199
+ })
200
+
201
+ /** A replay from `count` steps on: each next step after its gap, until the last. */
202
+ const replayStream = (loaded: Loaded, count: number, speed: number): Stream.Stream<string> => {
203
+ const { steps } = loaded
204
+ const frame = (fold: WebFold, gapMs: number): string =>
205
+ frameEvent(frameOf(fold, { steps: steps.length, lastSeq: loaded.lastSeq, gapMs }))
206
+ const first = foldSteps(start, steps.slice(0, count))
207
+ return Stream.make(frame(first, 0)).pipe(
208
+ Stream.concat(
209
+ Stream.unfold(first, (fold) => {
210
+ const next = steps[fold.count]
211
+ if (next === undefined) {
212
+ return Effect.succeed(undefined)
213
+ }
214
+ const gap = replayGap(steps[fold.count - 1]?.at ?? next.at, next.at, speed)
215
+ const advanced = advance(fold, next)
216
+ return Effect.as(Effect.sleep(Duration.millis(gap)), [
217
+ frame(advanced, gap),
218
+ advanced
219
+ ] as const)
220
+ })
221
+ ),
222
+ Stream.concat(Stream.make(endEvent))
223
+ )
224
+ }
225
+
226
+ /** A live run: the trace re-read now and every poll, until it says the run ended. */
227
+ const liveStream: Stream.Stream<string, FlowError> = Stream.fromEffectSchedule(
228
+ Effect.flatMap(load, liveFrame),
229
+ Schedule.spaced(pollInterval)
230
+ ).pipe(
231
+ Stream.takeUntil((frame) => frame.ended !== undefined),
232
+ Stream.map(frameEvent),
233
+ Stream.concat(Stream.make(endEvent))
234
+ )
235
+
236
+ const query = HttpServerRequest.schemaSearchParams(FrameQuery)
237
+ const failed = (error: unknown): Effect.Effect<HttpServerResponse.HttpServerResponse> =>
238
+ Effect.succeed(
239
+ HttpServerResponse.text(
240
+ typeof error === "object" && error !== null && "message" in error
241
+ ? String(error.message)
242
+ : "bad request",
243
+ { status: 400 }
244
+ )
245
+ )
246
+
247
+ const pages = webAssets.map((asset) =>
248
+ HttpRouter.route("GET", asset.path, () => {
249
+ const bytes = dependencies.asset(asset.file)
250
+ return Effect.succeed(
251
+ bytes === undefined
252
+ ? HttpServerResponse.text("missing", { status: 404 })
253
+ : HttpServerResponse.uint8Array(bytes, {
254
+ contentType: asset.type,
255
+ headers:
256
+ asset.path === "/" ? { "content-security-policy": contentSecurityPolicy } : {}
257
+ })
258
+ )
259
+ })
260
+ )
261
+ // The page names no icon; this keeps the browser's own request quiet.
262
+ const favicon = HttpRouter.route("GET", "/favicon.ico", () =>
263
+ Effect.succeed(HttpServerResponse.empty({ status: 204 }))
264
+ )
265
+
266
+ const run = HttpRouter.route(
267
+ "GET",
268
+ "/api/run",
269
+ Effect.gen(function* () {
270
+ const loaded = yield* load
271
+ return yield* HttpServerResponse.schemaJson(WebRun)({
272
+ mode: replay ? "replay" : "live",
273
+ runId: loaded.runId,
274
+ trace: basename(target.tracePath),
275
+ speed: speedOf(undefined),
276
+ steps: loaded.steps.map((step) => ({ seq: step.seq, at: step.at })),
277
+ lastSeq: loaded.lastSeq,
278
+ timeline: foldSteps(start, loaded.steps).timeline
279
+ })
280
+ }).pipe(Effect.catch(failed))
281
+ )
282
+
283
+ const frame = HttpRouter.route(
284
+ "GET",
285
+ "/api/frame",
286
+ Effect.gen(function* () {
287
+ const asked = yield* query
288
+ const loaded = yield* load
289
+ const body =
290
+ replay || asked.count !== undefined
291
+ ? replayFrame(
292
+ loaded,
293
+ Math.min(loaded.steps.length, Math.max(1, asked.count ?? loaded.steps.length))
294
+ )
295
+ : yield* liveFrame(loaded)
296
+ return yield* HttpServerResponse.schemaJson(WebFrame)(body)
297
+ }).pipe(Effect.catch(failed))
298
+ )
299
+
300
+ const stream = HttpRouter.route(
301
+ "GET",
302
+ "/api/stream",
303
+ Effect.gen(function* () {
304
+ const asked = yield* query
305
+ const loaded = yield* load
306
+ const body: Stream.Stream<string, FlowError> = replay
307
+ ? replayStream(
308
+ loaded,
309
+ Math.min(loaded.steps.length, Math.max(1, asked.count ?? 1)),
310
+ speedOf(asked.speed)
311
+ )
312
+ : liveStream
313
+ return HttpServerResponse.stream(Stream.encodeText(body), {
314
+ contentType: "text/event-stream",
315
+ headers: { connection: "keep-alive" }
316
+ })
317
+ }).pipe(Effect.catch(failed))
318
+ )
319
+
320
+ return Layer.mergeAll(HttpRouter.addAll([...pages, favicon, run, frame, stream]), guard)
321
+ })
322
+
323
+ /** Serves the page until the reader detaches; prints where to open it. */
324
+ export const runWebWatch = Effect.fn("@llm4ts/shell/WebWatch.run")(function* (
325
+ options: WebWatchOptions,
326
+ dependencies: WebWatchDependencies
327
+ ): Effect.fn.Return<void, FlowError | WatchTargetMissing | ServeError> {
328
+ const app = yield* webWatchApp(options, dependencies)
329
+ const host = options.host ?? "127.0.0.1"
330
+ const announce = Layer.effectDiscard(
331
+ HttpServer.addressFormattedWith((address) =>
332
+ dependencies.write(
333
+ `llm4ts watch --web${options.replay === true ? " --replay" : ""} · open ${address}/\nCtrl-C stops the server and detaches.\n`
334
+ )
335
+ )
336
+ )
337
+ let server: Server | undefined
338
+ const served = Layer.launch(
339
+ Layer.mergeAll(
340
+ HttpRouter.serve(app, { disableLogger: true, disableListenLog: true }),
341
+ announce
342
+ ).pipe(
343
+ Layer.provide(
344
+ NodeHttpServer.layer(
345
+ () => {
346
+ server = createServer()
347
+ return server
348
+ },
349
+ { host, port: options.port ?? 0 }
350
+ )
351
+ )
352
+ )
353
+ )
354
+ // A page holds its event stream open while the run is live, and the browser
355
+ // reopens it on the same keep-alive socket when it ends. A graceful close
356
+ // waits for those sockets, so it would never finish: on detach the server
357
+ // stops listening and drops every connection, then the layer shuts down.
358
+ const detach = Effect.andThen(
359
+ dependencies.detach,
360
+ Effect.sync(() => {
361
+ server?.close()
362
+ server?.closeAllConnections()
363
+ })
364
+ )
365
+ yield* Effect.raceFirst(served, detach)
366
+ yield* dependencies.write("detached\n")
367
+ })
368
+
369
+ // ── node wiring ─────────────────────────────────────────────────────────────
370
+
371
+ const webDir = new URL("../web/", import.meta.url)
372
+
373
+ /** A page file from `packages/shell/web/`, next to `src/` and `dist/` alike. */
374
+ export const nodeWebAsset = (file: string): Uint8Array | undefined => {
375
+ try {
376
+ return readFileSync(new URL(file, webDir))
377
+ } catch {
378
+ return undefined
379
+ }
380
+ }
381
+
382
+ /** Ctrl-C (or a SIGTERM): the server stops instead of the process dying under it. */
383
+ export const nodeDetach: Effect.Effect<void> = Effect.callback<void>((resume) => {
384
+ const stop = (): void => resume(Effect.void)
385
+ process.once("SIGINT", stop)
386
+ process.once("SIGTERM", stop)
387
+ return Effect.sync(() => {
388
+ process.off("SIGINT", stop)
389
+ process.off("SIGTERM", stop)
390
+ })
391
+ })
392
+
393
+ export const nodeWebWatchDependencies = (sources: TraceSources): WebWatchDependencies => ({
394
+ ...sources,
395
+ write: (text) => Effect.sync(() => void process.stdout.write(text)),
396
+ asset: nodeWebAsset,
397
+ detach: nodeDetach
398
+ })