@ordewell/web 0.12.2 → 0.12.4

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.
@@ -2,11 +2,12 @@
2
2
  'use strict';
3
3
 
4
4
  var hono = require('hono');
5
+ var core = require('@ordewell/core');
5
6
  var child_process = require('child_process');
6
7
  var crypto = require('crypto');
7
8
  var path = require('path');
8
- var core = require('@ordewell/core');
9
9
  var fs = require('fs');
10
+ var os = require('os');
10
11
  var ws = require('ws');
11
12
  var http = require('http');
12
13
 
@@ -30,7 +31,230 @@ function _interopNamespace(e) {
30
31
 
31
32
  var path__namespace = /*#__PURE__*/_interopNamespace(path);
32
33
  var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
34
+ var os__namespace = /*#__PURE__*/_interopNamespace(os);
35
+
36
+ var InvalidBodyError = class extends Error {
37
+ constructor(message) {
38
+ super(message);
39
+ this.name = "InvalidBodyError";
40
+ }
41
+ };
42
+ var ChildNotFoundError = class extends Error {
43
+ constructor() {
44
+ super("This tree has no such child plan.");
45
+ this.name = "ChildNotFoundError";
46
+ }
47
+ };
48
+ async function jsonObject(c) {
49
+ let parsed;
50
+ try {
51
+ parsed = await c.req.json();
52
+ } catch {
53
+ throw new InvalidBodyError("The request body must be valid JSON.");
54
+ }
55
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
56
+ throw new InvalidBodyError("The request body must be a JSON object.");
57
+ }
58
+ return parsed;
59
+ }
60
+ function classify(err) {
61
+ if (err instanceof InvalidBodyError) return { status: 400, code: "refused" };
62
+ if (err instanceof core.SessionNotFoundError) return { status: 404, code: "session_not_found" };
63
+ if (err instanceof ChildNotFoundError) return { status: 404, code: "child_not_found" };
64
+ if (err instanceof core.SessionHeldError) return { status: 409, code: "session_held" };
65
+ if (err instanceof core.NoPlanError) return { status: 400, code: "no_plan" };
66
+ if (err instanceof core.AlreadyExecutingError) return { status: 409, code: "already_executing" };
67
+ if (err instanceof core.WorkspaceNotAProjectError) return { status: 400, code: "workspace_not_a_project" };
68
+ if (err instanceof core.WorkspaceNotFoundError) return { status: 400, code: "workspace_not_found" };
69
+ if (err instanceof core.PlannerNotReadyError) return { status: 409, code: "planner_not_ready" };
70
+ if (err instanceof core.PlannerTurnStoppedError) return { status: 409, code: "planner_turn_stopped" };
71
+ if (err instanceof core.PlannerTurnDiscardedError) return { status: 409, code: "planner_turn_discarded" };
72
+ if (err instanceof core.ConversationBusyError) return { status: 409, code: "conversation_busy" };
73
+ if (err instanceof core.ConversationEditError || err instanceof core.PlanEditError || err instanceof core.TaskControlError) {
74
+ return { status: 400, code: "refused" };
75
+ }
76
+ return void 0;
77
+ }
78
+ function refuse(c, status, message, code) {
79
+ const body = code ? { error: message, code } : { error: message };
80
+ return c.json(body, status);
81
+ }
82
+ function failure(c, err, label, { fallback = 500, message = "Internal error" } = {}) {
83
+ const classified = classify(err);
84
+ const status = classified?.status ?? fallback;
85
+ if (status >= 500) console.error(`[web] ${label} failed:`, err);
86
+ const body = {
87
+ error: err instanceof Error && err.message || message,
88
+ ...classified ? { code: classified.code } : {},
89
+ ...err instanceof core.WorkspaceNotAProjectError ? { workspace: err.workspace } : {},
90
+ ...err instanceof core.PlannerNotReadyError ? { plannerNotReady: err.reason } : {},
91
+ ...err instanceof core.SessionHeldError ? { sessionHeld: err.held } : {}
92
+ };
93
+ return c.json(body, status);
94
+ }
95
+
96
+ // server/routes/children.ts
97
+ var ABOVE_THIS_PLAN = "A raise or a force is the plan above this one to give: this request sets neither.";
98
+ var CONTROL_REFUSALS = {
99
+ view_only: { status: 409, code: "child_view_only" },
100
+ refused: { status: 409, code: "child_refused" },
101
+ no_task: { status: 404, code: "child_task_not_found" },
102
+ not_waiting: { status: 409, code: "checkpoint_not_waiting" }
103
+ };
104
+ function childrenRoute(pool2) {
105
+ const router = new hono.Hono();
106
+ const childOf = async (c) => {
107
+ const child = await pool2.session(c.req.param("id")).children.find(c.req.param("childId"));
108
+ if (!child) throw new ChildNotFoundError();
109
+ return child;
110
+ };
111
+ const position = (c) => pool2.childPosition(c.req.param("id"), c.req.param("childId"));
112
+ const controlled = (c, outcome) => {
113
+ if (!outcome.ok) return refuse(c, CONTROL_REFUSALS[outcome.code].status, outcome.message, CONTROL_REFUSALS[outcome.code].code);
114
+ return c.json({ message: outcome.message, ...outcome.id ? { id: outcome.id } : {} });
115
+ };
116
+ const asksAboveItsPlan = (body) => "raiseTokens" in body || "force" in body;
117
+ router.get("/:id/children", async (c) => {
118
+ try {
119
+ return c.json({ children: await pool2.session(c.req.param("id")).children.list() });
120
+ } catch (err) {
121
+ return failure(c, err, "list child plans");
122
+ }
123
+ });
124
+ router.get("/:id/children/:childId", async (c) => {
125
+ try {
126
+ const child = await childOf(c);
127
+ return c.json({ ...child.view(), position: position(c) });
128
+ } catch (err) {
129
+ return failure(c, err, "read child plan");
130
+ }
131
+ });
132
+ router.get("/:id/children/:childId/tasks/:taskId/log", async (c) => {
133
+ try {
134
+ const child = await childOf(c);
135
+ return c.json({ attempts: core.listTaskLogAttempts(child.logLocation(), c.req.param("taskId")), position: position(c) });
136
+ } catch (err) {
137
+ return failure(c, err, "list child task log");
138
+ }
139
+ });
140
+ router.get("/:id/children/:childId/tasks/:taskId/log/:attempt", async (c) => {
141
+ try {
142
+ const child = await childOf(c);
143
+ const attempt = Number(c.req.param("attempt"));
144
+ if (!Number.isInteger(attempt) || attempt < 1) return refuse(c, 400, "attempt must be a positive integer");
145
+ return c.json({ attempt, events: core.taskLogForSurface(core.readTaskLog(child.logLocation(), c.req.param("taskId"), attempt)), position: position(c) });
146
+ } catch (err) {
147
+ return failure(c, err, "read child task log");
148
+ }
149
+ });
150
+ router.post("/:id/children/:childId/message", async (c) => {
151
+ try {
152
+ const child = await childOf(c);
153
+ const body = await jsonObject(c);
154
+ if (asksAboveItsPlan(body)) return refuse(c, 400, ABOVE_THIS_PLAN, "refused");
155
+ const { message } = body;
156
+ if (typeof message !== "string" || !message.trim()) return refuse(c, 400, "message must be a non-empty string");
157
+ const outcome = child.message(message);
158
+ if (!outcome.ok) return refuse(c, 409, outcome.message, outcome.code === "view_only" ? "child_view_only" : "child_refused");
159
+ return c.json({ status: outcome.status });
160
+ } catch (err) {
161
+ return failure(c, err, "message child plan");
162
+ }
163
+ });
164
+ router.post("/:id/children/:childId/tasks/:taskId/message", async (c) => {
165
+ try {
166
+ const child = await childOf(c);
167
+ const body = await jsonObject(c);
168
+ if (asksAboveItsPlan(body)) return refuse(c, 400, ABOVE_THIS_PLAN, "refused");
169
+ if (typeof body.message !== "string" || !body.message.trim()) return refuse(c, 400, "message must be a non-empty string", "refused");
170
+ return controlled(c, await child.control(c.req.param("taskId"), { kind: "message", text: body.message }));
171
+ } catch (err) {
172
+ return failure(c, err, "message child task");
173
+ }
174
+ });
175
+ for (const answer of ["approve", "reject"]) {
176
+ router.post(`/:id/children/:childId/tasks/:taskId/checkpoint/${answer}`, async (c) => {
177
+ try {
178
+ const child = await childOf(c);
179
+ const body = await jsonObject(c);
180
+ if (asksAboveItsPlan(body)) return refuse(c, 400, ABOVE_THIS_PLAN, "refused");
181
+ const { question } = body;
182
+ if (typeof question !== "string" || !question.trim()) return refuse(c, 400, "question must be the words the task is waiting on", "refused");
183
+ if (body.reason !== void 0 && typeof body.reason !== "string") return refuse(c, 400, "reason must be a string", "refused");
184
+ const reason = body.reason?.trim();
185
+ if (answer === "reject" && !reason) return refuse(c, 400, "A rejection needs a reason: it is all the runner has to go on.", "refused");
186
+ return controlled(c, await child.control(c.req.param("taskId"), { kind: "checkpoint", answer, question, ...reason ? { reason } : {} }));
187
+ } catch (err) {
188
+ return failure(c, err, "answer child checkpoint");
189
+ }
190
+ });
191
+ }
192
+ return router;
193
+ }
33
194
 
195
+ // server/pool/childStreams.ts
196
+ var ChildStreams = class {
197
+ constructor(stream) {
198
+ this.stream = stream;
199
+ }
200
+ stream;
201
+ watched = /* @__PURE__ */ new Map();
202
+ sequence = /* @__PURE__ */ new Map();
203
+ /** Snapshot and watching in one turn, as a root's socket has them: no frame can fall between. */
204
+ join(rootId, childId, child, ws) {
205
+ if (ws.readyState !== ws.OPEN) return;
206
+ const key = keyOf(rootId, childId);
207
+ const view = child.view();
208
+ ws.send(JSON.stringify({ type: "connected", sessionId: childId }));
209
+ ws.send(JSON.stringify({
210
+ type: "run_snapshot",
211
+ sessionId: childId,
212
+ view: view.run,
213
+ approvals: [],
214
+ ...this.position(rootId, childId)
215
+ }));
216
+ if (view.plannerCompaction) ws.send(JSON.stringify(view.plannerCompaction));
217
+ const watching = this.watched.get(key);
218
+ if (watching) {
219
+ watching.sockets.add(ws);
220
+ return;
221
+ }
222
+ const sockets = /* @__PURE__ */ new Set([ws]);
223
+ this.watched.set(key, { sockets, stop: child.watch((frame) => this.send(key, sockets, frame)) });
224
+ }
225
+ leave(rootId, childId, ws) {
226
+ const key = keyOf(rootId, childId);
227
+ const watching = this.watched.get(key);
228
+ if (!watching) return;
229
+ watching.sockets.delete(ws);
230
+ if (watching.sockets.size === 0) this.drop(key, watching);
231
+ }
232
+ position(rootId, childId) {
233
+ return { stream: this.stream, seq: this.sequence.get(keyOf(rootId, childId)) ?? 0 };
234
+ }
235
+ closeRoot(rootId, code) {
236
+ for (const [key, watching] of this.watched) {
237
+ if (!key.startsWith(keyOf(rootId, ""))) continue;
238
+ this.drop(key, watching);
239
+ for (const ws of watching.sockets) {
240
+ if (ws.readyState === ws.OPEN) ws.close(code, "Child plan closed");
241
+ }
242
+ }
243
+ }
244
+ send(key, sockets, frame) {
245
+ const seq = (this.sequence.get(key) ?? 0) + 1;
246
+ this.sequence.set(key, seq);
247
+ const payload = JSON.stringify({ ...frame, stream: this.stream, seq });
248
+ for (const ws of sockets) {
249
+ if (ws.readyState === ws.OPEN) ws.send(payload);
250
+ }
251
+ }
252
+ drop(key, watching) {
253
+ watching.stop();
254
+ this.watched.delete(key);
255
+ }
256
+ };
257
+ var keyOf = (rootId, childId) => `${rootId}\0${childId}`;
34
258
  var WebConfig = class extends core.BaseConfig {
35
259
  _enabledRunnersOverride;
36
260
  _providerModelLists;
@@ -139,7 +363,8 @@ function scanWorkspaces() {
139
363
  fsModule: fs__namespace,
140
364
  pathModule: path__namespace,
141
365
  cwd: process.cwd(),
142
- home: process.env.HOME || "/root",
366
+ // Not HOME, which Windows does not set: os.homedir() reads USERPROFILE there.
367
+ home: os__namespace.homedir(),
143
368
  projectDir: path__namespace.resolve(__dirname, "..", "..", "..", "..")
144
369
  });
145
370
  }
@@ -408,6 +633,7 @@ var OrchestratorPool = class {
408
633
  */
409
634
  stream = crypto.randomUUID();
410
635
  sequence = /* @__PURE__ */ new Map();
636
+ childStreams = new ChildStreams(this.stream);
411
637
  registry = new core.RunnerRegistry();
412
638
  modelResolver;
413
639
  /** A host that supplied its own resolver answers for every workspace, as a supplied probe does. */
@@ -442,9 +668,11 @@ var OrchestratorPool = class {
442
668
  codexSandbox;
443
669
  leaseHost;
444
670
  isolationPreview;
671
+ suppliedDockerCli;
445
672
  constructor(deps = {}) {
446
673
  const pluginNotice = core.removedPluginNotice();
447
674
  if (pluginNotice) console.warn(pluginNotice);
675
+ this.suppliedDockerCli = deps.dockerCli;
448
676
  this.runner = deps.runner ?? new core.StructuredRunner();
449
677
  this.suppliedRunnerInstallation = deps.runnerInstallation;
450
678
  this.runnerInstallation = deps.runnerInstallation ?? new core.RunnerInstallation(this.registry, void 0, void 0, {
@@ -513,6 +741,8 @@ var OrchestratorPool = class {
513
741
  if (!this.clients.has(sessionId)) this.clients.set(sessionId, /* @__PURE__ */ new Set());
514
742
  this.clients.get(sessionId).add(ws);
515
743
  this.connectAccountLimits(sessionId, ws);
744
+ const session = this.sessions.get(sessionId);
745
+ if (session) void this.tellTree(sessionId, session, [ws]);
516
746
  }
517
747
  unsubscribe(sessionId, ws) {
518
748
  this.clients.get(sessionId)?.delete(ws);
@@ -555,6 +785,31 @@ var OrchestratorPool = class {
555
785
  this.sessions.set(sessionId, session);
556
786
  this.sessionWorkspaces.set(sessionId, workspace);
557
787
  for (const ws of this.clients.get(sessionId) ?? []) this.connectAccountLimits(sessionId, ws);
788
+ session.children.onChange(() => void this.tellTree(sessionId, session));
789
+ }
790
+ /** The tree as it stands. A failed read tells nothing: the list route is where a surface hears why. */
791
+ async tellTree(sessionId, session, sockets) {
792
+ const children = await session.children.list().catch(() => []);
793
+ if (children.length === 0 || this.sessions.get(sessionId) !== session) return;
794
+ const payload = JSON.stringify({ type: "child_tree", sessionId, children });
795
+ for (const ws of sockets ?? this.clients.get(sessionId) ?? []) {
796
+ if (ws.readyState === ws.OPEN) ws.send(payload);
797
+ }
798
+ }
799
+ /** False for a child this root does not hold, or a root no longer loaded (ADR-0055 D20). */
800
+ async watchChild(rootId, childId, ws) {
801
+ const session = this.sessions.get(rootId);
802
+ const child = await session?.children.find(childId);
803
+ if (!child || this.sessions.get(rootId) !== session) return false;
804
+ this.childStreams.join(rootId, childId, child, ws);
805
+ return true;
806
+ }
807
+ unwatchChild(rootId, childId, ws) {
808
+ this.childStreams.leave(rootId, childId, ws);
809
+ }
810
+ /** What a read of the child taken now accounts for on its socket. */
811
+ childPosition(rootId, childId) {
812
+ return this.childStreams.position(rootId, childId);
558
813
  }
559
814
  broadcast(sessionId, msg) {
560
815
  const workspace = this.sessionWorkspaces.get(sessionId);
@@ -738,6 +993,19 @@ var OrchestratorPool = class {
738
993
  if (sessionId) this.sessions.get(sessionId)?.applyRunSettings(changes);
739
994
  return this.getSettings(sessionId, workspace);
740
995
  }
996
+ /** The `containers` setting as a surface shows it: `prove` starts a throwaway container to measure (ADR-0059 L3). */
997
+ containerStatus(prove, workspace) {
998
+ const { worktreeSetupCommand: setupCommand } = this.plannerConfig(void 0, workspace);
999
+ return core.containerStatus(this.settingsService.getAll().containers, { prove, ...this.docker(), ...setupCommand ? { setupCommand } : {} });
1000
+ }
1001
+ /** The way a surface changes that setting, and where it then stands; a running Session keeps what it opened with. */
1002
+ async changeContainers(change, workspace) {
1003
+ const refused = await core.changeContainers(change, { settings: this.settingsService, ...this.docker() });
1004
+ return { refused, status: await this.containerStatus(false, workspace) };
1005
+ }
1006
+ docker() {
1007
+ return this.suppliedDockerCli ? { cli: this.suppliedDockerCli } : {};
1008
+ }
741
1009
  /**
742
1010
  * The workspace whose runner catalog a settings read or write is judged
743
1011
  * against: an open session's own, else the one the client says it is in.
@@ -1163,6 +1431,7 @@ var OrchestratorPool = class {
1163
1431
  this.sessions.delete(sessionId);
1164
1432
  this.sessionWorkspaces.delete(sessionId);
1165
1433
  this.releaseUnusedAccountLimits();
1434
+ this.childStreams.closeRoot(sessionId, options?.notifyClients ? 1001 : 1012);
1166
1435
  if (!options?.notifyClients) return;
1167
1436
  const clients = this.clients.get(sessionId);
1168
1437
  if (!clients) return;
@@ -1198,7 +1467,7 @@ async function removeSession(sessionId, workspace, stop, close, reclaim) {
1198
1467
  await stop();
1199
1468
  const { refused } = await core.discardChildRuns(sessionId, workspace, core.createWorktreeIsolation({ config: new WebConfig() }));
1200
1469
  if (refused.length > 0) throw new Error(`The session was kept: ${refused.map(({ worktree, reason }) => `${worktree} (${reason})`).join(", ")}`);
1201
- close();
1470
+ await close();
1202
1471
  await reclaim();
1203
1472
  return core.deleteSession(sessionId, workspace);
1204
1473
  }
@@ -1222,60 +1491,6 @@ function stringField(value) {
1222
1491
  function workspaceKey(workspace) {
1223
1492
  return path.resolve(workspace ?? process.cwd());
1224
1493
  }
1225
- var InvalidBodyError = class extends Error {
1226
- constructor(message) {
1227
- super(message);
1228
- this.name = "InvalidBodyError";
1229
- }
1230
- };
1231
- async function jsonObject(c) {
1232
- let parsed;
1233
- try {
1234
- parsed = await c.req.json();
1235
- } catch {
1236
- throw new InvalidBodyError("The request body must be valid JSON.");
1237
- }
1238
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1239
- throw new InvalidBodyError("The request body must be a JSON object.");
1240
- }
1241
- return parsed;
1242
- }
1243
- function classify(err) {
1244
- if (err instanceof InvalidBodyError) return { status: 400, code: "refused" };
1245
- if (err instanceof core.SessionNotFoundError) return { status: 404, code: "session_not_found" };
1246
- if (err instanceof core.SessionHeldError) return { status: 409, code: "session_held" };
1247
- if (err instanceof core.NoPlanError) return { status: 400, code: "no_plan" };
1248
- if (err instanceof core.AlreadyExecutingError) return { status: 409, code: "already_executing" };
1249
- if (err instanceof core.WorkspaceNotAProjectError) return { status: 400, code: "workspace_not_a_project" };
1250
- if (err instanceof core.WorkspaceNotFoundError) return { status: 400, code: "workspace_not_found" };
1251
- if (err instanceof core.PlannerNotReadyError) return { status: 409, code: "planner_not_ready" };
1252
- if (err instanceof core.PlannerTurnStoppedError) return { status: 409, code: "planner_turn_stopped" };
1253
- if (err instanceof core.PlannerTurnDiscardedError) return { status: 409, code: "planner_turn_discarded" };
1254
- if (err instanceof core.ConversationBusyError) return { status: 409, code: "conversation_busy" };
1255
- if (err instanceof core.ConversationEditError || err instanceof core.PlanEditError || err instanceof core.TaskControlError) {
1256
- return { status: 400, code: "refused" };
1257
- }
1258
- return void 0;
1259
- }
1260
- function refuse(c, status, message, code) {
1261
- const body = code ? { error: message, code } : { error: message };
1262
- return c.json(body, status);
1263
- }
1264
- function failure(c, err, label, { fallback = 500, message = "Internal error" } = {}) {
1265
- const classified = classify(err);
1266
- const status = classified?.status ?? fallback;
1267
- if (status >= 500) console.error(`[web] ${label} failed:`, err);
1268
- const body = {
1269
- error: err instanceof Error && err.message || message,
1270
- ...classified ? { code: classified.code } : {},
1271
- ...err instanceof core.WorkspaceNotAProjectError ? { workspace: err.workspace } : {},
1272
- ...err instanceof core.PlannerNotReadyError ? { plannerNotReady: err.reason } : {},
1273
- ...err instanceof core.SessionHeldError ? { sessionHeld: err.held } : {}
1274
- };
1275
- return c.json(body, status);
1276
- }
1277
-
1278
- // server/routes/sessions.ts
1279
1494
  function sessionsRoute(pool2) {
1280
1495
  const router = new hono.Hono();
1281
1496
  router.get("/", (c) => {
@@ -1333,7 +1548,7 @@ function sessionsRoute(pool2) {
1333
1548
  const held = pool2.hasSession(id);
1334
1549
  let removed;
1335
1550
  try {
1336
- removed = await removeSession(id, ws, () => pool2.stopTree(id), () => pool2.destroy(id, { notifyClients: true }), () => pool2.reclaim(id));
1551
+ removed = await removeSession(id, ws, () => pool2.stopTree(id), () => pool2.close(id), () => pool2.reclaim(id));
1337
1552
  } catch (err) {
1338
1553
  return c.json({ ok: false, message: err instanceof Error ? err.message : String(err) });
1339
1554
  }
@@ -1746,8 +1961,39 @@ function approvalsRoute(pool2) {
1746
1961
  });
1747
1962
  return router;
1748
1963
  }
1964
+ function containerChange(body) {
1965
+ const change = Object.fromEntries(Object.entries(body).filter(([key]) => key !== "workspace"));
1966
+ if (Object.keys(change).length !== 1) return null;
1967
+ if (typeof change.on === "boolean") return { on: change.on };
1968
+ if (typeof change.image === "string") return { image: change.image };
1969
+ return "login" in change ? { login: change.login } : null;
1970
+ }
1749
1971
  function settingsRoute(pool2) {
1750
1972
  const router = new hono.Hono();
1973
+ router.use("/containers", async (c, next) => {
1974
+ if (!core.containersOffered()) return refuse(c, 404, "This build does not offer containers");
1975
+ return next();
1976
+ });
1977
+ router.get("/containers", async (c) => {
1978
+ try {
1979
+ const status = await pool2.containerStatus(c.req.query("prove") === "1", c.req.query("workspace") || void 0);
1980
+ return c.json(status);
1981
+ } catch (err) {
1982
+ return failure(c, err, "containers status");
1983
+ }
1984
+ });
1985
+ router.patch("/containers", async (c) => {
1986
+ try {
1987
+ const body = await jsonObject(c);
1988
+ const change = containerChange(body);
1989
+ if (!change) return refuse(c, 400, "One of on, image or login is required");
1990
+ const { workspace } = body;
1991
+ const result = await pool2.changeContainers(change, typeof workspace === "string" ? workspace || void 0 : void 0);
1992
+ return c.json(result);
1993
+ } catch (err) {
1994
+ return failure(c, err, "containers change", { fallback: 400 });
1995
+ }
1996
+ });
1751
1997
  router.get("/", async (c) => {
1752
1998
  await core.installedPlannerDetected();
1753
1999
  const sessionId = c.req.query("sessionId") || void 0;
@@ -1797,6 +2043,16 @@ function commandsRoute() {
1797
2043
  });
1798
2044
  return router;
1799
2045
  }
2046
+ var CHILD_PATH = /^\/ws\/session\/([^/]+)\/child\/([^/]+)$/;
2047
+ function joinChild(pool2, ws, rootId, childId) {
2048
+ const leave = () => pool2.unwatchChild(rootId, childId, ws);
2049
+ ws.on("close", leave);
2050
+ ws.on("error", leave);
2051
+ const refuse3 = () => ws.close(4404, "No such child plan in this tree");
2052
+ void pool2.watchChild(rootId, childId, ws).then((watching) => {
2053
+ if (!watching) refuse3();
2054
+ }, refuse3);
2055
+ }
1800
2056
  function createWsHandler(pool2) {
1801
2057
  const wss = new ws.WebSocketServer({
1802
2058
  noServer: true,
@@ -1807,6 +2063,11 @@ function createWsHandler(pool2) {
1807
2063
  });
1808
2064
  wss.on("connection", (ws, request) => {
1809
2065
  const url = new URL(request.url ?? "", `http://${request.headers.host}`);
2066
+ const child = CHILD_PATH.exec(url.pathname);
2067
+ if (child) {
2068
+ joinChild(pool2, ws, child[1], child[2]);
2069
+ return;
2070
+ }
1810
2071
  const sessionId = url.pathname.split("/").pop() || "";
1811
2072
  ws.on("close", () => {
1812
2073
  pool2.unsubscribe(sessionId, ws);
@@ -1910,6 +2171,7 @@ function createApp(pool2, admission) {
1910
2171
  });
1911
2172
  app.get("/api/server", (c) => c.json({ pid: process.pid, port: admission.port }));
1912
2173
  app.route("/api/sessions", sessionsRoute(pool2));
2174
+ app.route("/api/sessions", childrenRoute(pool2));
1913
2175
  app.route("/api/plans", plansRoute(pool2));
1914
2176
  app.route("/api/runners", runnersRoute(pool2));
1915
2177
  app.route("/api/models", modelsRoute(pool2));