@ordewell/web 0.13.1 → 0.13.3

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.
@@ -33,187 +33,20 @@ var path__namespace = /*#__PURE__*/_interopNamespace(path);
33
33
  var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
34
34
  var os__namespace = /*#__PURE__*/_interopNamespace(os);
35
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.WorkspaceReadError) {
74
- if (err.code === "gone") return { status: 410, code: "gone" };
75
- if (err.code === "path_refused") return { status: 403, code: "path_refused" };
76
- if (err.code === "path_not_found") return { status: 404, code: "path_not_found" };
77
- return { status: 400, code: "refused" };
78
- }
79
- if (err instanceof core.UserGitError) {
80
- if (err.code === "landing_branch_held" || err.code === "confirm_stale" || err.code === "stale") return { status: 409, code: err.code };
81
- return { status: 400, code: err.code };
82
- }
83
- if (err instanceof core.ConversationEditError || err instanceof core.PlanEditError || err instanceof core.TaskControlError) {
84
- return { status: 400, code: "refused" };
85
- }
86
- return void 0;
87
- }
88
- function refuse(c, status, message, code) {
89
- const body = code ? { error: message, code } : { error: message };
90
- return c.json(body, status);
91
- }
92
- function failure(c, err, label, { fallback = 500, message = "Internal error" } = {}) {
93
- const classified = classify(err);
94
- const status = classified?.status ?? fallback;
95
- if (status >= 500) console.error(`[web] ${label} failed:`, err);
96
- const body = {
97
- error: err instanceof Error && err.message || message,
98
- ...classified ? { code: classified.code } : {},
99
- ...err instanceof core.WorkspaceNotAProjectError ? { workspace: err.workspace } : {},
100
- ...err instanceof core.PlannerNotReadyError ? { plannerNotReady: err.reason } : {},
101
- ...err instanceof core.SessionHeldError ? { sessionHeld: err.held } : {},
102
- ...err instanceof core.UserGitError && err.detail.held ? { landingBranchHeld: err.detail.held } : {},
103
- ...err instanceof core.UserGitError && err.detail.difference ? { confirmStale: err.detail.difference } : {}
104
- };
105
- return c.json(body, status);
106
- }
107
-
108
- // server/routes/children.ts
109
- var ABOVE_THIS_PLAN = "A raise or a force is the plan above this one to give: this request sets neither.";
110
- var CONTROL_REFUSALS = {
111
- view_only: { status: 409, code: "child_view_only" },
112
- refused: { status: 409, code: "child_refused" },
113
- no_task: { status: 404, code: "child_task_not_found" },
114
- not_waiting: { status: 409, code: "checkpoint_not_waiting" }
115
- };
116
- function childrenRoute(pool) {
117
- const router = new hono.Hono();
118
- const childOf = async (c) => {
119
- const child = await pool.session(c.req.param("id")).children.find(c.req.param("childId"));
120
- if (!child) throw new ChildNotFoundError();
121
- return child;
122
- };
123
- const position = (c) => pool.childPosition(c.req.param("id"), c.req.param("childId"));
124
- const controlled = (c, outcome) => {
125
- if (!outcome.ok) return refuse(c, CONTROL_REFUSALS[outcome.code].status, outcome.message, CONTROL_REFUSALS[outcome.code].code);
126
- return c.json({ message: outcome.message, ...outcome.id ? { id: outcome.id } : {} });
127
- };
128
- const asksAboveItsPlan = (body) => "raiseTokens" in body || "force" in body;
129
- router.get("/:id/children", async (c) => {
130
- try {
131
- return c.json({ children: await pool.session(c.req.param("id")).children.list() });
132
- } catch (err) {
133
- return failure(c, err, "list child plans");
134
- }
135
- });
136
- router.get("/:id/children/:childId", async (c) => {
137
- try {
138
- const child = await childOf(c);
139
- return c.json({ ...child.view(), position: position(c) });
140
- } catch (err) {
141
- return failure(c, err, "read child plan");
142
- }
143
- });
144
- router.get("/:id/children/:childId/tasks/:taskId/log", async (c) => {
145
- try {
146
- const child = await childOf(c);
147
- return c.json({ attempts: core.listTaskLogAttempts(child.logLocation(), c.req.param("taskId")), position: position(c) });
148
- } catch (err) {
149
- return failure(c, err, "list child task log");
150
- }
151
- });
152
- router.get("/:id/children/:childId/tasks/:taskId/log/:attempt", async (c) => {
153
- try {
154
- const child = await childOf(c);
155
- const attempt = Number(c.req.param("attempt"));
156
- if (!Number.isInteger(attempt) || attempt < 1) return refuse(c, 400, "attempt must be a positive integer");
157
- return c.json({ attempt, events: core.taskLogForSurface(core.readTaskLog(child.logLocation(), c.req.param("taskId"), attempt)), position: position(c) });
158
- } catch (err) {
159
- return failure(c, err, "read child task log");
160
- }
161
- });
162
- router.post("/:id/children/:childId/message", async (c) => {
163
- try {
164
- const child = await childOf(c);
165
- const body = await jsonObject(c);
166
- if (asksAboveItsPlan(body)) return refuse(c, 400, ABOVE_THIS_PLAN, "refused");
167
- const { message } = body;
168
- if (typeof message !== "string" || !message.trim()) return refuse(c, 400, "message must be a non-empty string");
169
- const outcome = child.message(message);
170
- if (!outcome.ok) return refuse(c, 409, outcome.message, outcome.code === "view_only" ? "child_view_only" : "child_refused");
171
- return c.json({ status: outcome.status });
172
- } catch (err) {
173
- return failure(c, err, "message child plan");
174
- }
175
- });
176
- router.post("/:id/children/:childId/tasks/:taskId/message", 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
- if (typeof body.message !== "string" || !body.message.trim()) return refuse(c, 400, "message must be a non-empty string", "refused");
182
- return controlled(c, await child.control(c.req.param("taskId"), { kind: "message", text: body.message }));
183
- } catch (err) {
184
- return failure(c, err, "message child task");
185
- }
186
- });
187
- for (const answer of ["approve", "reject"]) {
188
- router.post(`/:id/children/:childId/tasks/:taskId/checkpoint/${answer}`, async (c) => {
189
- try {
190
- const child = await childOf(c);
191
- const body = await jsonObject(c);
192
- if (asksAboveItsPlan(body)) return refuse(c, 400, ABOVE_THIS_PLAN, "refused");
193
- const { question } = body;
194
- if (typeof question !== "string" || !question.trim()) return refuse(c, 400, "question must be the words the task is waiting on", "refused");
195
- if (body.reason !== void 0 && typeof body.reason !== "string") return refuse(c, 400, "reason must be a string", "refused");
196
- const reason = body.reason?.trim();
197
- if (answer === "reject" && !reason) return refuse(c, 400, "A rejection needs a reason: it is all the runner has to go on.", "refused");
198
- return controlled(c, await child.control(c.req.param("taskId"), { kind: "checkpoint", answer, question, ...reason ? { reason } : {} }));
199
- } catch (err) {
200
- return failure(c, err, "answer child checkpoint");
201
- }
202
- });
203
- }
204
- return router;
205
- }
206
-
207
36
  // server/pool/childStreams.ts
208
37
  var ChildStreams = class {
209
- constructor(stream) {
210
- this.stream = stream;
38
+ constructor(sequence, hears) {
39
+ this.sequence = sequence;
40
+ this.hears = hears;
211
41
  }
212
- stream;
42
+ sequence;
43
+ hears;
213
44
  watched = /* @__PURE__ */ new Map();
214
- sequence = /* @__PURE__ */ new Map();
215
- /** Snapshot and watching in one turn, as a root's socket has them: no frame can fall between. */
216
- join(rootId, childId, child, ws) {
45
+ /**
46
+ * Snapshot and watching in one turn, as a root's socket has them: no frame can
47
+ * fall between. `workspace` is the root's: its later frames reach only sockets allowed to hear it.
48
+ */
49
+ join(rootId, childId, child, ws, workspace) {
217
50
  if (ws.readyState !== ws.OPEN) return;
218
51
  const key = keyOf(rootId, childId);
219
52
  const view = child.view();
@@ -232,7 +65,7 @@ var ChildStreams = class {
232
65
  return;
233
66
  }
234
67
  const sockets = /* @__PURE__ */ new Set([ws]);
235
- this.watched.set(key, { sockets, stop: child.watch((frame) => this.send(key, sockets, frame)) });
68
+ this.watched.set(key, { sockets, stop: child.watch((frame) => this.send(key, sockets, workspace, frame)) });
236
69
  }
237
70
  leave(rootId, childId, ws) {
238
71
  const key = keyOf(rootId, childId);
@@ -242,7 +75,7 @@ var ChildStreams = class {
242
75
  if (watching.sockets.size === 0) this.drop(key, watching);
243
76
  }
244
77
  position(rootId, childId) {
245
- return { stream: this.stream, seq: this.sequence.get(keyOf(rootId, childId)) ?? 0 };
78
+ return this.sequence.position(keyOf(rootId, childId));
246
79
  }
247
80
  closeRoot(rootId, code) {
248
81
  for (const [key, watching] of this.watched) {
@@ -253,12 +86,10 @@ var ChildStreams = class {
253
86
  }
254
87
  }
255
88
  }
256
- send(key, sockets, frame) {
257
- const seq = (this.sequence.get(key) ?? 0) + 1;
258
- this.sequence.set(key, seq);
259
- const payload = JSON.stringify({ ...frame, stream: this.stream, seq });
89
+ send(key, sockets, workspace, frame) {
90
+ const payload = JSON.stringify({ ...frame, ...this.sequence.next(key) });
260
91
  for (const ws of sockets) {
261
- if (ws.readyState === ws.OPEN) ws.send(payload);
92
+ if (ws.readyState === ws.OPEN && this.hears(ws, workspace)) ws.send(payload);
262
93
  }
263
94
  }
264
95
  drop(key, watching) {
@@ -267,6 +98,25 @@ var ChildStreams = class {
267
98
  }
268
99
  };
269
100
  var keyOf = (rootId, childId) => `${rootId}\0${childId}`;
101
+
102
+ // server/pool/streamSequence.ts
103
+ var StreamSequence = class {
104
+ constructor(stream) {
105
+ this.stream = stream;
106
+ }
107
+ stream;
108
+ counts = /* @__PURE__ */ new Map();
109
+ /** The stamp of the next frame on `key`'s stream. */
110
+ next(key) {
111
+ const seq = (this.counts.get(key) ?? 0) + 1;
112
+ this.counts.set(key, seq);
113
+ return { stream: this.stream, seq };
114
+ }
115
+ /** The last frame on `key`'s stream: a read taken now accounts for it and everything before. */
116
+ position(key) {
117
+ return { stream: this.stream, seq: this.counts.get(key) ?? 0 };
118
+ }
119
+ };
270
120
  var WebConfig = class extends core.BaseConfig {
271
121
  _enabledRunnersOverride;
272
122
  _providerModelLists;
@@ -634,6 +484,12 @@ var PoolAwareRunner = class {
634
484
  };
635
485
 
636
486
  // server/pool/orchestratorPool.ts
487
+ var SessionOpenElsewhereError = class extends Error {
488
+ constructor(sessionId, workspace) {
489
+ super(`Session "${sessionId}" is open in this daemon for ${workspace}. Close it there before opening this workspace's copy.`);
490
+ this.name = "SessionOpenElsewhereError";
491
+ }
492
+ };
637
493
  var OrchestratorPool = class {
638
494
  // A daemon serves several workspaces; login selection must never follow
639
495
  // whichever session was opened most recently (ADR-0051).
@@ -643,15 +499,18 @@ var OrchestratorPool = class {
643
499
  limitsRevision = 0;
644
500
  sessions = /* @__PURE__ */ new Map();
645
501
  clients = /* @__PURE__ */ new Map();
502
+ /** The workspace each socket named when it subscribed, judged again whenever a session takes its id. */
503
+ socketWorkspaces = /* @__PURE__ */ new WeakMap();
646
504
  /**
647
- * This process's broadcast numbering (see `StreamStamp`), per session id
648
- * rather than per Session object: a session replaced under the same id
649
- * keeps counting up, so a client never mistakes its first broadcast for one
650
- * of the old session's it already showed.
505
+ * This process's broadcast numbering, per session id rather than per
506
+ * Session object: a session replaced under the same id keeps counting up,
507
+ * so a client never mistakes its first broadcast for one of the old
508
+ * session's it already showed. Child plans count on the same sequence,
509
+ * each under its own key.
651
510
  */
652
511
  stream = crypto.randomUUID();
653
- sequence = /* @__PURE__ */ new Map();
654
- childStreams = new ChildStreams(this.stream);
512
+ sequence = new StreamSequence(this.stream);
513
+ childStreams = new ChildStreams(this.sequence, (ws, workspace) => this.hears(ws, workspace));
655
514
  registry = new core.RunnerRegistry();
656
515
  modelResolver;
657
516
  /** A host that supplied its own resolver answers for every workspace, as a supplied probe does. */
@@ -755,7 +614,9 @@ var OrchestratorPool = class {
755
614
  throw err;
756
615
  }
757
616
  }
758
- subscribe(sessionId, ws) {
617
+ /** A socket naming a workspace keeps hearing the id only while no other workspace holds it; one naming none hears whoever does. */
618
+ subscribe(sessionId, ws, workspace) {
619
+ if (workspace !== void 0) this.socketWorkspaces.set(ws, workspace);
759
620
  if (!this.clients.has(sessionId)) this.clients.set(sessionId, /* @__PURE__ */ new Set());
760
621
  this.clients.get(sessionId).add(ws);
761
622
  this.connectAccountLimits(sessionId, ws);
@@ -780,17 +641,17 @@ var OrchestratorPool = class {
780
641
  monitor.subscribe((limits) => {
781
642
  for (const [id, clients] of this.clients) {
782
643
  if (this.sessionWorkspaces.get(id) !== workspace) continue;
783
- for (const client of clients) this.sendAccountLimits(id, client, limits);
644
+ for (const client of clients) this.sendAccountLimits(id, client, limits, workspace);
784
645
  }
785
646
  });
786
647
  }
787
- this.sendAccountLimits(sessionId, ws, monitor.snapshots());
648
+ this.sendAccountLimits(sessionId, ws, monitor.snapshots(), workspace);
788
649
  monitor.setForeground(true);
789
650
  monitor.surfaceConnected();
790
651
  }
791
- sendAccountLimits(sessionId, ws, limits) {
792
- if (ws.readyState !== ws.OPEN) return;
793
- ws.send(JSON.stringify({ type: "account_limits", sessionId, limits, stream: this.stream, revision: ++this.limitsRevision }));
652
+ /** `workspace` is the account the limits are read from; none for the empty greeting of an id nobody holds. */
653
+ sendAccountLimits(sessionId, ws, limits, workspace) {
654
+ this.send(sessionId, workspace, JSON.stringify({ type: "account_limits", sessionId, limits, stream: this.stream, revision: ++this.limitsRevision }), [ws]);
794
655
  }
795
656
  releaseUnusedAccountLimits() {
796
657
  for (const [workspace, monitor] of this.accountLimits) {
@@ -802,6 +663,13 @@ var OrchestratorPool = class {
802
663
  registerSession(sessionId, workspace, session) {
803
664
  this.sessions.set(sessionId, session);
804
665
  this.sessionWorkspaces.set(sessionId, workspace);
666
+ const clients = this.clients.get(sessionId);
667
+ for (const ws of clients ?? []) {
668
+ if (this.hears(ws, workspace)) continue;
669
+ clients?.delete(ws);
670
+ ws.close(4409, "Session open for another workspace");
671
+ }
672
+ if (clients?.size === 0) this.clients.delete(sessionId);
805
673
  for (const ws of this.clients.get(sessionId) ?? []) this.connectAccountLimits(sessionId, ws);
806
674
  session.children.onChange(() => void this.tellTree(sessionId, session));
807
675
  }
@@ -809,28 +677,46 @@ var OrchestratorPool = class {
809
677
  async tellTree(sessionId, session, sockets) {
810
678
  const children = await session.children.list().catch(() => []);
811
679
  if (children.length === 0 || this.sessions.get(sessionId) !== session) return;
812
- const payload = JSON.stringify({ type: "child_tree", sessionId, children });
680
+ this.send(sessionId, this.sessionWorkspaces.get(sessionId), JSON.stringify({ type: "child_tree", sessionId, children }), sockets);
681
+ }
682
+ /**
683
+ * The one way a frame of a session reaches its sockets: one that named
684
+ * another workspace than `workspace`, the one the frame speaks for, hears
685
+ * none of it. Registering a session closes such sockets, but frames are
686
+ * sent outside that window too: a load announces its usage before the
687
+ * session takes the id, and a replaced session's work may still be
688
+ * settling once another workspace's holds it.
689
+ */
690
+ send(sessionId, workspace, payload, sockets) {
813
691
  for (const ws of sockets ?? this.clients.get(sessionId) ?? []) {
814
- if (ws.readyState === ws.OPEN) ws.send(payload);
692
+ if (ws.readyState === ws.OPEN && this.hears(ws, workspace)) ws.send(payload);
815
693
  }
816
694
  }
695
+ /** Whether a socket may hear what `workspace`'s session says: always, unless both name a workspace and they differ. */
696
+ hears(ws, workspace) {
697
+ const named = this.socketWorkspaces.get(ws);
698
+ return named === void 0 || workspace === void 0 || sameWorkspace(named, workspace);
699
+ }
817
700
  /** False for a child this root does not hold, or a root no longer loaded (ADR-0055 D20). */
818
- async watchChild(rootId, childId, ws) {
701
+ async watchChild(rootId, childId, ws, workspace) {
702
+ if (workspace !== void 0) this.socketWorkspaces.set(ws, workspace);
819
703
  const session = this.sessions.get(rootId);
820
704
  const child = await session?.children.find(childId);
821
- if (!child || this.sessions.get(rootId) !== session) return false;
822
- this.childStreams.join(rootId, childId, child, ws);
705
+ const held = this.sessionWorkspaces.get(rootId);
706
+ if (!child || this.sessions.get(rootId) !== session || !this.hears(ws, held)) return false;
707
+ this.childStreams.join(rootId, childId, child, ws, held);
823
708
  return true;
824
709
  }
825
710
  unwatchChild(rootId, childId, ws) {
826
711
  this.childStreams.leave(rootId, childId, ws);
827
712
  }
828
- /** What a read of the child taken now accounts for on its socket. */
829
- childPosition(rootId, childId) {
713
+ /** What a read of the child taken now accounts for on its socket; refused, as {@link live} is, once another workspace holds the root. */
714
+ childPosition(rootId, childId, workspace) {
715
+ this.live(rootId, workspace);
830
716
  return this.childStreams.position(rootId, childId);
831
717
  }
832
- broadcast(sessionId, msg) {
833
- const workspace = this.sessionWorkspaces.get(sessionId);
718
+ /** `workspace` is the one of the Session that speaks, which need not be the one holding the id by the time it does. */
719
+ broadcast(sessionId, workspace, msg) {
834
720
  const monitor = workspace ? this.accountLimits.get(workspace) : void 0;
835
721
  if (msg.type === "planner_usage") monitor?.invalidate();
836
722
  else if (msg.type === "task_log" && msg.events.some((event) => event.type === "turn_end")) {
@@ -838,20 +724,36 @@ var OrchestratorPool = class {
838
724
  const runner = task && core.assignedRunnerOf(task);
839
725
  if (runner) monitor?.invalidate(runner);
840
726
  }
841
- const seq = (this.sequence.get(sessionId) ?? 0) + 1;
842
- this.sequence.set(sessionId, seq);
843
- const payload = JSON.stringify({ ...msg, stream: this.stream, seq });
844
- for (const ws of this.clients.get(sessionId) ?? []) {
845
- if (ws.readyState === ws.OPEN) ws.send(payload);
846
- }
727
+ this.send(sessionId, workspace, JSON.stringify({ ...msg, ...this.sequence.next(sessionId) }));
847
728
  }
848
729
  hasSession(sessionId) {
849
730
  return this.sessions.has(sessionId);
850
731
  }
732
+ /** Whether the session open under this id is this workspace's: only then do the id's live accessors speak for it. */
733
+ holds(sessionId, workspace) {
734
+ return this.heldHere(sessionId, workspace) !== void 0;
735
+ }
736
+ /** Whether the session open under this id is another workspace's: what the id's live accessors say is not this workspace's to read or act on. */
737
+ heldElsewhere(sessionId, workspace) {
738
+ return this.sessions.has(sessionId) && !this.holds(sessionId, workspace);
739
+ }
740
+ /**
741
+ * The session open under this id, as a client in `workspace` reaches it: the
742
+ * one lookup a route goes through to reach a live session by id. The pool
743
+ * keeps one session per id, so while another workspace holds it the id names
744
+ * that project's session, not the caller's, and the call is refused rather
745
+ * than served or acted on there. Undefined when none is open; a caller that
746
+ * names no workspace reaches it by the id alone.
747
+ */
748
+ live(sessionId, workspace) {
749
+ const held = this.sessionWorkspaces.get(sessionId);
750
+ if (held !== void 0 && workspace !== void 0 && !this.heldHere(sessionId, workspace)) throw new SessionOpenElsewhereError(sessionId, held);
751
+ return this.sessions.get(sessionId);
752
+ }
851
753
  /** The session open here under this id for this workspace, if any: an id names a session only within its workspace. */
852
754
  heldHere(sessionId, workspace) {
853
755
  const held = this.sessionWorkspaces.get(sessionId);
854
- return held !== void 0 && path.resolve(held) === path.resolve(workspace) ? this.sessions.get(sessionId) : void 0;
756
+ return held !== void 0 && sameWorkspace(held, workspace) ? this.sessions.get(sessionId) : void 0;
855
757
  }
856
758
  /**
857
759
  * Whether a session's run holds its landing branch (ADR-0062 G7): this
@@ -875,16 +777,6 @@ var OrchestratorPool = class {
875
777
  if (session?.planState) session.recordUserAction(text2);
876
778
  else core.appendUserAction(sessionId, workspace, { text: text2, at: (/* @__PURE__ */ new Date()).toISOString() });
877
779
  }
878
- /** Answer an approval prompt, the planner's or a task runner's. False means the id was unknown or already settled. */
879
- resolveApproval(sessionId, approvalId, answer) {
880
- return this.sessions.get(sessionId)?.resolveApproval(approvalId, answer) ?? false;
881
- }
882
- outstandingApprovals(sessionId) {
883
- return this.sessions.get(sessionId)?.outstandingApprovals() ?? [];
884
- }
885
- approvedScopes(sessionId) {
886
- return this.sessions.get(sessionId)?.approvedScopes() ?? [];
887
- }
888
780
  isExecuting(sessionId) {
889
781
  return this.sessions.get(sessionId)?.isExecuting ?? false;
890
782
  }
@@ -909,6 +801,28 @@ var OrchestratorPool = class {
909
801
  getGoal(sessionId) {
910
802
  return this.sessions.get(sessionId)?.currentGoal ?? "";
911
803
  }
804
+ /**
805
+ * A session's run as the session list says it (`SessionRunActivity`): for
806
+ * one held here for this workspace, this daemon's own word, by the test and
807
+ * the count the open session's header uses, so its row reads the same open
808
+ * or not; for one another host holds, that host's lease's `runLive`, read
809
+ * without taking it and only while its holder lives (ADR-0049); otherwise
810
+ * nothing. An id held here for another workspace says nothing of this one's.
811
+ */
812
+ runActivity(sessionId, workspace) {
813
+ const session = this.heldHere(sessionId, workspace);
814
+ if (session) {
815
+ if (!session.isExecuting && !session.activity.advancesOnItsOwn) return void 0;
816
+ return { live: true, ...core.planProgressCount(session.runSnapshot().tasks) };
817
+ }
818
+ let held;
819
+ try {
820
+ held = (this.leaseHost ?? core.processLeaseHost()).peek(sessionId, workspace);
821
+ } catch {
822
+ return void 0;
823
+ }
824
+ return held && !held.orphanedRunners && held.holder.runLive === true ? { live: true } : void 0;
825
+ }
912
826
  /** Null for a session this process is not holding: there is no run to describe. */
913
827
  runSnapshot(sessionId) {
914
828
  return this.sessions.get(sessionId)?.runSnapshot() ?? null;
@@ -930,7 +844,7 @@ var OrchestratorPool = class {
930
844
  }
931
845
  /** The last broadcast of the session so far: a snapshot taken now accounts for it and everything before. */
932
846
  streamPosition(sessionId) {
933
- return { stream: this.stream, seq: this.sequence.get(sessionId) ?? 0 };
847
+ return this.sequence.position(sessionId);
934
848
  }
935
849
  runtimeSettings() {
936
850
  return core.sessionRuntimeSettings(this.settingsService.getAll());
@@ -946,7 +860,7 @@ var OrchestratorPool = class {
946
860
  }
947
861
  const config = this.plannerConfig(modelOverride, workspace);
948
862
  const fsAdapter = new PoolFileSystem(workspace);
949
- const broadcast = (msg) => this.broadcast(sessionId, msg);
863
+ const broadcast = (msg) => this.broadcast(sessionId, workspace, msg);
950
864
  const runner = new PoolAwareRunner(sessionId, broadcast, this.runner);
951
865
  return core.createSession({
952
866
  config,
@@ -962,7 +876,7 @@ var OrchestratorPool = class {
962
876
  fsAdapter,
963
877
  broadcast,
964
878
  // The notification channel above is silent here; this is how a client hears how the run isolates.
965
- onNotice: (notice) => this.broadcast(sessionId, notice),
879
+ onNotice: (notice) => this.broadcast(sessionId, workspace, notice),
966
880
  modelResolver: this.resolverFor(workspace),
967
881
  settings: () => this.runtimeSettings(),
968
882
  sessionId,
@@ -1013,7 +927,7 @@ var OrchestratorPool = class {
1013
927
  getSettings(sessionId, workspace) {
1014
928
  const config = this.plannerConfig(void 0, this.settingsWorkspace(sessionId, workspace));
1015
929
  const userSettings = this.settingsService.getAll();
1016
- const live = sessionId ? this.sessions.get(sessionId) : void 0;
930
+ const live = sessionId ? this.live(sessionId, workspace) : void 0;
1017
931
  return {
1018
932
  orchestratorModel: config.orchestratorModel,
1019
933
  // Who plans (ADR-0009) — a vendor id, or one of the three harness
@@ -1044,8 +958,9 @@ var OrchestratorPool = class {
1044
958
  * for a value out of range.
1045
959
  */
1046
960
  updateRunSettings(changes2, sessionId, workspace) {
961
+ const live = sessionId ? this.live(sessionId, workspace) : void 0;
1047
962
  this.settingsService.updateRunSettings(changes2);
1048
- if (sessionId) this.sessions.get(sessionId)?.applyRunSettings(changes2);
963
+ live?.applyRunSettings(changes2);
1049
964
  return this.getSettings(sessionId, workspace);
1050
965
  }
1051
966
  /** The `containers` setting as a surface shows it: `prove` starts a throwaway container to measure (ADR-0059 L3). */
@@ -1063,12 +978,13 @@ var OrchestratorPool = class {
1063
978
  }
1064
979
  /**
1065
980
  * The workspace whose runner catalog a settings read or write is judged
1066
- * against: an open session's own, else the one the client says it is in.
1067
- * Without either the daemon's cwd stands in. One daemon serves several
981
+ * against: an open session's own, else the one the client says it is in,
982
+ * refused for a session another workspace holds under the id. Without either
983
+ * the daemon's cwd stands in. One daemon serves several
1068
984
  * workspaces, and each may name another Claude account in its environment.
1069
985
  */
1070
986
  settingsWorkspace(sessionId, workspace) {
1071
- return (sessionId ? this.sessions.get(sessionId)?.workspaceRoot : void 0) ?? workspace;
987
+ return (sessionId ? this.live(sessionId, workspace)?.workspaceRoot : void 0) ?? workspace;
1072
988
  }
1073
989
  /**
1074
990
  * The catalog `selectPlanner` should judge `provider`'s
@@ -1335,7 +1251,7 @@ var OrchestratorPool = class {
1335
1251
  );
1336
1252
  }
1337
1253
  async generatePlan(sessionId, goal, runners, workspace, modelOverride, options) {
1338
- const recheck = this.recheckSignedOutPlanner(workspace, this.plannerConfig(modelOverride).aiProvider);
1254
+ const recheck = this.recheckSignedOutPlanner(workspace, this.plannerConfig(modelOverride, workspace).aiProvider);
1339
1255
  if (recheck) await recheck;
1340
1256
  const session = this.openPlanningSession(sessionId, runners, workspace, modelOverride, options);
1341
1257
  return core.migratePlanState(await this.firstTurn(sessionId, session, () => session.generatePlan(goal, runners)));
@@ -1360,6 +1276,7 @@ var OrchestratorPool = class {
1360
1276
  * place of any live one, for {@link firstTurn} to run its first turn on.
1361
1277
  */
1362
1278
  openPlanningSession(sessionId, runners, workspace, modelOverride, options) {
1279
+ this.live(sessionId, workspace);
1363
1280
  const session = this.createSessionFor(sessionId, workspace, modelOverride, options);
1364
1281
  if (core.installedPlannerAnswered()) {
1365
1282
  session.assertPlannerReady();
@@ -1377,10 +1294,10 @@ var OrchestratorPool = class {
1377
1294
  * assistant message lives in conversationHistory).
1378
1295
  */
1379
1296
  async startPlanning(sessionId, goal, runners, workspace, modelOverride, options) {
1380
- const recheck = this.recheckSignedOutPlanner(workspace, this.plannerConfig(modelOverride).aiProvider);
1297
+ const recheck = this.recheckSignedOutPlanner(workspace, this.plannerConfig(modelOverride, workspace).aiProvider);
1381
1298
  if (recheck) await recheck;
1382
1299
  const session = this.openPlanningSession(sessionId, runners, workspace, modelOverride, options);
1383
- return this.firstTurn(sessionId, session, () => session.startPlanning(goal, runners));
1300
+ return this.firstTurn(sessionId, session, () => session.startPlanning(goal, runners, { surface: options?.surface }));
1384
1301
  }
1385
1302
  /**
1386
1303
  * Continue the planner dialogue with the user's reply: queued behind the
@@ -1389,15 +1306,15 @@ var OrchestratorPool = class {
1389
1306
  * session's own planner gate waits for the probe and judges the planner, as
1390
1307
  * it does for every turn.
1391
1308
  */
1392
- async continuePlanning(sessionId, message) {
1393
- const session = this.session(sessionId);
1309
+ async continuePlanning(sessionId, message, workspace, surface) {
1310
+ const session = this.session(sessionId, workspace);
1394
1311
  const recheck = this.recheckSignedOutPlanner(session.workspaceRoot, session.plannerProvider);
1395
1312
  if (recheck) await recheck;
1396
- return session.continueConversation(message);
1313
+ return session.continueConversation(message, { surface });
1397
1314
  }
1398
1315
  /** Condense a session's conversation. The summary turn is a planner turn, so `cancelPlanning` stops it. */
1399
- async compactConversation(sessionId) {
1400
- const session = this.session(sessionId);
1316
+ async compactConversation(sessionId, workspace) {
1317
+ const session = this.session(sessionId, workspace);
1401
1318
  const recheck = this.recheckSignedOutPlanner(session.workspaceRoot, session.plannerProvider);
1402
1319
  if (recheck) await recheck;
1403
1320
  const compaction = await session.compactConversation();
@@ -1409,15 +1326,15 @@ var OrchestratorPool = class {
1409
1326
  * waiting. The recheck is the one a reply does before the gate: a login done
1410
1327
  * with the runner's own command is seen here too.
1411
1328
  */
1412
- async forceSendPrompt(sessionId, message) {
1413
- const session = this.session(sessionId);
1329
+ async forceSendPrompt(sessionId, message, workspace, surface) {
1330
+ const session = this.session(sessionId, workspace);
1414
1331
  const recheck = this.recheckSignedOutPlanner(session.workspaceRoot, session.plannerProvider);
1415
1332
  if (recheck) await recheck;
1416
- return session.forceSendPrompt(message);
1333
+ return session.forceSendPrompt(message, { surface });
1417
1334
  }
1418
1335
  /** Retry a compaction paused on the planner's context: a planner turn, and gated as one. */
1419
- async retryPlannerCompaction(sessionId) {
1420
- const session = this.session(sessionId);
1336
+ async retryPlannerCompaction(sessionId, workspace) {
1337
+ const session = this.session(sessionId, workspace);
1421
1338
  const recheck = this.recheckSignedOutPlanner(session.workspaceRoot, session.plannerProvider);
1422
1339
  if (recheck) await recheck;
1423
1340
  return session.retryPlannerCompaction();
@@ -1427,8 +1344,8 @@ var OrchestratorPool = class {
1427
1344
  * there was one to cancel — the route reports that rather than 404ing a
1428
1345
  * session that simply is not planning right now.
1429
1346
  */
1430
- cancelPlanning(sessionId) {
1431
- return this.sessions.get(sessionId)?.abortPlannerTurn() ?? false;
1347
+ cancelPlanning(sessionId, workspace) {
1348
+ return this.live(sessionId, workspace)?.abortPlannerTurn() ?? false;
1432
1349
  }
1433
1350
  /**
1434
1351
  * Register a session persisted on disk so its plan becomes executable and
@@ -1440,10 +1357,12 @@ var OrchestratorPool = class {
1440
1357
  * only contacted when the user next sends a message.
1441
1358
  */
1442
1359
  adoptSavedSession(sessionId, workspace) {
1443
- const live = this.sessions.get(sessionId);
1360
+ const live = this.heldHere(sessionId, workspace);
1444
1361
  if (live?.planState) return live.planState;
1445
1362
  const saved = core.loadSession(sessionId, workspace);
1446
1363
  if (!saved) throw new core.SessionNotFoundError();
1364
+ const elsewhere = this.sessionWorkspaces.get(sessionId);
1365
+ if (!live && elsewhere !== void 0) throw new SessionOpenElsewhereError(sessionId, elsewhere);
1447
1366
  const session = this.createSessionFor(sessionId, workspace);
1448
1367
  try {
1449
1368
  session.loadPlan(saved.plan, saved.meta.goal, workspace, { sessionId: saved.meta.id });
@@ -1462,12 +1381,12 @@ var OrchestratorPool = class {
1462
1381
  * adopted by, reading back the file the fork was written to. The original
1463
1382
  * keeps running, or planning, untouched.
1464
1383
  */
1465
- forkConversation(sessionId) {
1466
- return this.adoptFork(this.session(sessionId).forkConversation());
1384
+ forkConversation(sessionId, workspace) {
1385
+ return this.adoptFork(this.session(sessionId, workspace).forkConversation());
1467
1386
  }
1468
1387
  /** A rewind is a fork from an earlier point, so it is adopted the same way. */
1469
- rewindConversation(sessionId, index) {
1470
- const fork = this.session(sessionId).rewindConversation(index);
1388
+ rewindConversation(sessionId, index, workspace) {
1389
+ const fork = this.session(sessionId, workspace).rewindConversation(index);
1471
1390
  return { ...this.adoptFork(fork), rewoundMessage: fork.rewoundMessage };
1472
1391
  }
1473
1392
  adoptFork(fork) {
@@ -1475,10 +1394,15 @@ var OrchestratorPool = class {
1475
1394
  }
1476
1395
  /**
1477
1396
  * Direct access to a session's interface — routes call the Session; the
1478
- * pool only registers sessions and fans broadcasts out to WS clients.
1397
+ * pool only registers sessions and fans broadcasts out to WS clients. A
1398
+ * caller naming a workspace is refused another's, as {@link live} is. The
1399
+ * workspace is required, if only as undefined, so that no caller reaches a
1400
+ * session by its id without saying whose it asks for; and a route calls it
1401
+ * where it acts, after whatever it awaited, since the id may name another
1402
+ * project's session by then.
1479
1403
  */
1480
- session(sessionId) {
1481
- const session = this.sessions.get(sessionId);
1404
+ session(sessionId, workspace) {
1405
+ const session = this.live(sessionId, workspace);
1482
1406
  if (!session) throw new core.SessionNotFoundError();
1483
1407
  return session;
1484
1408
  }
@@ -1490,6 +1414,7 @@ var OrchestratorPool = class {
1490
1414
  * longer exists — so those pass `notifyClients`.
1491
1415
  */
1492
1416
  destroy(sessionId, options) {
1417
+ const workspace = this.sessionWorkspaces.get(sessionId);
1493
1418
  this.sessions.get(sessionId)?.destroy();
1494
1419
  this.sessions.delete(sessionId);
1495
1420
  this.sessionWorkspaces.delete(sessionId);
@@ -1498,24 +1423,36 @@ var OrchestratorPool = class {
1498
1423
  if (!options?.notifyClients) return;
1499
1424
  const clients = this.clients.get(sessionId);
1500
1425
  if (!clients) return;
1501
- this.broadcast(sessionId, { type: "notice", level: "info", message: "Session closed." });
1426
+ this.broadcast(sessionId, workspace, { type: "notice", level: "info", message: "Session closed." });
1502
1427
  for (const ws of clients) {
1503
1428
  if (ws.readyState === ws.OPEN) ws.close(1001, "Session closed");
1504
1429
  }
1505
1430
  this.clients.delete(sessionId);
1506
1431
  }
1507
- /** Close a session for a surface that is done with it: it is dropped now, and this resolves once all it started has gone. */
1508
- async close(sessionId) {
1509
- const session = this.sessions.get(sessionId);
1432
+ /**
1433
+ * Close `workspace`'s session for a surface that is done with it: it is
1434
+ * dropped now, and this resolves once all it started has gone. Another
1435
+ * workspace's open under the id is left alone. Judged when called, not when
1436
+ * the request began: a delete calls this after its tree stop, by when the
1437
+ * id may name a session another project opened meanwhile.
1438
+ */
1439
+ async close(sessionId, workspace) {
1440
+ const session = this.heldHere(sessionId, workspace);
1441
+ if (!session) return;
1510
1442
  this.destroy(sessionId, { notifyClients: true });
1511
- await session?.gone;
1443
+ await session.gone;
1512
1444
  }
1513
- /** Stop a session's whole tree, and wait until it has gone; the session stays open (ADR-0055 D16). */
1514
- async stopTree(sessionId) {
1515
- await this.sessions.get(sessionId)?.stopSubtree();
1445
+ /** Stop the whole tree of `workspace`'s session, if it holds the id, and wait until it has gone; the session stays open (ADR-0055 D16). */
1446
+ async stopTree(sessionId, workspace) {
1447
+ await this.heldHere(sessionId, workspace)?.stopSubtree();
1516
1448
  }
1517
- /** What a session's tree left in the engine, which only the `containers` setting says to look for (ADR-0059 L6). */
1518
- reclaim(sessionId) {
1449
+ /**
1450
+ * What `workspace`'s session's tree left in the engine, which only the
1451
+ * `containers` setting says to look for (ADR-0059 L6). Nothing while another
1452
+ * workspace holds the id: its tree runs in containers under the same id.
1453
+ */
1454
+ reclaim(sessionId, workspace) {
1455
+ if (this.heldElsewhere(sessionId, workspace)) return Promise.resolve();
1519
1456
  return core.reclaimContainers(sessionId, this.settingsService.getAll().containers);
1520
1457
  }
1521
1458
  destroyAll() {
@@ -1551,33 +1488,243 @@ function changesPlanner(change) {
1551
1488
  function stringField(value) {
1552
1489
  return typeof value === "string" ? value : void 0;
1553
1490
  }
1491
+ function sameWorkspace(a, b) {
1492
+ return path.resolve(a) === path.resolve(b);
1493
+ }
1554
1494
  function workspaceKey(workspace) {
1555
1495
  return path.resolve(workspace ?? process.cwd());
1556
1496
  }
1497
+
1498
+ // server/routes/errors.ts
1499
+ var InvalidBodyError = class extends Error {
1500
+ constructor(message) {
1501
+ super(message);
1502
+ this.name = "InvalidBodyError";
1503
+ }
1504
+ };
1505
+ var ChildNotFoundError = class extends Error {
1506
+ constructor() {
1507
+ super("This tree has no such child plan.");
1508
+ this.name = "ChildNotFoundError";
1509
+ }
1510
+ };
1511
+ async function jsonObject(c) {
1512
+ let parsed;
1513
+ try {
1514
+ parsed = await c.req.json();
1515
+ } catch {
1516
+ throw new InvalidBodyError("The request body must be valid JSON.");
1517
+ }
1518
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1519
+ throw new InvalidBodyError("The request body must be a JSON object.");
1520
+ }
1521
+ return parsed;
1522
+ }
1523
+ function classify(err) {
1524
+ if (err instanceof InvalidBodyError) return { status: 400, code: "refused" };
1525
+ if (err instanceof core.SessionNotFoundError) return { status: 404, code: "session_not_found" };
1526
+ if (err instanceof ChildNotFoundError) return { status: 404, code: "child_not_found" };
1527
+ if (err instanceof core.SessionHeldError) return { status: 409, code: "session_held" };
1528
+ if (err instanceof SessionOpenElsewhereError) return { status: 409, code: "refused" };
1529
+ if (err instanceof core.NoPlanError) return { status: 400, code: "no_plan" };
1530
+ if (err instanceof core.AlreadyExecutingError) return { status: 409, code: "already_executing" };
1531
+ if (err instanceof core.WorkspaceNotAProjectError) return { status: 400, code: "workspace_not_a_project" };
1532
+ if (err instanceof core.WorkspaceNotFoundError) return { status: 400, code: "workspace_not_found" };
1533
+ if (err instanceof core.PlannerNotReadyError) return { status: 409, code: "planner_not_ready" };
1534
+ if (err instanceof core.PlannerTurnStoppedError) return { status: 409, code: "planner_turn_stopped" };
1535
+ if (err instanceof core.PlannerTurnDiscardedError) return { status: 409, code: "planner_turn_discarded" };
1536
+ if (err instanceof core.ConversationBusyError) return { status: 409, code: "conversation_busy" };
1537
+ if (err instanceof core.WorkspaceReadError) {
1538
+ if (err.code === "gone") return { status: 410, code: "gone" };
1539
+ if (err.code === "path_refused") return { status: 403, code: "path_refused" };
1540
+ if (err.code === "path_not_found") return { status: 404, code: "path_not_found" };
1541
+ return { status: 400, code: "refused" };
1542
+ }
1543
+ if (err instanceof core.UserGitError) {
1544
+ if (err.code === "landing_branch_held" || err.code === "confirm_stale" || err.code === "stale") return { status: 409, code: err.code };
1545
+ return { status: 400, code: err.code };
1546
+ }
1547
+ if (err instanceof core.ConversationEditError || err instanceof core.PlanEditError || err instanceof core.TaskControlError) {
1548
+ return { status: 400, code: "refused" };
1549
+ }
1550
+ return void 0;
1551
+ }
1552
+ function refuse(c, status, message, code) {
1553
+ const body = code ? { error: message, code } : { error: message };
1554
+ return c.json(body, status);
1555
+ }
1556
+ function failure(c, err, label, { fallback = 500, message = "Internal error" } = {}) {
1557
+ const classified = classify(err);
1558
+ const status = classified?.status ?? fallback;
1559
+ if (status >= 500) console.error(`[web] ${label} failed:`, err);
1560
+ const body = {
1561
+ error: err instanceof Error && err.message || message,
1562
+ ...classified ? { code: classified.code } : {},
1563
+ ...err instanceof core.WorkspaceNotAProjectError ? { workspace: err.workspace } : {},
1564
+ ...err instanceof core.PlannerNotReadyError ? { plannerNotReady: err.reason } : {},
1565
+ ...err instanceof core.SessionHeldError ? { sessionHeld: err.held } : {},
1566
+ ...err instanceof core.UserGitError && err.detail.held ? { landingBranchHeld: err.detail.held } : {},
1567
+ ...err instanceof core.UserGitError && err.detail.difference ? { confirmStale: err.detail.difference } : {}
1568
+ };
1569
+ return c.json(body, status);
1570
+ }
1571
+
1572
+ // server/routes/liveSession.ts
1573
+ function callerWorkspace(c) {
1574
+ return c.req.query("workspace") || void 0;
1575
+ }
1576
+ function sameWorkspace2(pool, param) {
1577
+ return async (c, next) => {
1578
+ const workspace = callerWorkspace(c);
1579
+ if (workspace) {
1580
+ try {
1581
+ pool.live(c.req.param(param) ?? "", workspace);
1582
+ } catch (err) {
1583
+ return failure(c, err, "reach session");
1584
+ }
1585
+ }
1586
+ await next();
1587
+ };
1588
+ }
1589
+
1590
+ // server/routes/children.ts
1591
+ var ABOVE_THIS_PLAN = "A raise or a force is the plan above this one to give: this request sets neither.";
1592
+ var CONTROL_REFUSALS = {
1593
+ view_only: { status: 409, code: "child_view_only" },
1594
+ refused: { status: 409, code: "child_refused" },
1595
+ no_task: { status: 404, code: "child_task_not_found" },
1596
+ not_waiting: { status: 409, code: "checkpoint_not_waiting" }
1597
+ };
1598
+ function childrenRoute(pool) {
1599
+ const router = new hono.Hono();
1600
+ router.use("/:id/children", sameWorkspace2(pool, "id"));
1601
+ router.use("/:id/children/*", sameWorkspace2(pool, "id"));
1602
+ const childOf = async (c) => {
1603
+ const child = await pool.session(c.req.param("id"), callerWorkspace(c)).children.find(c.req.param("childId"));
1604
+ if (!child) throw new ChildNotFoundError();
1605
+ return child;
1606
+ };
1607
+ const position = (c) => pool.childPosition(c.req.param("id"), c.req.param("childId"), callerWorkspace(c));
1608
+ const controlled = (c, outcome) => {
1609
+ if (!outcome.ok) return refuse(c, CONTROL_REFUSALS[outcome.code].status, outcome.message, CONTROL_REFUSALS[outcome.code].code);
1610
+ return c.json({ message: outcome.message, ...outcome.id ? { id: outcome.id } : {} });
1611
+ };
1612
+ const asksAboveItsPlan = (body) => "raiseTokens" in body || "force" in body;
1613
+ router.get("/:id/children", async (c) => {
1614
+ try {
1615
+ return c.json({ children: await pool.session(c.req.param("id"), callerWorkspace(c)).children.list() });
1616
+ } catch (err) {
1617
+ return failure(c, err, "list child plans");
1618
+ }
1619
+ });
1620
+ router.get("/:id/children/:childId", async (c) => {
1621
+ try {
1622
+ const child = await childOf(c);
1623
+ return c.json({ ...child.view(), position: position(c) });
1624
+ } catch (err) {
1625
+ return failure(c, err, "read child plan");
1626
+ }
1627
+ });
1628
+ router.get("/:id/children/:childId/tasks/:taskId/log", async (c) => {
1629
+ try {
1630
+ const child = await childOf(c);
1631
+ return c.json({ attempts: core.listTaskLogAttempts(child.logLocation(), c.req.param("taskId")), position: position(c) });
1632
+ } catch (err) {
1633
+ return failure(c, err, "list child task log");
1634
+ }
1635
+ });
1636
+ router.get("/:id/children/:childId/tasks/:taskId/log/:attempt", async (c) => {
1637
+ try {
1638
+ const child = await childOf(c);
1639
+ const attempt = Number(c.req.param("attempt"));
1640
+ if (!Number.isInteger(attempt) || attempt < 1) return refuse(c, 400, "attempt must be a positive integer");
1641
+ return c.json({ attempt, events: core.taskLogForSurface(core.readTaskLog(child.logLocation(), c.req.param("taskId"), attempt)), position: position(c) });
1642
+ } catch (err) {
1643
+ return failure(c, err, "read child task log");
1644
+ }
1645
+ });
1646
+ router.post("/:id/children/:childId/message", async (c) => {
1647
+ try {
1648
+ const body = await jsonObject(c);
1649
+ const child = await childOf(c);
1650
+ if (asksAboveItsPlan(body)) return refuse(c, 400, ABOVE_THIS_PLAN, "refused");
1651
+ const { message } = body;
1652
+ if (typeof message !== "string" || !message.trim()) return refuse(c, 400, "message must be a non-empty string");
1653
+ const outcome = child.message(message);
1654
+ if (!outcome.ok) return refuse(c, 409, outcome.message, outcome.code === "view_only" ? "child_view_only" : "child_refused");
1655
+ return c.json({ status: outcome.status });
1656
+ } catch (err) {
1657
+ return failure(c, err, "message child plan");
1658
+ }
1659
+ });
1660
+ router.post("/:id/children/:childId/tasks/:taskId/message", async (c) => {
1661
+ try {
1662
+ const body = await jsonObject(c);
1663
+ const child = await childOf(c);
1664
+ if (asksAboveItsPlan(body)) return refuse(c, 400, ABOVE_THIS_PLAN, "refused");
1665
+ if (typeof body.message !== "string" || !body.message.trim()) return refuse(c, 400, "message must be a non-empty string", "refused");
1666
+ return controlled(c, await child.control(c.req.param("taskId"), { kind: "message", text: body.message }));
1667
+ } catch (err) {
1668
+ return failure(c, err, "message child task");
1669
+ }
1670
+ });
1671
+ for (const answer of ["approve", "reject"]) {
1672
+ router.post(`/:id/children/:childId/tasks/:taskId/checkpoint/${answer}`, async (c) => {
1673
+ try {
1674
+ const body = await jsonObject(c);
1675
+ const child = await childOf(c);
1676
+ if (asksAboveItsPlan(body)) return refuse(c, 400, ABOVE_THIS_PLAN, "refused");
1677
+ const { question } = body;
1678
+ if (typeof question !== "string" || !question.trim()) return refuse(c, 400, "question must be the words the task is waiting on", "refused");
1679
+ if (body.reason !== void 0 && typeof body.reason !== "string") return refuse(c, 400, "reason must be a string", "refused");
1680
+ const reason = body.reason?.trim();
1681
+ if (answer === "reject" && !reason) return refuse(c, 400, "A rejection needs a reason: it is all the runner has to go on.", "refused");
1682
+ return controlled(c, await child.control(c.req.param("taskId"), { kind: "checkpoint", answer, question, ...reason ? { reason } : {} }));
1683
+ } catch (err) {
1684
+ return failure(c, err, "answer child checkpoint");
1685
+ }
1686
+ });
1687
+ }
1688
+ return router;
1689
+ }
1557
1690
  function sessionsRoute(pool) {
1558
1691
  const router = new hono.Hono();
1559
1692
  router.get("/", (c) => {
1560
- const ws = c.req.query("workspace") || process.cwd();
1561
- const sessions = getSessionList(ws);
1562
- return c.json(sessions);
1693
+ try {
1694
+ const ws = c.req.query("workspace") || process.cwd();
1695
+ const sessions = getSessionList(ws).map((meta) => {
1696
+ const run2 = pool.runActivity(meta.id, ws);
1697
+ return run2 ? { ...meta, run: run2 } : meta;
1698
+ });
1699
+ return c.json(sessions);
1700
+ } catch (err) {
1701
+ return failure(c, err, "list sessions");
1702
+ }
1563
1703
  });
1564
1704
  router.get("/:id", (c) => {
1565
- const ws = c.req.query("workspace") || process.cwd();
1566
- const id = c.req.param("id");
1567
- const saved = core.loadSession(id, ws);
1568
- if (!saved) return refuse(c, 404, "Session not found", "session_not_found");
1569
- const run2 = pool.runSnapshot(id);
1570
- const plannerTurnId = pool.plannerTurnId(id);
1571
- const plannerCompaction = pool.plannerCompaction(id);
1572
- const { conversationHistory, researchLog, plannerUsage, pendingTurns } = core.surfacePlan(pool.getPlan(id) ?? saved.plan);
1573
- return c.json({
1574
- meta: saved.meta,
1575
- plan: core.surfacePlanState(pool.getPlanState(id) ?? core.migratePlanState(saved.plan)),
1576
- conversation: { conversationHistory, researchLog, plannerUsage, pendingTurns },
1577
- ...run2 ? { run: run2 } : {},
1578
- ...plannerTurnId ? { plannerTurnId } : {},
1579
- ...plannerCompaction ? { plannerCompaction } : {}
1580
- });
1705
+ try {
1706
+ const ws = c.req.query("workspace") || process.cwd();
1707
+ const id = c.req.param("id");
1708
+ const saved = core.loadSession(id, ws);
1709
+ if (!saved) return refuse(c, 404, "Session not found", "session_not_found");
1710
+ const live = pool.holds(id, ws);
1711
+ const run2 = live ? pool.runSnapshot(id) : null;
1712
+ const plannerTurnId = live ? pool.plannerTurnId(id) : void 0;
1713
+ const plannerCompaction = live ? pool.plannerCompaction(id) : void 0;
1714
+ const { conversationHistory, researchLog, plannerUsage, pendingTurns } = core.surfacePlan((live ? pool.getPlan(id) : null) ?? saved.plan);
1715
+ return c.json({
1716
+ meta: saved.meta,
1717
+ plan: core.surfacePlanState((live ? pool.getPlanState(id) : null) ?? core.migratePlanState(saved.plan)),
1718
+ conversation: { conversationHistory, researchLog, plannerUsage, pendingTurns },
1719
+ ...run2 ? { run: run2 } : {},
1720
+ ...plannerTurnId ? { plannerTurnId } : {},
1721
+ ...plannerCompaction ? { plannerCompaction } : {},
1722
+ // Taken in the same turn as the read, so a client drops exactly the held frames it already holds.
1723
+ ...live ? { position: pool.streamPosition(id) } : {}
1724
+ });
1725
+ } catch (err) {
1726
+ return failure(c, err, "read session");
1727
+ }
1581
1728
  });
1582
1729
  router.post("/:id/load", (c) => {
1583
1730
  const ws = c.req.query("workspace") || process.cwd();
@@ -1593,29 +1740,39 @@ function sessionsRoute(pool) {
1593
1740
  goal: pool.getGoal(id),
1594
1741
  ...run2 ? { run: run2 } : {},
1595
1742
  ...plannerTurnId ? { plannerTurnId } : {},
1596
- ...plannerCompaction ? { plannerCompaction } : {}
1743
+ ...plannerCompaction ? { plannerCompaction } : {},
1744
+ position: pool.streamPosition(id)
1597
1745
  });
1598
1746
  } catch (err) {
1599
1747
  return failure(c, err, "load session", { message: "Failed to load session" });
1600
1748
  }
1601
1749
  });
1750
+ const position = (id, ws) => pool.heldElsewhere(id, ws) ? {} : { position: pool.streamPosition(id) };
1602
1751
  router.get("/:id/tasks/:taskId/log", (c) => {
1603
- const ws = c.req.query("workspace") || process.cwd();
1604
- return c.json({ attempts: core.listTaskLogAttempts({ baseDir: ws, sessionId: c.req.param("id") }, c.req.param("taskId")), position: pool.streamPosition(c.req.param("id")) });
1752
+ try {
1753
+ const ws = c.req.query("workspace") || process.cwd();
1754
+ return c.json({ attempts: core.listTaskLogAttempts({ baseDir: ws, sessionId: c.req.param("id") }, c.req.param("taskId")), ...position(c.req.param("id"), ws) });
1755
+ } catch (err) {
1756
+ return failure(c, err, "list task log");
1757
+ }
1605
1758
  });
1606
1759
  router.get("/:id/tasks/:taskId/log/:attempt", (c) => {
1607
- const ws = c.req.query("workspace") || process.cwd();
1608
- const attempt = Number(c.req.param("attempt"));
1609
- if (!Number.isInteger(attempt) || attempt < 1) return refuse(c, 400, "attempt must be a positive integer");
1610
- return c.json({ attempt, events: core.taskLogForSurface(core.readTaskLog({ baseDir: ws, sessionId: c.req.param("id") }, c.req.param("taskId"), attempt)), position: pool.streamPosition(c.req.param("id")) });
1760
+ try {
1761
+ const ws = c.req.query("workspace") || process.cwd();
1762
+ const attempt = Number(c.req.param("attempt"));
1763
+ if (!Number.isInteger(attempt) || attempt < 1) return refuse(c, 400, "attempt must be a positive integer");
1764
+ return c.json({ attempt, events: core.taskLogForSurface(core.readTaskLog({ baseDir: ws, sessionId: c.req.param("id") }, c.req.param("taskId"), attempt)), ...position(c.req.param("id"), ws) });
1765
+ } catch (err) {
1766
+ return failure(c, err, "read task log");
1767
+ }
1611
1768
  });
1612
1769
  router.delete("/:id", async (c) => {
1613
1770
  const ws = c.req.query("workspace") || process.cwd();
1614
1771
  const id = c.req.param("id");
1615
- const held = pool.hasSession(id);
1772
+ const held = pool.holds(id, ws);
1616
1773
  let removed;
1617
1774
  try {
1618
- removed = await removeSession(id, ws, () => pool.stopTree(id), () => pool.close(id), () => pool.reclaim(id));
1775
+ removed = await removeSession(id, ws, () => pool.stopTree(id, ws), () => pool.close(id, ws), () => pool.reclaim(id, ws));
1619
1776
  } catch (err) {
1620
1777
  return c.json({ ok: false, message: err instanceof Error ? err.message : String(err) });
1621
1778
  }
@@ -1626,8 +1783,13 @@ function sessionsRoute(pool) {
1626
1783
  });
1627
1784
  });
1628
1785
  router.post("/:id/close", async (c) => {
1629
- await pool.close(c.req.param("id"));
1630
- return c.json({ ok: true });
1786
+ try {
1787
+ const id = c.req.param("id");
1788
+ await pool.close(id, c.req.query("workspace") || process.cwd());
1789
+ return c.json({ ok: true });
1790
+ } catch (err) {
1791
+ return failure(c, err, "close session");
1792
+ }
1631
1793
  });
1632
1794
  return router;
1633
1795
  }
@@ -1642,6 +1804,8 @@ async function runUserCommand(session, command) {
1642
1804
  }
1643
1805
  function plansRoute(pool) {
1644
1806
  const router = new hono.Hono();
1807
+ router.use("/:sessionId", sameWorkspace2(pool, "sessionId"));
1808
+ router.use("/:sessionId/*", sameWorkspace2(pool, "sessionId"));
1645
1809
  router.post("/:sessionId/generate", async (c) => {
1646
1810
  try {
1647
1811
  const { goal, runners, workspace, model, allowInit } = await jsonObject(c);
@@ -1651,7 +1815,7 @@ function plansRoute(pool) {
1651
1815
  const runnerList = Array.isArray(runners) ? runners : runners ? [runners] : queryRunners ? queryRunners.split(",").map((s) => s.trim()).filter(Boolean) : void 0;
1652
1816
  const plan = await pool.generatePlan(c.req.param("sessionId"), goal, runnerList, ws, model, { allowInit });
1653
1817
  const { models, modelsByRunner } = await pool.getProviderModels(ws);
1654
- const notes = (pool.session(c.req.param("sessionId")).planState?.conversationHistory ?? []).filter((e) => e.kind === "system").map((e) => e.content);
1818
+ const notes = (pool.session(c.req.param("sessionId"), ws).planState?.conversationHistory ?? []).filter((e) => e.kind === "system").map((e) => e.content);
1655
1819
  return c.json({ plan: core.surfacePlanState(plan), models, modelsByRunner, ...notes.length > 0 ? { notes } : {} });
1656
1820
  } catch (err) {
1657
1821
  return failure(c, err, "generate", { message: "Plan generation failed" });
@@ -1659,7 +1823,7 @@ function plansRoute(pool) {
1659
1823
  });
1660
1824
  router.post("/:sessionId/execute", async (c) => {
1661
1825
  try {
1662
- const session = pool.session(c.req.param("sessionId"));
1826
+ const session = pool.session(c.req.param("sessionId"), callerWorkspace(c));
1663
1827
  if (!session.planState || session.planTasks.length === 0) throw new core.NoPlanError("execute");
1664
1828
  const { message } = await runUserCommand(session, { command: "run_plan" });
1665
1829
  return c.json({ status: "running", message });
@@ -1669,8 +1833,8 @@ function plansRoute(pool) {
1669
1833
  });
1670
1834
  router.post("/:sessionId/stop", async (c) => {
1671
1835
  try {
1672
- if (pool.hasSession(c.req.param("sessionId"))) {
1673
- const session = pool.session(c.req.param("sessionId"));
1836
+ const session = pool.live(c.req.param("sessionId"), callerWorkspace(c));
1837
+ if (session) {
1674
1838
  const outcome = await session.execute({ command: "stop_run" }, { kind: "user" });
1675
1839
  if (!outcome.ok && (session.isExecuting || session.startsPending)) throw new core.TaskControlError(outcome.message);
1676
1840
  return c.json({ status: "stopped", message: outcome.message });
@@ -1681,14 +1845,18 @@ function plansRoute(pool) {
1681
1845
  }
1682
1846
  });
1683
1847
  router.post("/:sessionId/planning/stop", (c) => {
1684
- const cancelled = pool.cancelPlanning(c.req.param("sessionId"));
1685
- return c.json({ cancelled });
1848
+ try {
1849
+ const cancelled = pool.cancelPlanning(c.req.param("sessionId"), callerWorkspace(c));
1850
+ return c.json({ cancelled });
1851
+ } catch (err) {
1852
+ return failure(c, err, "stop planning");
1853
+ }
1686
1854
  });
1687
1855
  router.post("/:sessionId/execute-command", async (c) => {
1688
1856
  try {
1689
1857
  const parsed = core.parseExecutionCommand(await jsonObject(c));
1690
1858
  if (!parsed.ok) return refuse(c, 400, parsed.message, "refused");
1691
- const outcome = await pool.session(c.req.param("sessionId")).execute(parsed.command, { kind: "user" });
1859
+ const outcome = await pool.session(c.req.param("sessionId"), callerWorkspace(c)).execute(parsed.command, { kind: "user" });
1692
1860
  if (!outcome.ok) {
1693
1861
  return c.json({ error: outcome.message, code: "refused", ...outcome.payload ? { payload: outcome.payload } : {} }, 400);
1694
1862
  }
@@ -1699,7 +1867,7 @@ function plansRoute(pool) {
1699
1867
  });
1700
1868
  router.get("/:sessionId/escalations", (c) => {
1701
1869
  try {
1702
- return c.json({ escalations: pool.session(c.req.param("sessionId")).escalations() });
1870
+ return c.json({ escalations: pool.session(c.req.param("sessionId"), callerWorkspace(c)).escalations() });
1703
1871
  } catch (err) {
1704
1872
  return failure(c, err, "escalations");
1705
1873
  }
@@ -1708,7 +1876,7 @@ function plansRoute(pool) {
1708
1876
  try {
1709
1877
  const { id, option, note, confirmed } = await jsonObject(c);
1710
1878
  if (typeof id !== "string" || typeof option !== "string") return refuse(c, 400, "id and option are required", "refused");
1711
- const outcome = await pool.session(c.req.param("sessionId")).answerEscalation(id, option, typeof note === "string" ? note : void 0, confirmed === true);
1879
+ const outcome = await pool.session(c.req.param("sessionId"), callerWorkspace(c)).answerEscalation(id, option, typeof note === "string" ? note : void 0, confirmed === true);
1712
1880
  if (!outcome.ok) return c.json({ error: outcome.message, code: "refused", ...outcome.payload ? { payload: outcome.payload } : {} }, 400);
1713
1881
  return c.json({ ok: true, message: outcome.message, ...outcome.payload ? { payload: outcome.payload } : {} });
1714
1882
  } catch (err) {
@@ -1721,7 +1889,7 @@ function plansRoute(pool) {
1721
1889
  const fields = typeof body === "object" && body !== null ? body : {};
1722
1890
  if (typeof fields.name !== "string" || !fields.name.trim()) return c.json({ error: "name is required" }, 400);
1723
1891
  const args = typeof fields.args === "string" ? fields.args : "";
1724
- const id = pool.session(c.req.param("sessionId")).invokeTaskCommand(c.req.param("taskId"), fields.name.trim(), args);
1892
+ const id = pool.session(c.req.param("sessionId"), callerWorkspace(c)).invokeTaskCommand(c.req.param("taskId"), fields.name.trim(), args);
1725
1893
  return c.json({ id });
1726
1894
  } catch (err) {
1727
1895
  return failure(c, err, "task edit");
@@ -1735,7 +1903,7 @@ function plansRoute(pool) {
1735
1903
  const raiseTokens = typeof body === "object" && body !== null && "raiseTokens" in body ? body.raiseTokens : void 0;
1736
1904
  const raise = typeof raiseTokens === "number" && Number.isSafeInteger(raiseTokens) && raiseTokens > 0 ? raiseTokens : void 0;
1737
1905
  if (raiseTokens !== void 0 && raise === void 0) return refuse(c, 400, "A raise is a whole number of tokens, 1 or more.", "refused");
1738
- const session = pool.session(c.req.param("sessionId"));
1906
+ const session = pool.session(c.req.param("sessionId"), callerWorkspace(c));
1739
1907
  const taskId = idOfRef(session, c.req.param("taskId"));
1740
1908
  if (!session.awaitsCheckpoint(taskId)) return refuse(c, 409, NO_CHECKPOINT, "checkpoint_not_waiting");
1741
1909
  const { message } = await runUserCommand(session, { command: "answer_checkpoint", task: taskId, answer, ...reason ? { reason } : {}, ...raise !== void 0 ? { raiseTokens: raise } : {} });
@@ -1747,7 +1915,7 @@ function plansRoute(pool) {
1747
1915
  }
1748
1916
  router.get("/:sessionId/tasks/:taskId/merge-gate", (c) => {
1749
1917
  try {
1750
- const session = pool.session(c.req.param("sessionId"));
1918
+ const session = pool.session(c.req.param("sessionId"), callerWorkspace(c));
1751
1919
  const tasks = core.flattenTasks(session.planState?.tasks ?? []);
1752
1920
  const mergeGate = session.mergeGate(idOfRef(session, c.req.param("taskId"))).map((id) => {
1753
1921
  const dep = tasks.find((t) => t.id === id);
@@ -1760,7 +1928,7 @@ function plansRoute(pool) {
1760
1928
  });
1761
1929
  router.get("/:sessionId/tasks/:taskId/revert-preview", async (c) => {
1762
1930
  try {
1763
- const session = pool.session(c.req.param("sessionId"));
1931
+ const session = pool.session(c.req.param("sessionId"), callerWorkspace(c));
1764
1932
  return c.json(await session.revertPreview(idOfRef(session, c.req.param("taskId"))));
1765
1933
  } catch (err) {
1766
1934
  return failure(c, err, "task edit");
@@ -1768,7 +1936,7 @@ function plansRoute(pool) {
1768
1936
  });
1769
1937
  router.get("/:sessionId/isolation/diff", async (c) => {
1770
1938
  try {
1771
- return c.json({ diff: await pool.session(c.req.param("sessionId")).reviewRunDiff() });
1939
+ return c.json({ diff: await pool.session(c.req.param("sessionId"), callerWorkspace(c)).reviewRunDiff() });
1772
1940
  } catch (err) {
1773
1941
  return failure(c, err, "task edit");
1774
1942
  }
@@ -1776,11 +1944,17 @@ function plansRoute(pool) {
1776
1944
  router.post("/:sessionId/isolation/merge", async (c) => {
1777
1945
  try {
1778
1946
  const body = await c.req.json().catch(() => ({}));
1779
- const pastChecks = typeof body === "object" && body !== null && "pastChecks" in body && body.pastChecks === true;
1780
- const outcome = await pool.session(c.req.param("sessionId")).execute(pastChecks ? { command: "merge_all", pastChecks: true } : { command: "merge_all" }, { kind: "user" });
1947
+ const yes2 = (name) => typeof body === "object" && body !== null && Reflect.get(body, name) === true;
1948
+ const outcome = await pool.session(c.req.param("sessionId"), callerWorkspace(c)).execute({
1949
+ command: "merge_all",
1950
+ ...yes2("pastChecks") ? { pastChecks: true } : {},
1951
+ ...yes2("besideOps") ? { besideOps: true } : {}
1952
+ }, { kind: "user" });
1781
1953
  if (outcome.payload?.kind === "merge") return c.json(outcome.payload.result);
1782
1954
  if (outcome.payload?.kind === "merge_hold") return refuse(c, 409, outcome.message, "merge_past_check");
1955
+ if (outcome.payload?.kind === "merge_beside_ops") return refuse(c, 409, outcome.message, "merge_beside_ops");
1783
1956
  if (!outcome.ok) throw new core.TaskControlError(outcome.message);
1957
+ if (!outcome.payload) return c.json({ outcome: "nothing", message: outcome.message });
1784
1958
  throw new Error("Merge all answered without its result.");
1785
1959
  } catch (err) {
1786
1960
  return failure(c, err, "task edit");
@@ -1794,7 +1968,7 @@ function plansRoute(pool) {
1794
1968
  ]) {
1795
1969
  router.post(`/:sessionId/isolation/${segment}`, async (c) => {
1796
1970
  try {
1797
- await run2(pool.session(c.req.param("sessionId")));
1971
+ await run2(pool.session(c.req.param("sessionId"), callerWorkspace(c)));
1798
1972
  return c.json({ ok: true });
1799
1973
  } catch (err) {
1800
1974
  return failure(c, err, "task edit");
@@ -1803,7 +1977,7 @@ function plansRoute(pool) {
1803
1977
  }
1804
1978
  router.post("/:sessionId/tasks/:taskId/resolve-conflict", async (c) => {
1805
1979
  try {
1806
- const plan = await pool.session(c.req.param("sessionId")).resolveConflictAsTask(c.req.param("taskId"));
1980
+ const plan = await pool.session(c.req.param("sessionId"), callerWorkspace(c)).resolveConflictAsTask(c.req.param("taskId"));
1807
1981
  return c.json({ plan: plan && core.surfacePlan(plan) });
1808
1982
  } catch (err) {
1809
1983
  return failure(c, err, "task edit");
@@ -1813,7 +1987,18 @@ function plansRoute(pool) {
1813
1987
  try {
1814
1988
  const changes2 = await jsonObject(c);
1815
1989
  if (changes2.assignedModel === null) changes2.assignedModel = void 0;
1816
- const result = await pool.session(c.req.param("sessionId")).updateTask(c.req.param("taskId"), changes2);
1990
+ const result = await pool.session(c.req.param("sessionId"), callerWorkspace(c)).updateTask(c.req.param("taskId"), changes2);
1991
+ if (!result) return refuse(c, 404, "Task not found", "task_not_found");
1992
+ return c.json({ ok: true });
1993
+ } catch (err) {
1994
+ return failure(c, err, "task edit");
1995
+ }
1996
+ });
1997
+ router.post("/:sessionId/tasks/:taskId/card-edit", async (c) => {
1998
+ try {
1999
+ const edit = await jsonObject(c);
2000
+ if (!core.isCardEdit(edit)) return refuse(c, 400, "Unknown card edit");
2001
+ const result = await pool.session(c.req.param("sessionId"), callerWorkspace(c)).cardEdit(c.req.param("taskId"), edit);
1817
2002
  if (!result) return refuse(c, 404, "Task not found", "task_not_found");
1818
2003
  return c.json({ ok: true });
1819
2004
  } catch (err) {
@@ -1822,7 +2007,7 @@ function plansRoute(pool) {
1822
2007
  });
1823
2008
  router.delete("/:sessionId/tasks/:taskId", async (c) => {
1824
2009
  try {
1825
- const result = await pool.session(c.req.param("sessionId")).removeTask(c.req.param("taskId"));
2010
+ const result = await pool.session(c.req.param("sessionId"), callerWorkspace(c)).removeTask(c.req.param("taskId"));
1826
2011
  if (!result) return refuse(c, 404, "Task not found", "task_not_found");
1827
2012
  return c.json({ ok: true });
1828
2013
  } catch (err) {
@@ -1832,7 +2017,7 @@ function plansRoute(pool) {
1832
2017
  router.post("/:sessionId/tasks", async (c) => {
1833
2018
  try {
1834
2019
  const body = await jsonObject(c);
1835
- const result = await pool.session(c.req.param("sessionId")).addTask(body);
2020
+ const result = await pool.session(c.req.param("sessionId"), callerWorkspace(c)).addTask(body);
1836
2021
  if (!result) return refuse(c, 404, "Session not found", "session_not_found");
1837
2022
  return c.json({ ok: true });
1838
2023
  } catch (err) {
@@ -1841,7 +2026,7 @@ function plansRoute(pool) {
1841
2026
  });
1842
2027
  router.post("/:sessionId/review/approve", async (c) => {
1843
2028
  try {
1844
- const session = pool.session(c.req.param("sessionId"));
2029
+ const session = pool.session(c.req.param("sessionId"), callerWorkspace(c));
1845
2030
  const plan = session.planState;
1846
2031
  if (!plan) throw new core.NoPlanError("review");
1847
2032
  const { message } = await runUserCommand(session, { command: "approve_review" });
@@ -1852,11 +2037,11 @@ function plansRoute(pool) {
1852
2037
  });
1853
2038
  router.post("/:sessionId/converse/start", async (c) => {
1854
2039
  try {
1855
- const { goal, runners, workspace, model, allowInit } = await jsonObject(c);
2040
+ const { goal, runners, workspace, model, allowInit, surface } = await jsonObject(c);
1856
2041
  if (!goal) return c.json({ error: "goal is required" }, 400);
1857
2042
  const ws = workspace || c.req.query("workspace") || process.cwd();
1858
2043
  const runnerList = Array.isArray(runners) ? runners : runners ? [runners] : void 0;
1859
- const plan = await pool.startPlanning(c.req.param("sessionId"), goal, runnerList, ws, model, { allowInit });
2044
+ const plan = await pool.startPlanning(c.req.param("sessionId"), goal, runnerList, ws, model, { allowInit, surface: core.clientSurface(surface) });
1860
2045
  return c.json({ plan: core.surfacePlan(plan) });
1861
2046
  } catch (err) {
1862
2047
  return failure(c, err, "converse start", { message: "Planning failed" });
@@ -1864,9 +2049,9 @@ function plansRoute(pool) {
1864
2049
  });
1865
2050
  router.post("/:sessionId/converse/message", async (c) => {
1866
2051
  try {
1867
- const { message } = await jsonObject(c);
2052
+ const { message, surface } = await jsonObject(c);
1868
2053
  if (!message) return c.json({ error: "message is required" }, 400);
1869
- const plan = await pool.continuePlanning(c.req.param("sessionId"), message);
2054
+ const plan = await pool.continuePlanning(c.req.param("sessionId"), message, callerWorkspace(c), core.clientSurface(surface));
1870
2055
  return c.json({ plan: core.surfacePlan(plan) });
1871
2056
  } catch (err) {
1872
2057
  return failure(c, err, "conversation message");
@@ -1874,9 +2059,9 @@ function plansRoute(pool) {
1874
2059
  });
1875
2060
  router.post("/:sessionId/converse/message/now", async (c) => {
1876
2061
  try {
1877
- const { message } = await jsonObject(c);
2062
+ const { message, surface } = await jsonObject(c);
1878
2063
  if (!message) return c.json({ error: "message is required" }, 400);
1879
- const plan = await pool.forceSendPrompt(c.req.param("sessionId"), message);
2064
+ const plan = await pool.forceSendPrompt(c.req.param("sessionId"), message, callerWorkspace(c), core.clientSurface(surface));
1880
2065
  return c.json({ plan: core.surfacePlan(plan) });
1881
2066
  } catch (err) {
1882
2067
  return failure(c, err, "conversation message");
@@ -1884,7 +2069,7 @@ function plansRoute(pool) {
1884
2069
  });
1885
2070
  router.post("/:sessionId/converse/resend/cancel", (c) => {
1886
2071
  try {
1887
- const cancelled = pool.session(c.req.param("sessionId")).cancelPlannerResend();
2072
+ const cancelled = pool.session(c.req.param("sessionId"), callerWorkspace(c)).cancelPlannerResend();
1888
2073
  return c.json({ cancelled });
1889
2074
  } catch (err) {
1890
2075
  return failure(c, err, "cancel resend", { fallback: 404, message: "Not found" });
@@ -1892,7 +2077,7 @@ function plansRoute(pool) {
1892
2077
  });
1893
2078
  router.post("/:sessionId/conversation/fork", (c) => {
1894
2079
  try {
1895
- const fork = pool.forkConversation(c.req.param("sessionId"));
2080
+ const fork = pool.forkConversation(c.req.param("sessionId"), callerWorkspace(c));
1896
2081
  return c.json({ ...fork, plan: core.surfacePlan(fork.plan) });
1897
2082
  } catch (err) {
1898
2083
  return failure(c, err, "conversation edit");
@@ -1900,7 +2085,7 @@ function plansRoute(pool) {
1900
2085
  });
1901
2086
  router.get("/:sessionId/conversation/rewind-targets", (c) => {
1902
2087
  try {
1903
- return c.json({ targets: pool.session(c.req.param("sessionId")).rewindTargets() });
2088
+ return c.json({ targets: pool.session(c.req.param("sessionId"), callerWorkspace(c)).rewindTargets() });
1904
2089
  } catch (err) {
1905
2090
  return failure(c, err, "conversation edit");
1906
2091
  }
@@ -1909,7 +2094,7 @@ function plansRoute(pool) {
1909
2094
  try {
1910
2095
  const { index } = await jsonObject(c);
1911
2096
  if (typeof index !== "number" || !Number.isInteger(index) || index < 0) return c.json({ error: "index must be a non-negative integer" }, 400);
1912
- const rewound = pool.rewindConversation(c.req.param("sessionId"), index);
2097
+ const rewound = pool.rewindConversation(c.req.param("sessionId"), index, callerWorkspace(c));
1913
2098
  return c.json({ ...rewound, plan: core.surfacePlan(rewound.plan) });
1914
2099
  } catch (err) {
1915
2100
  return failure(c, err, "conversation edit");
@@ -1917,7 +2102,7 @@ function plansRoute(pool) {
1917
2102
  });
1918
2103
  router.post("/:sessionId/conversation/compact", async (c) => {
1919
2104
  try {
1920
- const compacted = await pool.compactConversation(c.req.param("sessionId"));
2105
+ const compacted = await pool.compactConversation(c.req.param("sessionId"), callerWorkspace(c));
1921
2106
  return c.json({ ...compacted, plan: core.surfacePlan(compacted.plan) });
1922
2107
  } catch (err) {
1923
2108
  return failure(c, err, "conversation edit");
@@ -1925,30 +2110,38 @@ function plansRoute(pool) {
1925
2110
  });
1926
2111
  router.post("/:sessionId/conversation/compact/retry", async (c) => {
1927
2112
  try {
1928
- const plan = await pool.retryPlannerCompaction(c.req.param("sessionId"));
2113
+ const plan = await pool.retryPlannerCompaction(c.req.param("sessionId"), callerWorkspace(c));
1929
2114
  return c.json({ plan: core.surfacePlan(plan) });
1930
2115
  } catch (err) {
1931
2116
  return failure(c, err, "retry compaction");
1932
2117
  }
1933
2118
  });
1934
2119
  router.get("/:sessionId/prd", (c) => {
1935
- const plan = pool.getPlan(c.req.param("sessionId"));
1936
- if (!plan?.prdMarkdown) return refuse(c, 404, "No PRD found");
1937
- return c.json({ prdMarkdown: plan.prdMarkdown });
2120
+ try {
2121
+ const plan = pool.live(c.req.param("sessionId"), callerWorkspace(c))?.planState;
2122
+ if (!plan?.prdMarkdown) return refuse(c, 404, "No PRD found");
2123
+ return c.json({ prdMarkdown: plan.prdMarkdown });
2124
+ } catch (err) {
2125
+ return failure(c, err, "prd");
2126
+ }
1938
2127
  });
1939
2128
  return router;
1940
2129
  }
1941
2130
  function runnersRoute(pool) {
1942
2131
  const router = new hono.Hono();
1943
2132
  router.get("/", async (c) => {
1944
- const workspace = c.req.query("workspace");
1945
- const runners = await pool.getInstalledRunners(workspace);
1946
- await pool.discoverPlannerCatalogs(void 0, workspace);
1947
- const state = pool.getRunnerState(workspace);
1948
- return c.json({
1949
- runners,
1950
- orchestratorModel: state.orchestratorModel
1951
- });
2133
+ try {
2134
+ const workspace = c.req.query("workspace");
2135
+ const runners = await pool.getInstalledRunners(workspace);
2136
+ await pool.discoverPlannerCatalogs(void 0, workspace);
2137
+ const state = pool.getRunnerState(workspace);
2138
+ return c.json({
2139
+ runners,
2140
+ orchestratorModel: state.orchestratorModel
2141
+ });
2142
+ } catch (err) {
2143
+ return failure(c, err, "list runners");
2144
+ }
1952
2145
  });
1953
2146
  router.put("/:id", async (c) => {
1954
2147
  try {
@@ -1967,8 +2160,12 @@ function runnersRoute(pool) {
1967
2160
  function modelsRoute(pool) {
1968
2161
  const router = new hono.Hono();
1969
2162
  router.get("/", async (c) => {
1970
- const result = await pool.getProviderModels(c.req.query("workspace"));
1971
- return c.json(result);
2163
+ try {
2164
+ const result = await pool.getProviderModels(c.req.query("workspace"));
2165
+ return c.json(result);
2166
+ } catch (err) {
2167
+ return failure(c, err, "list models");
2168
+ }
1972
2169
  });
1973
2170
  return router;
1974
2171
  }
@@ -1985,8 +2182,12 @@ function workspacesRoute(pool) {
1985
2182
  }
1986
2183
  });
1987
2184
  router.get("/", (c) => {
1988
- const workspaces = scanWorkspaces2();
1989
- return c.json({ workspaces });
2185
+ try {
2186
+ const workspaces = scanWorkspaces2();
2187
+ return c.json({ workspaces });
2188
+ } catch (err) {
2189
+ return failure(c, err, "list workspaces");
2190
+ }
1990
2191
  });
1991
2192
  return router;
1992
2193
  }
@@ -2000,13 +2201,16 @@ function answerOf(body) {
2000
2201
  }
2001
2202
  function approvalsRoute(pool) {
2002
2203
  const router = new hono.Hono();
2204
+ router.use("/:sessionId", sameWorkspace2(pool, "sessionId"));
2205
+ router.use("/:sessionId/*", sameWorkspace2(pool, "sessionId"));
2003
2206
  router.get("/:sessionId", (c) => {
2004
2207
  const sessionId = c.req.param("sessionId");
2005
- if (!pool.hasSession(sessionId)) return refuse(c, 404, `Unknown session: ${sessionId}`, "session_not_found");
2006
- return c.json({
2007
- pending: pool.outstandingApprovals(sessionId),
2008
- approvedScopes: pool.approvedScopes(sessionId)
2009
- });
2208
+ try {
2209
+ const session = pool.session(sessionId, callerWorkspace(c));
2210
+ return c.json({ pending: session.outstandingApprovals(), approvedScopes: session.approvedScopes() });
2211
+ } catch (err) {
2212
+ return failure(c, err, "read approvals");
2213
+ }
2010
2214
  });
2011
2215
  router.post("/:sessionId/:approvalId", async (c) => {
2012
2216
  const sessionId = c.req.param("sessionId");
@@ -2014,15 +2218,20 @@ function approvalsRoute(pool) {
2014
2218
  if (!pool.hasSession(sessionId)) return refuse(c, 404, `Unknown session: ${sessionId}`, "session_not_found");
2015
2219
  const answer = answerOf(await c.req.json().catch(() => null));
2016
2220
  const decided = core.toApprovalDecision(answer);
2017
- const request = pool.outstandingApprovals(sessionId).find((pending) => pending.id === approvalId)?.request;
2018
- if (request?.taskId) {
2019
- const outcome = await pool.session(sessionId).execute(
2020
- { command: "answer_approval", task: request.taskId, approval: approvalId, answer: decided.decision, ...decided.decision === "deny" && decided.note ? { note: decided.note } : {} },
2021
- { kind: "user" }
2022
- );
2023
- if (!outcome.ok) return refuse(c, 400, outcome.message, "refused");
2024
- } else if (!pool.resolveApproval(sessionId, approvalId, answer)) {
2025
- return refuse(c, 409, "Approval is no longer outstanding: it timed out or was already answered.", "approval_not_outstanding");
2221
+ try {
2222
+ const session = pool.session(sessionId, callerWorkspace(c));
2223
+ const request = session.outstandingApprovals().find((pending) => pending.id === approvalId)?.request;
2224
+ if (request?.taskId) {
2225
+ const outcome = await session.execute(
2226
+ { command: "answer_approval", task: request.taskId, approval: approvalId, answer: decided.decision, ...decided.decision === "deny" && decided.note ? { note: decided.note } : {} },
2227
+ { kind: "user" }
2228
+ );
2229
+ if (!outcome.ok) return refuse(c, 400, outcome.message, "refused");
2230
+ } else if (!session.resolveApproval(approvalId, answer)) {
2231
+ return refuse(c, 409, "Approval is no longer outstanding: it timed out or was already answered.", "approval_not_outstanding");
2232
+ }
2233
+ } catch (err) {
2234
+ return failure(c, err, "answer approval");
2026
2235
  }
2027
2236
  return c.json({ ok: true, granted: core.isGranted(decided), decision: decided.decision });
2028
2237
  });
@@ -2062,12 +2271,16 @@ function settingsRoute(pool) {
2062
2271
  }
2063
2272
  });
2064
2273
  router.get("/", async (c) => {
2065
- await core.installedPlannerDetected();
2066
- const sessionId = c.req.query("sessionId") || void 0;
2067
- const workspace = c.req.query("workspace") || void 0;
2068
- await pool.discoverPlannerCatalogs(sessionId, workspace);
2069
- const settings = pool.getSettings(sessionId, workspace);
2070
- return c.json(settings);
2274
+ try {
2275
+ await core.installedPlannerDetected();
2276
+ const sessionId = c.req.query("sessionId") || void 0;
2277
+ const workspace = c.req.query("workspace") || void 0;
2278
+ await pool.discoverPlannerCatalogs(sessionId, workspace);
2279
+ const settings = pool.getSettings(sessionId, workspace);
2280
+ return c.json(settings);
2281
+ } catch (err) {
2282
+ return failure(c, err, "read settings");
2283
+ }
2071
2284
  });
2072
2285
  router.patch("/", async (c) => {
2073
2286
  try {
@@ -2098,18 +2311,6 @@ function settingsRoute(pool) {
2098
2311
  });
2099
2312
  return router;
2100
2313
  }
2101
- var COMMANDS = [];
2102
- function commandsRoute() {
2103
- const router = new hono.Hono();
2104
- router.get("/", (c) => {
2105
- return c.json({ commands: COMMANDS });
2106
- });
2107
- router.post("/:name", (c) => {
2108
- const name = c.req.param("name");
2109
- return refuse(c, 404, `Unknown command: ${name}`);
2110
- });
2111
- return router;
2112
- }
2113
2314
  var SCOPES = ["checkout", "integration", "task"];
2114
2315
  function workspaceOf(c) {
2115
2316
  const workspace = c.req.query("workspace") || process.cwd();
@@ -2320,12 +2521,19 @@ function mergePreflightRoute(reader) {
2320
2521
  return router;
2321
2522
  }
2322
2523
  var CHILD_PATH = /^\/ws\/session\/([^/]+)\/child\/([^/]+)$/;
2323
- function joinChild(pool, ws, rootId, childId) {
2524
+ function idOf(segment) {
2525
+ try {
2526
+ return decodeURIComponent(segment);
2527
+ } catch {
2528
+ return void 0;
2529
+ }
2530
+ }
2531
+ function joinChild(pool, ws, rootId, childId, workspace) {
2324
2532
  const leave = () => pool.unwatchChild(rootId, childId, ws);
2325
2533
  ws.on("close", leave);
2326
2534
  ws.on("error", leave);
2327
2535
  const refuse3 = () => ws.close(4404, "No such child plan in this tree");
2328
- void pool.watchChild(rootId, childId, ws).then((watching) => {
2536
+ void pool.watchChild(rootId, childId, ws, workspace).then((watching) => {
2329
2537
  if (!watching) refuse3();
2330
2538
  }, refuse3);
2331
2539
  }
@@ -2339,12 +2547,30 @@ function createWsHandler(pool) {
2339
2547
  });
2340
2548
  wss.on("connection", (ws, request) => {
2341
2549
  const url = new URL(request.url ?? "", `http://${request.headers.host}`);
2550
+ const malformed = () => ws.close(4400, "Malformed id in the socket path");
2551
+ const workspace = url.searchParams.get("workspace") || void 0;
2552
+ const elsewhere = (id) => {
2553
+ if (workspace === void 0) return false;
2554
+ try {
2555
+ pool.live(id, workspace);
2556
+ return false;
2557
+ } catch {
2558
+ ws.close(4409, "Session open for another workspace");
2559
+ return true;
2560
+ }
2561
+ };
2342
2562
  const child = CHILD_PATH.exec(url.pathname);
2343
2563
  if (child) {
2344
- joinChild(pool, ws, child[1], child[2]);
2564
+ const rootId = idOf(child[1]);
2565
+ const childId = idOf(child[2]);
2566
+ if (rootId === void 0 || childId === void 0) return malformed();
2567
+ if (elsewhere(rootId)) return;
2568
+ joinChild(pool, ws, rootId, childId, workspace);
2345
2569
  return;
2346
2570
  }
2347
- const sessionId = url.pathname.split("/").pop() || "";
2571
+ const sessionId = idOf(url.pathname.split("/").pop() || "");
2572
+ if (sessionId === void 0) return malformed();
2573
+ if (elsewhere(sessionId)) return;
2348
2574
  ws.on("close", () => {
2349
2575
  pool.unsubscribe(sessionId, ws);
2350
2576
  });
@@ -2366,7 +2592,7 @@ function createWsHandler(pool) {
2366
2592
  if (compaction) ws.send(JSON.stringify(compaction));
2367
2593
  const detection = pool.plannerDetection(sessionId);
2368
2594
  if (detection?.waiting) ws.send(JSON.stringify(detection));
2369
- pool.subscribe(sessionId, ws);
2595
+ pool.subscribe(sessionId, ws, workspace);
2370
2596
  });
2371
2597
  return (request, socket, head) => {
2372
2598
  wss.handleUpgrade(request, socket, head, (ws) => {
@@ -2487,13 +2713,12 @@ function createApp(pool, admission, reader = core.createWorkspaceReader({ config
2487
2713
  }));
2488
2714
  app.route("/api/sessions", sessionsRoute(pool));
2489
2715
  app.route("/api/sessions", childrenRoute(pool));
2490
- app.route("/api/plans", plansRoute(pool));
2491
2716
  app.route("/api/plans", taskDiffRoute(reader));
2492
2717
  app.route("/api/plans", mergePreflightRoute(reader));
2718
+ app.route("/api/plans", plansRoute(pool));
2493
2719
  app.route("/api/runners", runnersRoute(pool));
2494
2720
  app.route("/api/models", modelsRoute(pool));
2495
2721
  app.route("/api/settings", settingsRoute(pool));
2496
- app.route("/api/commands", commandsRoute());
2497
2722
  app.route("/api/workspaces", workspacesRoute(pool));
2498
2723
  app.route("/api/approvals", approvalsRoute(pool));
2499
2724
  app.route("/api/files", filesRoute(reader));
@@ -2643,6 +2868,16 @@ function createRequestListener(app, admission, maxBodyBytes = MAX_BODY_BYTES) {
2643
2868
  }
2644
2869
  };
2645
2870
  }
2871
+ function daemonHostKind(args, port) {
2872
+ const watchParentIdx = args.indexOf("--watch-parent");
2873
+ const ownerPid = watchParentIdx !== -1 ? parseInt(args[watchParentIdx + 1], 10) : void 0;
2874
+ return {
2875
+ kind: "daemon",
2876
+ port,
2877
+ ...ownerPid ? { ownerPid } : {},
2878
+ ...args.includes("--desktop-app") ? { app: "desktop" } : {}
2879
+ };
2880
+ }
2646
2881
  function runDaemon(args) {
2647
2882
  let port = 3742;
2648
2883
  const portIdx = args.indexOf("--port");
@@ -2654,7 +2889,7 @@ function runDaemon(args) {
2654
2889
  const pidFileIdx = args.indexOf("--pid-file");
2655
2890
  const pidFile = pidFileIdx !== -1 ? args[pidFileIdx + 1] : void 0;
2656
2891
  let ownsPidFile = false;
2657
- core.processLeaseHost().describe({ kind: "daemon", port, ...watchParentPid ? { ownerPid: watchParentPid } : {} });
2892
+ core.processLeaseHost().describe(daemonHostKind(args, port));
2658
2893
  const pool = new OrchestratorPool({ runner: new core.StructuredRunner() });
2659
2894
  void pool.detectInstalledPlanner();
2660
2895
  const server = http.createServer();
@@ -2672,9 +2907,11 @@ function runDaemon(args) {
2672
2907
  app.get("/", (c) => c.json({ message: "Ordewell API", docs: "/api/workspaces" }));
2673
2908
  server.on("request", createRequestListener(app, admission));
2674
2909
  attachWsHandler(server, pool, admission);
2675
- pool.getProviderModels().catch((err) => {
2676
- console.error(`[web] model discovery warmup failed: ${err?.message ?? err}`);
2677
- });
2910
+ if (!args.includes("--desktop-app")) {
2911
+ pool.getProviderModels().catch((err) => {
2912
+ console.error(`[web] model discovery warmup failed: ${err?.message ?? err}`);
2913
+ });
2914
+ }
2678
2915
  console.error(`[web] Ordewell API server: http://localhost:${port}`);
2679
2916
  });
2680
2917
  function shutdown() {