@johnz4021/illuminate 0.5.14 → 0.5.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -13,7 +13,9 @@ var __export = (target, all) => {
13
13
  import { spawn } from "node:child_process";
14
14
  function openBrowser(url) {
15
15
  const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
16
- spawn(cmd, args, { stdio: "ignore", detached: true }).unref();
16
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true });
17
+ child.on("error", (error) => console.error("Could not open the browser:", error.message));
18
+ child.unref();
17
19
  }
18
20
  var init_browser = __esm({
19
21
  "packages/server/src/browser.ts"() {
@@ -2459,7 +2461,15 @@ var init_format = __esm({
2459
2461
  /** Only on a map with `since`: this code was there at that commit and is gone now. Its `evidence` cites it as it was. */
2460
2462
  removed: z.boolean().optional(),
2461
2463
  /** The way through this box is on (see `Branch`); none for what the ways share. */
2462
- branch: Branch.optional()
2464
+ branch: Branch.optional(),
2465
+ /**
2466
+ * Only on a map of a change, for a box that changed: what it did at that commit and what it does now, in a few words
2467
+ * each ("Saves the message" / "Saves it and tells the listener"), so the Before and After views read differently. It
2468
+ * says how to describe what the checker found, not whether anything changed: it is shown only on a box the checker
2469
+ * marks changed.
2470
+ */
2471
+ before: z.string().min(1).max(60).optional(),
2472
+ after: z.string().min(1).max(60).optional()
2463
2473
  });
2464
2474
  Edge = z.object({
2465
2475
  id: Id,
@@ -2659,6 +2669,10 @@ function resolveCommit(root, ref) {
2659
2669
  const out = git(root, ["rev-parse", "--verify", "--quiet", "--end-of-options", `${ref}^{commit}`])?.trim();
2660
2670
  return out && /^[0-9a-f]{40,64}$/.test(out) ? out : null;
2661
2671
  }
2672
+ function forkPoint(root, commit) {
2673
+ const out = git(root, ["merge-base", "--end-of-options", commit, "HEAD"])?.trim();
2674
+ return out && /^[0-9a-f]{40,64}$/.test(out) ? out : commit;
2675
+ }
2662
2676
  function commitInfo(root, commit) {
2663
2677
  const out = git(root, ["show", "-s", "--format=%cI%x00%s", "--end-of-options", commit])?.trim();
2664
2678
  if (!out) return { date: null, subject: null };
@@ -3055,7 +3069,7 @@ function checkNode(n, now, cmp, window) {
3055
3069
  if (n.removed) return checkGone(cmp, (side) => checkNodeNow(n, side.repo, side.facts, window), (base) => nodeStillThere(n, now, base));
3056
3070
  const c = checkNodeAsIs(n, now.repo, now.facts, window);
3057
3071
  if (!cmp?.base || n.proposed || c.status !== "confirmed") return c;
3058
- const change = nodeChange(n, now, cmp.base);
3072
+ const change = nodeChange(n, c, now, cmp.base);
3059
3073
  return change ? { ...c, change } : c;
3060
3074
  }
3061
3075
  function checkNodeAsIs(n, repo, facts, window) {
@@ -3083,7 +3097,7 @@ function nodeStillThere(n, now, _base) {
3083
3097
  if (n.symbol && now.facts.get(fileOf(n.symbol))) return !!symbolIn(now, n.symbol);
3084
3098
  return n.evidence.some((e) => hasLine(now, e.file, e.text));
3085
3099
  }
3086
- function nodeChange(n, now, base) {
3100
+ function nodeChange(n, c, now, base) {
3087
3101
  if (n.symbol) {
3088
3102
  const file = fileOf(n.symbol);
3089
3103
  const cur = symbolIn(now, n.symbol);
@@ -3096,9 +3110,21 @@ function nodeChange(n, now, base) {
3096
3110
  return { kind: "changed", ...diff?.length && { diff } };
3097
3111
  }
3098
3112
  }
3099
- if (!n.evidence.length) return null;
3100
- if (n.evidence.every((e) => !base.repo.has(e.file))) return { kind: "added" };
3101
- return n.evidence.some((e) => !hasLine(base, e.file, e.text)) ? { kind: "changed" } : null;
3113
+ const fresh = n.evidence.flatMap((e, i) => hasLine(base, e.file, e.text) ? [] : [{ file: e.file, line: c.evidence[i]?.foundAt ?? e.line }]);
3114
+ if (!fresh.length) return null;
3115
+ if (fresh.length < n.evidence.length) return { kind: "changed" };
3116
+ return fresh.some((x) => inOldCode(now, base, x.file, x.line)) ? { kind: "changed" } : { kind: "added" };
3117
+ }
3118
+ function inOldCode(now, base, file, line) {
3119
+ if (!base.repo.has(file)) return false;
3120
+ const facts = now.facts.get(file);
3121
+ const text2 = now.repo.text(file);
3122
+ if (!facts || text2 === null) return true;
3123
+ const lines = text2.split("\n");
3124
+ const at = lines.slice(0, Math.max(0, line - 1)).reduce((sum, l) => sum + l.length + 1, 0) + (lines[line - 1]?.search(/\S/) ?? 0);
3125
+ let inner = null;
3126
+ for (const s of facts.symbols) if (s.span.start <= at && at < s.span.end && (!inner || s.span.end - s.span.start < inner.span.end - inner.span.start)) inner = s;
3127
+ return !!inner && !!symbolIn(base, inner.id);
3102
3128
  }
3103
3129
  function checkNodeNow(n, repo, facts, window) {
3104
3130
  const evidence = n.evidence.map((e) => checkEvidence(repo, e, window));
@@ -3778,7 +3804,7 @@ function explainerPrompt(map, report, selection, question, missing = "", wordsOn
3778
3804
  "",
3779
3805
  ...questionContext(map, report, selection, question),
3780
3806
  ...map.view === "journey" ? ["", "## This map is a journey", "It shows only what a person sees and does. Anything you add must be the same: `kind` is `screen`, `action` or `choice`, and no boxes for what goes on behind the screen. Say that part in words. A box or arrow you add off the main path carries the `branch` it is on (an existing branch's name, or a new short one in the person's words); one on the main path carries none."] : [],
3781
- ...map.since ? ["", "## This map shows a change", `It compares the code as it is now with commit ${map.since.slice(0, 12)}, and a program marks what is new or different since then. Anything you add is compared the same way, so don't mark it yourself. Only code that was deleted since that commit gets \`"removed": true\`, citing its lines as they were then (an arrow to or from a removed box is removed too).`] : [],
3807
+ ...map.since ? ["", "## This map shows a change", `It compares the code as it is now with commit ${map.since.slice(0, 12)}, and a program marks what is new or different since then. Anything you add is compared the same way, so don't mark it yourself. Only code that was deleted since that commit gets \`"removed": true\`, citing its lines as they were then (an arrow to or from a removed box is removed too). A box you add that changed since gets \`before\` and \`after\`: what it did then and does now, a few words each.`] : [],
3782
3808
  ...missing ? ["", `## Why the map alone wasn't enough
3783
3809
  ${missing}`] : [],
3784
3810
  "",
@@ -3868,11 +3894,12 @@ var init_prompts = __esm({
3868
3894
  ];
3869
3895
  CHANGE_RULES = [
3870
3896
  '## When the question is about a change (what changed, what a commit or a task did, "what did you just change")',
3871
- '- Set `"since"` on the map to the commit to compare with: "HEAD" for work that isn\'t committed yet, "HEAD~1" for the last commit, or the branch or commit they name. A question about how things work today gets no `since`.',
3897
+ '- Set `"since"` on the map to the commit to compare with: "HEAD" for work that isn\'t committed yet, "HEAD~1" for the last commit, the branch it will merge into for a pull request or a branch ("main", not "HEAD~1": a branch can have many commits; the program compares with where this branch left it), or the commit they name. A question about how things work today gets no `since`.',
3872
3898
  "- Draw the flow the change belongs to as it works now, the map you would draw if they had asked how it works: start where it starts and follow it through, steps that didn't change included. The person reads the change against those: a map where every box is new or changed shows no before, and can't be told from a map of something else. As a guide, at least a third of the boxes are ones that didn't change (the steps the change plugs into, what calls the new code, what it hands on to). Leave out helpers the change added that aren't steps of the flow.",
3873
3899
  "- Cite everything as usual. Don't mark what is new or different: a program compares every box and arrow with that commit and marks them itself. It compares a box that names its function (`symbol`) as that function, so give new and changed boxes their `symbol`; for anything else, cite a line that is new.",
3874
3900
  '- Code that was deleted is a box or arrow with `"removed": true`. It cites the code as it was at that commit: `file`, `line` and `text` from the old version (`git show <since>:<file>` shows it, when you can run git). An arrow to or from a removed box is removed too. The program checks that it was there then and is gone now, so use it only for code that is really gone, not for code that moved or was renamed.',
3875
3901
  '- In the explanation of each box that changed, say what is different now, in plain words ("Now also tells the listener"), not as a diff.',
3902
+ '- Give each box that changed (not one that is new) `before` and `after`: what it did at that commit and what it does now, a few words each (about 30 characters, so it fits on the box), the same kind of words as its name ("Saves the message" / "Also tells the listener"). The map shows them in its Before and After views, so the two read differently; it shows them only on boxes the program finds changed.',
3876
3903
  "- If you made the change yourself in this conversation, draw what you changed and what it touches. Other differences from that commit that aren't part of it stay off the map.",
3877
3904
  "- The walkthrough says what changed first, then follows the changed path in the order things happen."
3878
3905
  ];
@@ -4063,6 +4090,7 @@ async function answer(o) {
4063
4090
  resume: null,
4064
4091
  model: o.model,
4065
4092
  maxTurns: 3,
4093
+ onProgress: o.onProgress,
4066
4094
  signal: o.signal
4067
4095
  });
4068
4096
  cost += res2.cost ?? 0;
@@ -4385,7 +4413,7 @@ function pinned(parsed, root) {
4385
4413
  if (!parsed.ok || !parsed.map.since) return parsed;
4386
4414
  const commit = resolveCommit(root, parsed.map.since);
4387
4415
  if (!commit) return { ok: false, problems: [`since: "${parsed.map.since}" isn't a commit in this repo. Use "HEAD" for work that isn't committed yet, "HEAD~1" for the last commit, or leave \`since\` out if the map isn't about a change.`] };
4388
- return { ok: true, map: { ...parsed.map, since: commit } };
4416
+ return { ok: true, map: { ...parsed.map, since: forkPoint(root, commit) } };
4389
4417
  }
4390
4418
  async function makeMap(o) {
4391
4419
  const status = (text2) => o.onProgress?.({ kind: "status", text: text2 });
@@ -4394,8 +4422,8 @@ async function makeMap(o) {
4394
4422
  const hints = await headStart(o.root);
4395
4423
  const symbolsIn = symbolIndexOf(hints.scan);
4396
4424
  status(`${who} is exploring the code`);
4397
- const run = (prompt, resume, schema) => o.agent({ prompt, label: `Making the map for "${o.question}"`, schema, cwd: o.root, resume, model: o.model, onProgress: o.onProgress, signal: o.signal });
4398
- let res = await run(makerPrompt(o.question, hints.text), null, MAP_SCHEMA);
4425
+ const run2 = (prompt, resume, schema) => o.agent({ prompt, label: `Making the map for "${o.question}"`, schema, cwd: o.root, resume, model: o.model, onProgress: o.onProgress, signal: o.signal });
4426
+ let res = await run2(makerPrompt(o.question, hints.text), null, MAP_SCHEMA);
4399
4427
  let cost = res.cost ?? 0;
4400
4428
  let rounds = 1;
4401
4429
  const off = (r) => r.summary.unconfirmed + settledProposals(r).length;
@@ -4419,7 +4447,7 @@ async function makeMap(o) {
4419
4447
  }
4420
4448
  if (!repair || attempt >= (o.repairs ?? 2)) break;
4421
4449
  status(parsed.ok ? `Asking ${who} to fix the claims that didn't check out` : current ? `Asking ${who} to fix its changes` : `Asking ${who} to fix the map's structure`);
4422
- res = await run(repair.prompt, res.sessionId, repair.reply === "map" ? MAP_SCHEMA : MAP_PATCH_SCHEMA);
4450
+ res = await run2(repair.prompt, res.sessionId, repair.reply === "map" ? MAP_SCHEMA : MAP_PATCH_SCHEMA);
4423
4451
  reply = repair.reply;
4424
4452
  cost += res.cost ?? 0;
4425
4453
  rounds++;
@@ -4537,7 +4565,8 @@ async function startServer(o) {
4537
4565
  };
4538
4566
  const clients = /* @__PURE__ */ new Set();
4539
4567
  let port = 0;
4540
- const page = o.page ?? { name: "Claude", asks: "page" };
4568
+ const initialPage = o.page ?? { name: "Claude", asks: "page" };
4569
+ let page = initialPage;
4541
4570
  const busy = `${page.name} is still working on this map. Try again when it finishes.`;
4542
4571
  const selections = /* @__PURE__ */ new Map();
4543
4572
  let seen = null;
@@ -4639,7 +4668,7 @@ async function startServer(o) {
4639
4668
  endJob(mapId);
4640
4669
  if (r.answer.added.length || r.answer.screens?.length || r.answer.proposed?.length) publishMap(next);
4641
4670
  broadcast({ type: "answer", mapId, answer: r.answer });
4642
- broadcast({ type: "job", mapId, job: "ask", status: "done", question: q });
4671
+ broadcast({ type: "job", mapId, job: "ask", status: "done", question: q, fromChat: opts.fromChat });
4643
4672
  } catch (err) {
4644
4673
  endJob(mapId);
4645
4674
  broadcast({ type: "job", mapId, job: "ask", status: "failed", question: q, error: errorText(err) });
@@ -4662,7 +4691,7 @@ async function startServer(o) {
4662
4691
  };
4663
4692
  const picked = [...selection.nodes ?? [], ...selection.edges ?? [], ...selection.absences ?? []];
4664
4693
  const q = got?.step && !picked.length && question.trim() ? askAboutStep(got.step, question.trim()) : question;
4665
- startAsk(mapId, q, selection);
4694
+ startAsk(mapId, q, selection, { fromChat: true });
4666
4695
  return { mapId, question: q.trim(), selected: picked.map(name) };
4667
4696
  }
4668
4697
  function takeOffer(mapId, answerId, choice) {
@@ -4897,6 +4926,7 @@ async function startServer(o) {
4897
4926
  if (closing) return ws.close(STOPPED_CLOSE_CODE, "illuminate stopped");
4898
4927
  if (onMap && /^[a-z0-9-]{1,80}$/.test(onMap) && store.get(onMap)) sawPage(onMap);
4899
4928
  clients.add(ws);
4929
+ if (page !== initialPage) ws.send(JSON.stringify({ type: "agent", agent: page }));
4900
4930
  visited = true;
4901
4931
  armIdle();
4902
4932
  ws.on("close", () => {
@@ -4946,6 +4976,10 @@ async function startServer(o) {
4946
4976
  port,
4947
4977
  token,
4948
4978
  pageUrl: (mapId) => `${url}/${mapId ? `m/${mapId}` : ""}?t=${token}`,
4979
+ setPageAgent(agent2) {
4980
+ page = agent2;
4981
+ broadcast({ type: "agent", agent: agent2 });
4982
+ },
4949
4983
  startMap,
4950
4984
  askFromChat,
4951
4985
  lastSeen: () => seen,
@@ -5037,43 +5071,221 @@ async function checkForUpdate(o = {}) {
5037
5071
  return null;
5038
5072
  }
5039
5073
  }
5040
- function updateMessage(n, via, agent = "claude-code") {
5074
+ function updateMessage(n, via, advice = "") {
5041
5075
  const out = `A newer illuminate is out (${n.latest}; this is ${n.current}).`;
5042
5076
  if (via === "cli") return `${out} Update with: npm install -g ${PACKAGE}`;
5043
5077
  const tell = "Mention it to the person in one sentence after what you tell them about the map.";
5044
- if (agent === "codex") {
5045
- return `${out} ${tell} How to update depends on how they added illuminate to Codex; the README's Codex section says how. Don't change their setup yourself.`;
5046
- }
5047
- if (via === "mcp") {
5048
- return `${out} ${tell} They added illuminate with \`claude mcp add\`: restarting Claude Code gets the new version if that command uses \`@johnz4021/illuminate@latest\`; otherwise point them at the README's setup without the plugin. Don't change their setup yourself.`;
5049
- }
5050
- return [
5051
- out,
5052
- tell,
5053
- 'If Claude Code already said "Plugin updated" for illuminate, they only need to restart Claude Code.',
5054
- "Otherwise offer to run `claude plugin marketplace update illuminate` and then `claude plugin update illuminate@illuminate` for them; run them only if they say yes, then they restart Claude Code.",
5055
- "Also say that turning on auto-update (/plugin, then Marketplaces, illuminate, Enable auto-update) does this by itself next time."
5056
- ].join(" ");
5078
+ return [out, tell, advice].filter(Boolean).join(" ");
5057
5079
  }
5058
5080
  var VERSION, PACKAGE, DAY;
5059
5081
  var init_updates = __esm({
5060
5082
  "packages/server/src/updates.ts"() {
5061
5083
  "use strict";
5062
- VERSION = true ? "0.5.14" : void 0;
5084
+ VERSION = true ? "0.5.16" : void 0;
5063
5085
  PACKAGE = "@johnz4021/illuminate";
5064
5086
  DAY = 24 * 60 * 60 * 1e3;
5065
5087
  }
5066
5088
  });
5067
5089
 
5068
- // packages/server/src/host.ts
5069
- function hostOf(client) {
5070
- return client?.name === CODEX_CLIENT ? CODEX : CLAUDE_CODE;
5090
+ // packages/server/src/hosts/common.ts
5091
+ function withHostTools(own, adjust = (t) => t) {
5092
+ const shared = SHARED_TOOLS.map(adjust);
5093
+ const at = shared.findIndex((t) => t.name === "illuminate_fail") + 1;
5094
+ return [...shared.slice(0, at), ...own, ...shared.slice(at)];
5071
5095
  }
5072
- var CODEX_CLIENT, CLAUDE_CODE, CODEX;
5073
- var init_host = __esm({
5074
- "packages/server/src/host.ts"() {
5096
+ function requestText(r) {
5097
+ return [
5098
+ `## illuminate request ${r.id}: ${r.label}`,
5099
+ "",
5100
+ `When you're done, call illuminate_submit with request_id "${r.id}" and \`output\`: a JSON object matching the schema at the end. Don't edit any files.`,
5101
+ r.tools.length ? "" : "Answer from what is in this request alone. Don't read the code for this one.",
5102
+ r.continues ? "This follows on from your earlier work for illuminate in this conversation." : "",
5103
+ "",
5104
+ "---",
5105
+ r.prompt,
5106
+ "---",
5107
+ "",
5108
+ "## Output schema (JSON Schema)",
5109
+ JSON.stringify(r.schema)
5110
+ ].filter((line, i, all) => line !== "" || all[i - 1] !== "").join("\n");
5111
+ }
5112
+ var local, SHARED_TOOLS, browserLink, TELL_ABOUT_MAP, text;
5113
+ var init_common = __esm({
5114
+ "packages/server/src/hosts/common.ts"() {
5075
5115
  "use strict";
5076
- CODEX_CLIENT = "codex-mcp-client";
5116
+ local = (title, readOnly = false) => ({ title, readOnlyHint: readOnly, destructiveHint: false, idempotentHint: false, openWorldHint: false });
5117
+ SHARED_TOOLS = [
5118
+ {
5119
+ name: "illuminate_map",
5120
+ description: "Make a checked map that answers a question about how this codebase works, and open it in the person's browser. Returns the first piece of work for you to do.",
5121
+ annotations: local("Make a map"),
5122
+ inputSchema: {
5123
+ type: "object",
5124
+ properties: {
5125
+ question: { type: "string", maxLength: 300, description: "The person's question, in their own words (300 characters at most)." },
5126
+ repo: { type: "string", description: "The repo root, if not the project Claude Code was started in." }
5127
+ },
5128
+ required: ["question"]
5129
+ }
5130
+ },
5131
+ {
5132
+ name: "illuminate_next",
5133
+ description: "Get the next piece of work illuminate has for you (after an illuminate channel message).",
5134
+ annotations: local("Get the next request", true),
5135
+ inputSchema: { type: "object", properties: {} }
5136
+ },
5137
+ {
5138
+ name: "illuminate_submit",
5139
+ description: "Hand in your output for an illuminate request. It is checked; if it can't be read you get the problems back to fix. Returns the next piece of work, if there is one.",
5140
+ annotations: local("Hand in a request"),
5141
+ inputSchema: {
5142
+ type: "object",
5143
+ properties: {
5144
+ request_id: { type: "string" },
5145
+ output: { type: "object", description: "JSON matching the request's schema." }
5146
+ },
5147
+ required: ["request_id", "output"]
5148
+ }
5149
+ },
5150
+ {
5151
+ name: "illuminate_fail",
5152
+ description: "Give up on an illuminate request, saying why in plain words. The person sees it on the map.",
5153
+ annotations: local("Give up on a request"),
5154
+ inputSchema: {
5155
+ type: "object",
5156
+ properties: { request_id: { type: "string" }, reason: { type: "string" } },
5157
+ required: ["request_id", "reason"]
5158
+ }
5159
+ },
5160
+ {
5161
+ name: "illuminate_screens",
5162
+ description: "List what this repo can show of its screens: local pages being served right now, HTML files, preview setups and image files. Costs nothing; call it when a picture of the screen might help a map or an answer.",
5163
+ annotations: local("List screens", true),
5164
+ inputSchema: { type: "object", properties: { repo: { type: "string" } } }
5165
+ },
5166
+ {
5167
+ name: "illuminate_capture",
5168
+ description: "Screenshot one page so it can be a box's `screen` on a map: a `url` served on this machine (http://localhost:\u2026), or an HTML `file` in the repo. Returns the image for you to look at, the labelled things visible on it, and the capture id to put in the box's `screen`. Runs in a clean browser profile, so pages behind a login show their login page.",
5169
+ annotations: local("Screenshot a local page"),
5170
+ inputSchema: {
5171
+ type: "object",
5172
+ properties: {
5173
+ url: { type: "string", description: "A page on this machine, e.g. http://localhost:3000/patients" },
5174
+ file: { type: "string", description: "Or: a repo-relative .html file" },
5175
+ repo: { type: "string" }
5176
+ }
5177
+ }
5178
+ },
5179
+ {
5180
+ name: "illuminate_open",
5181
+ description: "Open saved maps in the person's browser: one map, or the list of all of them. Returns the maps saved in the repo.",
5182
+ annotations: local("Open saved maps"),
5183
+ inputSchema: {
5184
+ type: "object",
5185
+ properties: {
5186
+ map_id: { type: "string", description: "A saved map's id; leave out for the list." },
5187
+ repo: { type: "string" }
5188
+ }
5189
+ }
5190
+ }
5191
+ ];
5192
+ browserLink = (url) => `Opened in your browser. If the tab didn't appear, use this link: ${url}`;
5193
+ TELL_ABOUT_MAP = "Tell the person in a sentence; the map does the explaining.";
5194
+ text = (t, isError = false) => ({ content: [{ type: "text", text: t }], ...isError ? { isError } : {} });
5195
+ }
5196
+ });
5197
+
5198
+ // packages/server/src/hosts/claude-code.ts
5199
+ function claudeCodeUpdateAdvice(via) {
5200
+ if (via === "mcp") {
5201
+ return "They added illuminate with `claude mcp add`: restarting Claude Code gets the new version if that command uses `@johnz4021/illuminate@latest`; otherwise point them at the README's setup without the plugin. Don't change their setup yourself.";
5202
+ }
5203
+ return [
5204
+ 'If Claude Code already said "Plugin updated" for illuminate, they only need to restart Claude Code.',
5205
+ "Otherwise offer to run `claude plugin marketplace update illuminate` and then `claude plugin update illuminate@illuminate` for them; run them only if they say yes, then they restart Claude Code.",
5206
+ "Also say that turning on auto-update (/plugin, then Marketplaces, illuminate, Enable auto-update) does this by itself next time."
5207
+ ].join(" ");
5208
+ }
5209
+ function createClaudeCode(kit, o) {
5210
+ let quiet = 0;
5211
+ const closedListeners = /* @__PURE__ */ new Set();
5212
+ const deliver = (r, after = "") => `${requestText(r)}${after ? `
5213
+
5214
+ ${after}` : ""}`;
5215
+ async function listen(extra) {
5216
+ if (!kit.servers.size) return text(CLOSED);
5217
+ const stop = kit.keepAlive(extra);
5218
+ let closed = false;
5219
+ const ac = new AbortController();
5220
+ const onClosed = () => {
5221
+ closed = true;
5222
+ ac.abort();
5223
+ };
5224
+ const onAbort = () => ac.abort();
5225
+ extra.signal.addEventListener("abort", onAbort, { once: true });
5226
+ const timer = setTimeout(() => ac.abort(), o.listenMs);
5227
+ closedListeners.add(onClosed);
5228
+ try {
5229
+ const r = await kit.bridge.waitForNext(ac.signal);
5230
+ if (r) {
5231
+ quiet = 0;
5232
+ return text(deliver(r, "After illuminate_submit, call illuminate_listen again so questions on the map keep reaching you."));
5233
+ }
5234
+ if (closed) return text(CLOSED);
5235
+ if (extra.signal.aborted) return text("Stopped listening. Questions asked on the map wait until you call illuminate_listen again.");
5236
+ quiet++;
5237
+ if (quiet >= o.quietListens) {
5238
+ quiet = 0;
5239
+ return text("Nobody has asked on the map for about two hours, so illuminate stopped listening. Don't call illuminate_listen again unless the person asks you to listen, or asks for a map. Say nothing to the person about this.");
5240
+ }
5241
+ return text("Nothing was asked on the map yet. Call illuminate_listen again to keep listening, and say nothing to the person about it.");
5242
+ } finally {
5243
+ closedListeners.delete(onClosed);
5244
+ clearTimeout(timer);
5245
+ extra.signal.removeEventListener("abort", onAbort);
5246
+ stop();
5247
+ }
5248
+ }
5249
+ return {
5250
+ settings: () => CLAUDE_CODE,
5251
+ tools: CLAUDE_CODE_TOOLS,
5252
+ // Pushed as a channel message, for a session started with the development channels flag (others drop it).
5253
+ announce(r) {
5254
+ void kit.notify({
5255
+ method: "notifications/claude/channel",
5256
+ params: { content: `illuminate has work for you: ${r.label}. Call illuminate_next to get it.`, meta: { request_id: r.id } }
5257
+ }).catch(() => {
5258
+ });
5259
+ },
5260
+ deliver,
5261
+ async beforeCall(name) {
5262
+ if (name !== "illuminate_listen") quiet = 0;
5263
+ },
5264
+ async call(name, _args, extra) {
5265
+ return name === "illuminate_listen" ? listen(extra) : null;
5266
+ },
5267
+ closed() {
5268
+ for (const l of [...closedListeners]) l();
5269
+ },
5270
+ idle: async () => text("Nothing is waiting right now."),
5271
+ stillWorking: "illuminate is still working on its side. Call illuminate_listen: it returns when there is something for you.",
5272
+ followUp: LISTEN_AGAIN,
5273
+ opening: (url) => [browserLink(url), "Give the person the link."].join("\n"),
5274
+ opened: (url) => [`Opened ${url}`, "Call illuminate_listen so questions asked on the map reach you."],
5275
+ mapReady: (url) => [
5276
+ url ? `It's open in the browser: ${url}` : "",
5277
+ `${TELL_ABOUT_MAP} They can take the walkthrough, or select any box and ask about it there.`
5278
+ ],
5279
+ answered: (e) => `The answer to "${e.question}" is shown on the map. Call illuminate_listen again for their next question.`,
5280
+ pageText: (t) => t,
5281
+ updateAdvice: claudeCodeUpdateAdvice
5282
+ };
5283
+ }
5284
+ var CLAUDE_CODE, CLAUDE_CODE_INSTRUCTIONS, LISTEN, CLAUDE_CODE_TOOLS, CLOSED, LISTEN_AGAIN;
5285
+ var init_claude_code = __esm({
5286
+ "packages/server/src/hosts/claude-code.ts"() {
5287
+ "use strict";
5288
+ init_common();
5077
5289
  CLAUDE_CODE = {
5078
5290
  id: "claude-code",
5079
5291
  name: "Claude Code",
@@ -5085,118 +5297,485 @@ var init_host = __esm({
5085
5297
  nudgeMs: 3e4,
5086
5298
  waitMs: 9e4
5087
5299
  };
5088
- CODEX = {
5089
- id: "codex",
5090
- name: "Codex",
5091
- page: { name: "Codex", asks: "chat" },
5092
- claimed: "Codex is working on this in the Codex chat",
5093
- waiting: "Waiting for Codex to pick this up",
5094
- // Codex can't be woken from the page, so this is said as soon as it's clear nobody has it.
5095
- notPickedUp: `Codex can't see work started on this page. In the Codex chat, say "carry on with illuminate", and it will pick this up.`,
5096
- neverPickedUp: "Codex never picked this up, so nothing was answered. Ask in the Codex chat instead.",
5097
- nudgeMs: 1500,
5098
- // Codex's documented default tool timeout is 60 s; progress doesn't extend it.
5099
- waitMs: 4e4
5300
+ CLAUDE_CODE_INSTRUCTIONS = [
5301
+ "In Claude Code:",
5302
+ "- Once a map is ready or an answer is shown, call illuminate_listen and leave it running. It moves to the background, so the person keeps their terminal. When they ask something on the map it returns with a request: do it, submit it, then call illuminate_listen again. If it returns saying nothing was asked yet, call it again without telling the person. Only one is needed at a time.",
5303
+ "- If an illuminate channel message arrives instead, call illuminate_next to get the request."
5304
+ ];
5305
+ LISTEN = {
5306
+ name: "illuminate_listen",
5307
+ description: "Wait for the next question the person asks on the map (or a new map they start there). Keep one running whenever you have no illuminate work: it moves to the background, and returns with a request when they ask. Do the request, submit it, then call this again.",
5308
+ annotations: local("Listen to the map", true),
5309
+ inputSchema: { type: "object", properties: {} }
5100
5310
  };
5311
+ CLAUDE_CODE_TOOLS = withHostTools([LISTEN]);
5312
+ CLOSED = "The person closed illuminate, so there is nothing to listen to. Don't call illuminate_listen again unless they ask for a map or ask you to listen. Say nothing to the person about this.";
5313
+ LISTEN_AGAIN = "Then call illuminate_listen so questions they ask on the map reach you.";
5101
5314
  }
5102
5315
  });
5103
5316
 
5104
- // packages/server/src/bridge.ts
5105
- function createBridge(o) {
5106
- const host = o.host ?? (() => CLAUDE_CODE);
5107
- const giveUpMs = o.giveUpMs ?? 5 * 6e4;
5108
- const entries = [];
5109
- const waiters = [];
5110
- let n = 0;
5111
- const agent = (req) => new Promise((resolve5, reject) => {
5112
- if (req.signal?.aborted) return reject(new Error("Stopped."));
5113
- const h = host();
5114
- const entry = {
5115
- id: `r${++n}`,
5116
- label: req.label ?? "Work for illuminate",
5117
- prompt: req.prompt,
5118
- schema: req.schema,
5119
- tools: req.tools ?? ["Read", "Grep", "Glob"],
5120
- continues: !!req.resume,
5121
- handed: false,
5122
- claimed: () => req.onProgress?.({ kind: "status", text: h.claimed }),
5123
- timers: [],
5124
- resolve: (r) => {
5125
- settle(entry);
5126
- resolve5(r);
5127
- },
5128
- reject: (e) => {
5129
- settle(entry);
5130
- reject(e);
5131
- }
5132
- };
5133
- entries.push(entry);
5134
- req.signal?.addEventListener("abort", () => entry.reject(new Error("Stopped.")), { once: true });
5135
- const waiter = waiters.pop();
5136
- if (waiter) {
5137
- entry.handed = true;
5138
- entry.claimed();
5139
- waiter(entry);
5140
- return;
5317
+ // packages/server/src/hosts/codex-queue.ts
5318
+ import { execFile } from "node:child_process";
5319
+ import { promisify } from "node:util";
5320
+ async function findQueueCommand() {
5321
+ const candidates = ["codex"];
5322
+ if (process.platform === "darwin") candidates.push("/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex");
5323
+ for (const command of candidates) {
5324
+ try {
5325
+ await run(command, ["help", "queue"], { timeout: 5e3 });
5326
+ return command;
5327
+ } catch {
5141
5328
  }
5142
- req.onProgress?.({ kind: "status", text: h.waiting });
5143
- const later = (ms, f) => {
5144
- const t = setTimeout(() => {
5145
- if (!entry.handed && entries.includes(entry)) f();
5146
- }, ms);
5147
- t.unref?.();
5148
- entry.timers.push(t);
5149
- };
5150
- later(o.nudgeMs ?? h.nudgeMs, () => req.onProgress?.({ kind: "status", text: h.notPickedUp }));
5151
- later(giveUpMs, () => entry.reject(Object.assign(new Error(h.neverPickedUp), { unheard: true })));
5152
- o.announce(view(entry));
5153
- });
5154
- function settle(e) {
5155
- const i = entries.indexOf(e);
5156
- if (i >= 0) entries.splice(i, 1);
5157
- for (const t of e.timers) clearTimeout(t);
5158
- e.timers = [];
5159
5329
  }
5160
- const take = () => {
5161
- const e = entries.find((x) => !x.handed) ?? null;
5162
- if (e) {
5163
- e.handed = true;
5164
- e.claimed();
5165
- }
5166
- return e;
5167
- };
5168
- return {
5169
- agent,
5170
- next() {
5171
- const e = take() ?? entries[0] ?? null;
5172
- return e ? view(e) : null;
5173
- },
5174
- waitForNext(signal) {
5175
- const now = take();
5176
- if (now) return Promise.resolve(view(now));
5177
- if (signal.aborted) return Promise.resolve(null);
5178
- return new Promise((resolve5) => {
5179
- const waiter = (e) => {
5180
- signal.removeEventListener("abort", onAbort);
5181
- resolve5(view(e));
5182
- };
5183
- const onAbort = () => {
5184
- const i = waiters.indexOf(waiter);
5185
- if (i >= 0) waiters.splice(i, 1);
5186
- resolve5(null);
5187
- };
5188
- waiters.push(waiter);
5189
- signal.addEventListener("abort", onAbort, { once: true });
5190
- });
5191
- },
5192
- submit(id, output) {
5193
- const e = entries.find((x) => x.id === id);
5194
- if (!e) return { ok: false, problems: [`No request "${id}" is waiting. It may have been answered already, or stopped.`] };
5195
- let value = output;
5196
- if (typeof value === "string") {
5197
- try {
5198
- value = JSON.parse(value);
5199
- } catch {
5330
+ return null;
5331
+ }
5332
+ async function queueRequest(command, thread, ticket) {
5333
+ await run(
5334
+ command,
5335
+ [
5336
+ "queue",
5337
+ "--thread",
5338
+ thread,
5339
+ "--message",
5340
+ `Illuminate has a request from the map. Call illuminate_next with ticket "${ticket}". Complete the request through illuminate_submit. The answer belongs on the map.`
5341
+ ],
5342
+ { timeout: 15e3 }
5343
+ );
5344
+ }
5345
+ var run;
5346
+ var init_codex_queue = __esm({
5347
+ "packages/server/src/hosts/codex-queue.ts"() {
5348
+ "use strict";
5349
+ run = promisify(execFile);
5350
+ }
5351
+ });
5352
+
5353
+ // packages/server/src/hosts/codex-reply.ts
5354
+ import * as path9 from "node:path";
5355
+ function excerpt(b) {
5356
+ const marked = b.notes.length ? b.notes.map((n) => n.line) : b.cited;
5357
+ const end = b.start + b.lines.length - 1;
5358
+ let from = Math.max(b.start, Math.min(...marked) - AROUND);
5359
+ let to = Math.min(end, Math.max(...marked) + AROUND);
5360
+ if (to - from + 1 > MAX_LINES3) to = from + MAX_LINES3 - 1;
5361
+ if (!marked.length) [from, to] = [b.start, Math.min(end, b.start + MAX_LINES3 - 1)];
5362
+ return { start: from, lines: b.lines.slice(from - b.start, to - b.start + 1) };
5363
+ }
5364
+ function blockText(b) {
5365
+ const { start, lines } = excerpt(b);
5366
+ const width = String(start + lines.length - 1).length;
5367
+ const numbered = lines.map((l, i) => `${String(start + i).padStart(width)} ${l}`).join("\n");
5368
+ const where = `\`${b.file}\`${b.name ? ` \xB7 ${b.name}` : ""} (lines ${start}\u2013${start + lines.length - 1})`;
5369
+ const notes = b.notes.filter((n) => n.line >= start && n.line < start + lines.length).map((n) => `- Line ${n.line}: ${n.note}`);
5370
+ return [where, `\`\`\`${LANG[path9.extname(b.file)] ?? ""}`, numbered, "```", ...notes].join("\n");
5371
+ }
5372
+ function chatReply(root, a) {
5373
+ const parts = [a.concept.trim()];
5374
+ const unconfirmed = a.refs.filter((r) => r.status === "unconfirmed").map((r) => r.id);
5375
+ if (unconfirmed.length) parts.push(`_Not confirmed against the code: ${unconfirmed.join(", ")}._`);
5376
+ if (a.notes?.length) {
5377
+ const view2 = codeForNotes(root, a.notes);
5378
+ const blocks = view2.blocks.slice(0, MAX_BLOCKS2).map(blockText);
5379
+ if (blocks.length) parts.push(blocks.join("\n\n"));
5380
+ if (view2.missing) parts.push(`_${view2.missing} of the lines it points at aren't in the code any more, so they're left out._`);
5381
+ }
5382
+ if (a.fix) parts.push("A fix is proposed on the map: approve or reject it there.");
5383
+ return parts.join("\n\n");
5384
+ }
5385
+ var AROUND, MAX_LINES3, MAX_BLOCKS2, LANG;
5386
+ var init_codex_reply = __esm({
5387
+ "packages/server/src/hosts/codex-reply.ts"() {
5388
+ "use strict";
5389
+ init_src2();
5390
+ AROUND = 3;
5391
+ MAX_LINES3 = 30;
5392
+ MAX_BLOCKS2 = 4;
5393
+ LANG = {
5394
+ ".ts": "ts",
5395
+ ".tsx": "tsx",
5396
+ ".js": "js",
5397
+ ".jsx": "jsx",
5398
+ ".mjs": "js",
5399
+ ".cjs": "js",
5400
+ ".py": "python",
5401
+ ".go": "go",
5402
+ ".rs": "rust",
5403
+ ".java": "java",
5404
+ ".rb": "ruby",
5405
+ ".sol": "solidity",
5406
+ ".css": "css",
5407
+ ".html": "html",
5408
+ ".json": "json",
5409
+ ".sql": "sql",
5410
+ ".sh": "bash",
5411
+ ".yml": "yaml",
5412
+ ".yaml": "yaml",
5413
+ ".md": "markdown"
5414
+ };
5415
+ }
5416
+ });
5417
+
5418
+ // packages/server/src/hosts/codex.ts
5419
+ import { randomUUID } from "node:crypto";
5420
+ function inCodex(tool) {
5421
+ const props = { ...tool.inputSchema.properties };
5422
+ if (tool.name === "illuminate_next") {
5423
+ return {
5424
+ ...tool,
5425
+ description: "Get the next piece of work illuminate has for you, waiting up to 40 seconds for it. Call it when a result says illuminate is still working, when a queued turn supplies a ticket, or when the person says to carry on with illuminate.",
5426
+ inputSchema: { ...tool.inputSchema, properties: { ...props, ticket: { type: "string", description: "The opaque ticket from a queued Illuminate message. Pass it exactly." } } }
5427
+ };
5428
+ }
5429
+ if (tool.name === "illuminate_map" || tool.name === "illuminate_open") {
5430
+ props.thread_id = { type: "string", description: "Pass the current chat UUID from printenv CODEX_THREAD_ID in your shell to enable questions on the map. Omit if unavailable." };
5431
+ }
5432
+ if (!props.repo) return tool;
5433
+ return { ...tool, inputSchema: { ...tool.inputSchema, properties: { ...props, repo: { type: "string", description: "The absolute path of the repo you are working in. Pass it every time." } } } };
5434
+ }
5435
+ function partsOf(t, max) {
5436
+ const parts = [];
5437
+ let cur = null;
5438
+ for (const line of t.split("\n")) {
5439
+ let rest = line;
5440
+ while (rest.length > max) {
5441
+ if (cur !== null) parts.push(cur);
5442
+ cur = null;
5443
+ parts.push(rest.slice(0, max));
5444
+ rest = rest.slice(max);
5445
+ }
5446
+ if (cur !== null && cur.length + 1 + rest.length > max) {
5447
+ parts.push(cur);
5448
+ cur = null;
5449
+ }
5450
+ cur = cur === null ? rest : `${cur}
5451
+ ${rest}`;
5452
+ }
5453
+ if (cur !== null) parts.push(cur);
5454
+ return parts;
5455
+ }
5456
+ function createCodex(kit, o) {
5457
+ const queueClient = o.queue ?? { findCommand: findQueueCommand, send: queueRequest };
5458
+ let queue = null;
5459
+ let queueCommand;
5460
+ const instance = randomUUID();
5461
+ const parts = /* @__PURE__ */ new Map();
5462
+ const settings = () => queue ? PAIRED : CODEX;
5463
+ const whereToAsk = () => queue ? "Ask questions on the map. The checked answers appear there." : "Ask in the Codex chat. Call illuminate_ask for their question.";
5464
+ const partText = (id, i, all) => [
5465
+ `[illuminate request ${id}, part ${i + 1} of ${all.length}.${i + 1 < all.length ? ` Call illuminate_more with request_id "${id}" for part ${i + 2} before you start; the output schema is at the end of the last part.` : " This is the last part."}]`,
5466
+ "",
5467
+ all[i] ?? ""
5468
+ ].join("\n");
5469
+ const deliver = (r, after = "") => {
5470
+ const whole = `${requestText(r)}${after ? `
5471
+
5472
+ ${after}` : ""}`;
5473
+ if (whole.length <= o.partChars) return whole;
5474
+ const all = partsOf(whole, o.partChars);
5475
+ parts.set(r.id, { parts: all, next: 1 });
5476
+ return partText(r.id, 0, all);
5477
+ };
5478
+ const running = async () => (await Promise.all([...kit.servers.values()].map((s) => s.catch(() => null)))).filter((s) => !!s);
5479
+ async function pageFor(url) {
5480
+ const servers = await running();
5481
+ let at = null;
5482
+ try {
5483
+ at = typeof url === "string" && url ? new URL(url) : null;
5484
+ } catch {
5485
+ at = null;
5486
+ }
5487
+ const named = at && ["127.0.0.1", "localhost"].includes(at.hostname) ? servers.find((s) => String(s.port) === at.port) : void 0;
5488
+ if (named && at) return { server: named, mapId: /^\/m\/([a-z0-9-]{1,80})\/?$/.exec(at.pathname)?.[1] ?? null };
5489
+ const latest = servers.map((server) => ({ server, seen: server.lastSeen() })).filter((x) => x.seen).sort((a, b) => b.seen.at - a.seen.at)[0];
5490
+ return latest ? { server: latest.server, mapId: null } : null;
5491
+ }
5492
+ async function pair(thread) {
5493
+ if (typeof thread !== "string" || !CHAT_ID.test(thread)) return;
5494
+ queueCommand ??= queueClient.findCommand();
5495
+ const command = await queueCommand;
5496
+ if (!command || queue?.thread === thread) return;
5497
+ const alreadyPaired = !!queue;
5498
+ queue = { command, thread };
5499
+ if (!alreadyPaired) {
5500
+ const page = settings().page;
5501
+ await Promise.all([...kit.servers.values()].map((server) => server.then((s) => s.setPageAgent(page))));
5502
+ }
5503
+ }
5504
+ async function ask(args, extra) {
5505
+ const question = String(args.question ?? "").trim();
5506
+ if (!question) return text("Pass the person's question.", true);
5507
+ const page = await pageFor(args.url);
5508
+ if (!page) return text("No illuminate map is open right now. To answer from a map, make one with illuminate_map, or open a saved one with illuminate_open.", true);
5509
+ const asked = page.server.askFromChat(question, page.mapId);
5510
+ const first = await kit.whatNext(extra);
5511
+ const about = asked.selected.length ? ` about ${asked.selected.map((n) => `"${n}"`).join(", ")} (selected on the page)` : "";
5512
+ return { ...first, content: [{ type: "text", text: `Asked on the map "${asked.mapId}"${about}.
5513
+ ` }, ...first.content] };
5514
+ }
5515
+ function more(args) {
5516
+ const id = String(args.request_id ?? "");
5517
+ const got = parts.get(id);
5518
+ if (!got) return text(`Request "${id}" didn't come in parts, or isn't waiting any more.`, true);
5519
+ const want = typeof args.part === "number" ? Math.trunc(args.part) - 1 : got.next;
5520
+ if (want < 0 || want >= got.parts.length) return text(`Request ${id} has parts 1 to ${got.parts.length}.`, true);
5521
+ got.next = Math.min(want + 1, got.parts.length - 1);
5522
+ return text(partText(id, want, got.parts));
5523
+ }
5524
+ function claim(ticket) {
5525
+ const [source, id, suffix] = ticket.split("/");
5526
+ const request = source === instance && id && suffix === void 0 ? kit.bridge.next(id) : null;
5527
+ return text(request ? deliver(request) : "That map request has already been handled or expired.");
5528
+ }
5529
+ return {
5530
+ settings,
5531
+ tools: CODEX_TOOLS,
5532
+ announce(r) {
5533
+ const target = queue;
5534
+ if (!target) return;
5535
+ setImmediate(() => {
5536
+ if (!kit.bridge.unclaimed(r.id)) return;
5537
+ void queueClient.send(target.command, target.thread, `${instance}/${r.id}`).catch(() => {
5538
+ if (kit.bridge.unclaimed(r.id)) kit.bridge.fail(r.id, "Could not queue the question. Ask again in the Codex chat.");
5539
+ });
5540
+ });
5541
+ },
5542
+ deliver,
5543
+ async beforeCall(name, args, extra) {
5544
+ if (name === "illuminate_map" || name === "illuminate_open") await pair(extra._meta?.threadId ?? args.thread_id);
5545
+ },
5546
+ async call(name, args, extra) {
5547
+ switch (name) {
5548
+ case "illuminate_ask":
5549
+ return ask(args, extra);
5550
+ case "illuminate_more":
5551
+ return more(args);
5552
+ case "illuminate_listen":
5553
+ return text("illuminate_listen isn't used in Codex. When the person asks about the map in the chat, call illuminate_ask.", true);
5554
+ case "illuminate_next":
5555
+ return typeof args.ticket === "string" ? claim(args.ticket) : null;
5556
+ default:
5557
+ return null;
5558
+ }
5559
+ },
5560
+ forget(id) {
5561
+ parts.delete(id);
5562
+ },
5563
+ closed() {
5564
+ },
5565
+ // This is also how Codex keeps waiting (calls here can't run long) while illuminate has work going.
5566
+ async idle(extra) {
5567
+ const busy = (await Promise.all([...kit.servers.values()].map((s) => s.then((x) => x.working(), () => false)))).some(Boolean);
5568
+ return busy ? kit.whatNext(extra) : text("Nothing is waiting right now.");
5569
+ },
5570
+ stillWorking: "illuminate is still working on its side. Call illuminate_next to carry on: it waits for what comes next.",
5571
+ followUp: "",
5572
+ opening: (url) => [browserLink(url), whereToAsk()].join("\n"),
5573
+ opened: (url) => [browserLink(url), whereToAsk()],
5574
+ mapsListed: 200,
5575
+ mapReady: (url) => [
5576
+ url ? browserLink(url) : "",
5577
+ queue ? `${TELL_ABOUT_MAP} They can take the walkthrough, or select any box and ask about it there.` : `${TELL_ABOUT_MAP} They can take the walkthrough, or click a box or arrow on the map and ask about it here in the chat (then call illuminate_ask).`
5578
+ ],
5579
+ answered(e, root, a) {
5580
+ if (queue && !e.fromChat) return "The checked answer is on the map. Acknowledge briefly.";
5581
+ const offer = a?.offer?.status === "pending" ? a.offer : null;
5582
+ if (offer) {
5583
+ return `That question is about a different part of the app than this map shows. The map offers ${offer.existing ? `the map that already covers it ("${offer.existing.question}"), or ` : ""}a new map for "${offer.question}". Ask the person in a sentence whether they want a new map; if they do, call illuminate_map with that question.`;
5584
+ }
5585
+ if (a) {
5586
+ return [
5587
+ "illuminate checked the answer and lit up what it is about on the map. Post the reply between the lines to the person as your answer, unchanged: keep the code blocks and line numbers exactly as they are, and add nothing about the code that isn't in it.",
5588
+ "---",
5589
+ chatReply(root, a),
5590
+ "---"
5591
+ ].join("\n");
5592
+ }
5593
+ return `The answer to "${e.question}" is shown on the map. In the chat, say at most a sentence or two.`;
5594
+ },
5595
+ // Codex keeps only so much of a tool result, and the image matters more.
5596
+ pageText: (t) => t.slice(0, 4e3),
5597
+ updateAdvice: codexUpdateAdvice
5598
+ };
5599
+ }
5600
+ var CODEX_CLIENT, CODEX, PAIRED, CODEX_INSTRUCTIONS, OWN_TOOLS, CODEX_TOOLS, codexUpdateAdvice, CHAT_ID;
5601
+ var init_codex = __esm({
5602
+ "packages/server/src/hosts/codex.ts"() {
5603
+ "use strict";
5604
+ init_common();
5605
+ init_codex_queue();
5606
+ init_codex_reply();
5607
+ CODEX_CLIENT = "codex-mcp-client";
5608
+ CODEX = {
5609
+ id: "codex",
5610
+ name: "Codex",
5611
+ page: { name: "Codex", asks: "chat", sharesSelection: true },
5612
+ claimed: "Codex is working on this in the Codex chat",
5613
+ waiting: "Waiting for Codex to pick this up",
5614
+ // Without a paired chat, Codex can't be woken from the page, so this is said as soon as it's clear nobody has it.
5615
+ notPickedUp: `Codex can't see work started on this page. In the Codex chat, say "carry on with illuminate", and it will pick this up.`,
5616
+ neverPickedUp: "Codex never picked this up, so nothing was answered. Ask in the Codex chat instead.",
5617
+ nudgeMs: 1500,
5618
+ // Codex's documented default tool timeout is 60 s; progress doesn't extend it.
5619
+ waitMs: 4e4
5620
+ };
5621
+ PAIRED = {
5622
+ ...CODEX,
5623
+ page: { name: "Codex", asks: "page", sharesSelection: true },
5624
+ nudgeMs: 3e4,
5625
+ notPickedUp: "Waiting for Codex. If the chat is idle, say \u201Ccarry on with illuminate\u201D there."
5626
+ };
5627
+ CODEX_INSTRUCTIONS = [
5628
+ "In Codex (no illuminate_listen there):",
5629
+ "- For page questions, get the current chat UUID with printenv CODEX_THREAD_ID. Pass it as thread_id to illuminate_map or illuminate_open if available. A queued map message names a ticket: call illuminate_next with that ticket.",
5630
+ "- Pass `repo`, the absolute path of the project, to illuminate_map and illuminate_open. illuminate opens their default browser. Give them the link in case the tab didn't appear. A question sent from the map gets its checked answer on the map.",
5631
+ "- When the person asks about the map in the chat (the map, a box or arrow, what they selected, a walkthrough step), call illuminate_ask with their question and the page's current URL if you know it. illuminate adds what they selected on the page.",
5632
+ "- A long request comes in parts: read every part with illuminate_more before you start. If a result says illuminate is still working, or the person says to carry on with illuminate, call illuminate_next."
5633
+ ];
5634
+ OWN_TOOLS = [
5635
+ {
5636
+ name: "illuminate_ask",
5637
+ description: "Ask illuminate a question the person asked in this chat about an illuminate map that is open in the browser. illuminate adds what they have selected on the page and starts the answer; returns the first piece of work for you to do. Post the checked reply in the chat when instructed.",
5638
+ annotations: local("Ask about the open map"),
5639
+ inputSchema: {
5640
+ type: "object",
5641
+ properties: {
5642
+ question: { type: "string", maxLength: 2e3, description: "The person's question, in their own words." },
5643
+ url: { type: "string", description: "The map page's current URL in the browser (http://127.0.0.1:\u2026/m/\u2026), if you know it." }
5644
+ },
5645
+ required: ["question"]
5646
+ }
5647
+ },
5648
+ {
5649
+ name: "illuminate_more",
5650
+ description: "Read the next part of an illuminate request that came in parts. Read every part before you start on it.",
5651
+ annotations: local("Read the rest of a request", true),
5652
+ inputSchema: {
5653
+ type: "object",
5654
+ properties: {
5655
+ request_id: { type: "string" },
5656
+ part: { type: "number", description: "Which part (2 for the second). Leave out for the next one." }
5657
+ },
5658
+ required: ["request_id"]
5659
+ }
5660
+ }
5661
+ ];
5662
+ CODEX_TOOLS = withHostTools(OWN_TOOLS, inCodex);
5663
+ codexUpdateAdvice = () => "How to update depends on how they added illuminate to Codex; the README's Codex section says how. Don't change their setup yourself.";
5664
+ CHAT_ID = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
5665
+ }
5666
+ });
5667
+
5668
+ // packages/server/src/host.ts
5669
+ function hostIdOf(client) {
5670
+ return client?.name === CODEX_CLIENT ? "codex" : "claude-code";
5671
+ }
5672
+ var init_host = __esm({
5673
+ "packages/server/src/host.ts"() {
5674
+ "use strict";
5675
+ init_claude_code();
5676
+ init_codex();
5677
+ }
5678
+ });
5679
+
5680
+ // packages/server/src/bridge.ts
5681
+ function createBridge(o) {
5682
+ const host = o.host ?? (() => CLAUDE_CODE);
5683
+ const giveUpMs = o.giveUpMs ?? 5 * 6e4;
5684
+ const entries = [];
5685
+ const waiters = [];
5686
+ let n = 0;
5687
+ const agent = (req) => new Promise((resolve5, reject) => {
5688
+ if (req.signal?.aborted) return reject(new Error("Stopped."));
5689
+ const h = host();
5690
+ const entry = {
5691
+ id: `r${++n}`,
5692
+ label: req.label ?? "Work for illuminate",
5693
+ prompt: req.prompt,
5694
+ schema: req.schema,
5695
+ tools: req.tools ?? ["Read", "Grep", "Glob"],
5696
+ continues: !!req.resume,
5697
+ handed: false,
5698
+ claimed: () => req.onProgress?.({ kind: "status", text: h.claimed }),
5699
+ timers: [],
5700
+ resolve: (r) => {
5701
+ settle(entry);
5702
+ resolve5(r);
5703
+ },
5704
+ reject: (e) => {
5705
+ settle(entry);
5706
+ reject(e);
5707
+ }
5708
+ };
5709
+ entries.push(entry);
5710
+ req.signal?.addEventListener("abort", () => entry.reject(new Error("Stopped.")), { once: true });
5711
+ const waiter = waiters.pop();
5712
+ if (waiter) {
5713
+ entry.handed = true;
5714
+ entry.claimed();
5715
+ waiter(entry);
5716
+ return;
5717
+ }
5718
+ req.onProgress?.({ kind: "status", text: h.waiting });
5719
+ const later = (ms, f) => {
5720
+ const t = setTimeout(() => {
5721
+ if (!entry.handed && entries.includes(entry)) f();
5722
+ }, ms);
5723
+ t.unref?.();
5724
+ entry.timers.push(t);
5725
+ };
5726
+ later(o.nudgeMs ?? h.nudgeMs, () => req.onProgress?.({ kind: "status", text: h.notPickedUp }));
5727
+ later(giveUpMs, () => entry.reject(Object.assign(new Error(h.neverPickedUp), { unheard: true })));
5728
+ o.announce(view(entry));
5729
+ });
5730
+ function settle(e) {
5731
+ const i = entries.indexOf(e);
5732
+ if (i >= 0) entries.splice(i, 1);
5733
+ for (const t of e.timers) clearTimeout(t);
5734
+ e.timers = [];
5735
+ }
5736
+ const take = (id) => {
5737
+ const e = entries.find((x) => !x.handed && (!id || x.id === id)) ?? null;
5738
+ if (e) {
5739
+ e.handed = true;
5740
+ e.claimed();
5741
+ }
5742
+ return e;
5743
+ };
5744
+ return {
5745
+ agent,
5746
+ unclaimed(id) {
5747
+ return entries.some((e) => e.id === id && !e.handed);
5748
+ },
5749
+ next(id) {
5750
+ const e = take(id) ?? (id ? null : entries[0]) ?? null;
5751
+ return e ? view(e) : null;
5752
+ },
5753
+ waitForNext(signal) {
5754
+ const now = take();
5755
+ if (now) return Promise.resolve(view(now));
5756
+ if (signal.aborted) return Promise.resolve(null);
5757
+ return new Promise((resolve5) => {
5758
+ const waiter = (e) => {
5759
+ signal.removeEventListener("abort", onAbort);
5760
+ resolve5(view(e));
5761
+ };
5762
+ const onAbort = () => {
5763
+ const i = waiters.indexOf(waiter);
5764
+ if (i >= 0) waiters.splice(i, 1);
5765
+ resolve5(null);
5766
+ };
5767
+ waiters.push(waiter);
5768
+ signal.addEventListener("abort", onAbort, { once: true });
5769
+ });
5770
+ },
5771
+ submit(id, output) {
5772
+ const e = entries.find((x) => x.id === id);
5773
+ if (!e) return { ok: false, problems: [`No request "${id}" is waiting. It may have been answered already, or stopped.`] };
5774
+ let value = output;
5775
+ if (typeof value === "string") {
5776
+ try {
5777
+ value = JSON.parse(value);
5778
+ } catch {
5200
5779
  return { ok: false, problems: ["`output` must be a JSON object matching the schema, not text."] };
5201
5780
  }
5202
5781
  }
@@ -5239,7 +5818,7 @@ import { spawn as spawn2 } from "node:child_process";
5239
5818
  import * as crypto5 from "node:crypto";
5240
5819
  import * as fs13 from "node:fs";
5241
5820
  import * as os2 from "node:os";
5242
- import * as path9 from "node:path";
5821
+ import * as path10 from "node:path";
5243
5822
  import { pathToFileURL } from "node:url";
5244
5823
  import { WebSocket } from "ws";
5245
5824
  function findChrome() {
@@ -5264,11 +5843,11 @@ function resolveTarget(root, target) {
5264
5843
  const realRoot = fs13.realpathSync(root);
5265
5844
  let real;
5266
5845
  try {
5267
- real = fs13.realpathSync(path9.join(realRoot, rel));
5846
+ real = fs13.realpathSync(path10.join(realRoot, rel));
5268
5847
  } catch {
5269
5848
  return { ok: false, reason: `${rel} doesn't exist.` };
5270
5849
  }
5271
- if (!real.startsWith(realRoot + path9.sep)) return { ok: false, reason: "`file` must be inside the repo." };
5850
+ if (!real.startsWith(realRoot + path10.sep)) return { ok: false, reason: "`file` must be inside the repo." };
5272
5851
  return { ok: true, url: pathToFileURL(real).href, source: { kind: "file", file: rel } };
5273
5852
  }
5274
5853
  async function capture(root, target, shoot = shootWithChrome) {
@@ -5292,7 +5871,7 @@ async function capture(root, target, shoot = shootWithChrome) {
5292
5871
  elements: shot.elements
5293
5872
  };
5294
5873
  const p = capturePaths(fs13.realpathSync(root), id);
5295
- fs13.mkdirSync(path9.dirname(p.image), { recursive: true });
5874
+ fs13.mkdirSync(path10.dirname(p.image), { recursive: true });
5296
5875
  fs13.writeFileSync(p.image, shot.png);
5297
5876
  fs13.writeFileSync(p.record, `${JSON.stringify(record, null, 2)}
5298
5877
  `);
@@ -5311,14 +5890,14 @@ async function probe(port) {
5311
5890
  async function listScreens(root, o = {}) {
5312
5891
  const files = listRepoFiles(root, [...DEFAULT_IGNORE]).filter((f) => !isSecretPath(f));
5313
5892
  const html = files.filter((f) => /\.html?$/i.test(f));
5314
- const images = files.filter((f) => IMAGE_TYPES[path9.extname(f).toLowerCase()]);
5893
+ const images = files.filter((f) => IMAGE_TYPES[path10.extname(f).toLowerCase()]);
5315
5894
  const stories = files.filter((f) => /\.stories\.[jt]sx?$|\.stories\.mdx$/.test(f));
5316
5895
  const scenes = files.filter((f) => /\.(tscn|unity|prefab)$/.test(f));
5317
5896
  const ports = (o.ports ?? COMMON_PORTS).filter((p) => !(o.skipPorts ?? []).includes(p));
5318
5897
  const pages = (await Promise.all(ports.map(probe))).filter((p) => !!p);
5319
5898
  let scripts = {};
5320
5899
  try {
5321
- scripts = JSON.parse(fs13.readFileSync(path9.join(root, "package.json"), "utf8")).scripts ?? {};
5900
+ scripts = JSON.parse(fs13.readFileSync(path10.join(root, "package.json"), "utf8")).scripts ?? {};
5322
5901
  } catch {
5323
5902
  }
5324
5903
  const few = (list, max) => [...list.slice(0, max).map((f) => ` - ${f}`), ...list.length > max ? [` - \u2026and ${list.length - max} more`] : []];
@@ -5386,7 +5965,7 @@ var init_screens2 = __esm({
5386
5965
  shootWithChrome = async (url) => {
5387
5966
  const chrome = findChrome();
5388
5967
  if (!chrome) throw new Error("No Chrome, Chromium, Edge or Brave was found on this machine, so no screen can be captured. Use an image file or a sketch instead.");
5389
- const profile = fs13.mkdtempSync(path9.join(os2.tmpdir(), "illuminate-chrome-"));
5968
+ const profile = fs13.mkdtempSync(path10.join(os2.tmpdir(), "illuminate-chrome-"));
5390
5969
  let child = null;
5391
5970
  let ws = null;
5392
5971
  try {
@@ -5430,108 +6009,43 @@ var init_screens2 = __esm({
5430
6009
  });
5431
6010
  let n = 0;
5432
6011
  const waiting = /* @__PURE__ */ new Map();
5433
- const events = /* @__PURE__ */ new Map();
5434
- socket.on("message", (data) => {
5435
- const m = JSON.parse(String(data));
5436
- if (m.id !== void 0) {
5437
- const w = waiting.get(m.id);
5438
- waiting.delete(m.id);
5439
- if (m.error) w?.reject(new Error(m.error.message));
5440
- else w?.resolve(m.result ?? {});
5441
- } else if (m.method) events.get(m.method)?.();
5442
- });
5443
- const send = (method, params = {}, sessionId2) => new Promise((resolve5, reject) => {
5444
- const id = ++n;
5445
- waiting.set(id, { resolve: resolve5, reject });
5446
- socket.send(JSON.stringify({ id, method, params, ...sessionId2 ? { sessionId: sessionId2 } : {} }));
5447
- });
5448
- const { targetId } = await send("Target.createTarget", { url: "about:blank" });
5449
- const { sessionId } = await send("Target.attachToTarget", { targetId, flatten: true });
5450
- await send("Page.enable", {}, sessionId);
5451
- await send("Emulation.setDeviceMetricsOverride", { width: CAPTURE_WIDTH, height: CAPTURE_HEIGHT, deviceScaleFactor: 1, mobile: false }, sessionId);
5452
- const loaded = new Promise((resolve5) => {
5453
- events.set("Page.loadEventFired", resolve5);
5454
- setTimeout(resolve5, 15e3);
5455
- });
5456
- const nav = await send("Page.navigate", { url }, sessionId);
5457
- if (typeof nav.errorText === "string" && nav.errorText) throw new Error(`The page couldn't be opened (${nav.errorText}). Is it running?`);
5458
- await loaded;
5459
- await new Promise((r) => setTimeout(r, 700));
5460
- const read = await send("Runtime.evaluate", { expression: READ_PAGE, returnByValue: true }, sessionId);
5461
- const page = JSON.parse(read.result?.value ?? "{}");
5462
- const shot = await send("Page.captureScreenshot", { format: "png" }, sessionId);
5463
- return { png: Buffer.from(shot.data, "base64"), title: page.title ?? "", text: page.text ?? "", elements: page.elements ?? [] };
5464
- } finally {
5465
- ws?.close();
5466
- child?.kill("SIGKILL");
5467
- setTimeout(() => fs13.rm(profile, { recursive: true, force: true }, () => {
5468
- }), 500).unref?.();
5469
- }
5470
- };
5471
- }
5472
- });
5473
-
5474
- // packages/server/src/reply.ts
5475
- import * as path10 from "node:path";
5476
- function excerpt(b) {
5477
- const marked = b.notes.length ? b.notes.map((n) => n.line) : b.cited;
5478
- const end = b.start + b.lines.length - 1;
5479
- let from = Math.max(b.start, Math.min(...marked) - AROUND);
5480
- let to = Math.min(end, Math.max(...marked) + AROUND);
5481
- if (to - from + 1 > MAX_LINES3) to = from + MAX_LINES3 - 1;
5482
- if (!marked.length) [from, to] = [b.start, Math.min(end, b.start + MAX_LINES3 - 1)];
5483
- return { start: from, lines: b.lines.slice(from - b.start, to - b.start + 1) };
5484
- }
5485
- function blockText(b) {
5486
- const { start, lines } = excerpt(b);
5487
- const width = String(start + lines.length - 1).length;
5488
- const numbered = lines.map((l, i) => `${String(start + i).padStart(width)} ${l}`).join("\n");
5489
- const where = `\`${b.file}\`${b.name ? ` \xB7 ${b.name}` : ""} (lines ${start}\u2013${start + lines.length - 1})`;
5490
- const notes = b.notes.filter((n) => n.line >= start && n.line < start + lines.length).map((n) => `- Line ${n.line}: ${n.note}`);
5491
- return [where, `\`\`\`${LANG[path10.extname(b.file)] ?? ""}`, numbered, "```", ...notes].join("\n");
5492
- }
5493
- function chatReply(root, a) {
5494
- const parts = [a.concept.trim()];
5495
- const unconfirmed = a.refs.filter((r) => r.status === "unconfirmed").map((r) => r.id);
5496
- if (unconfirmed.length) parts.push(`_Not confirmed against the code: ${unconfirmed.join(", ")}._`);
5497
- if (a.notes?.length) {
5498
- const view2 = codeForNotes(root, a.notes);
5499
- const blocks = view2.blocks.slice(0, MAX_BLOCKS2).map(blockText);
5500
- if (blocks.length) parts.push(blocks.join("\n\n"));
5501
- if (view2.missing) parts.push(`_${view2.missing} of the lines it points at aren't in the code any more, so they're left out._`);
5502
- }
5503
- if (a.fix) parts.push("A fix is proposed on the map: approve or reject it there.");
5504
- return parts.join("\n\n");
5505
- }
5506
- var AROUND, MAX_LINES3, MAX_BLOCKS2, LANG;
5507
- var init_reply = __esm({
5508
- "packages/server/src/reply.ts"() {
5509
- "use strict";
5510
- init_src2();
5511
- AROUND = 3;
5512
- MAX_LINES3 = 30;
5513
- MAX_BLOCKS2 = 4;
5514
- LANG = {
5515
- ".ts": "ts",
5516
- ".tsx": "tsx",
5517
- ".js": "js",
5518
- ".jsx": "jsx",
5519
- ".mjs": "js",
5520
- ".cjs": "js",
5521
- ".py": "python",
5522
- ".go": "go",
5523
- ".rs": "rust",
5524
- ".java": "java",
5525
- ".rb": "ruby",
5526
- ".sol": "solidity",
5527
- ".css": "css",
5528
- ".html": "html",
5529
- ".json": "json",
5530
- ".sql": "sql",
5531
- ".sh": "bash",
5532
- ".yml": "yaml",
5533
- ".yaml": "yaml",
5534
- ".md": "markdown"
6012
+ const events = /* @__PURE__ */ new Map();
6013
+ socket.on("message", (data) => {
6014
+ const m = JSON.parse(String(data));
6015
+ if (m.id !== void 0) {
6016
+ const w = waiting.get(m.id);
6017
+ waiting.delete(m.id);
6018
+ if (m.error) w?.reject(new Error(m.error.message));
6019
+ else w?.resolve(m.result ?? {});
6020
+ } else if (m.method) events.get(m.method)?.();
6021
+ });
6022
+ const send = (method, params = {}, sessionId2) => new Promise((resolve5, reject) => {
6023
+ const id = ++n;
6024
+ waiting.set(id, { resolve: resolve5, reject });
6025
+ socket.send(JSON.stringify({ id, method, params, ...sessionId2 ? { sessionId: sessionId2 } : {} }));
6026
+ });
6027
+ const { targetId } = await send("Target.createTarget", { url: "about:blank" });
6028
+ const { sessionId } = await send("Target.attachToTarget", { targetId, flatten: true });
6029
+ await send("Page.enable", {}, sessionId);
6030
+ await send("Emulation.setDeviceMetricsOverride", { width: CAPTURE_WIDTH, height: CAPTURE_HEIGHT, deviceScaleFactor: 1, mobile: false }, sessionId);
6031
+ const loaded = new Promise((resolve5) => {
6032
+ events.set("Page.loadEventFired", resolve5);
6033
+ setTimeout(resolve5, 15e3);
6034
+ });
6035
+ const nav = await send("Page.navigate", { url }, sessionId);
6036
+ if (typeof nav.errorText === "string" && nav.errorText) throw new Error(`The page couldn't be opened (${nav.errorText}). Is it running?`);
6037
+ await loaded;
6038
+ await new Promise((r) => setTimeout(r, 700));
6039
+ const read = await send("Runtime.evaluate", { expression: READ_PAGE, returnByValue: true }, sessionId);
6040
+ const page = JSON.parse(read.result?.value ?? "{}");
6041
+ const shot = await send("Page.captureScreenshot", { format: "png" }, sessionId);
6042
+ return { png: Buffer.from(shot.data, "base64"), title: page.title ?? "", text: page.text ?? "", elements: page.elements ?? [] };
6043
+ } finally {
6044
+ ws?.close();
6045
+ child?.kill("SIGKILL");
6046
+ setTimeout(() => fs13.rm(profile, { recursive: true, force: true }, () => {
6047
+ }), 500).unref?.();
6048
+ }
5535
6049
  };
5536
6050
  }
5537
6051
  });
@@ -5550,110 +6064,25 @@ import * as fs14 from "node:fs";
5550
6064
  import * as path11 from "node:path";
5551
6065
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
5552
6066
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5553
- import {
5554
- CallToolRequestSchema,
5555
- ListToolsRequestSchema
5556
- } from "@modelcontextprotocol/sdk/types.js";
6067
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
5557
6068
  function toolsFor(host) {
5558
- if (host.id !== "codex") return TOOLS;
5559
- const withRepo = (t) => {
5560
- const props = t.inputSchema.properties ?? {};
5561
- if (!props.repo) return t;
5562
- return { ...t, inputSchema: { ...t.inputSchema, properties: { ...props, repo: { type: "string", description: "The absolute path of the repo you are working in. Pass it every time." } } } };
5563
- };
5564
- const shared = TOOLS.filter((t) => t.name !== "illuminate_listen").map((t) => withRepo({ ...t, ...CODEX_TOOLS[t.name] }));
5565
- const at = shared.findIndex((t) => t.name === "illuminate_fail") + 1;
5566
- return [...shared.slice(0, at), ...CODEX_ONLY, ...shared.slice(at)];
5567
- }
5568
- function requestText(r) {
5569
- return [
5570
- `## illuminate request ${r.id}: ${r.label}`,
5571
- "",
5572
- `When you're done, call illuminate_submit with request_id "${r.id}" and \`output\`: a JSON object matching the schema at the end. Don't edit any files.`,
5573
- r.tools.length ? "" : "Answer from what is in this request alone. Don't read the code for this one.",
5574
- r.continues ? "This follows on from your earlier work for illuminate in this conversation." : "",
5575
- "",
5576
- "---",
5577
- r.prompt,
5578
- "---",
5579
- "",
5580
- "## Output schema (JSON Schema)",
5581
- JSON.stringify(r.schema)
5582
- ].filter((line, i, all) => line !== "" || all[i - 1] !== "").join("\n");
5583
- }
5584
- function partsOf(t, max) {
5585
- const parts = [];
5586
- let cur = null;
5587
- for (const line of t.split("\n")) {
5588
- let rest = line;
5589
- while (rest.length > max) {
5590
- if (cur !== null) parts.push(cur);
5591
- cur = null;
5592
- parts.push(rest.slice(0, max));
5593
- rest = rest.slice(max);
5594
- }
5595
- if (cur !== null && cur.length + 1 + rest.length > max) {
5596
- parts.push(cur);
5597
- cur = null;
5598
- }
5599
- cur = cur === null ? rest : `${cur}
5600
- ${rest}`;
5601
- }
5602
- if (cur !== null) parts.push(cur);
5603
- return parts;
6069
+ return TOOLS_BY_HOST[host.id];
5604
6070
  }
5605
6071
  function createChannel(o) {
5606
6072
  const open = o.open ?? openBrowser;
5607
- const host = () => hostOf(mcp.getClientVersion());
5608
- const codex = () => host().id === "codex";
5609
- const waitMs = () => o.waitMs ?? host().waitMs;
5610
- const partChars = o.partChars ?? 28e3;
5611
6073
  const heartbeatMs = o.heartbeatMs ?? 3e4;
5612
- const listenMs = o.listenMs ?? 25 * 6e4;
5613
- const quietListens = o.quietListens ?? 5;
5614
- let quiet = 0;
5615
6074
  const servers = /* @__PURE__ */ new Map();
5616
- const closedListeners = /* @__PURE__ */ new Set();
5617
6075
  const finished = /* @__PURE__ */ new Set();
5618
6076
  const lastReport = /* @__PURE__ */ new Map();
5619
6077
  const lastAnswer = /* @__PURE__ */ new Map();
5620
- const parts = /* @__PURE__ */ new Map();
5621
- let updateChecked = false;
5622
- const updateNote = async () => {
5623
- if (updateChecked) return null;
5624
- updateChecked = true;
5625
- const newer = await Promise.race([(o.checkUpdate ?? checkForUpdate)(), new Promise((r) => setTimeout(() => r(null), 1500).unref?.())]);
5626
- return newer ? updateMessage(newer, o.via ?? "mcp", host().id) : null;
5627
- };
5628
6078
  const mcp = new Server(
5629
6079
  { name: "illuminate", version: VERSION ?? "0.0.0-dev" },
5630
6080
  { capabilities: { experimental: { "claude/channel": {} }, tools: {} }, instructions: CHANNEL_INSTRUCTIONS }
5631
6081
  );
5632
- const bridge = createBridge({
5633
- host,
5634
- announce: (r) => {
5635
- if (codex()) return;
5636
- void mcp.notification({
5637
- method: "notifications/claude/channel",
5638
- params: { content: `illuminate has work for you: ${r.label}. Call illuminate_next to get it.`, meta: { request_id: r.id } }
5639
- }).catch(() => {
5640
- });
5641
- }
5642
- });
5643
- const deliver = (r, after = "") => {
5644
- const whole = `${requestText(r)}${after ? `
5645
-
5646
- ${after}` : ""}`;
5647
- if (!codex() || whole.length <= partChars) return whole;
5648
- const all = partsOf(whole, partChars);
5649
- parts.set(r.id, { parts: all, next: 1 });
5650
- return partText(r.id, 0, all);
5651
- };
5652
- const partText = (id, i, all) => [
5653
- `[illuminate request ${id}, part ${i + 1} of ${all.length}.${i + 1 < all.length ? ` Call illuminate_more with request_id "${id}" for part ${i + 2} before you start; the output schema is at the end of the last part.` : " This is the last part."}]`,
5654
- "",
5655
- all[i] ?? ""
5656
- ].join("\n");
6082
+ let hosts = null;
6083
+ const host = () => hosts[hostIdOf(mcp.getClientVersion())];
6084
+ const waitMs = () => o.waitMs ?? host().settings().waitMs;
6085
+ const bridge = createBridge({ host: () => host().settings(), announce: (r) => host().announce(r) });
5657
6086
  const rootOf2 = (repo) => {
5658
6087
  const dir = path11.resolve(o.root, typeof repo === "string" && repo.trim() ? repo : ".");
5659
6088
  if (!fs14.existsSync(dir) || !fs14.statSync(dir).isDirectory()) throw new Error(`No such folder: ${dir}`);
@@ -5666,13 +6095,13 @@ ${after}` : ""}`;
5666
6095
  root,
5667
6096
  port: o.port ?? PORT,
5668
6097
  agent: bridge.agent,
5669
- page: host().page,
5670
- // Stop, or closing the last tab, stops the page's server and ends listening. The MCP server itself stays
5671
- // connected, so the next illuminate tool call starts a new page server.
6098
+ page: host().settings().page,
6099
+ // Stop, or closing the last tab, stops the page's server. The MCP server itself stays connected, so the next
6100
+ // illuminate tool call starts a new page server.
5672
6101
  autoStop: { afterLastTabMs: o.afterLastTabMs ?? 5e3 },
5673
6102
  onStop: () => {
5674
6103
  servers.delete(root);
5675
- if (!servers.size) for (const l of [...closedListeners]) l();
6104
+ if (!servers.size) host().closed();
5676
6105
  },
5677
6106
  onEvent: (e) => void onEvent(root, e)
5678
6107
  });
@@ -5681,9 +6110,6 @@ ${after}` : ""}`;
5681
6110
  }
5682
6111
  return s;
5683
6112
  };
5684
- const portNote = (s) => codex() && (o.port ?? PORT) === PORT && s.port !== PORT ? `illuminate is on port ${s.port} this time, since ${PORT} was taken, so the browser may ask again whether to open it.` : "";
5685
- const showInCodex = (url) => `Give the person this link: ${url}
5686
- If you have a built-in browser, open the link there, so the map sits beside this chat; don't open it in another browser.`;
5687
6113
  async function onEvent(root, e) {
5688
6114
  if (e.type === "map") lastReport.set(e.mapId, {
5689
6115
  confirmed: e.report.summary.confirmed,
@@ -5692,29 +6118,19 @@ If you have a built-in browser, open the link there, so the map sits beside this
5692
6118
  });
5693
6119
  if (e.type === "answer") lastAnswer.set(e.mapId, e.answer);
5694
6120
  if (e.type !== "job" || e.status === "started") return;
5695
- const listen = codex() ? "" : "Then call illuminate_listen so questions they ask on the map reach you.";
6121
+ const h = host();
5696
6122
  let message;
5697
- if (e.status === "failed") message = [`illuminate couldn't finish "${e.question}": ${e.error ?? "unknown error"}`, listen].filter(Boolean).join("\n");
6123
+ if (e.status === "failed") message = [`illuminate couldn't finish "${e.question}": ${e.error ?? "unknown error"}`, h.followUp].filter(Boolean).join("\n");
5698
6124
  else if (e.job === "make") {
5699
6125
  const s = await servers.get(root);
5700
6126
  const r = lastReport.get(e.mapId);
5701
6127
  message = [
5702
6128
  `The map for "${e.question}" is ready${r ? `: ${r.confirmed} of ${r.claims} claims confirmed against the code` : ""}.`,
5703
6129
  r?.hidden.length ? `Screens left out because they didn't check out: ${r.hidden.join(", ")}.` : "",
5704
- s ? codex() ? showInCodex(s.pageUrl(e.mapId)) : `It's open in the browser: ${s.pageUrl(e.mapId)}` : "",
5705
- codex() ? "Tell the person in a sentence; the map does the explaining. They can take the walkthrough, or click a box or arrow on the map and ask about it here in the chat (then call illuminate_ask)." : "Tell the person in a sentence; the map does the explaining. They can take the walkthrough, or select any box and ask about it there.",
5706
- listen
6130
+ ...h.mapReady(s ? s.pageUrl(e.mapId) : null),
6131
+ h.followUp
5707
6132
  ].filter(Boolean).join("\n");
5708
- } else if (codex()) {
5709
- const a = lastAnswer.get(e.mapId);
5710
- const offer = a?.offer?.status === "pending" ? a.offer : null;
5711
- message = offer ? `That question is about a different part of the app than this map shows. The map offers ${offer.existing ? `the map that already covers it ("${offer.existing.question}"), or ` : ""}a new map for "${offer.question}". Ask the person in a sentence whether they want a new map; if they do, call illuminate_map with that question.` : a ? [
5712
- "illuminate checked the answer and lit up what it is about on the map. Post the reply between the lines to the person as your answer, unchanged: keep the code blocks and line numbers exactly as they are, and add nothing about the code that isn't in it.",
5713
- "---",
5714
- chatReply(root, a),
5715
- "---"
5716
- ].join("\n") : `The answer to "${e.question}" is shown on the map. In the chat, say at most a sentence or two.`;
5717
- } else message = `The answer to "${e.question}" is shown on the map. Call illuminate_listen again for their next question.`;
6133
+ } else message = h.answered(e, root, lastAnswer.get(e.mapId));
5718
6134
  for (const f of [...finished]) f(message);
5719
6135
  }
5720
6136
  function keepAlive(extra) {
@@ -5746,10 +6162,9 @@ If you have a built-in browser, open the link there, so the map sits beside this
5746
6162
  done.then((message) => ({ message })),
5747
6163
  timer
5748
6164
  ]);
5749
- if (winner && "request" in winner) return text(deliver(winner.request));
6165
+ if (winner && "request" in winner) return text(host().deliver(winner.request));
5750
6166
  if (winner && "message" in winner) return text(winner.message);
5751
- if (codex()) return text("illuminate is still working on its side. Call illuminate_next to carry on: it waits for what comes next.");
5752
- return text("illuminate is still working on its side. Call illuminate_listen: it returns when there is something for you.");
6167
+ return text(host().stillWorking);
5753
6168
  } finally {
5754
6169
  stop();
5755
6170
  extra.signal.removeEventListener("abort", onAbort);
@@ -5757,24 +6172,33 @@ If you have a built-in browser, open the link there, so the map sits beside this
5757
6172
  if (onFinish) finished.delete(onFinish);
5758
6173
  }
5759
6174
  }
5760
- mcp.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: toolsFor(host()).map((t) => ({ ...t })) }));
5761
- async function pageFor(url) {
5762
- const running = (await Promise.all([...servers.values()].map((s) => s.catch(() => null)))).filter((s) => !!s);
5763
- let at = null;
5764
- try {
5765
- at = typeof url === "string" && url ? new URL(url) : null;
5766
- } catch {
5767
- at = null;
5768
- }
5769
- const named = at && ["127.0.0.1", "localhost"].includes(at.hostname) ? running.find((s) => String(s.port) === at.port) : void 0;
5770
- if (named && at) return { server: named, mapId: /^\/m\/([a-z0-9-]{1,80})\/?$/.exec(at.pathname)?.[1] ?? null };
5771
- const latest = running.map((server) => ({ server, seen: server.lastSeen() })).filter((x) => x.seen).sort((a, b) => b.seen.at - a.seen.at)[0];
5772
- return latest ? { server: latest.server, mapId: null } : null;
5773
- }
6175
+ const kit = {
6176
+ bridge,
6177
+ servers,
6178
+ whatNext,
6179
+ keepAlive,
6180
+ notify: (n) => mcp.notification(n)
6181
+ };
6182
+ hosts = {
6183
+ "claude-code": createClaudeCode(kit, { listenMs: o.listenMs ?? 25 * 6e4, quietListens: o.quietListens ?? 5 }),
6184
+ codex: createCodex(kit, { partChars: o.partChars ?? 28e3, queue: o.queue })
6185
+ };
6186
+ let updateChecked = false;
6187
+ const updateNote = async () => {
6188
+ if (updateChecked) return null;
6189
+ updateChecked = true;
6190
+ const newer = await Promise.race([(o.checkUpdate ?? checkForUpdate)(), new Promise((r) => setTimeout(() => r(null), 1500).unref?.())]);
6191
+ const via = o.via ?? "mcp";
6192
+ return newer ? updateMessage(newer, via, host().updateAdvice(via)) : null;
6193
+ };
6194
+ mcp.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: host().tools.map((t) => ({ ...t })) }));
5774
6195
  mcp.setRequestHandler(CallToolRequestSchema, async (req, extra) => {
5775
6196
  const args = req.params.arguments ?? {};
5776
- if (req.params.name !== "illuminate_listen") quiet = 0;
6197
+ const h = host();
5777
6198
  try {
6199
+ await h.beforeCall(req.params.name, args, extra);
6200
+ const own = await h.call(req.params.name, args, extra);
6201
+ if (own) return own;
5778
6202
  switch (req.params.name) {
5779
6203
  case "illuminate_map": {
5780
6204
  const question = String(args.question ?? "").trim();
@@ -5783,95 +6207,36 @@ If you have a built-in browser, open the link there, so the map sits beside this
5783
6207
  const id = server.startMap(question);
5784
6208
  const next = whatNext(extra);
5785
6209
  const url = server.pageUrl(id);
5786
- if (!codex()) open(url);
6210
+ open(url);
5787
6211
  const [first, update] = await Promise.all([next, updateNote()]);
5788
- const opening = codex() ? [`The map is being made. ${showInCodex(url)} The person can watch it being drawn while you work.`, portNote(server)].filter(Boolean).join("\n") : `The map is opening in the browser: ${url}
5789
- Tell the person, and give them the link in case the tab didn't appear.`;
5790
6212
  return {
5791
6213
  ...first,
5792
6214
  content: [
5793
- { type: "text", text: `${opening}
6215
+ { type: "text", text: `${h.opening(url)}
5794
6216
  ` },
5795
6217
  ...first.content,
5796
6218
  ...update ? [{ type: "text", text: update }] : []
5797
6219
  ]
5798
6220
  };
5799
6221
  }
5800
- case "illuminate_ask": {
5801
- const question = String(args.question ?? "").trim();
5802
- if (!question) return text("Pass the person's question.", true);
5803
- const page = await pageFor(args.url);
5804
- if (!page) return text("No illuminate map is open right now. To answer from a map, make one with illuminate_map, or open a saved one with illuminate_open.", true);
5805
- const asked = page.server.askFromChat(question, page.mapId);
5806
- const first = await whatNext(extra);
5807
- const about = asked.selected.length ? ` about ${asked.selected.map((n) => `"${n}"`).join(", ")} (selected on the page)` : "";
5808
- return { ...first, content: [{ type: "text", text: `Asked on the map "${asked.mapId}"${about}.
5809
- ` }, ...first.content] };
5810
- }
5811
- case "illuminate_more": {
5812
- const id = String(args.request_id ?? "");
5813
- const got = parts.get(id);
5814
- if (!got) return text(`Request "${id}" didn't come in parts, or isn't waiting any more.`, true);
5815
- const want = typeof args.part === "number" ? Math.trunc(args.part) - 1 : got.next;
5816
- if (want < 0 || want >= got.parts.length) return text(`Request ${id} has parts 1 to ${got.parts.length}.`, true);
5817
- got.next = Math.min(want + 1, got.parts.length - 1);
5818
- return text(partText(id, want, got.parts));
5819
- }
5820
- case "illuminate_listen": {
5821
- if (codex()) return text("illuminate_listen isn't used in Codex. When the person asks about the map in the chat, call illuminate_ask.", true);
5822
- if (!servers.size) return text(CLOSED);
5823
- const stop = keepAlive(extra);
5824
- let closed = false;
5825
- const onClosed = () => {
5826
- closed = true;
5827
- ac.abort();
5828
- };
5829
- const ac = new AbortController();
5830
- const onAbort = () => ac.abort();
5831
- extra.signal.addEventListener("abort", onAbort, { once: true });
5832
- const timer = setTimeout(() => ac.abort(), listenMs);
5833
- closedListeners.add(onClosed);
5834
- try {
5835
- const r = await bridge.waitForNext(ac.signal);
5836
- if (r) {
5837
- quiet = 0;
5838
- return text(deliver(r, "After illuminate_submit, call illuminate_listen again so questions on the map keep reaching you."));
5839
- }
5840
- if (closed) return text(CLOSED);
5841
- if (extra.signal.aborted) return text("Stopped listening. Questions asked on the map wait until you call illuminate_listen again.");
5842
- quiet++;
5843
- if (quiet >= quietListens) {
5844
- quiet = 0;
5845
- return text("Nobody has asked on the map for about two hours, so illuminate stopped listening. Don't call illuminate_listen again unless the person asks you to listen, or asks for a map. Say nothing to the person about this.");
5846
- }
5847
- return text("Nothing was asked on the map yet. Call illuminate_listen again to keep listening, and say nothing to the person about it.");
5848
- } finally {
5849
- closedListeners.delete(onClosed);
5850
- clearTimeout(timer);
5851
- extra.signal.removeEventListener("abort", onAbort);
5852
- stop();
5853
- }
5854
- }
5855
6222
  case "illuminate_next": {
5856
6223
  const r = bridge.next();
5857
- if (r) return text(deliver(r));
5858
- const busy = (await Promise.all([...servers.values()].map((s) => s.then((x) => x.working(), () => false)))).some(Boolean);
5859
- if (codex() && busy) return await whatNext(extra);
5860
- return text("Nothing is waiting right now.");
6224
+ return r ? text(h.deliver(r)) : await h.idle(extra);
5861
6225
  }
5862
6226
  case "illuminate_submit": {
5863
6227
  const id = String(args.request_id ?? "");
5864
6228
  const r = bridge.submit(id, args.output);
5865
6229
  if (r.ok) {
5866
- parts.delete(id);
6230
+ h.forget?.(id);
5867
6231
  return await whatNext(extra);
5868
6232
  }
5869
6233
  return text(`That output for ${id} can't be used yet. Fix these and call illuminate_submit again:
5870
6234
  ${r.problems.map((p) => `- ${p}`).join("\n")}`, true);
5871
6235
  }
5872
6236
  case "illuminate_fail": {
5873
- parts.delete(String(args.request_id ?? ""));
5874
- const ok = bridge.fail(String(args.request_id ?? ""), String(args.reason ?? "no reason given"));
6237
+ const id = String(args.request_id ?? "");
6238
+ h.forget?.(id);
6239
+ const ok = bridge.fail(id, String(args.reason ?? "no reason given"));
5875
6240
  return text(ok ? "Told the person on the map." : "No such request is waiting.");
5876
6241
  }
5877
6242
  case "illuminate_screens": {
@@ -5900,8 +6265,7 @@ ${r.problems.map((p) => `- ${p}`).join("\n")}`, true);
5900
6265
  labels.length ? `Labelled things visible:
5901
6266
  ${labels.map((l) => ` - ${l}`).join("\n")}` : "Nothing labelled is visible on it.",
5902
6267
  "",
5903
- // Codex keeps only so much of a tool result, and the image matters more.
5904
- `Text on the page: ${(codex() ? r.result.text.slice(0, 4e3) : r.result.text) || "(none)"}`
6268
+ `Text on the page: ${h.pageText(r.result.text) || "(none)"}`
5905
6269
  ].join("\n")
5906
6270
  },
5907
6271
  { type: "image", data: r.result.png.toString("base64"), mimeType: "image/png" }
@@ -5916,10 +6280,9 @@ ${labels.map((l) => ` - ${l}`).join("\n")}` : "Nothing labelled is visible on i
5916
6280
  const server = await serverFor(root);
5917
6281
  const mapId = typeof args.map_id === "string" && args.map_id ? args.map_id : void 0;
5918
6282
  const url = server.pageUrl(mapId);
5919
- if (!codex()) open(url);
5920
- const maps = createStore(root).list().slice(0, codex() ? 200 : void 0);
5921
- const opened = codex() ? [showInCodex(url), portNote(server), "When the person asks about the map here in the chat, call illuminate_ask."] : [`Opened ${url}`, "Call illuminate_listen so questions asked on the map reach you."];
5922
- return text([...opened.filter(Boolean), "", maps.length ? "Saved maps:" : "No maps saved in this repo yet.", ...maps.map((m) => `${m.id} ${m.question}`)].join("\n"));
6283
+ open(url);
6284
+ const maps = createStore(root).list().slice(0, h.mapsListed);
6285
+ return text([...h.opened(url).filter(Boolean), "", maps.length ? "Saved maps:" : "No maps saved in this repo yet.", ...maps.map((m) => `${m.id} ${m.question}`)].join("\n"));
5923
6286
  }
5924
6287
  default:
5925
6288
  return text(`Unknown tool: ${req.params.name}`, true);
@@ -5954,18 +6317,22 @@ async function runChannel(o) {
5954
6317
  process.on("SIGTERM", stop);
5955
6318
  await channel.mcp.connect(new StdioServerTransport());
5956
6319
  }
5957
- var CHANNEL_INSTRUCTIONS, local, TOOLS, CODEX_TOOLS, CODEX_ONLY, text, CLOSED, PORT;
6320
+ var CHANNEL_INSTRUCTIONS, TOOLS_BY_HOST, PORT;
5958
6321
  var init_channel = __esm({
5959
6322
  "packages/server/src/channel.ts"() {
5960
6323
  "use strict";
5961
6324
  init_bridge();
5962
6325
  init_browser();
5963
6326
  init_host();
6327
+ init_claude_code();
6328
+ init_codex();
6329
+ init_common();
5964
6330
  init_screens2();
5965
6331
  init_server();
5966
6332
  init_store();
5967
6333
  init_updates();
5968
- init_reply();
6334
+ init_common();
6335
+ init_codex();
5969
6336
  CHANNEL_INSTRUCTIONS = [
5970
6337
  "illuminate draws checked, interactive maps of how this codebase works, in the person's browser. You do the reading and writing; illuminate checks every claim against the code before it shows anything.",
5971
6338
  `- When the person asks how something works across files ("what happens when\u2026", "how does X reach Y", "what did this change do"), what someone sees or goes through in the app (a user journey), or how a change would look before it's made ("how would we add\u2026", "plan\u2026"), or asks for a map, diagram or walkthrough, call illuminate_map with their question in their own words.`,
@@ -5975,137 +6342,10 @@ var init_channel = __esm({
5975
6342
  "- A picture of the screen can ground a map for people who don't read code. Use your judgement: when a flow starts from something the person sees (a button, a form, a page) a screen on that box helps; for backend-only questions leave screens out. illuminate_screens lists what this repo can show; illuminate_capture screenshots a page already running on this machine, or an HTML file in the repo, and shows you the result. Look at it before using it: if it shows a login page, an error or the wrong state, don't use it. Never start the app yourself to get a screenshot. When nothing is running, a map can still show a wireframe of the page drawn from the code; the request explains how.",
5976
6343
  "- While working on an illuminate request, don't edit files or run commands that change anything, and never read secret files (.env, keys). A fix is only proposed; illuminate applies it after the person approves it on the map.",
5977
6344
  "- Answers are shown on the map. In the chat or terminal, say at most a sentence or two.",
5978
- "In Claude Code:",
5979
- "- Once a map is ready or an answer is shown, call illuminate_listen and leave it running. It moves to the background, so the person keeps their terminal. When they ask something on the map it returns with a request: do it, submit it, then call illuminate_listen again. If it returns saying nothing was asked yet, call it again without telling the person. Only one is needed at a time.",
5980
- "- If an illuminate channel message arrives instead, call illuminate_next to get the request.",
5981
- "In Codex (no illuminate_listen there):",
5982
- "- Pass `repo`, the absolute path of the project, to illuminate_map and illuminate_open. Give the person the map's link, and if you have a built-in browser, open it there so the map sits beside the chat.",
5983
- "- While a map is open and the person asks about it in the chat (the map, a box or arrow, what they selected, a walkthrough step), call illuminate_ask with their question and the page's current URL if you know it. illuminate adds what they selected on the page.",
5984
- "- A long request comes in parts: read every part with illuminate_more before you start. If a result says illuminate is still working, or the person says to carry on with illuminate, call illuminate_next."
6345
+ ...CLAUDE_CODE_INSTRUCTIONS,
6346
+ ...CODEX_INSTRUCTIONS
5985
6347
  ].join("\n");
5986
- local = (title, readOnly = false) => ({ title, readOnlyHint: readOnly, destructiveHint: false, idempotentHint: false, openWorldHint: false });
5987
- TOOLS = [
5988
- {
5989
- name: "illuminate_map",
5990
- description: "Make a checked map that answers a question about how this codebase works, and open it in the person's browser. Returns the first piece of work for you to do.",
5991
- annotations: local("Make a map"),
5992
- inputSchema: {
5993
- type: "object",
5994
- properties: {
5995
- question: { type: "string", maxLength: 300, description: "The person's question, in their own words (300 characters at most)." },
5996
- repo: { type: "string", description: "The repo root, if not the project Claude Code was started in." }
5997
- },
5998
- required: ["question"]
5999
- }
6000
- },
6001
- {
6002
- name: "illuminate_next",
6003
- description: "Get the next piece of work illuminate has for you (after an illuminate channel message).",
6004
- annotations: local("Get the next request", true),
6005
- inputSchema: { type: "object", properties: {} }
6006
- },
6007
- {
6008
- name: "illuminate_submit",
6009
- description: "Hand in your output for an illuminate request. It is checked; if it can't be read you get the problems back to fix. Returns the next piece of work, if there is one.",
6010
- annotations: local("Hand in a request"),
6011
- inputSchema: {
6012
- type: "object",
6013
- properties: {
6014
- request_id: { type: "string" },
6015
- output: { type: "object", description: "JSON matching the request's schema." }
6016
- },
6017
- required: ["request_id", "output"]
6018
- }
6019
- },
6020
- {
6021
- name: "illuminate_fail",
6022
- description: "Give up on an illuminate request, saying why in plain words. The person sees it on the map.",
6023
- annotations: local("Give up on a request"),
6024
- inputSchema: {
6025
- type: "object",
6026
- properties: { request_id: { type: "string" }, reason: { type: "string" } },
6027
- required: ["request_id", "reason"]
6028
- }
6029
- },
6030
- {
6031
- name: "illuminate_listen",
6032
- description: "Wait for the next question the person asks on the map (or a new map they start there). Keep one running whenever you have no illuminate work: it moves to the background, and returns with a request when they ask. Do the request, submit it, then call this again.",
6033
- annotations: local("Listen to the map", true),
6034
- inputSchema: { type: "object", properties: {} }
6035
- },
6036
- {
6037
- name: "illuminate_screens",
6038
- description: "List what this repo can show of its screens: local pages being served right now, HTML files, preview setups and image files. Costs nothing; call it when a picture of the screen might help a map or an answer.",
6039
- annotations: local("List screens", true),
6040
- inputSchema: { type: "object", properties: { repo: { type: "string" } } }
6041
- },
6042
- {
6043
- name: "illuminate_capture",
6044
- description: "Screenshot one page so it can be a box's `screen` on a map: a `url` served on this machine (http://localhost:\u2026), or an HTML `file` in the repo. Returns the image for you to look at, the labelled things visible on it, and the capture id to put in the box's `screen`. Runs in a clean browser profile, so pages behind a login show their login page.",
6045
- annotations: local("Screenshot a local page"),
6046
- inputSchema: {
6047
- type: "object",
6048
- properties: {
6049
- url: { type: "string", description: "A page on this machine, e.g. http://localhost:3000/patients" },
6050
- file: { type: "string", description: "Or: a repo-relative .html file" },
6051
- repo: { type: "string" }
6052
- }
6053
- }
6054
- },
6055
- {
6056
- name: "illuminate_open",
6057
- description: "Open saved maps in the person's browser: one map, or the list of all of them. Returns the maps saved in the repo.",
6058
- annotations: local("Open saved maps"),
6059
- inputSchema: {
6060
- type: "object",
6061
- properties: {
6062
- map_id: { type: "string", description: "A saved map's id; leave out for the list." },
6063
- repo: { type: "string" }
6064
- }
6065
- }
6066
- }
6067
- ];
6068
- CODEX_TOOLS = {
6069
- illuminate_map: {
6070
- description: "Make a checked map that answers a question about how this codebase works. Returns the map page's link to give the person (open it in your built-in browser if you have one) and the first piece of work for you to do."
6071
- },
6072
- illuminate_next: {
6073
- description: "Get the next piece of work illuminate has for you, waiting up to 40 seconds for it. Call it when a result says illuminate is still working, or when the person says to carry on with illuminate."
6074
- },
6075
- illuminate_open: {
6076
- description: "Get the link to saved maps: one map, or the list of all of them, to open in your built-in browser or give the person. Returns the maps saved in the repo."
6077
- }
6078
- };
6079
- CODEX_ONLY = [
6080
- {
6081
- name: "illuminate_ask",
6082
- description: "Ask illuminate a question the person asked in this chat about an illuminate map that is open in the browser. illuminate adds what they have selected on the page and starts the answer; returns the first piece of work for you to do. The answer is shown on the map.",
6083
- annotations: local("Ask about the open map"),
6084
- inputSchema: {
6085
- type: "object",
6086
- properties: {
6087
- question: { type: "string", maxLength: 2e3, description: "The person's question, in their own words." },
6088
- url: { type: "string", description: "The map page's current URL in the browser (http://127.0.0.1:\u2026/m/\u2026), if you know it." }
6089
- },
6090
- required: ["question"]
6091
- }
6092
- },
6093
- {
6094
- name: "illuminate_more",
6095
- description: "Read the next part of an illuminate request that came in parts. Read every part before you start on it.",
6096
- annotations: local("Read the rest of a request", true),
6097
- inputSchema: {
6098
- type: "object",
6099
- properties: {
6100
- request_id: { type: "string" },
6101
- part: { type: "number", description: "Which part (2 for the second). Leave out for the next one." }
6102
- },
6103
- required: ["request_id"]
6104
- }
6105
- }
6106
- ];
6107
- text = (t, isError = false) => ({ content: [{ type: "text", text: t }], ...isError ? { isError } : {} });
6108
- CLOSED = "The person closed illuminate, so there is nothing to listen to. Don't call illuminate_listen again unless they ask for a map or ask you to listen. Say nothing to the person about this.";
6348
+ TOOLS_BY_HOST = { "claude-code": CLAUDE_CODE_TOOLS, codex: CODEX_TOOLS };
6109
6349
  PORT = 4317;
6110
6350
  }
6111
6351
  });