usepilot 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/index.js CHANGED
@@ -37164,6 +37164,19 @@ function originOf(url2) {
37164
37164
  return null;
37165
37165
  }
37166
37166
  }
37167
+ function isLocalHost(hostname3) {
37168
+ const h = hostname3.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
37169
+ if (!h) return false;
37170
+ if (h === "localhost" || h === "0.0.0.0" || h === "::1" || h === "::") return true;
37171
+ if (/\.(localhost|local|test|internal|lan|home\.arpa)$/.test(h)) return true;
37172
+ const v4 = /^(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/.exec(h);
37173
+ if (v4) {
37174
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
37175
+ return a === 127 || a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 169 && b === 254;
37176
+ }
37177
+ if (h.includes(":")) return /^f[cd][0-9a-f]{2}:/.test(h) || /^fe[89ab][0-9a-f]:/.test(h);
37178
+ return !h.includes(".");
37179
+ }
37167
37180
  function originKey(origin) {
37168
37181
  return origin.replace(/^(https?:\/\/)(?:127\.0\.0\.1|\[::1\])(?=[:/]|$)/, "$1localhost").replace(/\/$/, "");
37169
37182
  }
@@ -37575,6 +37588,8 @@ var Hub = class {
37575
37588
  now;
37576
37589
  agents = /* @__PURE__ */ new Map();
37577
37590
  pages = /* @__PURE__ */ new Set();
37591
+ /** Sites the designer quit Pilot on: their agents' waits end at once, until one runs /pilot there again. */
37592
+ quitOrigins = /* @__PURE__ */ new Set();
37578
37593
  jobs = /* @__PURE__ */ new Map();
37579
37594
  waiters = [];
37580
37595
  checks = /* @__PURE__ */ new Map();
@@ -37622,8 +37637,33 @@ var Hub = class {
37622
37637
  if (!keep.has(id) && agent.seen < cutoff && !this.waiters.some((w) => w.agentId === id)) this.unregister(id);
37623
37638
  }
37624
37639
  }
37640
+ /**
37641
+ * The designer quit Pilot on `origin` (the whole site): its agents' waits
37642
+ * end with `quit`, so their chats stop the loop and are theirs again, and
37643
+ * so do their next waits (an agent on a job finishes it first) until one
37644
+ * runs /pilot there again; its open pages close Pilot. Jobs aren't touched
37645
+ * here: the page takes back the ones still queued.
37646
+ */
37647
+ quit(origin) {
37648
+ const key = originKey(origin);
37649
+ this.quitOrigins.add(key);
37650
+ for (const waiter of this.waiters.filter((w) => w.origin === key)) {
37651
+ this.waiters = this.waiters.filter((w) => w !== waiter);
37652
+ waiter.resolve(null, true);
37653
+ }
37654
+ this.sendTo(key, { type: "quit" });
37655
+ this.notifyAgents(key);
37656
+ }
37657
+ /**
37658
+ * The sites with Pilot open in a browser now (the origins of the connected
37659
+ * pages, each once): where /pilot can launch without being told a URL.
37660
+ */
37661
+ pageOrigins() {
37662
+ return [...new Set([...this.pages].map((p) => p.origin))];
37663
+ }
37625
37664
  /** An agent ran /pilot: registers it and tells the open pages of `origin` to launch Pilot. Returns how many pages got it. */
37626
37665
  launch(info, origin) {
37666
+ this.quitOrigins.delete(originKey(origin));
37627
37667
  this.register(info, origin);
37628
37668
  return this.sendTo(originKey(origin), { type: "launch", agent: this.shown(info) });
37629
37669
  }
@@ -37635,16 +37675,17 @@ var Hub = class {
37635
37675
  wait(info, origin, timeoutMs, signal) {
37636
37676
  this.register(info, origin);
37637
37677
  const key = originKey(origin);
37678
+ if (this.quitOrigins.has(key)) return Promise.resolve({ job: null, quit: true });
37638
37679
  const queued = this.oldestQueued(key);
37639
37680
  if (queued) return Promise.resolve({ job: this.take(queued, this.shown(info)) });
37640
37681
  return new Promise((resolve3) => {
37641
37682
  const waiter = {
37642
37683
  agentId: info.id,
37643
37684
  origin: key,
37644
- resolve: (job) => {
37685
+ resolve: (job, quit) => {
37645
37686
  clearTimeout(timer);
37646
37687
  signal?.removeEventListener("abort", onAbort);
37647
- resolve3({ job });
37688
+ resolve3(quit ? { job: null, quit: true } : { job });
37648
37689
  }
37649
37690
  };
37650
37691
  const timer = setTimeout(() => this.endWait(waiter, null), timeoutMs);
@@ -37890,6 +37931,10 @@ async function handle(hub, req, res, attachments) {
37890
37931
  return;
37891
37932
  }
37892
37933
  if (path === "/events" && req.method === "GET") return events(hub, origin, req, res);
37934
+ if (path === "/quit" && req.method === "POST") {
37935
+ hub.quit(origin);
37936
+ return json2(res, 200, { ok: true });
37937
+ }
37893
37938
  if (req.method !== "POST") return json2(res, 405, { error: "POST only" });
37894
37939
  if (!hub.hasAgents(origin)) return json2(res, 403, { error: "no agent works on this page: run /pilot in your agent" });
37895
37940
  if (path === "/components") return json2(res, 200, { components: projectComponents(hub.folders(origin)) });
@@ -37954,6 +37999,8 @@ async function handleAgent(hub, action, data, req, res) {
37954
37999
  if (!d.origin) return json2(res, 400, { error: "origin needed" });
37955
38000
  hub.register(d.agent, d.origin);
37956
38001
  return json2(res, 200, { ok: true });
38002
+ case "pages":
38003
+ return json2(res, 200, { origins: hub.pageOrigins() });
37957
38004
  case "launch":
37958
38005
  if (!d.origin) return json2(res, 400, { error: "origin needed" });
37959
38006
  return json2(res, 200, { pages: hub.launch(d.agent, d.origin) });
@@ -38044,6 +38091,9 @@ var LocalApi = class {
38044
38091
  localAgents.add(agent.id);
38045
38092
  return this.hub.launch(agent, origin);
38046
38093
  }
38094
+ async pages() {
38095
+ return this.hub.pageOrigins();
38096
+ }
38047
38097
  wait(agent, origin, timeoutMs, signal) {
38048
38098
  localAgents.add(agent.id);
38049
38099
  return this.hub.wait(agent, origin, timeoutMs, signal);
@@ -38080,6 +38130,14 @@ var RemoteApi = class {
38080
38130
  async launch(agent, origin) {
38081
38131
  return (await this.post("launch", { agent, origin })).pages;
38082
38132
  }
38133
+ async pages() {
38134
+ try {
38135
+ return (await this.post("pages", {})).origins;
38136
+ } catch (error62) {
38137
+ if (isConnectionError(error62)) throw error62;
38138
+ return [];
38139
+ }
38140
+ }
38083
38141
  wait(agent, origin, timeoutMs, signal) {
38084
38142
  return this.post("wait", { agent, origin, timeoutMs }, signal);
38085
38143
  }
@@ -38117,6 +38175,10 @@ var Bridge = class {
38117
38175
  this.startHeartbeat();
38118
38176
  return pages;
38119
38177
  }
38178
+ /** The sites with Pilot open in a browser (their origins). */
38179
+ pages() {
38180
+ return this.call((api) => api.pages());
38181
+ }
38120
38182
  /** Waits up to `timeoutMs` for a job; survives the hub moving to another process mid-wait. */
38121
38183
  async wait(origin, timeoutMs, signal) {
38122
38184
  this.origin = origin;
@@ -38512,10 +38574,10 @@ import { homedir } from "os";
38512
38574
  import { join as join5, relative as relative4 } from "path";
38513
38575
 
38514
38576
  // ../../skills/pilot/SKILL.md
38515
- var SKILL_default = "---\nname: pilot\ndescription: Hand the UI to the designer with Pilot, then apply the design edits they send, job after job. Use when the user runs /pilot, says they want to take control of the design or edit the UI in the browser, or pastes a \"Pilot design edits\" brief, or asks to update Pilot.\n---\n\n# Pilot\n\nPilot lets the designer edit the running app in the browser. They select elements, change CSS properties with Pilot's editors, and press **Send**. Each Send reaches you as a **job**: plain CSS `property: from \u2192 to` (and new text, when they rewrote one) on identifiable elements, for you to write into the source in this project's conventions. The designer keeps designing while you work; Pilot previews each job's changes until you report it done, then checks them against the page's real CSS.\n\n## When the user asks to update Pilot\n\nRun `npx usepilot@latest update` in the app's folder (the one with `usepilot` in its `package.json`), and tell the user in a few lines what it prints: the new version and the steps left (restart the app's dev server, open a new chat).\n\n## When the user runs /pilot (or asks to launch Pilot)\n\n0. **Check that Pilot's tools are here** (`pilot_launch`, `pilot_wait_for_edits`, `pilot_done`). If they aren't, don't look for them in files, packages or settings: they come from Pilot's MCP server, which an agent loads when a chat starts, so a chat opened before Pilot was set up doesn't have them. Say so in one or two lines and stop: open a new chat (approve Pilot's server if asked, or turn it on in the agent's MCP settings: Cursor keeps a project's new servers off until they're switched on in Cursor Settings, MCP section), then run `/pilot` there. If the project has no Pilot at all (no `usepilot` in its `package.json`), offer to set it up instead: `npx usepilot@latest init --agent <you>`.\n1. **Find the page.** Work out the URL of the app's dev server: the dev script and its config (`vite.config.*` \u2192 `server.port`, Next.js \u2192 3000, a `--port` flag\u2026), or a server already running in a terminal. If the dev server isn't running, start it in the background. If you can't tell the URL, ask.\n2. **Launch:** call `pilot_launch` with that URL and `folder`, the project's folder as an absolute path (your working directory): Pilot searches the code there for each job, and some agents start its server elsewhere. Pilot opens in the page (if the page isn't open yet, tell the designer to open it).\n3. **Tell the designer** in one line that Pilot is ready: select an element, edit, press Send.\n4. **Wait:** call `pilot_wait_for_edits`. It returns a job when the designer presses Send, or \"no edits yet\" after a while: call it again, without saying anything to the user. In Claude Code, a wait longer than two minutes moves to the background: end your turn with a short \"Waiting for your edits\", and the job arrives as the task's result.\n5. **Apply the job** (below), then call `pilot_done` with the job id and short notes, and go back to step 4. When several jobs were queued, one wait returns them all: do them all, then call `pilot_done` once per job, each with its own id and notes.\n\nKeep looping until the user asks you to stop. Keep your messages between jobs short: a line on what you changed (and anything you approximated) is enough. If the user talks to you meanwhile, help them, and keep (or start again) a wait in the background so their next Send reaches you (queued jobs are kept).\n\n## Applying a job\n\nJobs come in three kinds:\n\n- **Edits** (basic): the designer set every value; you only translate them. **Speed is what matters**: go straight to the code, apply, call `pilot_done`. No screenshots, browser checks, builds or tests: Pilot checks the page itself and sends back what didn't land.\n- **Comments**: the designer's own words about one element (\"make it the brand green\", \"can this be calmer?\"), with the thread so far. Do what the latest one asks: a specific, small ask right away (like an edit), an open-ended one as an advanced task (below). A question gets an answer and no change. Your `pilot_done` notes are your reply in their thread, a small chat box for quick design back-and-forth: one short sentence, like a chat message (about 120 characters), with no lists or code blocks. Not a report: they see the result on the page.\n- **Tasks** (advanced), like **Make responsive** and **Break and fix**: the designer selected an element and asked for an outcome (work at every viewport width; hold up with odd but realistic content, like very long text, with the real content put back after testing). They need judgment more than speed. The prompt has the steps. Check the result with `pilot_check_widths` (numbers for every width, no screenshots needed). If you can hand it to a more capable model than the one you run on (a subagent, or another model your agent offers), do, then call `pilot_done` with its notes. Pilot checks the widths again when you're done; problems come back once as a follow-up.\n\n### Edits\n\nThe values are **design instructions, not code**: the designer's intent. Use your judgment and write production code the way this project already styles things, whatever it uses. First look at how the element's component is styled, and follow that. For example:\n\n- **Utility classes (Tailwind):** the closest utility or theme value (`border-radius: 12px` \u2192 `rounded-xl`, `padding-top: 24px` \u2192 `pt-6`). Arbitrary values only when nothing fits.\n- **CSS / CSS modules / Sass:** edit the rule that styles the element. Don't add a new override.\n- **Design tokens / CSS variables:** prefer an existing token that matches. Don't hard-code its value.\n- **CSS-in-JS and compiled styles (StyleX, vanilla-extract, Panda, styled-components, Emotion):** edit the style definition where the component is styled, with the project's tokens.\n- **A component library's props (MUI, Chakra\u2026):** use its props and theme values before any custom CSS.\n\nRules:\n\n- Never leave inline styles or `!important` behind. Pilot's preview is only a preview.\n- Find each element by its selector, DOM path and text snippet, then the component that renders it.\n- **Shared code, only some copies:** an element's \"Look-alikes\" line counts the elements like it the job leaves out. If they come from the same code (a shared component, a loop over data) and the designer didn't say which they meant, don't guess: do the rest of the job, leave that part, and ask with `pilot_done`'s `question` (one short sentence, the component's name in **bold**) and `choices` \"All of them\", \"Only this\", \"New variant\" (your suggestion first). Go on with other jobs; the answer comes back as that job. **All of them**: change the component itself. **Only this**: change it where it's used, with what the component accepts (classes through its `className`, merged the project's way; a prop), else the smallest pass-through, not a variant. **New variant**: add a named option the way the component defines variants (`cva`, a `variant` prop), use it here, and name it in your notes. Don't ask when the designer already said, when every copy is in the job, or when nothing else uses that code.\n- **Widths:** a change for some viewport widths goes in a media query; use the project's breakpoints when one matches (or is within a few pixels). \"Every width\" means no media query should override it.\n- **Removed:** the element shouldn't declare the property at all (not `0` or `none`).\n- **Text:** the designer rewrote the element's copy. Change it where it comes from (the markup, a prop, a translation file), for this element only; Pilot checks that the page shows the new text.\n- If you approximated a value to fit a token or scale, say which and by how much in `pilot_done`'s notes (`22px \u2192 pt-6, 24px`). Pilot checks the page after each job: a change that doesn't give the designer's value comes back to you once as a follow-up. Fix it, or keep a deliberate choice and say why; after that, Pilot takes what the code gives.\n- Don't run builds or tests for a job unless it's needed: hot reload shows the result, and the designer is waiting to see it.\n";
38577
+ var SKILL_default = "---\nname: pilot\ndescription: Hand the UI to the designer with Pilot, then apply the design edits they send, job after job. Use when the user runs /pilot, says they want to take control of the design or edit the UI in the browser, or pastes a \"Pilot design edits\" brief, or asks to update Pilot.\n---\n\n# Pilot\n\nPilot lets the designer edit the running app in the browser. They select elements, change CSS properties with Pilot's editors, and press **Send**. Each Send reaches you as a **job**: plain CSS `property: from \u2192 to` (and new text, when they rewrote one) on identifiable elements, for you to write into the source in this project's conventions. The designer keeps designing while you work; Pilot previews each job's changes until you report it done, then checks them against the page's real CSS.\n\n## When the user asks to update Pilot\n\nRun `npx usepilot@latest update` in the app's folder (the one with `usepilot` in its `package.json`), and tell the user in a few lines what it prints: the new version and the steps left (restart the app's dev server, open a new chat).\n\n## When the user runs /pilot (or asks to launch Pilot)\n\n0. **Check that Pilot's tools are here** (`pilot_launch`, `pilot_wait_for_edits`, `pilot_done`). If they aren't, don't look for them in files, packages or settings: they come from Pilot's MCP server, which an agent loads when a chat starts, so a chat opened before Pilot was set up doesn't have them. Say so in one or two lines and stop: open a new chat (approve Pilot's server if asked, or turn it on in the agent's MCP settings: Cursor keeps a project's new servers off until they're switched on in Cursor Settings, MCP section), then run `/pilot` there. If the project has no Pilot at all (no `usepilot` in its `package.json`), offer to set it up instead: `npx usepilot@latest init --agent <you>`.\n1. **Launch:** call `pilot_launch` with `folder`, the project's folder as an absolute path (your working directory): Pilot searches the code there for each job, and some agents start its server elsewhere. **Pilot works on the whole site, every page**, not on one page: leave `url` out and it launches on the site where Pilot is open in the browser. Pass the site's address (any page of it; only the scheme, host and port count) only when it asks, or when several sites are open. Don't pick a page from the file you have open, and don't open one for the designer.\n2. **If no page has Pilot open:** make sure the app's dev server runs (start it in the background if it doesn't), ask the designer to open the app (any page), and call `pilot_launch` again. Don't investigate ports or processes: what `pilot_launch` says is what's wrong.\n3. **Tell the designer** in one line that Pilot is ready on every page: select an element, edit, press Send.\n4. **Wait:** call `pilot_wait_for_edits`. It returns a job when the designer presses Send, or \"no edits yet\" after a while: call it again, without saying anything to the user. If it says the designer quit Pilot, stop: tell the user in one line that Pilot is closed (`/pilot` starts it again), and end your turn. In Claude Code, a wait longer than two minutes moves to the background: end your turn with a short \"Waiting for your edits\", and the job arrives as the task's result.\n5. **Apply the job** (below), then call `pilot_done` with the job id and short notes, and go back to step 4. When several jobs were queued, one wait returns them all: do them all, then call `pilot_done` once per job, each with its own id and notes.\n\nKeep looping until the user asks you to stop. Keep your messages between jobs short: a line on what you changed (and anything you approximated) is enough. If the user talks to you meanwhile, help them, and keep (or start again) a wait in the background so their next Send reaches you (queued jobs are kept).\n\n## Applying a job\n\nJobs come in three kinds:\n\n- **Edits** (basic): the designer set every value; you only translate them. **Speed is what matters**: go straight to the code, apply, call `pilot_done`. No screenshots, browser checks, builds or tests: Pilot checks the page itself and sends back what didn't land.\n- **Comments**: the designer's own words about one element (\"make it the brand green\", \"can this be calmer?\"), with the thread so far. Do what the latest one asks: a specific, small ask right away (like an edit), an open-ended one as an advanced task (below). A question gets an answer and no change. Your `pilot_done` notes are your reply in their thread, a small chat box for quick design back-and-forth: one short sentence, like a chat message (about 120 characters), with no lists or code blocks. Not a report: they see the result on the page.\n- **Tasks** (advanced), like **Make responsive** and **Break and fix**: the designer selected an element and asked for an outcome (work at every viewport width; hold up with odd but realistic content, like very long text, with the real content put back after testing). They need judgment more than speed. The prompt has the steps. Check the result with `pilot_check_widths` (numbers for every width, no screenshots needed). If you can hand it to a more capable model than the one you run on (a subagent, or another model your agent offers), do, then call `pilot_done` with its notes. Pilot checks the widths again when you're done; problems come back once as a follow-up.\n\n### Edits\n\nThe values are **design instructions, not code**: the designer's intent. Use your judgment and write production code the way this project already styles things, whatever it uses. First look at how the element's component is styled, and follow that. For example:\n\n- **Utility classes (Tailwind):** the closest utility or theme value (`border-radius: 12px` \u2192 `rounded-xl`, `padding-top: 24px` \u2192 `pt-6`). Arbitrary values only when nothing fits.\n- **CSS / CSS modules / Sass:** edit the rule that styles the element. Don't add a new override.\n- **Design tokens / CSS variables:** prefer an existing token that matches. Don't hard-code its value.\n- **CSS-in-JS and compiled styles (StyleX, vanilla-extract, Panda, styled-components, Emotion):** edit the style definition where the component is styled, with the project's tokens.\n- **A component library's props (MUI, Chakra\u2026):** use its props and theme values before any custom CSS.\n\nRules:\n\n- Never leave inline styles or `!important` behind. Pilot's preview is only a preview.\n- Find each element by its selector, DOM path and text snippet, then the component that renders it.\n- **Shared code, only some copies:** an element's \"Look-alikes\" line counts the elements like it the job leaves out. If they come from the same code (a shared component, a loop over data) and the designer didn't say which they meant, don't guess: do the rest of the job, leave that part, and ask with `pilot_done`'s `question` (one short sentence, the component's name in **bold**) and `choices` \"All of them\", \"Only this\", \"New variant\" (your suggestion first). Go on with other jobs; the answer comes back as that job. **All of them**: change the component itself. **Only this**: change it where it's used, with what the component accepts (classes through its `className`, merged the project's way; a prop), else the smallest pass-through, not a variant. **New variant**: add a named option the way the component defines variants (`cva`, a `variant` prop), use it here, and name it in your notes. Don't ask when the designer already said, when every copy is in the job, or when nothing else uses that code.\n- **Widths:** a change for some viewport widths goes in a media query; use the project's breakpoints when one matches (or is within a few pixels). \"Every width\" means no media query should override it.\n- **Removed:** the element shouldn't declare the property at all (not `0` or `none`).\n- **Text:** the designer rewrote the element's copy. Change it where it comes from (the markup, a prop, a translation file), for this element only; Pilot checks that the page shows the new text.\n- If you approximated a value to fit a token or scale, say which and by how much in `pilot_done`'s notes (`22px \u2192 pt-6, 24px`). Pilot checks the page after each job: a change that doesn't give the designer's value comes back to you once as a follow-up. Fix it, or keep a deliberate choice and say why; after that, Pilot takes what the code gives.\n- Don't run builds or tests for a job unless it's needed: hot reload shows the result, and the designer is waiting to see it.\n";
38516
38578
 
38517
38579
  // src/setup.ts
38518
- var MCP_SERVER = { command: "npx", args: ["-y", "usepilot", "mcp"] };
38580
+ var MCP_SERVER = { command: "npx", args: ["-y", "usepilot@latest", "mcp"] };
38519
38581
  async function setup(options = {}) {
38520
38582
  return options.project ? setupProject(options.cwd ?? process.cwd()) : setupMachine(options.home ?? homedir());
38521
38583
  }
@@ -38525,7 +38587,7 @@ async function setupMachine(home) {
38525
38587
 
38526
38588
  Now register Pilot's MCP server with Claude Code, once, for every project:
38527
38589
 
38528
- claude mcp add --scope user pilot -- npx -y usepilot mcp
38590
+ claude mcp add --scope user pilot -- npx -y usepilot@latest mcp
38529
38591
 
38530
38592
  Then, in any Claude Code chat: /pilot
38531
38593
  (For a repo you share, run \`npx usepilot setup --project\` in it instead.)
@@ -38585,7 +38647,7 @@ async function addMcpServer(file2) {
38585
38647
  }
38586
38648
 
38587
38649
  // src/version.ts
38588
- var VERSION = "0.11.0";
38650
+ var VERSION = "0.13.0";
38589
38651
  function olderThan(a, b) {
38590
38652
  const parts = (v) => v.replace(/^[^\d]*/, "").split(/[.-]/).slice(0, 3).map((n) => Number.parseInt(n, 10) || 0);
38591
38653
  const [x, y] = [parts(a), parts(b)];
@@ -38689,6 +38751,40 @@ function agentsWithPilot(root, home, platform = process.platform) {
38689
38751
  return a.id !== "codex" && existsSync5(join6(machine.skills(home), "pilot"));
38690
38752
  }).map((a) => a.id);
38691
38753
  }
38754
+ function isStaleServer(entry) {
38755
+ const e = entry;
38756
+ return !!e && e.command === "npx" && Array.isArray(e.args) && e.args.includes("usepilot");
38757
+ }
38758
+ async function freshenServers(root, home, platform, run) {
38759
+ const moved = [];
38760
+ const files = [
38761
+ ...AGENT_IDS.flatMap((id) => {
38762
+ const m = MACHINE[id].mcp;
38763
+ return m ? [{ file: m.file(home, platform), key: m.key }] : [];
38764
+ }),
38765
+ ...AGENTS.flatMap((a) => a.mcp ? [{ file: join6(root, a.mcp.file), key: a.mcp.key }] : [])
38766
+ ];
38767
+ for (const { file: file2, key } of files) {
38768
+ const config2 = readJson(file2);
38769
+ const entry = config2?.[key]?.pilot;
38770
+ if (!config2 || !entry || !isStaleServer(entry)) continue;
38771
+ entry.args = entry.args.map((a) => a === "usepilot" ? "usepilot@latest" : a);
38772
+ await writeFile3(file2, `${JSON.stringify(config2, null, 2)}
38773
+ `);
38774
+ moved.push(tilde(file2, home));
38775
+ }
38776
+ const claude = readJson(join6(home, ".claude.json"))?.mcpServers?.pilot;
38777
+ const codex = /\[mcp_servers\.pilot\][^[]*"usepilot"/.test(readText(join6(home, ".codex", "config.toml")));
38778
+ for (const [id, stale, remove] of [
38779
+ ["claude-code", isStaleServer(claude), ["mcp", "remove", "--scope", "user", "pilot"]],
38780
+ ["codex", codex, ["mcp", "remove", "pilot"]]
38781
+ ]) {
38782
+ const command2 = MACHINE[id].command;
38783
+ if (!stale || !command2) continue;
38784
+ if (run(command2.cmd, [...remove], home) && run(command2.cmd, command2.args, home)) moved.push(id === "codex" ? "Codex" : "Claude Code");
38785
+ }
38786
+ return moved;
38787
+ }
38692
38788
  function installArgs(pm, spec = "usepilot") {
38693
38789
  return pm === "npm" ? ["install", "-D", spec] : pm === "bun" ? ["add", "-d", spec] : ["add", "-D", spec];
38694
38790
  }
@@ -38804,6 +38900,8 @@ ${apps.map((a) => `- ${a}`).join("\n")}` : "."}
38804
38900
  `**Connect yourself:** run \`npx usepilot@latest init --agent <you>\` in ${cwd}, with \`<you>\` the agent you are: ${AGENT_IDS.map((a) => `\`${a}\``).join(", ")}.`
38805
38901
  );
38806
38902
  }
38903
+ const moved = await freshenServers(root, home, options.platform ?? process.platform, run);
38904
+ if (moved.length) done.push(`Pilot's server now always starts the latest version (${moved.map((m) => `\`${m}\``).join(", ")}): it used to keep the one it downloaded first.`);
38807
38905
  if (framework.loads) done.push(`The app already loads Pilot (\`${relative5(cwd, framework.loads)}\`).`);
38808
38906
  else todo.push(loadStep(framework, cwd));
38809
38907
  const me = AGENTS.find((a) => a.id === named);
@@ -39007,7 +39105,13 @@ export function Pilot() {
39007
39105
  case "webpack":
39008
39106
  return `${intro} In the app's entry file, ${at(framework.file, "the one its bundler config starts from")}, add:${code("js", 'if (process.env.NODE_ENV === "development") import("usepilot/auto");')}`;
39009
39107
  default:
39010
- return `${intro} Import \`usepilot/auto\` from code that runs in the browser, only in development (\`import.meta.env.DEV\` with Vite, \`process.env.NODE_ENV === "development"\` with webpack). It shows the toolbar when the page loads.`;
39108
+ return `${intro} With no bundler Pilot knows (a server-rendered site: PHP, Rails, Django, plain HTML), add it to the layout every page shares (Pilot works on every page), as one tag pointing at Pilot's file where the dev server serves it: \`<script type="module" src="\u2026/node_modules/usepilot/dist/pilot-auto.js"></script>\`. **It must never be output on a server, whatever a request says.** Print it only when both hold: Pilot's own file is on disk (\`node_modules/usepilot/dist/pilot-auto.js\`: a dev dependency, never on a server, as long as the deploy leaves \`node_modules\` out or installs without dev dependencies: check the project's deploy rules, and ask the user if you can't tell), and the project's own development setting says so (an environment variable like \`APP_ENV=local\`, or the local config file that isn't deployed; ask the user if there's none). Never decide from the request (the Host header, the client's IP): a proxy or a client can make them say anything. For example, in PHP:${code(
39109
+ "php",
39110
+ `<?php if (is_file(__DIR__ . '/node_modules/usepilot/dist/pilot-auto.js') && getenv('APP_ENV') === 'local') { ?>
39111
+ <script type="module" src="/node_modules/usepilot/dist/pilot-auto.js"></script>
39112
+ <?php } ?>`
39113
+ )}
39114
+ With a bundler, import \`usepilot/auto\` from the browser code, only in development (\`import.meta.env.DEV\` with Vite, \`process.env.NODE_ENV === "development"\` with webpack). Either way Pilot itself won't run on a public address.`;
39011
39115
  }
39012
39116
  }
39013
39117
  async function addServer(file2, key, entry) {
@@ -39054,8 +39158,8 @@ var PROGRESS_MS = 2e4;
39054
39158
  var INSTRUCTIONS = `Pilot lets the designer edit the running app in the browser and send the edits back to you as jobs.
39055
39159
 
39056
39160
  The loop, when the user asks to launch or start Pilot, runs /pilot, or asks to hand the design over:
39057
- 1. Find the page: the URL of the app's dev server, from the dev script and its config (vite.config \u2192 server.port, Next.js \u2192 3000, a --port flag\u2026) or a server already running. If it isn't running, start it in the background; if you can't tell the URL, ask. Call pilot_launch with that URL and \`folder\`, the project's folder as an absolute path (your working directory: Pilot searches the code there for each job, and some clients start its server in another folder): Pilot opens in that page (if the page isn't open, tell the user to open it), then tell the user in one line that Pilot is ready: select an element, edit, press Send.
39058
- 2. Call pilot_wait_for_edits. It returns a job when the designer presses Send, or "no edits yet" after a while: then call it again. (In Claude Code a long wait moves to the background: the job arrives as its result.)
39161
+ 1. Launch: call pilot_launch with \`folder\`, the project's folder as an absolute path (your working directory: Pilot searches the code there for each job, and some clients start its server in another folder). Pilot works on the whole site, every page, not one page: leave \`url\` out and it launches on the site where Pilot is open in the browser; pass the site's address (any page; only the scheme, host and port count) only when it asks, or when several are open. Don't pick a page from the file you have open, and don't open one for the user. If no page has Pilot open, make sure the dev server runs (start it in the background), and ask the user to open the app. Then tell the user in one line that Pilot is ready on every page: select an element, edit, press Send.
39162
+ 2. Call pilot_wait_for_edits. It returns a job when the designer presses Send, or "no edits yet" after a while: then call it again. When the designer quits Pilot it says so: stop the loop, tell the user in one line that Pilot is closed (/pilot starts it again), and end your turn. (In Claude Code a long wait moves to the background: the job arrives as its result.)
39059
39163
  3. Apply the job's edits to the source: they're design instructions, not code, so write production code the way the project already styles things, whatever it uses (see the job's guidelines). Edits are basic: every value is given, so be fast (no screenshots or browser checks: Pilot checks the page). A "make responsive" job is an advanced task: make one element work at every viewport width. A "break and fix" job is one too: stress-test one element with odd but realistic content, fix what breaks, and put the real content back. Their prompts list the steps; check the result with pilot_check_widths (numbers for every width, instead of screenshots). If you can hand advanced tasks to a more capable model than the one you run on (a subagent, or another model your agent offers), do. A "comment" job is the designer's own words about one element: do what it asks (simple asks right away, open-ended ones as advanced tasks), and your pilot_done notes are your reply in their thread: one short sentence, like a chat message, not a report.
39060
39164
  4. Call pilot_done with the job id and short notes (values you approximated, anything you did differently). When part of a job needs the designer's decision (they changed only some copies of shared code: each element's "Look-alikes" line counts the others; the jobs' guidelines say when, and what each answer means), do the rest, leave that part, and ask with pilot_done's question and choices ("${SHARED_CHOICES.all.label}", "${SHARED_CHOICES.one.label}", "${SHARED_CHOICES.variant.label}", your suggestion first); go on with other jobs, and their answer comes back as that job. Then call pilot_wait_for_edits again. When several jobs were queued, one wait returns them all: do them all, then call pilot_done once per job, each with its own id and notes.
39061
39165
 
@@ -39200,6 +39304,7 @@ function projectFolder(candidate) {
39200
39304
  path = resolve2(path);
39201
39305
  return existsSync6(path) && searchable(path) ? path : null;
39202
39306
  }
39307
+ var QUIT_NOTE = "The designer quit Pilot. Stop here: don't call pilot_wait_for_edits again. Tell the user in one short line that Pilot is closed and that /pilot starts it again, then end your turn.";
39203
39308
  function createPilotServer(options = {}) {
39204
39309
  const port = options.port ?? (Number(process.env.PILOT_PORT) || DEFAULT_BRIDGE_PORT);
39205
39310
  const cwd = options.cwd ?? process.cwd();
@@ -39231,26 +39336,43 @@ function createPilotServer(options = {}) {
39231
39336
  "pilot_launch",
39232
39337
  {
39233
39338
  title: "Launch Pilot",
39234
- description: "Opens Pilot in the page the designer works on, and routes that page's edits to you. Call it first when the user asks to launch or start Pilot (or runs /pilot). Then call pilot_wait_for_edits.",
39339
+ description: "Opens Pilot on the site the designer works on, every page of it (the ones open and those opened next), and routes its edits to you. Call it first when the user asks to launch or start Pilot (or runs /pilot). Then call pilot_wait_for_edits.",
39235
39340
  inputSchema: {
39236
- url: external_exports.string().describe("The page's URL on the app's dev server, e.g. http://localhost:5173 (find it in the dev server's config or output)."),
39341
+ url: external_exports.string().optional().describe(
39342
+ "The site's address on its dev server, e.g. http://localhost:5173: any page of it, Pilot works on every page (only the scheme, host and port count). Leave it out to launch on the site where Pilot is open in the browser."
39343
+ ),
39237
39344
  folder: external_exports.string().optional().describe(
39238
39345
  "The project's folder, as an absolute path: your working directory (the app's folder, with its package.json). Pilot searches its code there for each job. Always pass it: some clients start Pilot's server in another folder."
39239
39346
  )
39240
39347
  }
39241
39348
  },
39242
39349
  async ({ url: url2, folder }) => {
39243
- const o = originOf(url2);
39244
- if (!o) return text(`"${url2}" isn't a page URL. Pass the dev server's URL, e.g. http://localhost:5173.`, true);
39245
- origin = o;
39350
+ let o = url2 ? originOf(url2) : null;
39351
+ if (url2 && !o) return text(`"${url2}" isn't a page URL. Pass the dev server's URL, e.g. http://localhost:5173.`, true);
39246
39352
  const given = projectFolder(folder);
39247
39353
  if (given) useProject(given);
39248
39354
  const lost = !searchable(project) && !given ? ` Pilot can't search the project's code from ${project}${folder ? ` (nor from ${folder}: it needs a package.json or a .git)` : ""}: call pilot_launch again with \`folder\` set to the project's folder (absolute).` : "";
39249
39355
  try {
39356
+ const open2 = (await bridge.pages()).filter((p) => isLocalHost(new URL(p).hostname));
39357
+ if (!o) {
39358
+ if (open2.length > 1) {
39359
+ return text(
39360
+ `Pilot is open on several sites: ${open2.join(", ")}. Call pilot_launch again with the one the designer works on as \`url\` (ask if you can't tell).${lost}`
39361
+ );
39362
+ }
39363
+ if (!open2.length) {
39364
+ return text(
39365
+ `No page has Pilot open yet. Ask the designer to open the app in the browser (any page: Pilot works on every page of the site), with its dev server running (start it if it isn't), then call pilot_launch again. Don't open a page for them.${lost}`
39366
+ );
39367
+ }
39368
+ o = open2[0];
39369
+ }
39370
+ origin = o;
39250
39371
  const pages = await bridge.launch(o);
39251
- const where = pages > 0 ? `Pilot is open in ${pages === 1 ? "the page" : `${pages} pages`} at ${o}.` : `No page at ${o} is connected yet. Ask the designer to open ${url2} (with the dev server running): Pilot opens there.`;
39372
+ const others = open2.filter((p) => p !== originKey(o));
39373
+ const where = pages > 0 ? `Pilot is open on ${o}, on every page: the ${pages === 1 ? "one" : pages} open now, and the ones the designer opens next.` : others.length ? `No page at ${o} has Pilot open, but ${others.join(", ")} does: a different host or port is another site to Pilot (a proxy's, say). If that's the one the designer uses, call pilot_launch again with it.` : `No page at ${o} is connected yet. Ask the designer to open the site (any page: Pilot works on every page), with the dev server running: Pilot opens there. Don't open a page for them, and don't pick one.`;
39252
39374
  const installed = searchable(project) ? installedVersion(project, project) : null;
39253
- const stale = installed && olderThan(VERSION, installed) ? ` This chat's Pilot server is ${VERSION}, older than the project's ${installed}: tell the user to restart it, so it loads ${installed}. ${RESTART[clientOf(client) ?? "other"]}` : "";
39375
+ const stale = installed && olderThan(VERSION, installed) ? ` This chat's Pilot server is ${VERSION}, older than the project's ${installed}, so they may not connect. Don't look into ports or processes: tell the user to run \`npx usepilot@latest update\` in the app's folder (it makes the server start the latest Pilot), then restart it. ${RESTART[clientOf(client) ?? "other"]}` : installed && pages === 0 && olderThan(installed, VERSION) ? ` The project's Pilot is ${installed}, older than this server's ${VERSION}, so the page may not connect. Don't look into ports or processes: tell the user to run \`npx usepilot@latest update\` in the app's folder, then restart the app's dev server.` : "";
39254
39376
  return text(`${where} Now call pilot_wait_for_edits and wait for the designer to press Send.${lost}${stale}`);
39255
39377
  } catch (error62) {
39256
39378
  return text(`Pilot couldn't start its bridge: ${error62.message}`, true);
@@ -39262,7 +39384,7 @@ function createPilotServer(options = {}) {
39262
39384
  {
39263
39385
  title: "Wait for design edits",
39264
39386
  // The edit guidelines live here, read once with the tool, not repeated in every job (they're the most frequent).
39265
- description: `Waits for the designer to press Send in Pilot, and returns the job to apply (or several, when they were queued: do them all, and report each done). Returns "no edits yet" after a few minutes: call it again to keep waiting. Call pilot_launch first.
39387
+ description: `Waits for the designer to press Send in Pilot, and returns the job to apply (or several, when they were queued: do them all, and report each done). Returns "no edits yet" after a few minutes: call it again to keep waiting. Returns that the designer quit Pilot when they did: then stop, don't wait again. Call pilot_launch first.
39266
39388
 
39267
39389
  Guidelines for every design-edits job (the job doesn't repeat them):
39268
39390
  ${EDIT_GUIDELINES.join("\n")}`,
@@ -39280,7 +39402,8 @@ ${EDIT_GUIDELINES.join("\n")}`,
39280
39402
  });
39281
39403
  }, PROGRESS_MS) : null;
39282
39404
  try {
39283
- const { job } = await bridge.wait(origin, waitMs, extra.signal);
39405
+ const { job, quit } = await bridge.wait(origin, waitMs, extra.signal);
39406
+ if (quit) return text(QUIT_NOTE);
39284
39407
  if (!job) return text("No edits yet. Call pilot_wait_for_edits again to keep waiting (the designer can keep editing meanwhile).");
39285
39408
  const jobs = [job, ...await takeQueued(job, () => bridge.wait(origin, 0, extra.signal))];
39286
39409
  const parts = await Promise.all(
@@ -39407,6 +39530,7 @@ Run this in your app's folder, the one where Pilot was set up. To set Pilot up i
39407
39530
  await writeSkill(folder);
39408
39531
  skills.push(folder.startsWith(home) ? `~${folder.slice(home.length)}` : folder);
39409
39532
  }
39533
+ const servers = installed ? await freshenServers(root, home, options.platform ?? process.platform, run) : [];
39410
39534
  if (!installed) {
39411
39535
  return `# Pilot: not updated
39412
39536
 
@@ -39417,7 +39541,7 @@ ${pm} ${args.join(" ")}
39417
39541
  \`\`\`
39418
39542
  `;
39419
39543
  }
39420
- const changed = !!before && !!after && olderThan(before, after);
39544
+ const changed = !!before && !!after && olderThan(before, after) || servers.length > 0;
39421
39545
  const agents = agentsWithPilot(root, home, options.platform);
39422
39546
  const steps = [
39423
39547
  "Restart your app's dev server, so the page loads the new Pilot.",
@@ -39429,12 +39553,16 @@ ${pm} ${args.join(" ")}
39429
39553
  "Update Pilot in your other projects too (`npx usepilot@latest update` in each): this version can't share its connection with older ones."
39430
39554
  );
39431
39555
  }
39432
- const headline = changed ? `# Pilot updated: ${before} \u2192 ${after}` : `# Pilot is up to date (${after ?? VERSION})`;
39556
+ const bumped = !!before && !!after && olderThan(before, after);
39557
+ const headline = bumped ? `# Pilot updated: ${before} \u2192 ${after}` : servers.length ? `# Pilot is up to date (${after ?? VERSION}); its server is fixed` : `# Pilot is up to date (${after ?? VERSION})`;
39433
39558
  const skillLine = skills.length ? `
39434
39559
  The \`pilot\` skill is updated too (${skills.map((s) => `\`${s}\``).join(", ")}).
39560
+ ` : "";
39561
+ const serverLine = servers.length ? `
39562
+ Pilot's server now always starts the latest version (${servers.map((s) => `\`${s}\``).join(", ")}): it used to keep the one it downloaded first.
39435
39563
  ` : "";
39436
39564
  return `${headline}
39437
- ${skillLine}
39565
+ ${skillLine}${serverLine}
39438
39566
  ${changed ? `Next:
39439
39567
  ${steps.map((s, i) => `${i + 1}. ${s}`).join("\n")}
39440
39568
  ` : "Nothing else to do.\n"}`;