easel-canvas 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,560 @@
1
+ // AI-generated with Claude Code, 2026-11-29, reviewed by Hyun Park
2
+ // AI requests that go to the agent the person is already talking to (host mode). A request is a comment marked For AI: the comment
3
+ // gains forAgent (true for any agent, or one agent's label) and request { state, by, client, takenAt, doneAt, attach, … }. The states:
4
+ // waiting → taken → done | failed; a waiting request can be cancelled (it stays as an ordinary comment) or sent to Easel's own chat,
5
+ // a failed one can go back to waiting, a taken one cannot be cancelled (undo afterwards through the board's activity tag). Agents
6
+ // connect with a hello (bin/mcp.mjs), list requests with the same context block Easel's chat builds, take one (atomic: every comment
7
+ // write runs in store.exclusive) and finish it. Also: where AI requests go for this project (.easel/requests.json) and
8
+ // resolve_pick (a picked element from the host's own element picker → file, path, outerHTML).
9
+ import fs from "node:fs/promises";
10
+ import path from "node:path";
11
+
12
+ import { cleanAgent } from "./agents.mjs";
13
+ import { buildPrompt } from "./chat.mjs";
14
+ import { boardFile, routeWrite } from "./forks.mjs";
15
+ import { easelDir, rootOf, toPosix, writeAtomic } from "./fsutil.mjs";
16
+ import { elementChildren, findBody, hashText, inspect, parseHtml, rangeOf, textOf } from "./html.mjs";
17
+ import { requestScope } from "./history.mjs";
18
+ import { readBody, safeJoin, sendJson } from "./index.mjs";
19
+ import { real, within } from "./registry.mjs";
20
+
21
+ /** An agent that has not said hello again for this long is no longer listed (bin/mcp.mjs says hello every minute) */
22
+ export const AGENT_STALE_MS = 3 * 60 * 1000;
23
+ /** A waiting request nobody has looked at for this long shows "No agent has looked yet" */
24
+ export const NOBODY_MS = 10 * 60 * 1000;
25
+
26
+ const OUTER_LIMIT = 4096;
27
+ /** How an agent changes a board for a request: the same sentence in take_request, the context block, SKILL.md and /easel:requests */
28
+ export const WRITE_RULE = "Change boards only through write_board (read_board first, then send the whole HTML); do not use file-editing tools. If you cannot do it, call finish_request with status failed and the reason.";
29
+ const newId = (p) => `${p}${Date.now().toString(36)}${Math.random().toString(36).slice(2, 5)}`;
30
+
31
+ /* ---------- The request state machine (pure: each returns the changed comment or throws { status, message }) ---------- */
32
+
33
+ const fail = (status, message) => Object.assign(new Error(message), { status });
34
+ const clone = (c) => JSON.parse(JSON.stringify(c));
35
+ const isRequest = (c) => !!c?.forAgent && !!c.request;
36
+ /** forAgent as stored: true (any agent) or one agent's label */
37
+ export const addressee = (to) => (typeof to === "string" && to.trim() && to.trim().toLowerCase() !== "any" ? cleanAgent(to) : true);
38
+ /** Whether agent `by` may take a request addressed to forAgent */
39
+ export const meantFor = (forAgent, by) => forAgent === true || String(forAgent).toLowerCase() === String(by ?? "").toLowerCase();
40
+
41
+ /** Marks a comment For AI: a new waiting request (attach: what it points at, for the agent and the canvas) */
42
+ export function markRequest(c, { to, attach, now = Date.now() } = {}) {
43
+ if (c.resolved) throw fail(409, "That comment is resolved; reopen it first");
44
+ if (isRequest(c) && ["waiting", "taken"].includes(c.request.state)) throw fail(409, `That comment is already a request (${c.request.state})`);
45
+ const n = clone(c);
46
+ n.forAgent = addressee(to);
47
+ n.request = { state: "waiting", at: new Date(now).toISOString(), ...(attach && Object.keys(attach).length ? { attach } : {}) };
48
+ return n;
49
+ }
50
+
51
+ /** Cancel while waiting: the comment stays, as an ordinary comment */
52
+ export function cancelRequest(c) {
53
+ if (!isRequest(c)) throw fail(409, "That comment is not a request");
54
+ if (c.request.state === "taken") throw fail(409, `${c.request.by ?? "An agent"} has taken it; it cannot be cancelled now. Undo the change when it is done.`);
55
+ const n = clone(c);
56
+ delete n.forAgent;
57
+ delete n.request;
58
+ return n;
59
+ }
60
+
61
+ /** An agent takes a waiting request: one agent only, and only one meant for it */
62
+ export function takeRequest(c, { by, client, now = Date.now() }) {
63
+ if (!isRequest(c)) throw fail(404, "That comment is not a request");
64
+ const r = c.request;
65
+ if (r.state === "taken") throw fail(409, r.client && r.client === client ? "You have already taken this request" : `Already taken by ${r.by ?? "another agent"}`);
66
+ if (r.state === "done") throw fail(409, `Already done by ${r.by ?? "another agent"}`);
67
+ if (r.state === "failed") throw fail(409, "This request failed; the person has to send it again");
68
+ if (!meantFor(c.forAgent, by)) throw fail(403, `This request is for ${c.forAgent}, not ${by}; skip it`);
69
+ const n = clone(c);
70
+ n.request = { ...r, state: "taken", by, client, takenAt: new Date(now).toISOString() };
71
+ delete n.request.left;
72
+ return n;
73
+ }
74
+
75
+ /** The agent that took a request finishes it: done (its reply becomes a reply and the comment is resolved) or failed (the reason shows) */
76
+ export function finishRequest(c, { by, client, status, reply, changed = [], steps = [], now = Date.now() }) {
77
+ if (!isRequest(c)) throw fail(404, "That comment is not a request");
78
+ const r = c.request;
79
+ if (r.state !== "taken") throw fail(409, r.state === "waiting" ? "Take the request with take_request first" : `This request is already ${r.state}`);
80
+ if (r.client && client && r.client !== client && r.by !== by) throw fail(409, `Taken by ${r.by ?? "another agent"}, not you`);
81
+ if (status !== "done" && status !== "failed") throw fail(400, "status is done or failed");
82
+ const text = String(reply ?? "").trim();
83
+ if (status === "failed" && !text) throw fail(400, "Say why it failed in reply");
84
+ const n = clone(c);
85
+ const at = new Date(now).toISOString();
86
+ n.request = { ...r, state: status, doneAt: at, ...(status === "failed" ? { reason: text.slice(0, 500) } : {}), ...(changed.length ? { changed } : {}), ...(steps.length ? { steps } : {}) };
87
+ if (status === "done") {
88
+ if (text) {
89
+ // The agent's one line is a reply, and the request points at it so the finished comment can say it next to what changed
90
+ const rep = { id: newId("r"), author: by ?? r.by ?? "AI", text, createdAt: at };
91
+ n.replies = [...(n.replies ?? []), rep];
92
+ n.request.replyId = rep.id;
93
+ }
94
+ n.resolved = true;
95
+ }
96
+ return n;
97
+ }
98
+
99
+ /** Retry after a failure: waiting again */
100
+ export function retryRequest(c) {
101
+ if (!isRequest(c) || c.request.state !== "failed") throw fail(409, "Only a failed request can be sent again");
102
+ const n = clone(c);
103
+ const { attach, at } = n.request;
104
+ n.request = { state: "waiting", at: at ?? new Date().toISOString(), ...(attach ? { attach } : {}) };
105
+ return n;
106
+ }
107
+
108
+ /** The agent that took it left before finishing: waiting again, saying who left */
109
+ export function leftRequest(c) {
110
+ if (!isRequest(c) || c.request.state !== "taken") return c;
111
+ const n = clone(c);
112
+ const { attach, at, by } = n.request;
113
+ n.request = { state: "waiting", at, ...(attach ? { attach } : {}), left: by ?? "An agent" };
114
+ return n;
115
+ }
116
+
117
+ /** "No agent has looked yet": still waiting, and no agent connected, or none has listed it for NOBODY_MS */
118
+ export function nobodyTook(c, { now = Date.now(), connected = 0, nobodyMs = NOBODY_MS } = {}) {
119
+ if (!isRequest(c) || c.request.state !== "waiting") return false;
120
+ if (!connected) return true;
121
+ if (c.request.seenAt) return false;
122
+ return now - Date.parse(c.request.at ?? 0) > nobodyMs;
123
+ }
124
+
125
+ /**
126
+ * Whether a done request's own undo steps can still be undone: ready (all applied), undone (taken back by Undo the change, a tag's
127
+ * Undo or a plain undo), gone (not in this server's history: it restarted, or the history was cleared). Worked out from the history
128
+ * each time the comments are read, never stored
129
+ */
130
+ export function undoState(history, ids) {
131
+ if (!ids?.length) return null;
132
+ const { undo, redo } = history.entries();
133
+ const undid = new Set(undo.flatMap((s) => s.undid ?? []));
134
+ const redone = new Set(redo.map((s) => s.id));
135
+ if (ids.every((id) => undid.has(id) || redone.has(id))) return "undone";
136
+ const applied = new Set(undo.map((s) => s.id));
137
+ return ids.every((id) => applied.has(id)) ? "ready" : "gone";
138
+ }
139
+
140
+ /** What a view-only export keeps of a comment: an ordinary comment, without request status or controls */
141
+ export function plainComment(c) {
142
+ if (!c || (!("forAgent" in c) && !("request" in c))) return c;
143
+ const { forAgent, request, ...rest } = c;
144
+ return rest;
145
+ }
146
+
147
+ /* ---------- Connected agents (in memory) ---------- */
148
+
149
+ export function createAgentList({ staleMs = AGENT_STALE_MS, onChange = () => {} } = {}) {
150
+ const list = new Map(); // client → { client, label, cwd, here, at, seen }
151
+ const fresh = () => [...list.values()].filter((a) => Date.now() - a.seen < staleMs);
152
+ return {
153
+ hello(a) {
154
+ const cur = list.get(a.client);
155
+ list.set(a.client, { ...cur, ...a, at: cur?.at ?? Date.now(), seen: Date.now() });
156
+ if (!cur) onChange();
157
+ },
158
+ seen(client) {
159
+ const a = client && list.get(client);
160
+ if (a) a.seen = Date.now();
161
+ },
162
+ bye(client) {
163
+ if (list.delete(client)) onChange();
164
+ },
165
+ list: () => fresh().map(({ client, label, here, at }) => ({ client, label, here, at })),
166
+ labelOf: (client) => list.get(client)?.label ?? null,
167
+ };
168
+ }
169
+
170
+ /* ---------- Settings: where AI requests go, per project (.easel/requests.json, never committed) ---------- */
171
+
172
+ export const DEFAULT_SETTINGS = { mode: "chat", to: "any", intro: false };
173
+ async function readSettings(dir) {
174
+ try {
175
+ const d = JSON.parse(await fs.readFile(path.join(dir, ".easel", "requests.json"), "utf8"));
176
+ return { mode: d.mode === "host" ? "host" : "chat", to: typeof d.to === "string" && d.to ? cleanAgent(d.to) : "any", intro: !!d.intro };
177
+ } catch {
178
+ return { ...DEFAULT_SETTINGS };
179
+ }
180
+ }
181
+ async function writeSettings(dir, s) {
182
+ await writeAtomic(path.join(await easelDir(dir), "requests.json"), JSON.stringify(s, null, 1) + "\n");
183
+ }
184
+
185
+ /* ---------- resolve_pick: a picked element → file, path, outerHTML ---------- */
186
+
187
+ /** Every element of a document with its path ("0/5"), depth-first */
188
+ function* walk(node, prefix = "") {
189
+ const kids = elementChildren(node);
190
+ for (let i = 0; i < kids.length; i++) {
191
+ const p = prefix ? `${prefix}/${i}` : String(i);
192
+ yield { node: kids[i], path: p };
193
+ yield* walk(kids[i], p);
194
+ }
195
+ }
196
+ const squash = (s) => String(s ?? "").replace(/\s+/g, " ").replace(/>\s+</g, "><").trim();
197
+ const attr = (n, name) => n.attrs?.find((a) => a.name === name)?.value;
198
+
199
+ /** One compound selector (tag, #id, .class, [attr], [attr=value]) against a parse5 element */
200
+ function matchCompound(n, sel) {
201
+ const re = /([a-zA-Z][\w-]*)|#([\w-]+)|\.([\w-]+)|\[([\w-]+)(?:([~^$*|]?=)["']?([^"'\]]*)["']?)?\]/g;
202
+ let m;
203
+ let used = 0;
204
+ while ((m = re.exec(sel))) {
205
+ used += m[0].length;
206
+ if (m[1] && n.tagName !== m[1].toLowerCase()) return false;
207
+ if (m[2] && attr(n, "id") !== m[2]) return false;
208
+ if (m[3] && !(attr(n, "class") ?? "").split(/\s+/).includes(m[3])) return false;
209
+ if (m[4]) {
210
+ const v = attr(n, m[4]);
211
+ if (v == null) return false;
212
+ if (m[5] === "=" && v !== m[6]) return false;
213
+ if (m[5] === "*=" && !v.includes(m[6])) return false;
214
+ if (m[5] === "^=" && !v.startsWith(m[6])) return false;
215
+ if (m[5] === "$=" && !v.endsWith(m[6])) return false;
216
+ }
217
+ }
218
+ return used === sel.replace(/:[\w-]+(\([^)]*\))?/g, "").length;
219
+ }
220
+ /** A selector made of compound parts with descendant or child combinators ("main .card > button.primary") */
221
+ export function matchSelector(n, selector) {
222
+ const parts = String(selector).trim().replace(/\s*>\s*/g, " > ").split(/\s+/).filter(Boolean);
223
+ const test = (node, i) => {
224
+ if (!node || !node.tagName || !matchCompound(node, parts[i])) return false;
225
+ if (i === 0) return true;
226
+ if (parts[i - 1] === ">") return test(node.parentNode, i - 2);
227
+ for (let p = node.parentNode; p && p.tagName; p = p.parentNode) if (test(p, i - 1)) return true;
228
+ return false;
229
+ };
230
+ return parts.length > 0 && test(n, parts.length - 1);
231
+ }
232
+
233
+ /** Candidates in one board's HTML for what the picker saw */
234
+ export function findInHtml(html, { html: picked, selector, text } = {}) {
235
+ const doc = parseHtml(html);
236
+ const body = findBody(doc);
237
+ if (!body) return [];
238
+ const want = picked ? squash(picked) : "";
239
+ const words = text ? squash(text).toLowerCase() : "";
240
+ const hits = [];
241
+ for (const { node, path: p } of walk(body)) {
242
+ const r = rangeOf(node);
243
+ if (!r) continue;
244
+ const src = html.slice(r.start, r.end);
245
+ let score = 0;
246
+ if (want) {
247
+ const s = squash(src);
248
+ if (s === want) score = 3;
249
+ else if (want.length > 24 && s.startsWith(want.slice(0, Math.min(want.length, 200)))) score = 2;
250
+ else continue;
251
+ }
252
+ if (selector) {
253
+ if (!matchSelector(node, selector)) continue;
254
+ score += 1;
255
+ }
256
+ if (words) {
257
+ const t = squash(textOf(node)).toLowerCase();
258
+ if (t === words) score += 2;
259
+ else if (!want && !selector) continue;
260
+ }
261
+ hits.push({ path: p, source: src, score, depth: p.split("/").length });
262
+ }
263
+ // Best score first; among equals the deepest (the element itself, not the containers around it)
264
+ return hits.sort((a, b) => b.score - a.score || b.depth - a.depth);
265
+ }
266
+
267
+ /* ---------- Routes ---------- */
268
+
269
+ async function readComments(ctx) {
270
+ try {
271
+ const d = JSON.parse(await fs.readFile(path.join(ctx.dir, "comments.json"), "utf8"));
272
+ return Array.isArray(d.comments) ? d.comments : [];
273
+ } catch {
274
+ return [];
275
+ }
276
+ }
277
+ async function writeComments(ctx, comments) {
278
+ await writeAtomic(path.join(ctx.dir, "comments.json"), JSON.stringify({ comments }, null, 1) + "\n");
279
+ ctx.broadcast({ type: "comments-changed" });
280
+ }
281
+
282
+ /** What an agent reads for one request: its fields and the context block Easel's own chat would send (server/chat.mjs buildPrompt) */
283
+ async function requestContext(ctx, c, chatState) {
284
+ let selection = null;
285
+ if (c.path) {
286
+ const html = await fs.readFile(safeJoin(ctx.store.screensDir, c.file) ?? "", "utf8").catch(() => null);
287
+ const info = html != null ? inspect(html, c.path) : null;
288
+ if (info) selection = { file: c.file, path: c.path, tag: info.tag, label: c.request?.attach?.label ?? null, outerHTML: info.source.length > OUTER_LIMIT ? info.source.slice(0, OUTER_LIMIT) + "…" : info.source };
289
+ }
290
+ const boards = [...new Set([c.file, ...(c.request?.attach?.boards ?? [])])].filter(boardFile);
291
+ const body = {
292
+ text: `${c.text}\n\n(Easel request ${c.id} from ${c.author}${c.path && !selection ? `, at path ${c.path} (the element is gone)` : ""}. Do only what it asks. ${WRITE_RULE} When finished call finish_request with id "${c.id}", status done and a one-line reply saying what changed.)`,
293
+ attach: { boards, selection: !!selection, visible: false },
294
+ agent: "claude",
295
+ };
296
+ return buildPrompt(ctx, body, { selection, context: null, errors: chatState?.errors ?? {} });
297
+ }
298
+
299
+ /** A request as the agent sees it */
300
+ const brief = (c, by) => ({
301
+ id: c.id,
302
+ state: c.request.state,
303
+ for: c.forAgent === true ? "any agent" : c.forAgent,
304
+ meantForYou: meantFor(c.forAgent, by),
305
+ file: c.file,
306
+ path: c.path || null,
307
+ text: c.text,
308
+ author: c.author,
309
+ at: c.request.at,
310
+ ...(c.request.attach?.kind ? { kind: c.request.attach.kind } : {}),
311
+ ...(c.request.by ? { by: c.request.by } : {}),
312
+ ...(c.request.left ? { left: c.request.left } : {}),
313
+ });
314
+
315
+ /** In-memory: each taken request's board contents when it was taken, so finishing can tell which boards changed */
316
+ const bases = new Map();
317
+ const readScreenText = (ctx, f) => fs.readFile(safeJoin(ctx.store.screensDir, f) ?? "", "utf8").catch(() => null);
318
+
319
+ /** One request change, inside store.exclusive. Throws { status } for a refusal */
320
+ async function change(ctx, b, s) {
321
+ const list = await readComments(ctx);
322
+ const save = async (n) => {
323
+ const i = list.findIndex((x) => x.id === n.id);
324
+ if (i >= 0) list[i] = n;
325
+ else list.push(n);
326
+ await writeComments(ctx, list);
327
+ return n;
328
+ };
329
+ const find = () => {
330
+ const c = list.find((x) => x.id === b.id);
331
+ if (!c) throw fail(404, "Request not found");
332
+ return c;
333
+ };
334
+ if (b.action === "create") {
335
+ if (!boardFile(b.file) || !String(b.text ?? "").trim()) throw fail(400, "file and text are required");
336
+ const c = { id: newId("c"), file: b.file, path: b.path ?? "", text: String(b.text).trim(), author: b.author ?? s.person ?? process.env.USER ?? "unknown", createdAt: new Date().toISOString(), resolved: false };
337
+ const settings = await readSettings(ctx.dir);
338
+ return { comment: await save(markRequest(c, { to: b.to ?? settings.to, attach: b.attach })) };
339
+ }
340
+ if (b.action === "mark") {
341
+ const settings = await readSettings(ctx.dir);
342
+ return { comment: await save(markRequest(find(), { to: b.to ?? settings.to, attach: b.attach })) };
343
+ }
344
+ if (b.action === "cancel") return { comment: await save(cancelRequest(find())) };
345
+ if (b.action === "retry") return { comment: await save(retryRequest(find())) };
346
+ // Use Easel chat: the request becomes an ordinary comment again and the app attaches it to its own chat
347
+ if (b.action === "chat") {
348
+ const c = find();
349
+ if (c.request?.state === "taken") throw fail(409, `${c.request.by ?? "An agent"} has taken it`);
350
+ return { comment: await save(cancelRequest(c)) };
351
+ }
352
+ if (b.action === "take") {
353
+ const by = s.agent ?? cleanAgent(b.by);
354
+ if (!by) throw fail(400, "Only an agent can take a request");
355
+ const c = takeRequest(find(), { by, client: s.client ?? null });
356
+ // Claim its board like claim_board: the agent holds it (others see "… is editing"), or gets a fork when another agent is on it
357
+ const claim = await routeWrite(ctx, c.file);
358
+ const before = await readScreenText(ctx, claim.file);
359
+ if (!claim.created) ctx.occupancy.agentWrite(claim.file, by, { client: s.client, before });
360
+ bases.set(c.id, { [claim.file]: before == null ? null : hashText(before), ...(claim.file !== c.file ? { [c.file]: hashText((await readScreenText(ctx, c.file)) ?? "") } : {}) });
361
+ c.request.file = claim.file;
362
+ await save(c);
363
+ return { take: { c, by, claim } };
364
+ }
365
+ if (b.action === "finish") {
366
+ const c0 = find();
367
+ const by = s.agent ?? c0.request?.by;
368
+ const changed = [];
369
+ for (const [f, h] of Object.entries(bases.get(c0.id) ?? {})) {
370
+ const now = await readScreenText(ctx, f);
371
+ if ((now == null ? null : hashText(now)) !== h) changed.push(f);
372
+ }
373
+ // Its own undo steps: the agent's writes (write_board, edits through Easel) and outside writes to the boards it held, since it took
374
+ // the request. "Undo the change" undoes exactly these, however many there were, and nothing the same agent did before
375
+ const since = Date.parse(c0.request?.takenAt ?? "") || 0;
376
+ const held = new Set(Object.keys(bases.get(c0.id) ?? {}).map((f) => safeJoin(ctx.store.screensDir, f)));
377
+ await ctx.history.observe();
378
+ const steps = ctx.history
379
+ .entries()
380
+ .undo.filter((st) => (st.lastAt ?? st.at) >= since && (st.by === by || (!st.by && !st.person && st.outside)) && st.changes.some((ch) => held.has(ch.path)))
381
+ .map((st) => st.id);
382
+ const c = finishRequest(c0, { by, client: s.client ?? null, status: b.status, reply: b.reply, changed, steps });
383
+ bases.delete(c.id);
384
+ await save(c);
385
+ // Its boards show "… · done" now rather than after the quiet time
386
+ if (s.client) ctx.occupancy.clientGone(s.client);
387
+ return { request: brief(c, by), changed, resolved: c.resolved };
388
+ }
389
+ throw fail(400, "Unknown action");
390
+ }
391
+
392
+ /** The connected-agent list of a canvas, made on first use */
393
+ export const agentsOf = (ctx) => (ctx.agentList ??= createAgentList({ onChange: () => ctx.broadcast({ type: "agents-changed" }) }));
394
+
395
+ export function requestRoutes({ chatState, getSelection } = {}) {
396
+ return [
397
+ // Agents connect (bin/mcp.mjs after initialize, then every minute) and leave
398
+ [
399
+ "POST",
400
+ "/api/agents/hello",
401
+ async (req, res, url, ctx) => {
402
+ const b = await readBody(req);
403
+ const s = requestScope.getStore();
404
+ const client = cleanAgent(b.client) || s?.client;
405
+ if (!client) return sendJson(res, 400, { error: "client is required" });
406
+ const label = cleanAgent(b.label) || s?.agent || "AI";
407
+ let here = false;
408
+ try {
409
+ here = !!b.cwd && within(real(String(b.cwd)), real(rootOf(ctx.dir)));
410
+ } catch {
411
+ here = false;
412
+ }
413
+ agentsOf(ctx).hello({ client, label, cwd: String(b.cwd ?? ""), here });
414
+ const settings = await readSettings(ctx.dir);
415
+ sendJson(res, 200, { ok: true, mode: settings.mode, waiting: (await readComments(ctx)).filter((c) => isRequest(c) && c.request.state === "waiting" && meantFor(c.forAgent, label)).length });
416
+ },
417
+ ],
418
+ [
419
+ "POST",
420
+ "/api/agents/bye",
421
+ async (req, res, url, ctx) => {
422
+ const client = cleanAgent((await readBody(req)).client);
423
+ if (!client) return sendJson(res, 400, { error: "client is required" });
424
+ agentsOf(ctx).bye(client);
425
+ // Requests it had taken go back to waiting ("left before finishing")
426
+ await ctx.store.exclusive(async () => {
427
+ const list = await readComments(ctx);
428
+ let changed = false;
429
+ const next = list.map((c) => {
430
+ if (isRequest(c) && c.request.state === "taken" && c.request.client === client) {
431
+ changed = true;
432
+ bases.delete(c.id);
433
+ return leftRequest(c);
434
+ }
435
+ return c;
436
+ });
437
+ if (changed) await writeComments(ctx, next);
438
+ });
439
+ sendJson(res, 200, { ok: true });
440
+ },
441
+ ],
442
+ ["GET", "/api/agents/connected", async (req, res, url, ctx) => sendJson(res, 200, { agents: agentsOf(ctx).list() })],
443
+ // Where AI requests go for this project
444
+ ["GET", "/api/requests/settings", async (req, res, url, ctx) => sendJson(res, 200, await readSettings(ctx.dir))],
445
+ [
446
+ "POST",
447
+ "/api/requests/settings",
448
+ async (req, res, url, ctx) => {
449
+ const b = await readBody(req);
450
+ const cur = await readSettings(ctx.dir);
451
+ const next = {
452
+ mode: b.mode === "host" || b.mode === "chat" ? b.mode : cur.mode,
453
+ to: typeof b.to === "string" ? cleanAgent(b.to) || "any" : cur.to,
454
+ intro: b.intro === undefined ? cur.intro : !!b.intro,
455
+ };
456
+ await writeSettings(ctx.dir, next);
457
+ ctx.broadcast({ type: "requests-settings", settings: next });
458
+ sendJson(res, 200, next);
459
+ },
460
+ ],
461
+ // The requests an agent can see: waiting and taken ones, with the context block for each (?context=0 leaves it out)
462
+ [
463
+ "GET",
464
+ "/api/requests",
465
+ async (req, res, url, ctx) => {
466
+ const s = requestScope.getStore();
467
+ const by = s?.agent ?? url.searchParams.get("by") ?? "";
468
+ agentsOf(ctx).seen(s?.client);
469
+ const all = await readComments(ctx);
470
+ const open = all.filter((c) => isRequest(c) && (c.request.state === "waiting" || c.request.state === "taken"));
471
+ const withContext = url.searchParams.get("context") !== "0";
472
+ const out = [];
473
+ for (const c of open) out.push({ ...brief(c, by), ...(withContext && c.request.state === "waiting" && meantFor(c.forAgent, by) ? { context: await requestContext(ctx, c, chatState) } : {}) });
474
+ // An agent has looked: the waiting ones meant for it are no longer "nobody has looked"
475
+ if (s?.agent && s.client && open.some((c) => c.request.state === "waiting" && !c.request.seenAt && meantFor(c.forAgent, by))) {
476
+ await ctx.store.exclusive(async () => {
477
+ const list = await readComments(ctx);
478
+ const at = new Date().toISOString();
479
+ for (const c of list) if (isRequest(c) && c.request.state === "waiting" && !c.request.seenAt && meantFor(c.forAgent, by)) c.request.seenAt = at;
480
+ await writeComments(ctx, list);
481
+ });
482
+ }
483
+ sendJson(res, 200, { requests: out });
484
+ },
485
+ ],
486
+ // Every change to a request (runs in store.exclusive: /api/comments… is a locked route, so take is atomic)
487
+ // Every change to a request. The read-modify-write runs in store.exclusive (with every other comment and board write), so take is
488
+ // atomic; the context block is built after, outside the lock (buildPrompt reads the board through the store)
489
+ [
490
+ "POST",
491
+ "/api/requests",
492
+ async (req, res, url, ctx) => {
493
+ const b = await readBody(req);
494
+ const s = requestScope.getStore() ?? {};
495
+ let r;
496
+ try {
497
+ r = await ctx.store.exclusive(() => change(ctx, b, s));
498
+ } catch (e) {
499
+ if (e.status) return sendJson(res, e.status, { error: e.message });
500
+ throw e;
501
+ }
502
+ if (r.take) {
503
+ const { c, by, claim } = r.take;
504
+ agentsOf(ctx).seen(s.client);
505
+ const dir = toPosix(path.relative(rootOf(ctx.dir), ctx.store.screensDir)) || "screens";
506
+ return sendJson(res, 200, {
507
+ request: brief(c, by),
508
+ edit: `${dir}/${claim.file}`,
509
+ forked: claim.forked,
510
+ message: claim.forked ? `${claim.while ?? "Another agent"} is editing ${c.file}, so a fork was made for you: ${dir}/${claim.file}. ${WRITE_RULE}` : `You hold ${dir}/${claim.file} now. ${WRITE_RULE}`,
511
+ context: await requestContext(ctx, c, chatState),
512
+ });
513
+ }
514
+ sendJson(res, 200, r);
515
+ },
516
+ ],
517
+ // The host's element picker saw part of a board: which file and element it is
518
+ [
519
+ "POST",
520
+ "/api/pick/resolve",
521
+ async (req, res, url, ctx) => {
522
+ const b = await readBody(req);
523
+ const screens = toPosix(path.relative(rootOf(ctx.dir), ctx.store.screensDir)) || "screens";
524
+ const sel = getSelection?.() ?? null;
525
+ const answer = async (file, p, how) => {
526
+ const html = await readScreenText(ctx, file);
527
+ const info = html != null && p ? inspect(html, p) : null;
528
+ if (!info) return sendJson(res, 404, { error: `No element at ${p} in ${file}` });
529
+ return sendJson(res, 200, { file: `${screens}/${file}`, board: file, path: p, tag: info.tag, outerHTML: info.source.length > OUTER_LIMIT ? info.source.slice(0, OUTER_LIMIT) + "…" : info.source, how });
530
+ };
531
+ const html = typeof b.html === "string" ? b.html : "";
532
+ // The board frame Easel draws carries where it is (data-easel-file, and data-easel-path while an element is selected on it)
533
+ const fileAttr = /data-easel-file="([^"]+)"/.exec(html)?.[1];
534
+ if (fileAttr) {
535
+ const file = fileAttr.startsWith(screens + "/") ? fileAttr.slice(screens.length + 1) : fileAttr;
536
+ const p = /data-easel-path="([^"]+)"/.exec(html)?.[1];
537
+ if (p) return answer(file, p, "frame");
538
+ if (sel?.file === file) return answer(file, sel.path, "frame + selection");
539
+ return sendJson(res, 200, { file: `${screens}/${file}`, board: file, path: null, how: "frame", note: "The pick is the whole board; nothing is selected on it" });
540
+ }
541
+ if (!html.trim() && !b.selector && !b.text) {
542
+ if (!sel) return sendJson(res, 404, { error: "Nothing picked and nothing selected in Easel" });
543
+ return answer(sel.file, sel.path, "selection");
544
+ }
545
+ const files = (await ctx.store.syncBoard()).files ?? [];
546
+ const found = [];
547
+ for (const f of files) {
548
+ const src = await readScreenText(ctx, f);
549
+ if (src == null) continue;
550
+ for (const h of findInHtml(src, { html: html || undefined, selector: b.selector, text: b.text }).slice(0, 3)) found.push({ file: f, ...h });
551
+ }
552
+ found.sort((a, b2) => b2.score - a.score || b2.depth - a.depth);
553
+ if (!found.length) return sendJson(res, 404, { error: "No element on any board matches that" });
554
+ const best = found[0];
555
+ const others = found.filter((x) => x !== best && x.score === best.score).slice(0, 5).map((x) => ({ file: `${screens}/${x.file}`, path: x.path }));
556
+ return sendJson(res, 200, { file: `${screens}/${best.file}`, board: best.file, path: best.path, outerHTML: best.source.length > OUTER_LIMIT ? best.source.slice(0, OUTER_LIMIT) + "…" : best.source, how: html ? "html" : b.selector ? "selector" : "text", ...(others.length ? { alsoMatches: others } : {}) });
557
+ },
558
+ ],
559
+ ];
560
+ }