usepilot 0.15.0 → 0.17.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
@@ -1,812 +1,59 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __pilotRequire } from "node:module"; const require = __pilotRequire(import.meta.url);
3
+ import {
4
+ AGENTS,
5
+ BRIDGE_VERSION,
6
+ RunnerError,
7
+ agentFromEnv,
8
+ configFile,
9
+ detectAgents,
10
+ installCommand,
11
+ isAgentKind,
12
+ markSetUp,
13
+ projectName,
14
+ relPath,
15
+ saveAgent,
16
+ shownPath,
17
+ startRunner,
18
+ startWithDevServer
19
+ } from "./chunk-B43K6Q5Y.js";
3
20
 
4
21
  // src/index.ts
22
+ import { spawn } from "child_process";
5
23
  import { createInterface } from "readline/promises";
6
24
 
7
- // src/agents.ts
8
- import { spawn } from "child_process";
9
- import { statSync } from "fs";
10
- import { homedir } from "os";
11
- import { delimiter, join } from "path";
12
- var AGENT_KINDS = ["claude", "codex", "cursor"];
13
- function parseStream(stdout) {
14
- let session;
15
- let reply;
16
- let error;
17
- for (const line of stdout.split("\n")) {
18
- const event = jsonLine(line);
19
- if (!event) continue;
20
- if (typeof event.session_id === "string") session = event.session_id;
21
- if (event.type === "assistant") {
22
- const text = textOf(event.message);
23
- if (text.trim()) reply = text.trim();
24
- }
25
- if (event.type === "result") {
26
- if (event.is_error) error = String(event.result ?? event.error ?? "The agent stopped with an error.");
27
- else if (!reply && typeof event.result === "string" && event.result.trim()) reply = event.result.trim();
28
- }
29
- }
30
- if (!session && !reply && !error) error = lastLines(stdout) || "The agent printed nothing.";
31
- return { session, reply, error };
32
- }
33
- function parseCodex(stdout) {
34
- let session;
35
- let reply;
36
- let error;
37
- for (const line of stdout.split("\n")) {
38
- const event = jsonLine(line);
39
- if (!event) continue;
40
- if (event.type === "thread.started" && typeof event.thread_id === "string") session = event.thread_id;
41
- const item = event.item;
42
- if (event.type === "item.completed" && item?.type === "agent_message" && item.text?.trim()) reply = item.text.trim();
43
- if (event.type === "error" || event.type === "turn.failed") {
44
- const e = event.error;
45
- error = String(event.message ?? e?.message ?? "The agent stopped with an error.");
46
- }
47
- }
48
- if (!session && !reply && !error) error = lastLines(stdout) || "The agent printed nothing.";
49
- return { session, reply, error };
50
- }
51
- var AGENTS = {
52
- claude: {
53
- kind: "claude",
54
- label: "Claude Code",
55
- bins: ["claude"],
56
- install: "curl -fsSL https://claude.ai/install.sh | bash",
57
- signIn: "claude auth login",
58
- status: { args: ["auth", "status"], ok: (out) => /"loggedIn"\s*:\s*true/.test(out) },
59
- // The designer's own settings (allow rules, MCP servers, skills), edits in the project accepted.
60
- // A run can't prompt: `-p` refuses what would ask (checked; `--permission-prompts none` says the
61
- // same, but older versions don't know it). Reading the user's skills is allowed, read-only: its
62
- // chat would ask before a skill reads its other files there, and a run can't answer.
63
- args: ({ resume, readDirs = [] }) => [
64
- "-p",
65
- "--output-format",
66
- "stream-json",
67
- "--verbose",
68
- "--permission-mode",
69
- "acceptEdits",
70
- "--allowedTools",
71
- "Read(~/.claude/skills/**)",
72
- ...readDirs.flatMap((d) => ["--add-dir", d]),
73
- ...resume ? ["--resume", resume] : []
74
- ],
75
- parse: parseStream,
76
- skills: { project: [".claude/skills"], home: [".claude/skills"] },
77
- invokeSkill: (name) => `/${name}`
78
- },
79
- codex: {
80
- kind: "codex",
81
- label: "Codex",
82
- bins: ["codex"],
83
- install: "npm install -g @openai/codex",
84
- signIn: "codex login",
85
- status: { args: ["login", "status"], ok: (_out, code) => code === 0 },
86
- // Its sandbox in the mode its chat uses for a project (writes in the project), with the designer's
87
- // own settings for the rest (network, web search, rules). `exec` never asks: what would is refused.
88
- // On Windows the sandbox needs a mode, or a run is read-only; "unelevated" needs no admin rights.
89
- args: ({ resume, images = [], platform = process.platform }) => [
90
- "exec",
91
- "--json",
92
- "-s",
93
- "workspace-write",
94
- ...platform === "win32" ? ["-c", 'windows.sandbox="unelevated"'] : [],
95
- "--skip-git-repo-check",
96
- ...images.flatMap((i) => ["-i", i]),
97
- ...resume ? ["resume", resume] : [],
98
- "-"
99
- ],
100
- parse: parseCodex,
101
- skills: { project: [".agents/skills"], home: [".agents/skills", ".codex/skills"] },
102
- invokeSkill: (name) => "$" + name
103
- },
104
- cursor: {
105
- kind: "cursor",
106
- label: "Cursor",
107
- bins: ["cursor-agent", "agent"],
108
- install: "curl https://cursor.com/install -fsS | bash",
109
- signIn: "cursor-agent login",
110
- status: { args: ["status"], ok: (out) => /logged in/i.test(out) && !/not logged in/i.test(out) },
111
- keyEnv: "CURSOR_API_KEY",
112
- // Its allowlist mode, not its sandbox: the sandbox doesn't exist on Windows and fails on Ubuntu's
113
- // default AppArmor settings. Without `--force`, a run is refused what the user's allowlist doesn't
114
- // allow (it can't ask): writes outside the project, web fetches, shell commands. Checked on all three.
115
- args: ({ resume }) => ["-p", "--output-format", "stream-json", "--trust", "--sandbox", "disabled", ...resume ? ["--resume", resume] : []],
116
- parse: parseStream,
117
- skills: { project: [".agents/skills", ".cursor/skills"], home: [".cursor/skills"] },
118
- invokeSkill: (name) => `/${name}`
119
- }
120
- };
121
- function isAgentKind(value) {
122
- return typeof value === "string" && AGENT_KINDS.includes(value);
123
- }
124
- function findBin(names, env = process.env, platform = process.platform, home = homedir()) {
125
- const win = platform === "win32";
126
- const exts = win ? (env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";").filter(Boolean).map((e) => e.toLowerCase()) : [""];
127
- const dirs = [...(env.PATH ?? env.Path ?? "").split(win ? ";" : delimiter), join(home, ".local", "bin")].filter(Boolean);
128
- for (const name of names) {
129
- for (const dir of dirs) {
130
- for (const ext of exts) {
131
- const file = join(dir, name + ext);
132
- try {
133
- if (statSync(file).isFile()) return file;
134
- } catch {
135
- }
136
- }
137
- }
138
- }
139
- return null;
140
- }
141
- function agentFromEnv(env = process.env) {
142
- if (env.CLAUDECODE || env.CLAUDE_CODE_ENTRYPOINT) return "claude";
143
- if (env.CURSOR_AGENT || env.CURSOR_TRACE_ID) return "cursor";
144
- if (env.CODEX_SANDBOX || env.CODEX_SANDBOX_NETWORK_DISABLED || env.CODEX_MANAGED_BY_NPM || env.CODEX_THREAD_ID) return "codex";
145
- return null;
146
- }
147
- async function detectAgents(kinds = AGENT_KINDS) {
148
- const found = await Promise.all(
149
- kinds.map(async (kind) => {
150
- const cli = AGENTS[kind];
151
- const bin = findBin(cli.bins);
152
- if (!bin) return null;
153
- if (cli.keyEnv && process.env[cli.keyEnv]) return { kind, bin, signedIn: true };
154
- const { stdout, stderr, code } = await exec(bin, cli.status.args, { timeoutMs: 15e3 });
155
- return { kind, bin, signedIn: cli.status.ok(stdout + stderr, code) };
156
- })
157
- );
158
- return found.filter((a) => !!a);
159
- }
160
- function exec(bin, args, options = {}) {
161
- return new Promise((resolve3) => {
162
- const shell = process.platform === "win32" && /\.(cmd|bat)$/i.test(bin);
163
- const child = shell ? spawn([bin, ...args].map(quoteForCmd).join(" "), { cwd: options.cwd, shell: true, windowsHide: true, env: options.env ?? childEnv() }) : spawn(bin, args, { cwd: options.cwd, windowsHide: true, env: options.env ?? childEnv() });
164
- let stdout = "";
165
- let stderr = "";
166
- let killed = false;
167
- const kill = () => {
168
- killed = true;
169
- child.kill();
170
- };
171
- child.stdout?.on("data", (d) => {
172
- const text = d.toString();
173
- stdout += text;
174
- options.onStdout?.(text);
175
- });
176
- child.stderr?.on("data", (d) => stderr += d.toString());
177
- const timer = options.timeoutMs ? setTimeout(kill, options.timeoutMs) : null;
178
- options.signal?.addEventListener("abort", kill, { once: true });
179
- const finish = (code) => {
180
- if (timer) clearTimeout(timer);
181
- options.signal?.removeEventListener("abort", kill);
182
- resolve3({ stdout, stderr, code, killed });
183
- };
184
- child.on("error", (e) => {
185
- stderr += String(e);
186
- finish(-1);
187
- });
188
- child.on("close", finish);
189
- child.stdin?.on("error", () => {
190
- });
191
- child.stdin?.end(options.input ?? "");
192
- });
193
- }
194
- function quoteForCmd(arg) {
195
- return /^[\w\-.:\\/=,]+$/.test(arg) ? arg : `"${arg.replace(/"/g, '""')}"`;
196
- }
197
- function childEnv(env = process.env) {
198
- const { CLAUDECODE: _a, CLAUDE_CODE_ENTRYPOINT: _b, ...rest } = env;
199
- return rest;
200
- }
201
- function jsonLine(line) {
202
- const text = line.trim();
203
- if (!text.startsWith("{")) return null;
204
- try {
205
- return JSON.parse(text);
206
- } catch {
207
- return null;
208
- }
209
- }
210
- function textOf(message) {
211
- const content = message?.content;
212
- if (typeof content === "string") return content;
213
- if (!Array.isArray(content)) return "";
214
- return content.filter((c) => c?.type === "text" && typeof c.text === "string").map((c) => c.text).join("");
215
- }
216
- function lastLines(text) {
217
- return text.trim().split("\n").slice(-3).join("\n").slice(0, 500);
218
- }
25
+ // ../usepilot/GUIDE.md
26
+ var GUIDE_default = "# Pilot guide\n\nHow to use Pilot, task by task. This guide is for **usepilot 0.17.0**: it ships with Pilot, so the copy in your project (`node_modules/usepilot/GUIDE.md`, or `npx usepilot guide`) always matches the version you have.\n\n**Agents:** when someone asks how to do something with Pilot, answer from this file. If it isn't here, Pilot doesn't do it yet: say so rather than guessing.\n\n## Contents\n\n- [Setting up](#setting-up)\n- [Opening, hiding and closing Pilot](#opening-hiding-and-closing-pilot)\n- [The toolbar](#the-toolbar)\n- [Selecting elements](#selecting-elements)\n- [Editing properties](#editing-properties)\n- [Variables and tokens](#variables-and-tokens)\n- [Screen widths (breakpoints)](#screen-widths-breakpoints)\n- [Hover, focus, dark mode and other states](#hover-focus-dark-mode-and-other-states)\n- [Editing text](#editing-text)\n- [Undo, discard and reloads](#undo-discard-and-reloads)\n- [Sending changes to your agent](#sending-changes-to-your-agent)\n- [Comments](#comments)\n- [Skills and Pilot's tasks (the / list)](#skills-and-pilots-tasks-the--list)\n- [Mentions (@)](#mentions-)\n- [When the agent asks you something](#when-the-agent-asks-you-something)\n- [Measuring distances](#measuring-distances)\n- [The DOM tree](#the-dom-tree)\n- [Keyboard shortcuts](#keyboard-shortcuts)\n- [When something's wrong](#when-somethings-wrong)\n- [What Pilot doesn't do (yet)](#what-pilot-doesnt-do-yet)\n- [Commands and options](#commands-and-options)\n\n## Setting up\n\n1. **Add Pilot to the project**: ask your agent, in the project, to *run `npx usepilot@latest init` and follow what it prints*. It installs Pilot as a dev dependency, loads it in development only (Pilot never ships to your live site), and sets it to start with your dev server. Pilot runs your agent's command-line tool for each job, not its chat window: if that isn't installed, your agent installs it, after asking you.\n2. **Restart your dev server** and open your app. Pilot opens on every page, and you can design right away. The dev server's terminal shows each job's progress (`[pilot]` lines).\n3. **Sign in once, when Pilot asks.** The first time you send something (Send, or a comment), Pilot opens your agent's sign-in page in your browser; what you sent waits, and goes once you've signed in. Already signed in to your agent's command-line tool? Nothing to do. To sign in in a terminal instead: `claude auth login`, `codex login` or `cursor-agent login`.\n\n**Your teammates:** the setup lives in the project's files, but Pilot starts with the dev server only on computers where it's set up (where `init` or `npx usepilot` ran). Teammates who haven't set it up see one line in their dev server's terminal and nothing else; to use Pilot, they run `npx usepilot init` in the project once.\n\n**A dev server Pilot can't start with?** Run `npx usepilot` in the project's folder, in a terminal beside it, and keep it running.\n\n**Choosing the agent:** Pilot uses the agent you set it up with. `npx usepilot init --agent codex` (or `claude`, `cursor`) switches, remembered for the project; then restart your dev server. (`npx usepilot --agent codex` does the same when you run Pilot that way.)\n\n**What the agent may do:** edit the project's files, and whatever you've already set it to always allow. Anything it would normally ask permission for is refused, since no one is there to answer; its reply says what was refused. For an MCP server or a website, the reply has a **Copy instructions** button: paste them into your agent's chat to allow it for this project. Commands are never allowed this way.\n\n**Updating:** run `npx usepilot@latest update` in the project's folder, then restart your dev server (and `npx usepilot`, if you run it).\n\n## Opening, hiding and closing Pilot\n\n- **Option+P** (Alt+P on Windows and Linux) opens Pilot on any page of your app. Pilot starting (with the dev server, or `npx usepilot`) also opens it in the app's open tabs.\n- **Hide:** Option+P again, or the toolbar's eye button, hides Pilot in this tab and keeps everything as it was (the selection, the dialog, what you typed). The page is fully yours meanwhile: hover, click and focus work normally, your edits stay on it. Press Option+P again to come back. Use it to try a hover or a click for real.\n- **Close:** the toolbar's last button closes Pilot in every tab of the site. Jobs keep running, and Option+P opens it again.\n- Pilot remembers per browser tab whether it's open, so reloads don't open or close it.\n\n## The toolbar\n\nFrom left to right:\n\n| Button | What it does |\n| --- | --- |\n| **Comment** (speech bubble, Option+C) | Click an element to ask the agent for a change in your own words. Its count is the threads waiting for you; clicking it while it's on goes to the next one. |\n| **Select** (cursor, Option+V) | Click an element to edit its properties. |\n| **Send** | Sends your changes not sent yet to the agent, as one job. Its count is how many it would send. |\n| **Discard** (brush) | Takes your unsent changes off the page, in one undo step. Sent ones stay. |\n| **Jobs** (a robot at a laptop) | Shows while jobs are running, with how many. Clicking it scrolls to the next job's elements. |\n| **Hide** (eye) | Hides Pilot in this tab, everything kept. |\n| **Close** | Closes Pilot on the whole site. |\n\nDrag the toolbar by the strip along its top edge; it stays where you put it.\n\n## Selecting elements\n\n- **Select** (Option+V), then **hover** an element to see its name and size, and **click** to select it. The click doesn't reach the page, so links and buttons don't fire.\n- **Several elements:** Shift+click adds an element or takes it out. A plain click selects just one again.\n- **Select similar** (a button above the selection's corner) adds every element like the selected one: in a React or Vue app, the same part of every instance of its component (every card's title, not every heading); elsewhere, the same part of every repeated copy.\n- **Show in DOM** (`< >` on the selection's corner) opens the [DOM tree](#the-dom-tree) on it.\n- **Esc** clears the selection; with nothing selected, Esc turns the tool off.\n- Grid containers show their grid lines and numbers; hovering an element stripes its padding, margin and gaps.\n- The selection survives your agent's reloads (hot reload and full reloads).\n\n## Editing properties\n\nSelect an element and its **property dialog** opens beside it.\n\n- **With nothing typed**, it lists every property the element sets, grouped (Layout, Position, Appearance, Effects, Transform, Typography, Interactivity, SVG, Visibility).\n- **Search** by CSS name or Tailwind class: `p`, `pt`, `px`, `w`, `min-w`, `gap`, `display`, `items`, `aspect`, `bg`, `font`, `text`, `rounded`, `shadow`\u2026 Abbreviations work too (`mxw` is max-width). The search finds properties only: type values in the editor (`pt-4` in the search isn't a value).\n- **Tab** or **Enter** goes into the editor, **Enter** applies and goes back to the search for the next property: `pt` Tab `24` Enter.\n- **Values:** type a number (`12` is 12px), any CSS unit, a keyword (`auto`), math (`100% - 20px`), or a [variable](#variables-and-tokens). **\u2191/\u2193** step by 1, **Shift** by 10; the scroll wheel does the same on a field being edited. Some fields have a **drag handle** to scrub the value.\n- **Linked sides** work like Tailwind: `p` sets all four sides, `px` left and right, `py` top and bottom. The button beside padding, margin, inset, gap and radius switches between one value and each side.\n- **Several selected:** each change goes to all of them. A field whose value differs between them says **Mixed**; typing a value sets it on all.\n- **Clearing a field** (empty it and press Enter) means \"this element doesn't set this property\": Pilot takes the property off that element, not set to 0.\n- **Rich properties** (box shadow, filter, backdrop filter, mask image) show their values as chips: click one to edit it in a panel beside the dialog, **+** to add one.\n- **Copy and paste:** right-click a property's name for **Copy CSS**, **Copy properties** and **Paste properties** (onto the selected elements).\n- **Fields show what your CSS declares**, not computed values; hover a field to see what math or a variable comes to.\n- The dialog stays where it opened while you edit; drag it by the strip along its top edge.\n\n## Variables and tokens\n\nUse your project's tokens anywhere a value goes:\n\n- **Type `--`** in a field to list the page's CSS variables that fit (spacing for a padding, colors for a color\u2026), filtered as you type, by name or value. It works inside math too: `calc(--sp`\u2026\n- **The variable button** on the right edge of a hovered field opens the same list to browse.\n- **\u2191/\u2193** on a field holding a token move along its scale (`--space-3` \u2192 `--space-4`); Shift+drag on the handle does the same.\n- Tokens kept in files rather than CSS (a W3C or Style Dictionary `tokens.json`, Sass `$variables`) are listed too while Pilot runs for the project. Tailwind v3 configs aren't read.\n\nThe agent writes the token the project's way, never a raw value.\n\n## Screen widths (breakpoints)\n\n**By default, an edit goes where your CSS already puts it at the current window width.** With `pt-2 md:pt-4 lg:pt-12` and the window between md and lg, padding-top shows and changes the `md:` value. Resize, and the field follows. Where nothing sets the property, the edit is the base value.\n\nTo choose the widths yourself, start the search with a **width modifier**:\n\n- `from-768 ` (with a space): from 768px up. `to-767 `: up to 767px. Both make a range: `from-768 to-1199 `.\n- `base `: the value with no media query (no breakpoint).\n- `all-widths `: one value at every width; your breakpoint rules for that property are removed.\n- After `from-` or `to-`, a list offers the window's width and the page's breakpoints; **Tab** takes the suggestion.\n- **The width ruler:** hover the very top of the window to see the window's width and the page's breakpoints. Click the width or a breakpoint to set `from` it; Shift+click for `to`.\n- While a property is in use, the ruler shows bars for where its values apply: green where your edit goes.\n\nModifiers stay set across selections until you remove them (the pill's \xD7, or Backspace at the start of the search). Click **default** in the pill row to go back to no modifiers without losing them. Edits for widths other than the window's don't show on the page until you resize into them.\n\n## Hover, focus, dark mode and other states\n\nStart the search with a state, Tailwind style, or type `/` to pick one:\n\n| Modifier | Edits |\n| --- | --- |\n| `hover:` `focus:` `focus-visible:` `active:` | the element in that state |\n| `dark:` `light:` | the page in dark (or light-only) mode, the way your project does dark mode |\n| `before:` `after:` `placeholder:` | the element's `::before`, `::after`, or a field's placeholder |\n\n- They combine with each other and with widths: `hover:from-768 `, `dark:hover:`.\n- **`before:` and `after:`** add `content: \"\"` with your first change when the element has no `::before` (`::after`) yet, so it's drawn; one Cmd+Z takes both back. Type its text in **content** (`Popular`, `\u2713`): Pilot adds the quotes.\n- **Pilot doesn't force the state on the page.** The fields show and edit what's set for that state; to see it, hide Pilot (Option+P) and hover or focus the element, or switch your system or site to dark mode.\n- **`/` at the start of the search** lists every modifier, and first the combinations this element already uses, with what each sets.\n\n## Editing text\n\nWith **Select** on, **double-click** a text to edit it in place. **Enter** is done, **Esc** cancels. In an element with other elements inside, you edit the run of text under the pointer. Text edits are sent and undone like any other change.\n\n## Undo, discard and reloads\n\n- **Cmd/Ctrl+Z** undoes, **Cmd/Ctrl+Shift+Z** (or Ctrl+Y) redoes. A whole drag is one step.\n- **Discard** takes every unsent change off the page, as one undo step.\n- Your changes survive reloads in the same browser tab, and stay previewed on the page until they're really in your code.\n\n## Sending changes to your agent\n\n- **Send** sends your unsent changes as one job. Keep designing: new changes go in the next job, and up to five jobs run at once.\n- While a job is on an element, it shows a **loader** on its corner; its tooltip says where the job stands. Hover the loader and click the \xD7 to **stop** the job.\n- A new change or comment on an element with a job on it **waits** (\"Queued\") and goes once that job is done, so two jobs never edit the same element at once.\n- **Pilot checks the page** when the agent is done. What landed stops being previewed. What didn't goes back to the agent once; after that, Pilot accepts what the code gives. To insist on a value, edit it again and Send.\n- The agent writes your changes in the project's own way (Tailwind classes, CSS modules, tokens\u2026), never as inline styles.\n\n## Comments\n\n- **Comment** (Option+C), click an element (Shift+click for several), and write what you want in your own words. **Enter** sends, **Shift+Enter** is a new line, **Esc** closes (your draft is kept).\n- **Attach** images, text files or PDFs with the attach button, or drop them on the box.\n- **Unsent edits go along:** edits you made on those elements show as a chip (\"2 changes\") and go with the comment; remove the chip to keep them for Send. Where the comment and an edit disagree, the comment wins.\n- Each element has a **thread**: the agent replies in it, and you can reply to follow up (\"a bit more\"): the agent remembers the thread.\n- A thread with a reply to read shows a **comment icon** on its element and counts on the Comment button.\n- **Edit manually**, under a reply that changed the element's look, switches to Select with those elements selected, to fine-tune what the agent chose.\n- **Mark as solved** (or Option+Enter) closes the thread.\n- **Stop** (beside send) cancels the job while the agent works.\n\n## Skills and Pilot's tasks (the / list)\n\nType `/` at the start of a word in the comment box:\n\n- **Your agent's skills**, the ones its own `/` shows (the project's, then yours). A bare `/` lists the first few; type to see every match (`/emil`). Pick one and the agent uses it for this comment.\n- **Props**, on a component's instance: lists the props that change how it looks. Reply with a line like `tone: dark` to change one.\n- **Make responsive**: makes the element work at every screen width. Pilot checks the result at a phone width, each breakpoint and a wide desktop, and sends problems back to the agent once.\n\n## Mentions (@)\n\nType `@` in a comment to name things instead of describing them: the page's **tokens** and **breakpoints** (`--color-brand`, `@768px`), its **components** (`@ProductCard`, also ones not on this page while Pilot runs for the project), and its **named elements** (`@section#features`). The agent gets exactly what you picked, and where it is in the code.\n\n## When the agent asks you something\n\nWhen part of a job needs your decision, the agent asks in a thread instead of guessing, and does the rest. It leaves that part unchanged until you answer, and says so (\"Not changed yet: \u2026\"). The most common question: you changed one card, or commented on it, and the cards share one component. A question about several elements gets a thread of its own. Answer with a button:\n\n- **All of them** changes the component itself.\n- **Only this** changes this one instance.\n- **New variant** adds a named option to the component and uses it here.\n\nOr write your own answer (only the buttons' exact words are read as \"every copy\" for the loaders). Selecting every instance of a component (Select similar) already says \"all of them\", so the agent changes the component without asking.\n\nOnce you answer, the loaders show where the agent works now: on the element it asked about, and with **All of them** on every instance like it on the page. The rest of the job's elements are done.\n\n## Measuring distances\n\nWith an element selected, **hold Alt (Option)** and move the pointer: Pilot shows the distances from the selection to the element under the pointer (or to its parent), in red. Release Alt to go back.\n\n## The DOM tree\n\n**Alt+D** (or Show in DOM) opens a tree of the page's elements, to select what's hard to click: overlapping, zero-size or hidden elements. Click a row to select it, **\u2191/\u2193** to move, **\u2192/\u2190** to open and close. Cmd/Ctrl+click adds a row, Shift+click selects a range. In a React or Vue app, **Components** at the top switches to the tree of component instances. `::before` and `::after` are listed too, not selectable: hover one to see its box on the page.\n\n## Keyboard shortcuts\n\n| Keys | Does |\n| --- | --- |\n| **Option+P** (Alt+P) | Open Pilot; once open, hide and show it |\n| **Option+V** / **Option+C** | Select tool / Comment tool |\n| **Alt+D** | DOM tree |\n| hold **Alt** | Measure distances |\n| **Esc** | One step back: editor \u2192 search \u2192 clear search \u2192 close the dialog \u2192 turn the tool off |\n| **Cmd/Ctrl+Z**, **Cmd/Ctrl+Shift+Z** | Undo, redo |\n| **Tab** / **Enter** in the search | Into the editor |\n| **Enter** in an editor | Apply, back to the search |\n| **\u2191/\u2193**, **Shift+\u2191/\u2193** | Step a value by 1, by 10 (a token: along its scale) |\n| **Tab** / **Shift+Tab** in an editor | Next / previous field |\n| `/` at the start of the search | Modifiers (widths, states) |\n| **Backspace** at the start of the search | Remove the last modifier |\n| double-click a text | Edit it in place |\n| **Shift+click** | Add to the selection |\n| **Enter** / **Option+Enter** in a comment | Send / mark as solved |\n\nThe shortcuts with Option work in Pilot's own fields too, but not while you're typing in the page's fields.\n\n## When something's wrong\n\nPilot says when it's stuck: a red **!** on a toolbar button (hover it for what to do), a red warning on an element's corner, or a red reply in a thread.\n\n- **The toolbar doesn't appear.** Pilot only loads in development, in the browser. Press Option+P. If nothing happens, ask your agent to check where `usepilot/auto` is imported (Option+P is ignored while you type in the page's fields).\n- **\"Pilot isn't running for this site\"**: restart your dev server, which starts Pilot (its terminal says why, if it doesn't). Without that setup, run `npx usepilot` in the project's folder and keep it running. Its terminal says why it skipped the page (another project's page, or a loader set up before 0.15: run `npx usepilot@latest update`).\n- **\"Sign in to \u2026\"**: your agent isn't signed in. Click Send to open its sign-in page; what you sent goes once you've signed in. If the page doesn't open, or the sign-in doesn't finish, sign in in a terminal (see [Setting up](#setting-up)).\n- **Your agent's tool isn't installed**: ask your agent to install its command-line tool (or run the command Pilot shows). What you sent waits, and goes once it's ready.\n- **\"\u2026 couldn't do this job\"**: the dev server's terminal (or the one running `npx usepilot`) shows what the agent said.\n- **\"\u2026 needs an update\"**: your agent's command-line tool is too old for Pilot; run the command it gives.\n- **\"\u2026 has gone quiet\"**: no sign of work for 2 minutes. Click to stop the job, then send again.\n- **A reply says something was refused**: the agent wasn't allowed to do it in its settings. See *What the agent may do* in [Setting up](#setting-up).\n- **A change shows on the page but not in the code yet**: it stays previewed until the agent's job lands. A change for another screen width or a state can't be checked on the page, so Pilot takes the agent's word for it.\n\n## What Pilot doesn't do (yet)\n\n- It never edits your code itself, and never runs on your live site: the agent writes the code.\n- No adding, moving or deleting elements from Pilot: ask in a comment.\n- No forcing hover or focus on the page while editing those states (hide Pilot to try them).\n- No values typed in the search (`pt-4` + Enter): search for the property, then type the value.\n- No Copy prompt: everything goes through Pilot running for the project (with the dev server, or `npx usepilot`).\n- Components are read in React and Vue only (not Svelte or Angular). Tailwind v3 config tokens aren't read.\n- Props work on one component instance at a time.\n\n## Commands and options\n\n| Command | Does |\n| --- | --- |\n| `usepilot dev -- <command>` | Run your dev server with Pilot in it, in a `package.json` script (`\"dev\": \"usepilot dev -- vite\"`); Vite and Next.js use their own way (`usepilot/vite`, `usepilot/next`), set up by `init` |\n| `npx usepilot` | Run Pilot for this project, beside a dev server Pilot doesn't start with. `--agent claude\\|codex\\|cursor` picks the agent, `--url <address>` gives the app's address when Pilot can't tell |\n| `npx usepilot@latest init` | Set Pilot up in a project (ask your agent to run it) |\n| `npx usepilot@latest update` | Update Pilot in this project |\n| `npx usepilot guide` | Print this guide |\n| `npx usepilot help` | List the commands |\n\nOptions, where your app loads Pilot:\n\n```ts\nimport { mountPilot } from \"usepilot\";\n\nmountPilot({\n shortcut: \"alt+p\", // or \"ctrl+shift+e\", or false\n launch: false, // true: open on load\n nameAttributes: [\"data-block\"], // attributes your project names elements with\n project: \"my-app\", // your package.json's name: npx usepilot runs for its own project's pages\n});\n```\n";
219
27
 
220
28
  // src/init.ts
221
29
  import { spawnSync } from "child_process";
222
- import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync3 } from "fs";
223
- import { homedir as homedir3 } from "os";
224
- import { dirname as dirname2, join as join4, relative } from "path";
225
-
226
- // src/config.ts
227
- import { mkdirSync, readFileSync, writeFileSync } from "fs";
228
- import { homedir as homedir2 } from "os";
229
- import { basename, dirname, join as join2, resolve } from "path";
230
-
231
- // ../protocol/src/types.ts
232
- function mentionText(reference) {
233
- return reference.kind === "token" ? reference.name : `@${reference.name}`;
234
- }
235
- var ATTACHMENT_TYPES = {
236
- png: "image/png",
237
- jpg: "image/jpeg",
238
- gif: "image/gif",
239
- webp: "image/webp",
240
- pdf: "application/pdf",
241
- txt: "text/plain",
242
- md: "text/markdown",
243
- csv: "text/csv",
244
- json: "application/json"
245
- };
246
- var ATTACHMENT_ID = /^[a-f0-9]{64}\.(png|jpg|gif|webp|pdf|txt|md|csv|json)$/;
247
- function attachmentKind(name) {
248
- const ext = name.split(".").pop()?.toLowerCase();
249
- return ext === "pdf" ? "pdf" : ext === "png" || ext === "jpg" || ext === "jpeg" || ext === "gif" || ext === "webp" ? "image" : "text";
250
- }
251
- var BY_EXTENSION = {
252
- png: "image/png",
253
- jpg: "image/jpeg",
254
- jpeg: "image/jpeg",
255
- gif: "image/gif",
256
- webp: "image/webp",
257
- pdf: "application/pdf",
258
- txt: "text/plain",
259
- log: "text/plain",
260
- text: "text/plain",
261
- md: "text/markdown",
262
- markdown: "text/markdown",
263
- csv: "text/csv",
264
- json: "application/json"
265
- };
266
- var ATTACHMENT_ACCEPT = [...new Set(Object.values(ATTACHMENT_TYPES))].join(",") + "," + Object.keys(BY_EXTENSION).map((e) => `.${e}`).join(",");
267
- function requestTargets(request) {
268
- return [request.target, ...request.others ?? []];
269
- }
270
-
271
- // ../protocol/src/format.ts
272
- function formatPrompt(changeSet) {
273
- if (changeSet.request?.kind === "responsive") return formatResponsive(changeSet, changeSet.request);
274
- if (changeSet.request?.kind === "break-and-fix") return formatBreakFix(changeSet, changeSet.request);
275
- if (changeSet.request?.kind === "comment") return formatComment(changeSet, changeSet.request);
276
- if (changeSet.request?.kind === "props") return formatProps(changeSet, changeSet.request);
277
- const { page, edits, note } = changeSet;
278
- const lines = [
279
- "# Pilot design edits",
280
- "",
281
- "A designer adjusted the UI below in the browser with Pilot. Apply these changes to the source code.",
282
- "",
283
- "Guidelines:",
284
- ...editGuidelines(),
285
- "",
286
- `Page: ${page.url} (${page.title || "untitled"}) at ${page.viewport.width}x${page.viewport.height}`
287
- ];
288
- if (note?.trim()) {
289
- lines.push("", `Designer note: ${note.trim()}`);
290
- }
291
- edits.forEach((edit, index) => {
292
- lines.push("", ...formatEdit(edit, index + 1));
293
- });
294
- lines.push(...fileTokenLines(changeSet.fileTokens));
295
- return `${lines.join("\n")}
296
- `;
297
- }
298
- function fileTokenLines(tokens) {
299
- if (!tokens?.length) return [];
300
- return [
301
- "",
302
- "## The project's tokens in these values",
303
- "",
304
- "Some values use tokens from the project's files, which Pilot previewed as CSS variables of its own: they're not in the code. Write each the way the project uses that token (its utility, its variable, its theme), never the `var(--\u2026)` itself:",
305
- "",
306
- ...tokens.map((t) => `- \`var(${t.variable})\` is \`${t.name}\` in \`${t.file}${t.line ? `:${t.line}` : ""}\` (\`${t.value}\`)`)
307
- ];
308
- }
309
- function advancedTask() {
310
- return "**An advanced task: it needs judgment more than speed.** If you can hand work to a more capable model than the one you run on (a subagent, or another model your agent offers), do: give it this whole prompt, have it make the changes, and report back with what it did.";
311
- }
312
- var DESIGN_INTENT = "**These are design instructions, not code**: the designer's intent, shown as plain CSS values. Use your judgment and write production code the way this project already styles things, whatever it uses (Tailwind, CSS or Sass modules, StyleX, vanilla-extract, Panda, styled-components, Emotion, a component library's props\u2026). First look at how each element's component is styled, and follow that: its tokens and scale, its variants and props, and the rule that already styles it rather than a new override.";
313
- var PRODUCTION_CODE = "No inline styles, no `!important`, no hard-coded values where a token or utility fits.";
314
- var SHARED_CHOICES = {
315
- all: { label: "All of them", means: "change the component (or the shared code) itself, so every instance gets it." },
316
- one: {
317
- label: "Only this",
318
- means: "change it where this instance is used, with what the component already accepts: classes passed through its `className` (merged the way the project does, `cn`, `twMerge`), or one of its props. If it accepts neither, add the smallest pass-through (accept a `className`), not a variant. Never inline styles."
319
- },
320
- variant: {
321
- label: "New variant",
322
- means: "add a named option to the component, the way it defines its variants (a `cva` variant, a `variant` or `size` prop, a modifier class), named for its purpose, and use it here. Say its name in your notes."
323
- }
324
- };
325
- function sharedChoiceMeaning(answer) {
326
- const said = answer.trim().toLowerCase();
327
- const choice = Object.values(SHARED_CHOICES).find((c) => c.label.toLowerCase() === said);
328
- return choice ? `**${choice.label}**: ${choice.means}` : null;
329
- }
330
- function sharedCode() {
331
- return [
332
- `**Shared code, only some copies:** an element's "Look-alikes" line counts the elements like it that this job leaves out (other instances of its component, or the same part of other copies). 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 in one short sentence, the component's name in **bold**, with three choices, your suggestion first: "${SHARED_CHOICES.all.label}", "${SHARED_CHOICES.one.label}", "${SHARED_CHOICES.variant.label}" (as the question in your reply's \`pilot\` block). Their answer comes back to you as this job.`,
333
- ...Object.values(SHARED_CHOICES).map((c) => `**${c.label}**: ${c.means}`),
334
- `Don't ask when the designer already said (in the comment or note: "only here", "every card", "as a variant"), when every copy is in the job, or when nothing else uses that code: just change it.`
335
- ].join(" ");
336
- }
337
- function editGuidelines() {
338
- return [
339
- `- ${DESIGN_INTENT}`,
340
- `- ${PRODUCTION_CODE} Prefer an existing token or utility when it matches the value (or is within a pixel or two): utility classes take the closest one in the project's scale or theme (\`padding-top: 24px\` \u2192 \`pt-6\`), arbitrary values only when nothing fits. Mention any value you had to approximate.`,
341
- "- Find each element by its selector, DOM path and text, then the component that renders it. Change only the listed elements.",
342
- `- ${sharedCode()}`,
343
- "- A removed property means the element shouldn't declare it at all: not `0` or `none`, the declaration gone.",
344
- "- No screenshots, builds or tests for these edits: hot reload shows them, and Pilot checks the page itself.",
345
- `- Widths are viewport widths in CSS px, both ends included. Use this project's breakpoints when one matches (or is within a few pixels), else a custom media query, and say which. "Every width" means no media query: the value holds at every viewport width, and no existing media query should override it.`,
346
- "- A Text change is the element's copy (all of its text, or the part between its child elements): replace the old text with the new one where it comes from (the markup, a prop, a translation file, a CMS fixture), the rest of the element as it is. If the same text is used elsewhere, change only this element's, unless the designer's note says otherwise.",
347
- "- A State is the element state the change is for, all of them together (\"hover, active\": hovered and pressed). Use the project's own form: Tailwind's variants (`hover:`, `focus-visible:`, `hover:active:`), `:hover` and the like in CSS. Without a state, the change is for the element as it is (any state)."
348
- ];
349
- }
350
- var PROJECT_CODE = `**Write production code in the project's own styling system**, whatever it uses (Tailwind, CSS or Sass modules, StyleX, styled-components\u2026), following how this element's component is styled: its tokens and scale, the rule that already styles it. ${PRODUCTION_CODE}`;
351
- var ACTION_ASKED = {
352
- responsive: "asked you to make it responsive",
353
- "break-and-fix": "asked you to break and fix it",
354
- props: "asked for the component's props"
355
- };
356
- function propValue(value) {
357
- return value === void 0 ? "*not set*" : `\`${typeof value === "string" ? JSON.stringify(value) : String(value)}\``;
358
- }
359
- function formatProps(changeSet, request) {
360
- const { page, note } = changeSet;
361
- const current = Object.entries(request.current);
362
- const lines = [
363
- "# Pilot: props",
364
- "",
365
- `A designer selected an instance of the \`${request.component}\` component in the browser with Pilot, to change it through its props from a list. Read the component's code and list its props for them. **Don't change any code.**`,
366
- "",
367
- `Page: ${page.url} (${page.title || "untitled"}), seen at ${page.viewport.width}x${page.viewport.height}`,
368
- "",
369
- ...elementsSection(request),
370
- ...request.usedIn ? [`- This instance is written in: \`${request.usedIn}\``] : [],
371
- "",
372
- "## Its props now (read from the page)",
373
- "",
374
- ...current.length ? current.map(([name, value]) => `- \`${name}\`: ${propValue(value)}`) : ["None that Pilot could read (it reads strings, numbers and on-off values)."],
375
- ...note?.trim() ? ["", `Designer note: ${note.trim()}`] : [],
376
- ...request.attachments?.length ? ["", ...attachmentLines(request.attachments, `The designer attached ${countFiles(request.attachments.length)}:`)] : [],
377
- ...request.references?.length ? ["", ...referenceLines(request.references)] : [],
378
- "",
379
- "## What to list",
380
- "",
381
- "- **The props that change how it looks or what it shows:** variants, sizes, tones, on-off flags (`disabled`, `loading`), short texts (a label, a title), numbers (a count). Not event handlers, refs, children, class names or styles.",
382
- '- **For each:** `name`; `type`: `options` (one of a set of values), `boolean`, `text` or `number`; for `options`, every value it accepts, from its types (a union like `"primary" | "ghost"`), its variants config (cva, tailwind-variants, a variants object), its prop validation (a Vue `validator`, `PropTypes.oneOf`), or how the component uses it; `default` when it has one; `description` in a few words when the name doesn\'t say.',
383
- "- The most useful first (the main variant, then the size, then the rest); 12 at most.",
384
- "",
385
- "Reply with one short sentence for the designer, like a chat message (\"Button has 3 props you can change\"), and the list as `props` in your reply's `pilot` block. Pilot shows the props in the designer's thread, each with its value on this instance; what they pick comes back to you as a comment, a `name: value` line per prop (`tone: dark`), to set where this instance is written. If none is worth listing, say so and leave the block out."
386
- ];
387
- return `${lines.join("\n")}
388
- `;
389
- }
390
- function formatBreakFix(changeSet, request) {
391
- const { page, note } = changeSet;
392
- const { breakpoints } = request;
393
- const several = requestTargets(request).length;
394
- const widths = breakpoints.length ? breakpoints.map((b) => `${b}px`).join(", ") : "none found (it may use container queries, or none yet)";
395
- const lines = [
396
- "# Pilot: break and fix",
397
- "",
398
- several > 1 ? `A designer selected the ${several} elements below together in the browser with Pilot and asked you to stress-test each of them: make sure they hold up with real-world content, not only the placeholder values they were built with, and fix what breaks. Content should never break the layout.` : "A designer selected the element below in the browser with Pilot and asked you to stress-test it: make sure it holds up with real-world content, not only the placeholder values it was built with, and fix what breaks. Content should never break the layout.",
399
- "",
400
- `Page: ${page.url} (${page.title || "untitled"}), seen at ${page.viewport.width}x${page.viewport.height}`,
401
- `The page's breakpoints (the widths its media queries test): ${widths}`,
402
- "",
403
- advancedTask()
404
- ];
405
- if (note?.trim()) lines.push("", `Designer note: ${note.trim()}`);
406
- if (request.attachments?.length)
407
- lines.push("", ...attachmentLines(request.attachments, `The designer attached ${countFiles(request.attachments.length)}:`));
408
- if (request.references?.length) lines.push("", ...referenceLines(request.references));
409
- lines.push(
410
- "",
411
- ...elementsSection(request),
412
- "",
413
- "## How to do it",
414
- "",
415
- "1. **Find the element's component and where its content comes from**: props, data, a CMS or an API, translations. List what can vary: each text, how many repeated items there are, optional parts (an image, a subtitle, a badge), numbers, names, URLs.",
416
- "2. **Think of the odd but realistic content each can get**: text far longer than the placeholder (a 120-character title, a long person or product name) and much shorter or empty; long words with no spaces (URLs, emails, IDs, compound words); optional parts missing (no image, no subtitle, an empty list) and many repeated items instead of a few; big numbers and prices; the longer strings of other languages; images (and background images) in odd shapes, very wide, very tall, tiny or low-resolution, and images that fail to load.",
417
- "3. **Find where it breaks**: for each kind of odd content, read the layout code and work out what it would do: content sticking out of the viewport, spilling out of its parent, clipped, or overlapping; items that shrink when they shouldn't (an icon or avatar squeezed by flex), buttons that stretch, rows that misalign, text wrapping under an icon, images stretched or squashed. If trying it helps, put the content in temporarily and take it out again; no browser or screenshots.",
418
- "4. **Fix what breaks, without changing how it looks with its usual content**, the way this project does it (its utilities, its components):",
419
- " - **Long text:** truncate it with an ellipsis (`truncate`, `text-overflow: ellipsis`) where one line matters, or clamp it to a few lines (`line-clamp-*`) where it can wrap; when the full text is lost, show it on hover (`title`, or the project's tooltip).",
420
- " - **Flex and grid:** `min-width: 0` (`min-w-0`) on items holding text so they can shrink; `flex-shrink: 0` (`shrink-0`) on icons, avatars and buttons that mustn't; `minmax(0, 1fr)` columns; wrapping rows (`flex-wrap`) instead of overflowing ones.",
421
- " - **Long words:** `overflow-wrap: anywhere` (`break-words`) where text must wrap.",
422
- " - **Images:** `object-fit: cover` for photos that should fill their frame, `contain` where cropping would lose something (logos, product shots); for background images, `background-size: cover` (or `contain`) with a sensible `background-position`. A fixed `aspect-ratio` (or size) on the frame, so the layout doesn't jump while an image loads or when its shape is odd, and a fallback when it fails or is missing (a plain background, initials, an icon), never a broken-image box.",
423
- " - **Missing parts:** no gap or empty box left behind; a simple empty state only where one is clearly needed.",
424
- " In the check, an ellipsis on your deliberately long text is the fix working, not a problem.",
425
- "5. **Put the real content back.** Remove every temporary value you added: nothing of the test may stay in the code. With its usual content, the element must look as it did at the designer's width.",
426
- `6. **Report** in your notes, in a line or two, what broke and how you fixed it, and anything for the designer to decide (a content limit to agree on, an empty state to design). When you report it done, Pilot runs the width check once more, with the usual content: problems come back to you once, as a follow-up.`,
427
- "",
428
- several > 1 ? `Change only these elements and what they need (their children, their containers). If they come from a shared component, fix it there, so every instance gets sturdier, as long as its usual look doesn't change; ask before anything that would. ${firstChecked()}` : "Change only this element and what it needs (its children, its container). If it's a shared component, fix it there, so every instance gets sturdier, as long as its usual look doesn't change; ask before anything that would.",
429
- "",
430
- PROJECT_CODE
431
- );
432
- return `${lines.join("\n")}
433
- `;
434
- }
435
- function formatResponsive(changeSet, request) {
436
- const { page, note } = changeSet;
437
- const { breakpoints } = request;
438
- const several = requestTargets(request).length;
439
- const widths = breakpoints.length ? breakpoints.map((b) => `${b}px`).join(", ") : "none found (it may use container queries, or none yet)";
440
- const lines = [
441
- "# Pilot: make responsive",
442
- "",
443
- several > 1 ? `A designer selected the ${several} elements below together in the browser with Pilot and asked you to make each of them work well at every viewport width, from a narrow phone to a wide desktop. Decide the changes yourself and apply them to the source code.` : "A designer selected the element below in the browser with Pilot and asked you to make it work well at every viewport width, from a narrow phone to a wide desktop. Decide the changes yourself and apply them to the source code.",
444
- "",
445
- `Page: ${page.url} (${page.title || "untitled"}), seen at ${page.viewport.width}x${page.viewport.height}`,
446
- `The page's breakpoints (the widths its media queries test): ${widths}`,
447
- "",
448
- advancedTask()
449
- ];
450
- if (note?.trim()) lines.push("", `Designer note: ${note.trim()}`);
451
- if (request.attachments?.length)
452
- lines.push("", ...attachmentLines(request.attachments, `The designer attached ${countFiles(request.attachments.length)}:`));
453
- if (request.references?.length) lines.push("", ...referenceLines(request.references));
454
- lines.push(
455
- "",
456
- ...elementsSection(request),
457
- "",
458
- "## How to do it",
459
- "",
460
- "1. **Find the element's component** and the layout around it (its parent and siblings): a fix often belongs to the container, not the element.",
461
- "2. **Learn how this project does responsive**: its breakpoints and their names (Tailwind config or theme, CSS variables, existing media queries), whether components respond to their container instead (container queries, `@container`), and whether it writes mobile-first (min-width) or desktop-first (max-width). Use its breakpoints; don't invent new ones.",
462
- "3. **Find similar components** that already have responsive rules (other cards, lists, headers, forms in this project) and follow the same patterns, so this one behaves like its siblings.",
463
- "4. **Make the smallest changes that work**, in the project's conventions (Tailwind variants like `md:`, the media queries it already uses, its tokens): layout first (stacking, wrapping, columns, flex direction), then spacing and type size. Hide content only as a last resort, and say so. Don't change how it looks at the width the designer is working at unless that width has a problem too. Never leave inline styles.",
464
- "5. **Check every width from the code**: work out how the element lays out at a phone width (375px), each breakpoint and 1px below it, and a wide desktop (1440px), and fix what wouldn't fit. No browser or screenshots: when you're done, Pilot loads the page at those widths, measures the element (sticking out of the viewport, spilling out of its parent, clipped content, overlaps, anything changed at the designer's width) and sends back what it finds, once.",
465
- `6. **Report** in your notes what changed at which widths, in a line or two, and anything you left for the designer to decide. When you report it done, Pilot runs the width check once more: problems come back to you once, as a follow-up.`,
466
- "",
467
- several > 1 ? `Change only these elements and what their layout needs (their containers, their children). ${firstChecked()}` : "Change only this element and what its layout needs (its container, its children).",
468
- "",
469
- sharedCode(),
470
- "",
471
- PROJECT_CODE
472
- );
473
- return `${lines.join("\n")}
474
- `;
475
- }
476
- function formatComment(changeSet, request) {
477
- const { page, edits } = changeSet;
478
- const { thread, breakpoints } = request;
479
- const several = requestTargets(request).length;
480
- const latest = thread.at(-1);
481
- const earlier = thread.slice(0, -1);
482
- const widths = breakpoints.length ? breakpoints.map((b) => `${b}px`).join(", ") : "none found (it may use container queries, or none yet)";
483
- const lines = [
484
- "# Pilot: comment",
485
- "",
486
- several > 1 ? `A designer left a comment on the ${several} elements below, selected together in the browser with Pilot: it's about each of them. Do what it asks in the source code (or, if it's a question, answer it).` : "A designer left a comment on the element below, in the browser with Pilot. Do what it asks in the source code (or, if it's a question, answer it).",
487
- "",
488
- `Page: ${page.url} (${page.title || "untitled"}), seen at ${page.viewport.width}x${page.viewport.height}`,
489
- `The page's breakpoints (the widths its media queries test): ${widths}`,
490
- "",
491
- ...elementsSection(request),
492
- "",
493
- "## The comment",
494
- "",
495
- // Props set from the thread, with no words: the props are the comment.
496
- ...latest?.props && !latest.text.trim() && !latest.attachments?.length ? ["The designer set props on this instance (below), with no words."] : latest?.skill && !latest.text.trim() && !latest.attachments?.length ? [`The designer picked the skill \`${latest.skill}\` (below), with no words: use it on ${several > 1 ? "these elements" : "this element"}.`] : commentLines(latest)
497
- ];
498
- if (latest?.skill) {
499
- lines.push(
500
- "",
501
- "## The skill to use",
502
- "",
503
- `The designer asked you to use their skill \`${latest.skill}\` for this comment: load it the way you load skills, and follow it for ${several > 1 ? "these elements" : "this element"}. Where it and the guidelines below differ, the skill wins; what it doesn't say, they cover. If a step needs something you can't do in this run (a permission you don't have, a tool that isn't there), skip it and say so in your reply. If there's no skill by that name, say so and don't guess what it does.`
504
- );
505
- }
506
- if (latest?.props?.set.length) {
507
- const { component, usedIn, set } = latest.props;
508
- lines.push(
509
- "",
510
- "## Props to set",
511
- "",
512
- `The designer picked new values for this \`${component}\` instance's props from the list you gave (the \`name: value\` lines in their comment):`,
513
- "",
514
- ...set.map((c) => `- \`${c.name}\`: ${propValue(c.from)} \u2192 ${propValue(c.to)}`),
515
- "",
516
- `Set them where this instance is written${usedIn ? ` (\`${usedIn}\`, its \`<${component} \u2026>\`)` : ` (its \`<${component} \u2026>\`)`}, not in the component itself: only this instance changes. If that line renders several instances (a loop over data) or the value comes from data or a variable, ask (the question in your reply's \`pilot\` block) before changing it for all of them. Pilot reads the instance's props on the page when you're done.`
517
- );
518
- }
519
- if (edits.length) {
520
- lines.push(
521
- "",
522
- "## The designer's edits, sent with the comment",
523
- "",
524
- `Before writing it, the designer changed these in Pilot's editor: apply them too, exactly, as design edits. The comment may be about them ("like this, on mobile too"). Pilot checks them on the page when you're done.`,
525
- "",
526
- "Guidelines:",
527
- ...editGuidelines()
528
- );
529
- edits.forEach((edit, index) => lines.push("", ...formatEdit(edit, index + 1).map((l) => l.startsWith("## ") ? `#${l}` : l)));
530
- lines.push(...fileTokenLines(changeSet.fileTokens));
531
- }
532
- if (earlier.length) {
533
- lines.push("", "## The thread so far (you already did what it asked)", "");
534
- for (const m of earlier) {
535
- const files = m.attachments?.length ? ` (${countFiles(m.attachments.length)})` : "";
536
- const action = m.action ? ` (${ACTION_ASKED[m.action]})` : m.skill ? ` (with the skill \`${m.skill}\`)` : "";
537
- lines.push(`- **${m.from === "designer" ? "Designer" : "You"}:**${action}${files} ${m.text.replace(/\s*\n\s*/g, " ")}`.trimEnd());
538
- }
539
- }
540
- lines.push(
541
- "",
542
- "## How to do it",
543
- "",
544
- "- **A specific, small ask** (a color, a size, a spacing, a text): make it right away, in the project's conventions (its tokens, utilities, components). Speed matters: no screenshots or builds.",
545
- "- **An open-ended ask that needs design judgment** (make it calmer, rework this layout): it's an advanced task. If you can hand work to a more capable model than the one you run on (a subagent, or another model your agent offers), do: give it this prompt (with the job id), and report back with its notes.",
546
- `- The designer was looking at the page ${page.viewport.width}px wide. If the comment is about how it looks at that width only, scope the change with the project's breakpoints; otherwise it's for every width.`,
547
- `- ${PROJECT_CODE}`,
548
- several > 1 ? "- Change only what the comment is about, on each of these elements." : "- Change only what the comment is about.",
549
- `- ${sharedCode()}`,
550
- "- **A question, not a change:** answer it, and change nothing.",
551
- latest?.skill ? "- **Your notes are your reply in the designer's thread:** reply as the skill says (findings, a report, options to pick from), as long as it needs to be. Markdown shows (lists, bold, inline `code`, code blocks); headings show as bold lines." : "- **Your notes are your reply in the designer's thread, a small chat box for quick design back-and-forth:** keep it concise, like a chat message: what you changed, or your answer, or what you need from them, in a few short sentences at most. No headings, and not a report: the designer sees the result on the page."
552
- );
553
- return `${lines.join("\n")}
554
- `;
555
- }
556
- function commentLines(message) {
557
- const text = message?.text.trim() ?? "";
558
- const files = message?.attachments ?? [];
559
- const out = text ? [quote(text)] : [];
560
- const references = message?.references ?? [];
561
- if (references.length) out.push("", ...referenceLines(references));
562
- if (!files.length) return out.length ? out : ["> (empty)"];
563
- const one = files.length === 1;
564
- if (out.length) out.push("");
565
- out.push(
566
- text ? `The designer attached ${countFiles(files.length)} to it:` : `The comment is ${countFiles(files.length)}, with no words. ${one ? "It" : "They"} may hold the instructions: a screenshot, a sketch, notes, a spec. If it's unclear what to do, ask in your reply instead of guessing.`,
567
- "",
568
- ...attachmentLines(files)
569
- );
570
- return out;
571
- }
572
- function referenceLines(references) {
573
- const picked = references.some((r) => r.kind !== "unlisted");
574
- return [
575
- picked ? "What it mentions with `@`, each as it reads in the comment (the ones picked from Pilot's list are exact: use them, don't look for others):" : "What it mentions with `@`, as it reads in the comment:",
576
- "",
577
- ...references.map(referenceLine)
578
- ];
579
- }
580
- function referenceLine(reference) {
581
- const as = `- \`${mentionText(reference)}\`:`;
582
- if (reference.kind === "token" && reference.source)
583
- return `${as} a design token from the project's files (\`${reference.source.file}${reference.source.line ? `:${reference.source.line}` : ""}\`), now \`${reference.value}\`. Use this token the way the project does (its utility, its variable, its theme); it isn't a CSS variable on the page.`;
584
- if (reference.kind === "token")
585
- return `${as} a design token (a CSS variable on the page), now \`${reference.value}\`. Use this token (\`var(${reference.name})\`, or the project's form of it).`;
586
- if (reference.kind === "unlisted")
587
- return `${as} a name the designer typed that Pilot didn't find on the page or among the project's components: probably a component or a part of the page. Search the project for \`${reference.name}\`, and ask in your reply if it's unclear what it is.`;
588
- if (reference.kind === "component") {
589
- const t = reference.target;
590
- const source = reference.source ?? (t?.source?.file ? { file: t.source.file, line: t.source.line } : void 0);
591
- const where = source ? `, declared in \`${source.file}${source.line ? `:${source.line}` : ""}\`` : `; find its declaration (\`function ${reference.name}\`, \`const ${reference.name} =\`, \`class ${reference.name}\`, or a \`${reference.name}.vue\` or \`.svelte\` file)`;
592
- return t ? `${as} the \`${reference.name}\` component${where}; one of its instances on the page: \`${t.selector}\`.` : `${as} the \`${reference.name}\` component${where}. It isn't on this page.`;
593
- }
594
- const el = reference.target;
595
- const component = el.source?.component ? `, inside the \`${el.source.component}\` component` : "";
596
- return `${as} an element on the page: \`${el.path}\`, selector \`${el.selector}\`${el.text ? `, text "${el.text}"` : ""}${component}.`;
597
- }
598
- function attachmentLines(files, intro) {
599
- const lines = files.map((file) => {
600
- const kind = attachmentKind(file.id);
601
- const how = kind === "pdf" ? "a PDF: open it at this path" : kind === "image" ? "an image, shown with this job" : "a text file, its contents shown with this job";
602
- return `- ${file.name ? `${file.name} ` : ""}(${how}): \`${file.path ?? file.id}\``;
603
- });
604
- return intro ? [intro, "", ...lines] : lines;
605
- }
606
- function countFiles(n) {
607
- return n === 1 ? "a file" : `${n} files`;
608
- }
609
- function quote(text) {
610
- return text.trim().split("\n").map((l) => `> ${l}`).join("\n");
611
- }
612
- function firstChecked() {
613
- return "Pilot's width check after you're done measures the first of them; read the code for the others.";
614
- }
615
- function elementsSection(request) {
616
- const targets = requestTargets(request);
617
- if (targets.length === 1) return [`## \`${request.target.path}\``, "", ...targetLines(request.target)];
618
- const out = [`## The elements (${targets.length})`];
619
- targets.forEach((target, i) => out.push("", `### ${i + 1}. \`${target.path}\``, "", ...targetLines(target)));
620
- return out;
621
- }
622
- function targetLines(target) {
623
- const out = [`- Selector: \`${target.selector}\``];
624
- if (target.text) out.push(`- Text: "${target.text}"`);
625
- if (target.source?.component || target.source?.file) {
626
- const { component, file, line } = target.source;
627
- const where = [component && `\`${component}\``, file && `\`${file}${line ? `:${line}` : ""}\``].filter(Boolean).join(", in ");
628
- out.push(`- Component: ${where}`);
629
- }
630
- if (target.lookAlikes) {
631
- const of = target.lookAlikesOf ? `other instances of \`${target.lookAlikesOf}\`, the same part of each` : "the same part of other copies";
632
- out.push(`- Look-alikes: ${target.lookAlikes} more on the page (${of}), not in this job`);
633
- }
634
- return out;
635
- }
636
- function formatEdit(edit, n) {
637
- const { target, changes, texts } = edit;
638
- const out = [`## ${n}. \`${target.path}\``, "", ...targetLines(target)];
639
- if (texts?.length) out.push("", "Text (from \u2192 to):", "", ...texts.map((t) => `- ${JSON.stringify(t.from)} \u2192 ${JSON.stringify(t.to)}`));
640
- if (!changes.length) return out;
641
- const withStates = changes.some((c) => c.states?.length);
642
- out.push(
643
- "",
644
- withStates ? "| Property | From | To | Widths | State |" : "| Property | From | To | Widths |",
645
- withStates ? "| --- | --- | --- | --- | --- |" : "| --- | --- | --- | --- |"
646
- );
647
- for (const c of changes) {
648
- const to = c.removed ? "*removed*" : `\`${c.to}\``;
649
- const from = c.from ? `\`${c.from}\`` : "*not set*";
650
- const widths = c.widths ? describeWidths(c.widths) : "every width";
651
- out.push(`| \`${c.property}\` | ${from} | ${to} | ${widths} |${withStates ? ` ${describeStates(c.states)} |` : ""}`);
652
- }
653
- const notes = changes.flatMap((c) => [c.removed && removalNote(c), mediaNote(c)].filter((n2) => !!n2));
654
- if (notes.length) out.push("", ...notes.map((n2) => `- ${n2}`));
655
- return out;
656
- }
657
- function describeStates(states) {
658
- return states?.length ? states.join(", ") : "\u2014";
659
- }
660
- function describeWidths({ min, max }) {
661
- if (min !== void 0 && min === max) return `${min}px only`;
662
- if (min !== void 0 && max !== void 0) return `${min}\u2013${max}px`;
663
- if (min !== void 0) return `from ${min}px`;
664
- if (max !== void 0) return `to ${max}px`;
665
- return "every width";
666
- }
667
- function mediaNote(c) {
668
- const media = c.source?.kind === "rule" ? c.source.media : void 0;
669
- if (!media) return null;
670
- const today = `\`${c.property}\` is set inside \`@media ${media}\` today.`;
671
- return c.widths ? `${today} The change is for ${describeWidths(c.widths)}.` : `${today} The change is for every width, so that media query shouldn't override it.`;
672
- }
673
- function removalNote(c) {
674
- const note = `\`${c.property}\` is removed: this element shouldn't set it (not \`0\` or \`none\`), so it gets what the cascade gives without it (another rule, the inherited value, or the default).`;
675
- const source = c.source;
676
- if (!source) return note;
677
- if (source.kind === "inline") return `${note} It's set in the element's own \`style\` attribute.`;
678
- const shared = source.elements && source.elements > 1 ? `, which matches ${source.elements} elements on the page: remove it for this element only, unless the designer's note says otherwise` : "";
679
- return `${note} It comes from \`${source.selector}\`${shared}.`;
680
- }
681
-
682
- // ../protocol/src/bridge.ts
683
- var BRIDGE_VERSION = 8;
684
- var DEFAULT_BRIDGE_PORT = 4747 + BRIDGE_VERSION;
685
- var SKILL_NAME = /^[A-Za-z0-9][\w.:-]{0,63}$/;
686
- var MAX_CHOICES = 4;
687
- function questionOf(value) {
688
- const q = value;
689
- if (typeof q?.text !== "string" || !q.text.trim()) return void 0;
690
- const choices = (Array.isArray(q.choices) ? q.choices : []).filter((c) => typeof c === "string").map((c) => c.trim().slice(0, 60)).filter(Boolean).slice(0, MAX_CHOICES);
691
- return { text: q.text.trim().slice(0, 500), ...choices.length ? { choices } : {} };
692
- }
693
- function sessionOf(value) {
694
- const s = value;
695
- if (typeof s?.agent !== "string" || !/^[a-z]{1,20}$/.test(s.agent)) return void 0;
696
- if (typeof s.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9-]{7,99}$/.test(s.id)) return void 0;
697
- return { agent: s.agent, id: s.id };
698
- }
699
- function jobErrorOf(value) {
700
- const e = value;
701
- if (typeof e?.title !== "string" || !e.title.trim()) return void 0;
702
- return { title: e.title.trim().slice(0, 200), detail: typeof e.detail === "string" ? e.detail.trim().slice(0, 1e3) : "" };
703
- }
704
- var MAX_PROPS = 20;
705
- function propsOf(value) {
706
- if (!Array.isArray(value)) return void 0;
707
- const scalar = (v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean";
708
- const props = value.flatMap((p) => {
709
- const name = typeof p?.name === "string" ? p.name.trim().slice(0, 60) : "";
710
- const type = ["options", "boolean", "text", "number"].includes(p?.type) ? p.type : null;
711
- if (!name || !type) return [];
712
- const options = Array.isArray(p.options) ? [...new Set(p.options.filter(scalar).map(String))].slice(0, 30) : [];
713
- if (type === "options" && !options.length) return [];
714
- return [
715
- {
716
- name,
717
- type,
718
- ...type === "options" ? { options } : {},
719
- ...scalar(p.default) ? { default: p.default } : {},
720
- ...typeof p.description === "string" && p.description.trim() ? { description: p.description.trim().slice(0, 120) } : {}
721
- }
722
- ];
723
- });
724
- return props.length ? props.slice(0, MAX_PROPS) : void 0;
725
- }
726
- function projectNameOf(value) {
727
- return typeof value === "string" && /^[\w@./-]{1,120}$/.test(value.trim()) ? value.trim() : void 0;
728
- }
729
- function originOf(url) {
730
- try {
731
- const u = new URL(url.includes("://") ? url : `http://${url}`);
732
- return u.protocol === "http:" || u.protocol === "https:" ? u.origin : null;
733
- } catch {
734
- return null;
735
- }
736
- }
737
- function isLocalHost(hostname) {
738
- const h = hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
739
- if (!h) return false;
740
- if (h === "localhost" || h === "0.0.0.0" || h === "::1" || h === "::") return true;
741
- if (/\.(localhost|local|test|internal|lan|home\.arpa)$/.test(h)) return true;
742
- const v4 = /^(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/.exec(h);
743
- if (v4) {
744
- const [a, b] = [Number(v4[1]), Number(v4[2])];
745
- return a === 127 || a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 169 && b === 254;
746
- }
747
- if (h.includes(":")) return /^f[cd][0-9a-f]{2}:/.test(h) || /^fe[89ab][0-9a-f]:/.test(h);
748
- return !h.includes(".");
749
- }
750
- function originKey(origin) {
751
- return origin.replace(/^(https?:\/\/)(?:127\.0\.0\.1|\[::1\])(?=[:/]|$)/, "$1localhost").replace(/\/$/, "");
752
- }
753
-
754
- // src/config.ts
755
- function configFile(env = process.env, platform = process.platform, home = homedir2()) {
756
- const base = platform === "win32" ? env.APPDATA ?? join2(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME ?? join2(home, ".config");
757
- return join2(base, "usepilot", "projects.json");
758
- }
759
- function read(file) {
760
- try {
761
- const data = JSON.parse(readFileSync(file, "utf8"));
762
- return data && typeof data === "object" ? data : {};
763
- } catch {
764
- return {};
765
- }
766
- }
767
- function savedAgent(folder, file = configFile()) {
768
- const agent = read(file)[resolve(folder)]?.agent;
769
- return isAgentKind(agent) ? agent : void 0;
770
- }
771
- function saveAgent(folder, agent, file = configFile()) {
772
- const projects = read(file);
773
- projects[resolve(folder)] = { ...projects[resolve(folder)], agent };
774
- mkdirSync(dirname(file), { recursive: true });
775
- writeFileSync(file, `${JSON.stringify(projects, null, 2)}
776
- `);
777
- }
778
- function projectName(folder) {
779
- try {
780
- const name = projectNameOf(JSON.parse(readFileSync(join2(folder, "package.json"), "utf8")).name);
781
- if (name) return name;
782
- } catch {
783
- }
784
- return projectNameOf(basename(resolve(folder))) ?? "project";
785
- }
30
+ import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2 } from "fs";
31
+ import { homedir } from "os";
32
+ import { dirname, join as join2 } from "path";
786
33
 
787
34
  // src/legacy.ts
788
- import { existsSync, lstatSync, readFileSync as readFileSync2 } from "fs";
35
+ import { existsSync, lstatSync, readFileSync } from "fs";
789
36
  import { readFile, rm, unlink, writeFile } from "fs/promises";
790
- import { join as join3 } from "path";
37
+ import { join } from "path";
791
38
  function serverConfigs(root, home, platform) {
792
39
  return [
793
- { file: join3(home, ".cursor", "mcp.json"), key: "mcpServers" },
794
- { file: join3(vscodeUserDir(home, platform), "mcp.json"), key: "servers" },
795
- { file: join3(root, ".mcp.json"), key: "mcpServers" },
796
- { file: join3(root, ".cursor", "mcp.json"), key: "mcpServers" },
797
- { file: join3(root, ".vscode", "mcp.json"), key: "servers" }
40
+ { file: join(home, ".cursor", "mcp.json"), key: "mcpServers" },
41
+ { file: join(vscodeUserDir(home, platform), "mcp.json"), key: "servers" },
42
+ { file: join(root, ".mcp.json"), key: "mcpServers" },
43
+ { file: join(root, ".cursor", "mcp.json"), key: "mcpServers" },
44
+ { file: join(root, ".vscode", "mcp.json"), key: "servers" }
798
45
  ];
799
46
  }
800
47
  function skillFolders(root, home) {
801
48
  return [
802
- join3(home, ".claude", "skills", "pilot"),
803
- join3(home, ".cursor", "skills", "pilot"),
804
- join3(home, ".copilot", "skills", "pilot"),
805
- join3(home, ".agents", "skills", "pilot"),
806
- join3(root, ".claude", "skills", "pilot"),
807
- join3(root, ".cursor", "skills", "pilot"),
808
- join3(root, ".github", "skills", "pilot"),
809
- join3(root, ".agents", "skills", "pilot")
49
+ join(home, ".claude", "skills", "pilot"),
50
+ join(home, ".cursor", "skills", "pilot"),
51
+ join(home, ".copilot", "skills", "pilot"),
52
+ join(home, ".agents", "skills", "pilot"),
53
+ join(root, ".claude", "skills", "pilot"),
54
+ join(root, ".cursor", "skills", "pilot"),
55
+ join(root, ".github", "skills", "pilot"),
56
+ join(root, ".agents", "skills", "pilot")
810
57
  ];
811
58
  }
812
59
  function isPilotServer(entry) {
@@ -832,9 +79,9 @@ async function removeOldSetup(root, home, platform, run2) {
832
79
  `);
833
80
  removed.push(tilde(file, home));
834
81
  }
835
- const claude = readJson(join3(home, ".claude.json"))?.mcpServers?.pilot;
82
+ const claude = readJson(join(home, ".claude.json"))?.mcpServers?.pilot;
836
83
  if (isPilotServer(claude) && run2("claude", ["mcp", "remove", "--scope", "user", "pilot"], home)) removed.push("Claude Code's `pilot` server");
837
- if (/\[mcp_servers\.pilot\][^[]*usepilot/.test(readText(join3(home, ".codex", "config.toml"))) && run2("codex", ["mcp", "remove", "pilot"], home))
84
+ if (/\[mcp_servers\.pilot\][^[]*usepilot/.test(readText(join(home, ".codex", "config.toml"))) && run2("codex", ["mcp", "remove", "pilot"], home))
838
85
  removed.push("Codex's `pilot` server");
839
86
  for (const folder of skillFolders(root, home)) {
840
87
  if (!await removeSkill(folder)) continue;
@@ -849,22 +96,22 @@ async function removeSkill(folder) {
849
96
  } catch {
850
97
  return false;
851
98
  }
852
- if (!/^name:\s*pilot\s*$/m.test(readText(join3(folder, "SKILL.md")))) return false;
99
+ if (!/^name:\s*pilot\s*$/m.test(readText(join(folder, "SKILL.md")))) return false;
853
100
  if (link) await unlink(folder);
854
101
  else await rm(folder, { recursive: true, force: true });
855
102
  return true;
856
103
  }
857
104
  function vscodeUserDir(home, platform) {
858
- if (platform === "darwin") return join3(home, "Library", "Application Support", "Code", "User");
859
- if (platform === "win32") return join3(process.env.APPDATA ?? join3(home, "AppData", "Roaming"), "Code", "User");
860
- return join3(home, ".config", "Code", "User");
105
+ if (platform === "darwin") return join(home, "Library", "Application Support", "Code", "User");
106
+ if (platform === "win32") return join(process.env.APPDATA ?? join(home, "AppData", "Roaming"), "Code", "User");
107
+ return join(home, ".config", "Code", "User");
861
108
  }
862
109
  function tilde(path, home) {
863
- return path.startsWith(home) ? `~${path.slice(home.length)}` : path;
110
+ return shownPath(path.startsWith(home) ? `~${path.slice(home.length)}` : path);
864
111
  }
865
112
  function readText(file) {
866
113
  try {
867
- return existsSync(file) ? readFileSync2(file, "utf8") : "";
114
+ return existsSync(file) ? readFileSync(file, "utf8") : "";
868
115
  } catch {
869
116
  return "";
870
117
  }
@@ -878,7 +125,7 @@ function readJson(file) {
878
125
  }
879
126
 
880
127
  // src/version.ts
881
- var VERSION = "0.15.0";
128
+ var VERSION = "0.17.0";
882
129
  function olderThan(a, b) {
883
130
  const parts = (v) => v.replace(/^[^\d]*/, "").split(/[.-]/).slice(0, 3).map((n) => Number.parseInt(n, 10) || 0);
884
131
  const [x, y] = [parts(a), parts(b)];
@@ -891,48 +138,98 @@ function agentKindOf(value) {
891
138
  const v = value?.toLowerCase().replace(/^claude-code$/, "claude");
892
139
  return isAgentKind(v) ? v : void 0;
893
140
  }
894
- function agentsToInstall() {
895
- return Object.values(AGENTS).map((cli) => `${cli.label}: \`${cli.install}\`, then \`${cli.signIn}\``).join("; ");
141
+ function agentsToInstall(platform = process.platform) {
142
+ return Object.values(AGENTS).map((cli) => `${cli.label}: \`${installCommand(cli, platform)}\`, then \`${cli.signIn}\``).join("; ");
896
143
  }
897
144
  function installedVersion(cwd, root) {
898
- for (let dir = cwd; ; dir = dirname2(dir)) {
899
- const version = readJson2(join4(dir, "node_modules", "usepilot", "package.json"))?.version;
145
+ for (let dir = cwd; ; dir = dirname(dir)) {
146
+ const version = readJson2(join2(dir, "node_modules", "usepilot", "package.json"))?.version;
900
147
  if (version) return version;
901
- if (dir === root || dirname2(dir) === dir) return null;
148
+ if (dir === root || dirname(dir) === dir) return null;
902
149
  }
903
150
  }
904
151
  function installArgs(pm, spec = "usepilot") {
905
152
  return pm === "npm" ? ["install", "-D", spec] : pm === "bun" ? ["add", "-d", spec] : ["add", "-D", spec];
906
153
  }
907
- function agentLines(found, wanted) {
154
+ function agentLines(found, wanted, platform = process.platform) {
908
155
  const ready = found.filter((a) => a.signedIn);
909
156
  const label = (kind) => AGENTS[kind].label;
157
+ const signInLater = (cli) => `They sign in to ${cli.label} once, when Pilot asks: its toolbar has a sign-in button the first time they send (or \`${cli.signIn}\` in a terminal).`;
158
+ const shell = platform === "win32" ? " in PowerShell" : "";
910
159
  if (wanted) {
911
160
  const it = found.find((a) => a.kind === wanted);
912
161
  const cli = AGENTS[wanted];
913
162
  if (it?.signedIn) return { done: [`Pilot will run ${cli.label} for this project (signed in).`], todo: [] };
163
+ if (it) return { done: [`Pilot will run ${cli.label} for this project.`], todo: [`**Tell the user** ${signInLater(cli)}`] };
914
164
  return {
915
165
  done: [],
916
166
  todo: [
917
- it ? `**Tell the user** to sign in to ${cli.label}'s command-line tool: \`${cli.signIn}\` in a terminal.` : `**Tell the user** to install ${cli.label}'s command-line tool and sign in: \`${cli.install}\`, then \`${cli.signIn}\`.`
167
+ `**Install ${cli.label}'s command-line tool**: Pilot runs it for each job (not this chat). Ask the user first, then run \`${installCommand(cli, platform)}\`${shell} (${cli.label}'s own installer). **Tell the user** ${signInLater(cli)}`
918
168
  ]
919
169
  };
920
170
  }
921
171
  if (ready.length === 1) return { done: [`Pilot will run ${label(ready[0].kind)}, signed in here, for each job.`], todo: [] };
922
172
  if (ready.length > 1)
923
- return { done: [`Found ${ready.map((a) => label(a.kind)).join(" and ")} signed in: \`npx usepilot\` asks which to run, the first time.`], todo: [] };
924
- const installed = found.map((a) => `${label(a.kind)} (\`${AGENTS[a.kind].signIn}\`)`);
173
+ return { done: [`Found ${ready.map((a) => label(a.kind)).join(" and ")} signed in: Pilot runs the first, the first time (\`npx usepilot --agent <name>\` picks another).`], todo: [] };
174
+ const installed = found[0];
175
+ if (installed) return { done: [`Pilot will run ${label(installed.kind)} for this project.`], todo: [`**Tell the user** ${signInLater(AGENTS[installed.kind])}`] };
925
176
  return {
926
177
  done: [],
927
178
  todo: [
928
- installed.length ? `**Tell the user** Pilot runs their coding agent's command-line tool for each job, and it isn't signed in: sign in to ${installed.join(" or ")} in a terminal.` : `**Tell the user** Pilot runs their coding agent's command-line tool for each job, and none is installed here. One of: ${agentsToInstall()}.`
179
+ `**Ask the user which coding agent Pilot should run** for each job (none's command-line tool is installed here), then install it and run init again with \`--agent <claude|codex|cursor>\`. One of: ${agentsToInstall(platform)}${shell}.`
929
180
  ]
930
181
  };
931
182
  }
183
+ function devServerStep(framework, cwd, pkg) {
184
+ const first = (...files) => files.map((f) => join2(cwd, f)).find((f) => existsSync2(f));
185
+ const code = (lang, text) => `
186
+
187
+ \`\`\`${lang}
188
+ ${text.replace(/^(?=.)/gm, " ")}
189
+ \`\`\``;
190
+ const intro = "**Start Pilot with the app's dev server**, so the user never runs `npx usepilot`:";
191
+ const end = " It only runs in development (never in a build or on a server).";
192
+ const config = (names) => first(...names.flatMap((n) => [".ts", ".mts", ".js", ".mjs", ".cjs"].map((e) => `${n}${e}`)));
193
+ const has = (file, text) => !!file && readText2(file).includes(text);
194
+ const viteLike = ["vite", "vite-html", "sveltekit", "react-router"].includes(framework.kind);
195
+ if (viteLike || framework.kind === "astro" || framework.kind === "nuxt") {
196
+ const name2 = framework.kind === "astro" ? "astro.config" : framework.kind === "nuxt" ? "nuxt.config" : "vite.config";
197
+ const file = config([name2]);
198
+ if (has(file, "usepilot/vite")) return { done: `Pilot starts with the dev server (\`usepilot/vite\` in \`${relPath(cwd, file)}\`).` };
199
+ const at = file ? `\`${relPath(cwd, file)}\`` : `its config (create \`${name2}.ts\` if there's none)`;
200
+ const where = viteLike ? "its `plugins` (keep the others)" : "its `vite.plugins` (create `vite: { plugins: [] }` if there's none, keep the others)";
201
+ return {
202
+ todo: `${intro} in ${at}, add Pilot's Vite plugin to ${where}:${code("ts", 'import { pilot } from "usepilot/vite";\n\n// in the config:\nplugins: [pilot()],')}
203
+
204
+ Vite applies it only while it serves: never in a build or on a server.`
205
+ };
206
+ }
207
+ if (framework.kind === "next-app" || framework.kind === "next-pages") {
208
+ const file = config(["next.config"]);
209
+ if (has(file, "usepilot/next")) return { done: `Pilot starts with the dev server (\`withPilot\` in \`${relPath(cwd, file)}\`).` };
210
+ const at = file ? `\`${relPath(cwd, file)}\`` : "`next.config.ts` (create it if there's none)";
211
+ return {
212
+ todo: `${intro} in ${at}, wrap the exported config with \`withPilot\`:${code("ts", 'import { withPilot } from "usepilot/next";\n\nexport default withPilot(nextConfig);')}
213
+
214
+ In a CommonJS config (\`module.exports\`): \`module.exports = withPilot(nextConfig)\`, with \`const { withPilot } = require("usepilot/next")\`.${end} Pilot starts only in \`next dev\`.`
215
+ };
216
+ }
217
+ const scripts = pkg.scripts ?? {};
218
+ const name = Object.keys(scripts).find((s) => s === "dev" || ["start", "serve", "develop"].includes(s) && DEV_SERVER.test(scripts[s]));
219
+ if (!name) return {};
220
+ const script = scripts[name];
221
+ if (/\busepilot dev\b/.test(script)) return { done: `Pilot starts with the dev server (\`${name}\` runs through \`usepilot dev\`).` };
222
+ if (script.includes('"')) return {};
223
+ const wrapped = /[&|;<>]/.test(script) ? `usepilot dev -- "${script}"` : `usepilot dev -- ${script}`;
224
+ return {
225
+ todo: `${intro} in \`package.json\`, run its \`${name}\` script through Pilot: \`"${name}": ${JSON.stringify(wrapped)}\`. Pilot starts and stops with the dev server.${end}`
226
+ };
227
+ }
228
+ var DEV_SERVER = /\b(ng serve|react-scripts start|gatsby develop|vue-cli-service serve|webpack(-dev-server| serve)|rsbuild dev|rspack (serve|dev)|parcel(?! build)|vite(?! (build|preview)))\b/;
932
229
  async function init(options = {}) {
933
230
  const cwd = options.cwd ?? process.cwd();
934
231
  const run2 = options.run ?? runCommand;
935
- const pkgFile = join4(cwd, "package.json");
232
+ const pkgFile = join2(cwd, "package.json");
936
233
  if (!existsSync2(pkgFile)) {
937
234
  return `# Pilot: not set up
938
235
 
@@ -968,20 +265,26 @@ ${apps.map((a) => `- ${a}`).join("\n")}` : "."}
968
265
  else todo.push(`Install Pilot as a dev dependency: run \`${install}\` in ${cwd}.`);
969
266
  const wanted = agentKindOf(options.agent) ?? agentFromEnv(options.env ?? process.env) ?? void 0;
970
267
  const found = await (options.detect ?? detectAgents)();
971
- const agents = agentLines(found, wanted);
268
+ const platform = options.platform ?? process.platform;
269
+ const agents = agentLines(found, wanted, platform);
972
270
  done.push(...agents.done);
973
271
  todo.push(...agents.todo);
974
- if (wanted && found.some((a) => a.kind === wanted && a.signedIn)) saveAgent(cwd, wanted, options.configFile);
975
- const home = options.home ?? homedir3();
976
- const removed = await removeOldSetup(root, home, options.platform ?? process.platform, run2);
272
+ const home = options.home ?? homedir();
273
+ const settings = options.configFile ?? configFile(options.env ?? process.env, platform, home);
274
+ if (wanted) saveAgent(cwd, wanted, settings);
275
+ markSetUp(cwd, settings);
276
+ const removed = await removeOldSetup(root, home, platform, run2);
977
277
  if (removed.length) done.push(`Removed Pilot's old chat setup (its MCP server and \`/pilot\` skill): ${removed.map((r) => `\`${r}\``).join(", ")}. Pilot runs the agent itself now.`);
978
278
  if (framework.loads) {
979
279
  const naming = namingStep(framework.loads, cwd);
980
280
  if (naming) todo.push(naming);
981
- else done.push(`The app already loads Pilot (\`${relative(cwd, framework.loads)}\`).`);
281
+ else done.push(`The app already loads Pilot (\`${relPath(cwd, framework.loads)}\`).`);
982
282
  } else todo.push(loadStep(framework, cwd));
283
+ const devServer = devServerStep(framework, cwd, pkg);
284
+ if (devServer.done) done.push(devServer.done);
285
+ if (devServer.todo) todo.push(devServer.todo);
983
286
  todo.push(
984
- `**Tell the user**, in a few lines: Pilot is set up. To use it, run \`npx usepilot\` in ${cwd}, in a terminal beside the app's dev server, and open the app: Pilot opens on every page. They design and press Send (or comment on an element), Pilot runs their agent for each job, and the terminal shows what it does. No chat needs to stay open; without \`npx usepilot\` running, the toolbar says so.`
287
+ devServer.done || devServer.todo ? `**Tell the user**, in a few lines: Pilot is set up. It starts with the app's dev server: they restart it (if it's running) and open the app, and Pilot opens on every page. They design and press Send (or comment on an element), Pilot runs their agent for each job, and the dev server's terminal shows what it does. No chat needs to stay open. ${GUIDE_LINE}` : `**Tell the user**, in a few lines: Pilot is set up. To use it, run \`npx usepilot\` in ${cwd}, in a terminal beside the app's dev server, and open the app: Pilot opens on every page. They design and press Send (or comment on an element), Pilot runs their agent for each job, and the terminal shows what it does. No chat needs to stay open; without \`npx usepilot\` running, the toolbar says so. ${GUIDE_LINE}`
985
288
  );
986
289
  return `# Pilot: set up
987
290
 
@@ -992,24 +295,25 @@ Left for you (the agent), in order:
992
295
  ${todo.map((t, i) => `${i + 1}. ${t}`).join("\n")}
993
296
  `;
994
297
  }
298
+ var GUIDE_LINE = "For how to do anything in Pilot, `npx usepilot guide` prints the guide for this version (also in `node_modules/usepilot/GUIDE.md`): read it when they ask how Pilot works, rather than the package's code.";
995
299
  function projectRoot(cwd) {
996
- for (let dir = cwd; ; dir = dirname2(dir)) {
997
- if (existsSync2(join4(dir, ".git"))) return dir;
998
- if (dirname2(dir) === dir) return cwd;
300
+ for (let dir = cwd; ; dir = dirname(dir)) {
301
+ if (existsSync2(join2(dir, ".git"))) return dir;
302
+ if (dirname(dir) === dir) return cwd;
999
303
  }
1000
304
  }
1001
305
  function packageManager(cwd, root) {
1002
- for (let dir = cwd; ; dir = dirname2(dir)) {
1003
- if (existsSync2(join4(dir, "pnpm-lock.yaml"))) return "pnpm";
1004
- if (existsSync2(join4(dir, "yarn.lock"))) return "yarn";
1005
- if (existsSync2(join4(dir, "bun.lock")) || existsSync2(join4(dir, "bun.lockb"))) return "bun";
1006
- if (existsSync2(join4(dir, "package-lock.json"))) return "npm";
1007
- if (dir === root || dirname2(dir) === dir) return "npm";
306
+ for (let dir = cwd; ; dir = dirname(dir)) {
307
+ if (existsSync2(join2(dir, "pnpm-lock.yaml"))) return "pnpm";
308
+ if (existsSync2(join2(dir, "yarn.lock"))) return "yarn";
309
+ if (existsSync2(join2(dir, "bun.lock")) || existsSync2(join2(dir, "bun.lockb"))) return "bun";
310
+ if (existsSync2(join2(dir, "package-lock.json"))) return "npm";
311
+ if (dir === root || dirname(dir) === dir) return "npm";
1008
312
  }
1009
313
  }
1010
314
  function detectFramework(cwd, deps) {
1011
315
  const has = (name) => name in deps;
1012
- const first = (...files) => files.map((f) => join4(cwd, f)).find((f) => existsSync2(f));
316
+ const first = (...files) => files.map((f) => join2(cwd, f)).find((f) => existsSync2(f));
1013
317
  const loads = findLoader(cwd);
1014
318
  const result = (kind, file) => ({ kind, file, loads });
1015
319
  if (has("next")) {
@@ -1028,16 +332,20 @@ function detectFramework(cwd, deps) {
1028
332
  if (has("@sveltejs/kit")) return result("sveltekit", first("src/hooks.client.ts", "src/hooks.client.js"));
1029
333
  if (has("astro")) return result("astro");
1030
334
  if (has("@react-router/dev") || has("@remix-run/react")) return result("react-router", first("app/root.tsx", "app/root.jsx"));
335
+ if (has("@angular/core")) return result("angular", first("src/main.ts"));
336
+ if (has("gatsby")) return result("gatsby", first(...GATSBY_BROWSER));
1031
337
  if (has("vite") || Object.keys(deps).some((d) => d.startsWith("@vitejs/"))) {
1032
338
  const entry = viteEntry(cwd);
1033
339
  if (entry) return result("vite", entry);
1034
- if (existsSync2(join4(cwd, "index.html"))) {
1035
- const config = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"].map((f) => join4(cwd, f)).find((f) => existsSync2(f));
340
+ if (existsSync2(join2(cwd, "index.html"))) {
341
+ const config = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"].map((f) => join2(cwd, f)).find((f) => existsSync2(f));
1036
342
  return result("vite-html", config);
1037
343
  }
1038
344
  return result("vite");
1039
345
  }
1040
- if (has("react-scripts") || has("webpack")) {
346
+ if (has("@rsbuild/core")) return result("rsbuild", first(...JS_ENTRIES));
347
+ if (has("parcel")) return result("parcel", parcelEntry(cwd));
348
+ if (has("react-scripts") || has("webpack") || has("@vue/cli-service") || has("@rspack/core") || has("@rspack/cli")) {
1041
349
  return result(
1042
350
  "webpack",
1043
351
  first("src/index.tsx", "src/index.ts", "src/index.jsx", "src/index.js", "src/main.tsx", "src/main.ts", "src/main.js")
@@ -1045,20 +353,36 @@ function detectFramework(cwd, deps) {
1045
353
  }
1046
354
  return { kind: "unknown", loads };
1047
355
  }
356
+ var GATSBY_BROWSER = ["gatsby-browser.tsx", "gatsby-browser.ts", "gatsby-browser.jsx", "gatsby-browser.js"];
357
+ var JS_ENTRIES = ["src/index.tsx", "src/index.ts", "src/index.jsx", "src/index.js", "src/main.tsx", "src/main.ts", "src/main.jsx", "src/main.js"];
358
+ function parcelEntry(cwd) {
359
+ const source = readJson2(join2(cwd, "package.json"))?.source;
360
+ const page = [...typeof source === "string" ? [source] : Array.isArray(source) ? source.filter((s) => typeof s === "string") : [], "index.html", "src/index.html"].map((f) => join2(cwd, f)).find((f) => f.endsWith(".html") && existsSync2(f));
361
+ if (page) {
362
+ for (const tag of readFileSync2(page, "utf8").match(/<script\b[^>]*>/gi) ?? []) {
363
+ const src = /src=["']([^"'?#]+)/i.exec(tag)?.[1];
364
+ const file = src && !/^[a-z]+:|^\/\//i.test(src) ? join2(src.startsWith("/") ? cwd : dirname(page), src) : void 0;
365
+ if (file && existsSync2(file)) return file;
366
+ }
367
+ }
368
+ if (typeof source === "string" && /\.[mc]?[jt]sx?$/.test(source) && existsSync2(join2(cwd, source))) return join2(cwd, source);
369
+ return JS_ENTRIES.map((f) => join2(cwd, f)).find((f) => existsSync2(f));
370
+ }
1048
371
  function viteEntry(cwd) {
1049
- const html = join4(cwd, "index.html");
372
+ const html = join2(cwd, "index.html");
1050
373
  if (existsSync2(html)) {
1051
- for (const tag of readFileSync3(html, "utf8").match(/<script\b[^>]*>/gi) ?? []) {
374
+ for (const tag of readFileSync2(html, "utf8").match(/<script\b[^>]*>/gi) ?? []) {
1052
375
  if (!/type=["']module["']/i.test(tag)) continue;
1053
376
  const src = /src=["']\/?([^"'?#]+)/i.exec(tag)?.[1];
1054
- if (src && existsSync2(join4(cwd, src))) return join4(cwd, src);
377
+ if (src && existsSync2(join2(cwd, src))) return join2(cwd, src);
1055
378
  }
1056
379
  return void 0;
1057
380
  }
1058
- return ["src/main.tsx", "src/main.ts", "src/main.jsx", "src/main.js", "src/index.tsx", "src/index.ts"].map((f) => join4(cwd, f)).find((f) => existsSync2(f));
381
+ return ["src/main.tsx", "src/main.ts", "src/main.jsx", "src/main.js", "src/index.tsx", "src/index.ts"].map((f) => join2(cwd, f)).find((f) => existsSync2(f));
1059
382
  }
1060
383
  var SOURCE_DIRS = ["src", "app", "pages", "plugins", "components", "lib"];
1061
384
  var SOURCE_FILE = /\.(m?[jt]sx?|vue|svelte|astro|html)$/;
385
+ var LOADS_PILOT = /["']usepilot(\/auto)?["']|node_modules\/usepilot\/dist\//;
1062
386
  function findLoader(cwd) {
1063
387
  let budget = 3e3;
1064
388
  const walk = (dir, depth) => {
@@ -1070,9 +394,9 @@ function findLoader(cwd) {
1070
394
  }
1071
395
  for (const name of names) {
1072
396
  if (budget-- <= 0 || name === "node_modules" || name.startsWith(".")) continue;
1073
- const path = join4(dir, name);
397
+ const path = join2(dir, name);
1074
398
  if (SOURCE_FILE.test(name)) {
1075
- if (/["']usepilot(\/auto)?["']/.test(readText2(path))) return path;
399
+ if (LOADS_PILOT.test(readText2(path))) return path;
1076
400
  } else if (depth > 0 && !name.includes(".")) {
1077
401
  const found = walk(path, depth - 1);
1078
402
  if (found) return found;
@@ -1080,41 +404,41 @@ function findLoader(cwd) {
1080
404
  }
1081
405
  return void 0;
1082
406
  };
1083
- for (const name of ["index.html", "vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"]) {
1084
- const file = join4(cwd, name);
1085
- if (existsSync2(file) && /usepilot/.test(readText2(file))) return file;
407
+ for (const name of ["index.html", "vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs", ...GATSBY_BROWSER]) {
408
+ const file = join2(cwd, name);
409
+ if (existsSync2(file) && LOADS_PILOT.test(readText2(file))) return file;
1086
410
  }
1087
411
  for (const dir of SOURCE_DIRS) {
1088
- const found = walk(join4(cwd, dir), 6);
412
+ const found = walk(join2(cwd, dir), 6);
1089
413
  if (found) return found;
1090
414
  }
1091
415
  return void 0;
1092
416
  }
1093
417
  function readText2(file) {
1094
418
  try {
1095
- return readFileSync3(file, "utf8");
419
+ return readFileSync2(file, "utf8");
1096
420
  } catch {
1097
421
  return "";
1098
422
  }
1099
423
  }
1100
424
  function isWorkspaceRoot(cwd, pkg) {
1101
- return !!pkg.workspaces || existsSync2(join4(cwd, "pnpm-workspace.yaml"));
425
+ return !!pkg.workspaces || existsSync2(join2(cwd, "pnpm-workspace.yaml"));
1102
426
  }
1103
427
  function workspaceApps(cwd) {
1104
428
  const found = [];
1105
429
  for (const group of ["apps", "packages", "examples", "sites"]) {
1106
- const dir = join4(cwd, group);
430
+ const dir = join2(cwd, group);
1107
431
  if (!existsSync2(dir)) continue;
1108
432
  for (const name of readdirSync(dir)) {
1109
- const pkg = readJson2(join4(dir, name, "package.json"));
1110
- if (pkg && detectFramework(join4(dir, name), { ...pkg.dependencies, ...pkg.devDependencies }).kind !== "unknown")
1111
- found.push(join4(group, name));
433
+ const pkg = readJson2(join2(dir, name, "package.json"));
434
+ if (pkg && detectFramework(join2(dir, name), { ...pkg.dependencies, ...pkg.devDependencies }).kind !== "unknown")
435
+ found.push(`${group}/${name}`);
1112
436
  }
1113
437
  }
1114
438
  return found;
1115
439
  }
1116
440
  function baseLoadStep(framework, cwd) {
1117
- const at = (file, otherwise) => file ? `\`${relative(cwd, file)}\`` : otherwise;
441
+ const at = (file, otherwise) => file ? `\`${relPath(cwd, file)}\`` : otherwise;
1118
442
  const code = (lang, text) => `
1119
443
 
1120
444
  \`\`\`${lang}
@@ -1176,8 +500,23 @@ export function Pilot() {
1176
500
  if (import.meta.env.DEV) import("usepilot/auto");
1177
501
  }, []);`
1178
502
  )}`;
503
+ case "angular":
504
+ return `${intro} It's Angular: in ${at(framework.file, "the file that bootstraps the app (`src/main.ts`)")}, after the bootstrap, add:${code("ts", 'if (typeof ngDevMode === "undefined" || ngDevMode) import("usepilot/auto");')}
505
+
506
+ Use \`ngDevMode\`, not \`isDevMode()\`: Angular's production build sets \`ngDevMode\` to false and drops Pilot from the bundle, while \`isDevMode()\` is decided in the browser and leaves Pilot's files in the build.`;
507
+ case "gatsby":
508
+ return `${intro} It's Gatsby: in ${at(framework.file, "`gatsby-browser.js` at the app's root (create it if there's none)")}, in its \`onClientEntry\` (add the export if there's none, keep the others):${code(
509
+ "js",
510
+ `export const onClientEntry = () => {
511
+ if (process.env.NODE_ENV === "development") import("usepilot/auto");
512
+ };`
513
+ )}`;
514
+ case "rsbuild":
515
+ return `${intro} It's Rsbuild: in its entry module, ${at(framework.file, "the one `source.entry` in its config names (`src/index` by default)")}, add:${code("ts", 'if (import.meta.env.DEV) import("usepilot/auto");')}`;
516
+ case "parcel":
517
+ return `${intro} It's Parcel: in the script its HTML page loads, ${at(framework.file, "the `<script src>` of the page Parcel builds")}, add:${code("js", 'if (process.env.NODE_ENV === "development") import("usepilot/auto");')}`;
1179
518
  case "webpack":
1180
- 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");')}`;
519
+ return `${intro} It's webpack, or a tool built on it (Create React App, Vue CLI, Rspack): 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");')}`;
1181
520
  default:
1182
521
  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(
1183
522
  "php",
@@ -1193,26 +532,26 @@ function loaderCall(name) {
1193
532
  }
1194
533
  function loadStep(framework, cwd) {
1195
534
  const name = projectName(cwd);
1196
- const json2 = JSON.stringify(name);
535
+ const json = JSON.stringify(name);
1197
536
  return baseLoadStep(framework, cwd).replaceAll('import("usepilot/auto")', loaderCall(name)).replaceAll(
1198
537
  '<script type="module" src="/node_modules/usepilot/dist/pilot-auto.js"></script>',
1199
- `<script type="module">import { mountPilot } from "/node_modules/usepilot/dist/pilot.js"; mountPilot({ project: ${json2} });</script>`
538
+ `<script type="module">import { mountPilot } from "/node_modules/usepilot/dist/pilot.js"; mountPilot({ project: ${json} });</script>`
1200
539
  ).replaceAll(
1201
540
  '`<script type="module" src="\u2026/node_modules/usepilot/dist/pilot-auto.js"></script>`',
1202
- `\`<script type="module">import { mountPilot } from "\u2026/node_modules/usepilot/dist/pilot.js"; mountPilot({ project: ${json2} });</script>\``
541
+ `\`<script type="module">import { mountPilot } from "\u2026/node_modules/usepilot/dist/pilot.js"; mountPilot({ project: ${json} });</script>\``
1203
542
  ).replaceAll("import `usepilot/auto` from the browser code", `call \`${loaderCall(name)}\` from the browser code`) + `
1204
543
 
1205
- The \`project\` (${json2}, this package's name) tells \`npx usepilot\` which pages are this project's: keep it as it is.`;
544
+ The \`project\` (${json}, this package's name) tells \`npx usepilot\` which pages are this project's: keep it as it is.`;
1206
545
  }
1207
546
  function namingStep(file, cwd) {
1208
547
  const name = projectName(cwd);
1209
548
  const text = readText2(file);
1210
549
  if (new RegExp(`project:\\s*["'\`]${name.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}["'\`]`).test(text)) return null;
1211
- return `**Name this project in Pilot's loader** (\`${relative(cwd, file)}\`): \`npx usepilot\` runs only for pages that say which project they are. Replace \`import("usepilot/auto")\` with \`${loaderCall(name)}\` (keep its development-only check), or set \`project: ${JSON.stringify(name)}\` where it calls \`mountPilot\`.`;
550
+ return `**Name this project in Pilot's loader** (\`${relPath(cwd, file)}\`): \`npx usepilot\` runs only for pages that say which project they are. Replace \`import("usepilot/auto")\` with \`${loaderCall(name)}\` (keep its development-only check), or set \`project: ${JSON.stringify(name)}\` where it calls \`mountPilot\`.`;
1212
551
  }
1213
552
  function readJson2(file) {
1214
553
  try {
1215
- return JSON.parse(readFileSync3(file, "utf8"));
554
+ return JSON.parse(readFileSync2(file, "utf8"));
1216
555
  } catch {
1217
556
  return null;
1218
557
  }
@@ -1222,1922 +561,96 @@ function runCommand(command2, args, cwd) {
1222
561
  return result.status === 0;
1223
562
  }
1224
563
 
1225
- // src/run.ts
1226
- import { randomUUID as randomUUID2 } from "crypto";
1227
- import { existsSync as existsSync7 } from "fs";
1228
- import { basename as basename6 } from "path";
1229
-
1230
- // src/server.ts
1231
- import { createServer } from "http";
564
+ // src/update.ts
565
+ import { spawnSync as spawnSync2 } from "child_process";
566
+ import { existsSync as existsSync3, readdirSync as readdirSync2, readFileSync as readFileSync3 } from "fs";
567
+ import { homedir as homedir2 } from "os";
568
+ import { dirname as dirname2, join as join3 } from "path";
569
+ async function update(options = {}) {
570
+ const cwd = options.cwd ?? process.cwd();
571
+ const run2 = options.run ?? runCommand2;
572
+ const home = options.home ?? homedir2();
573
+ const pkg = readJson3(join3(cwd, "package.json"));
574
+ const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
575
+ if (!pkg || !deps.usepilot) {
576
+ return `# Pilot isn't installed here
1232
577
 
1233
- // src/attachments.ts
1234
- import { createHash } from "crypto";
1235
- import { existsSync as existsSync3 } from "fs";
1236
- import { mkdir, readdir, readFile as readFile2, rm as rm2, stat, writeFile as writeFile2 } from "fs/promises";
1237
- import { tmpdir } from "os";
1238
- import { basename as basename2, dirname as dirname3, join as join5 } from "path";
1239
- var FOLDER = "pilot-attachments";
1240
- var MAX_ATTACHMENT_BYTES = 1e7;
1241
- var MAX_INLINE_IMAGE = 35e5;
1242
- var MAX_INLINE_TEXT = 1e5;
1243
- var KEEP_MS = 7 * 24 * 60 * 60 * 1e3;
1244
- function attachmentsDir(base = tmpdir()) {
1245
- return join5(base, FOLDER);
1246
- }
1247
- function extensionOf(type) {
1248
- const given = type.split(";")[0]?.trim().toLowerCase();
1249
- const found = Object.entries(ATTACHMENT_TYPES).find(([, t]) => t === given);
1250
- return found ? found[0] : null;
1251
- }
1252
- function looksLike(bytes, ext) {
1253
- const starts = (...sig) => sig.every((b, i) => bytes[i] === b);
1254
- switch (ext) {
1255
- case "png":
1256
- return starts(137, 80, 78, 71);
1257
- case "jpg":
1258
- return starts(255, 216, 255);
1259
- case "gif":
1260
- return starts(71, 73, 70, 56);
1261
- case "webp":
1262
- return starts(82, 73, 70, 70) && bytes.subarray(8, 12).toString("latin1") === "WEBP";
1263
- case "pdf":
1264
- return bytes.subarray(0, 5).toString("latin1") === "%PDF-";
1265
- default:
1266
- if (bytes.includes(0)) return false;
1267
- try {
1268
- new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1269
- return true;
1270
- } catch {
1271
- return false;
1272
- }
578
+ Run this in your app's folder, the one where Pilot was set up. To set Pilot up in this one, run \`npx usepilot@latest init\` instead.
579
+ `;
1273
580
  }
1274
- }
1275
- async function saveAttachment(bytes, type, dir = attachmentsDir()) {
1276
- const ext = extensionOf(type);
1277
- if (!ext || bytes.length === 0 || bytes.length > MAX_ATTACHMENT_BYTES || !looksLike(bytes, ext)) return null;
1278
- const id = `${createHash("sha256").update(bytes).digest("hex")}.${ext}`;
1279
- await mkdir(dir, { recursive: true });
1280
- const path = join5(dir, id);
1281
- if (!existsSync3(path)) await writeFile2(path, bytes);
1282
- return id;
1283
- }
1284
- function withAttachmentPaths(job, dir = attachmentsDir()) {
1285
- const request = job.changeSet.request;
1286
- const kept = (files) => {
1287
- if (!Array.isArray(files)) return void 0;
1288
- const valid = files.filter((file) => typeof file?.id === "string" && ATTACHMENT_ID.test(file.id) && existsSync3(join5(dir, file.id))).slice(0, 20).map((file) => ({
1289
- id: file.id,
1290
- name: typeof file.name === "string" ? file.name.slice(0, 200) : void 0,
1291
- path: join5(dir, file.id)
1292
- }));
1293
- return valid.length ? valid : void 0;
1294
- };
1295
- if (request && request.kind !== "comment")
1296
- return { ...job, changeSet: { ...job.changeSet, request: { ...request, attachments: kept(request.attachments) } } };
1297
- if (request?.kind !== "comment") return job;
1298
- const thread = request.thread.map((message) => message.attachments ? { ...message, attachments: kept(message.attachments) } : message);
1299
- return { ...job, changeSet: { ...job.changeSet, request: { ...request, thread } } };
1300
- }
1301
- function newAttachments(job) {
1302
- const request = job.changeSet.request;
1303
- let files;
1304
- if (request && request.kind !== "comment") files = request.attachments ?? [];
1305
- else if (request?.kind === "comment") {
1306
- const lastReply = request.thread.map((m) => m.from).lastIndexOf("agent");
1307
- files = request.thread.slice(lastReply + 1).flatMap((m) => m.attachments ?? []);
1308
- } else return [];
1309
- return files.filter((f) => !!f.path && basename2(dirname3(f.path)) === FOLDER && ATTACHMENT_ID.test(basename2(f.path)));
1310
- }
1311
- async function attachmentBlocks(job) {
1312
- const blocks = [];
1313
- for (const file of newAttachments(job)) {
1314
- const path = file.path;
1315
- const kind = attachmentKind(path);
1316
- if (kind === "pdf") continue;
1317
- try {
1318
- const size = (await stat(path)).size;
1319
- if (kind === "image") {
1320
- if (size > MAX_INLINE_IMAGE) continue;
1321
- const ext = basename2(path).split(".").pop();
1322
- blocks.push({ type: "image", data: (await readFile2(path)).toString("base64"), mimeType: ATTACHMENT_TYPES[ext] });
1323
- } else {
1324
- if (size > MAX_INLINE_TEXT) continue;
1325
- const name = file.name ?? basename2(path);
1326
- blocks.push({
1327
- type: "text",
1328
- text: `Attached file ${name}, as the designer sent it:
581
+ const root = projectRoot(cwd);
582
+ const before = installedVersion(cwd, root);
583
+ const oldBridge = bridgeOf(cwd, root);
584
+ const pm = packageManager(cwd, root);
585
+ const args = installArgs(pm, "usepilot@latest");
586
+ const installed = run2(pm, args, cwd);
587
+ const after = installed ? installedVersion(cwd, root) ?? VERSION : before;
588
+ const removed = installed ? await removeOldSetup(root, home, options.platform ?? process.platform, run2) : [];
589
+ if (!installed) {
590
+ return `# Pilot: not updated
1329
591
 
1330
- ${await readFile2(path, "utf8")}
592
+ Installing the latest Pilot didn't work (the output is above). Run this in ${cwd}, then \`npx usepilot@latest update\` again:
1331
593
 
1332
- (end of ${name})`
1333
- });
1334
- }
1335
- } catch {
1336
- }
594
+ \`\`\`
595
+ ${pm} ${args.join(" ")}
596
+ \`\`\`
597
+ `;
1337
598
  }
1338
- return blocks;
1339
- }
1340
- async function sweepAttachments(dir = attachmentsDir(), now = Date.now()) {
1341
- try {
1342
- for (const name of await readdir(dir)) {
1343
- if (!ATTACHMENT_ID.test(name)) continue;
1344
- const path = join5(dir, name);
1345
- if (now - (await stat(path)).mtimeMs > KEEP_MS) await rm2(path, { force: true });
1346
- }
1347
- } catch {
599
+ const framework = detectFramework(cwd, deps);
600
+ const loader = framework.loads;
601
+ const unnamed = loader ? !!namingStep(loader, cwd) : oldBridge !== null && oldBridge < 8;
602
+ const devServer = devServerStep(framework, cwd, pkg);
603
+ const bumped = !!before && !!after && olderThan(before, after);
604
+ const changed = bumped || removed.length > 0 || unnamed;
605
+ const initFor = [
606
+ ...unnamed ? ["names this project in Pilot's loader, so Pilot knows the app's pages are this project's"] : [],
607
+ ...devServer.todo ? ["sets Pilot to start with your dev server, so there's no `npx usepilot` to run"] : []
608
+ ];
609
+ const steps = [
610
+ ...initFor.length ? [`Ask your agent to run \`npx usepilot@latest init\` in the app's folder: it ${initFor.join(", and ")}.`] : [],
611
+ "Restart your app's dev server, so the page loads the new Pilot.",
612
+ ...devServer.done ? [] : ["Restart `npx usepilot` in the app's folder, if you run it (Ctrl+C, then run it again), so Pilot runs the new version."]
613
+ ];
614
+ if (oldBridge !== null && oldBridge !== BRIDGE_VERSION) {
615
+ steps.push(
616
+ "Update Pilot in your other projects too (`npx usepilot@latest update` in each): this version can't share its connection with older ones."
617
+ );
1348
618
  }
619
+ const headline = bumped ? `# Pilot updated: ${before} \u2192 ${after}` : `# Pilot is up to date (${after ?? VERSION})`;
620
+ const removedLine = removed.length ? `
621
+ Pilot's old chat setup is removed (${removed.map((r) => `\`${r}\``).join(", ")}): Pilot runs your agent itself now. Run \`npx usepilot\` in your app's folder, beside its dev server, instead of \`/pilot\` in a chat.
622
+ ` : "";
623
+ return `${headline}
624
+ ${removedLine}
625
+ ${changed ? `Next:
626
+ ${steps.map((s, i) => `${i + 1}. ${s}`).join("\n")}
627
+ ` : "Nothing else to do.\n"}
628
+ How to use Pilot, this version: \`npx usepilot guide\` (also in \`node_modules/usepilot/GUIDE.md\`).
629
+ `;
1349
630
  }
1350
-
1351
- // src/components.ts
1352
- import { existsSync as existsSync4, readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
1353
- import { basename as basename3, dirname as dirname4, extname, join as join6, relative as relative2 } from "path";
1354
- var SKIP = /* @__PURE__ */ new Set([
1355
- "node_modules",
1356
- "dist",
1357
- "build",
1358
- "out",
1359
- "coverage",
1360
- "vendor",
1361
- ".git",
1362
- ".next",
1363
- ".nuxt",
1364
- ".svelte-kit",
1365
- ".output",
1366
- ".vercel",
1367
- ".turbo",
1368
- ".cache",
1369
- "storybook-static",
1370
- "__tests__",
1371
- "__mocks__"
1372
- ]);
1373
- var EXTENSIONS = /* @__PURE__ */ new Set([".jsx", ".tsx", ".js", ".vue", ".svelte"]);
1374
- var NOT_COMPONENTS = /\.(test|spec|stories|story|d)\.[jt]sx?$/;
1375
- var ROUTE_FILES = /^(page|layout|template|loading|error|not-found|default|route|_app|_document)\.[jt]sx?$/;
1376
- var MAX_FILES = 8e3;
1377
- var MAX_FILE_BYTES = 512e3;
1378
- var BUDGET_MS = 1500;
1379
- var cache = /* @__PURE__ */ new Map();
1380
- function projectComponents(folders) {
1381
- const roots = [...new Set(folders.map(workspaceRoot))];
1382
- const out = [];
1383
- const seen = /* @__PURE__ */ new Set();
1384
- const deadline = Date.now() + BUDGET_MS;
1385
- for (const root of roots) {
1386
- for (const c of scan(root, deadline)) {
1387
- const key = `${c.name} ${c.file}`;
1388
- if (!seen.has(key)) {
1389
- seen.add(key);
1390
- out.push(c);
631
+ function bridgeOf(cwd, root) {
632
+ for (let dir = cwd; ; dir = dirname2(dir)) {
633
+ const folder = join3(dir, "node_modules", "usepilot", "cli");
634
+ if (existsSync3(join3(folder, "index.js"))) {
635
+ for (const name of readdirSync2(folder).filter((f) => f.endsWith(".js"))) {
636
+ const match = /BRIDGE_VERSION = (\d+)/.exec(readFileSync3(join3(folder, name), "utf8"));
637
+ if (match) return Number(match[1]);
1391
638
  }
639
+ return null;
1392
640
  }
1393
- }
1394
- return out;
1395
- }
1396
- function workspaceRoot(folder) {
1397
- let dir = folder;
1398
- for (; ; ) {
1399
- if (isWorkspace(dir)) return dir;
1400
- const parent = dirname4(dir);
1401
- if (existsSync4(join6(dir, ".git")) || parent === dir) return folder;
1402
- dir = parent;
641
+ if (dir === root || dirname2(dir) === dir) return null;
1403
642
  }
1404
643
  }
1405
- function isWorkspace(dir) {
1406
- if (["pnpm-workspace.yaml", "lerna.json", "nx.json", "turbo.json"].some((f) => existsSync4(join6(dir, f)))) return true;
644
+ function readJson3(file) {
1407
645
  try {
1408
- return "workspaces" in JSON.parse(readFileSync4(join6(dir, "package.json"), "utf8"));
646
+ return JSON.parse(readFileSync3(file, "utf8"));
1409
647
  } catch {
1410
- return false;
648
+ return null;
1411
649
  }
1412
650
  }
1413
- function scan(root, deadline) {
1414
- const known = cache.get(root) ?? /* @__PURE__ */ new Map();
1415
- const now = /* @__PURE__ */ new Map();
1416
- const out = [];
1417
- const walk = (dir) => {
1418
- let entries;
1419
- try {
1420
- entries = readdirSync2(dir, { withFileTypes: true });
1421
- } catch {
1422
- return;
1423
- }
1424
- for (const entry of entries) {
1425
- if (now.size >= MAX_FILES || Date.now() > deadline) return;
1426
- const name = entry.name;
1427
- if (SKIP.has(name) || name.startsWith(".")) continue;
1428
- const path = join6(dir, name);
1429
- if (entry.isDirectory()) {
1430
- walk(path);
1431
- continue;
1432
- }
1433
- if (!entry.isFile() || !EXTENSIONS.has(extname(name)) || NOT_COMPONENTS.test(name) || ROUTE_FILES.test(name)) continue;
1434
- let stat2;
1435
- try {
1436
- stat2 = statSync2(path);
1437
- } catch {
1438
- continue;
1439
- }
1440
- if (stat2.size > MAX_FILE_BYTES) continue;
1441
- const before = known.get(path);
1442
- const cached = before && before.mtime === stat2.mtimeMs ? before : { mtime: stat2.mtimeMs, components: read2(path) };
1443
- now.set(path, cached);
1444
- const file = relative2(root, path);
1445
- for (const c of cached.components) out.push({ name: c.name, file, line: c.line });
1446
- }
1447
- };
1448
- walk(root);
1449
- cache.set(root, now);
1450
- return out;
1451
- }
1452
- function fileComponentName(path) {
1453
- return basename3(path, extname(path)).split(/[-_.\s]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join("");
1454
- }
1455
- var NAME = "[A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*";
1456
- var FUNCTION = new RegExp(`^\\s*(export\\s+)?(?:default\\s+)?(?:async\\s+)?function\\s+(${NAME})\\b`);
1457
- var CONSTANT = new RegExp(`^\\s*(export\\s+)?(?:const|let|var)\\s+(${NAME})\\s*(?::[^=]+)?=\\s*(.*)$`);
1458
- var COMPONENT_VALUE = /^(?:\(|async\s*\(|function\b|[A-Za-z_$][\w$]*\s*=>|(?:React\.)?(?:forwardRef|memo|lazy)\b|styled[.(]|defineComponent\b|component\$)/;
1459
- function read2(path) {
1460
- const ext = extname(path);
1461
- if (ext === ".vue" || ext === ".svelte") return [{ name: fileComponentName(path), line: 1 }];
1462
- let source;
1463
- try {
1464
- source = readFileSync4(path, "utf8");
1465
- } catch {
1466
- return [];
1467
- }
1468
- if (!/<[A-Za-z]|styled[.(]/.test(source)) return [];
1469
- const found = [];
1470
- const lines = source.split("\n");
1471
- for (let i = 0; i < lines.length; i++) {
1472
- const line = lines[i];
1473
- const fn = FUNCTION.exec(line);
1474
- const constant = fn ? null : CONSTANT.exec(line);
1475
- const m = fn ?? constant;
1476
- if (!m) continue;
1477
- const name = m[2];
1478
- if (constant && !COMPONENT_VALUE.test((constant[3] ?? "").trim())) continue;
1479
- const exported = !!m[1] || new RegExp(`export\\s+default\\s+${name}\\b|export\\s*\\{[^}]*\\b${name}\\b[^}]*\\}`).test(source);
1480
- if (exported && !found.some((f) => f.name === name)) found.push({ name, line: i + 1 });
1481
- }
1482
- return found;
1483
- }
1484
-
1485
- // src/skills.ts
1486
- import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync5, statSync as statSync3 } from "fs";
1487
- import { homedir as homedir4 } from "os";
1488
- import { dirname as dirname5, join as join7 } from "path";
1489
- function skillFolders2(cli, project, home = homedir4()) {
1490
- const folders = [...projectRoots(project).flatMap((dir) => cli.skills.project.map((rel) => join7(dir, rel))), ...cli.skills.home.map((rel) => join7(home, rel))];
1491
- return [...new Set(folders)];
1492
- }
1493
- function projectRoots(project) {
1494
- const roots = [project];
1495
- let dir = project;
1496
- while (!existsSync5(join7(dir, ".git"))) {
1497
- const up = dirname5(dir);
1498
- if (up === dir) return [project];
1499
- dir = up;
1500
- roots.push(dir);
1501
- }
1502
- return roots;
1503
- }
1504
- function findSkills(folders) {
1505
- const found = /* @__PURE__ */ new Map();
1506
- for (const folder of folders) {
1507
- let entries;
1508
- try {
1509
- entries = readdirSync3(folder);
1510
- } catch {
1511
- continue;
1512
- }
1513
- for (const entry of entries.sort()) {
1514
- if (entry.startsWith(".")) continue;
1515
- const meta = readSkill(join7(folder, entry, "SKILL.md"));
1516
- if (!meta) continue;
1517
- const name = meta.name || entry;
1518
- if (!SKILL_NAME.test(name) || found.has(name)) continue;
1519
- found.set(name, { name, ...meta.description ? { description: meta.description } : {} });
1520
- }
1521
- }
1522
- return [...found.values()].sort((a, b) => a.name.localeCompare(b.name));
1523
- }
1524
- var MAX_SKILL_BYTES = 256e3;
1525
- var MAX_DESCRIPTION = 300;
1526
- function readSkill(file) {
1527
- try {
1528
- if (statSync3(file).size > MAX_SKILL_BYTES) return null;
1529
- const meta = frontmatter(readFileSync5(file, "utf8"));
1530
- const description = meta.description?.replace(/\s+/g, " ").trim();
1531
- return {
1532
- name: meta.name?.trim(),
1533
- description: description && description.length > MAX_DESCRIPTION ? `${description.slice(0, MAX_DESCRIPTION - 1).trimEnd()}\u2026` : description
1534
- };
1535
- } catch {
1536
- return null;
1537
- }
1538
- }
1539
- function frontmatter(text) {
1540
- const block = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text)?.[1];
1541
- if (block === void 0) return {};
1542
- const lines = block.split(/\r?\n/);
1543
- const out = {};
1544
- for (let i = 0; i < lines.length; i++) {
1545
- const pair = /^([A-Za-z][\w-]*):[ \t]*(.*)$/.exec(lines[i]);
1546
- if (!pair) continue;
1547
- const key = pair[1];
1548
- let value = pair[2].trim();
1549
- const more = [];
1550
- while (i + 1 < lines.length && (/^[ \t]+\S/.test(lines[i + 1]) || !lines[i + 1].trim())) more.push(lines[++i].trim());
1551
- if (/^[>|][+-]?$/.test(value)) value = more.filter(Boolean).join(value.startsWith("|") ? "\n" : " ");
1552
- else if (more.some(Boolean)) value = [value, ...more].filter(Boolean).join(" ");
1553
- out[key] = unquote(value);
1554
- }
1555
- return out;
1556
- }
1557
- function unquote(value) {
1558
- if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) return value.slice(1, -1).replace(/''/g, "'");
1559
- if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) return value.slice(1, -1).replace(/\\(["\\])/g, "$1").replace(/\\n/g, "\n");
1560
- return value;
1561
- }
1562
-
1563
- // src/tokenFiles.ts
1564
- import { readdirSync as readdirSync4, readFileSync as readFileSync6, statSync as statSync4 } from "fs";
1565
- import { basename as basename4, dirname as dirname6, join as join8, relative as relative3 } from "path";
1566
- var MAX_FILES2 = 8e3;
1567
- var MAX_FILE_BYTES2 = 512e3;
1568
- var MAX_TOKENS = 1e3;
1569
- var BUDGET_MS2 = 1500;
1570
- function isTokenJson(path) {
1571
- const name = basename4(path).toLowerCase();
1572
- if (!name.endsWith(".json") || name === "package.json" || name.startsWith("tsconfig")) return false;
1573
- return /(^|[.-])(design-)?tokens?\.json$/.test(name) || /(^|\/)(design-)?tokens?$/.test(dirname6(path).toLowerCase());
1574
- }
1575
- function isTokenSass(path) {
1576
- const name = basename4(path).toLowerCase();
1577
- return /\.s[ac]ss$/.test(name) && /(token|variable|vars?\b|theme|colou?r|spacing|typograph|radius|radii|shadow|breakpoint)/.test(name);
1578
- }
1579
- var cache2 = /* @__PURE__ */ new Map();
1580
- function fileTokens(folders) {
1581
- const out = [];
1582
- const seen = /* @__PURE__ */ new Set();
1583
- const deadline = Date.now() + BUDGET_MS2;
1584
- for (const root of new Set(folders.map(workspaceRoot))) {
1585
- for (const t of scan2(root, deadline)) {
1586
- if (out.length >= MAX_TOKENS) return out;
1587
- if (!seen.has(t.name)) {
1588
- seen.add(t.name);
1589
- out.push(t);
1590
- }
1591
- }
1592
- }
1593
- return out;
1594
- }
1595
- function scan2(root, deadline) {
1596
- const known = cache2.get(root) ?? /* @__PURE__ */ new Map();
1597
- const now = /* @__PURE__ */ new Map();
1598
- const out = [];
1599
- let files = 0;
1600
- const walk = (dir) => {
1601
- let entries;
1602
- try {
1603
- entries = readdirSync4(dir, { withFileTypes: true });
1604
- } catch {
1605
- return;
1606
- }
1607
- for (const entry of entries) {
1608
- if (files >= MAX_FILES2 || Date.now() > deadline) return;
1609
- const name = entry.name;
1610
- if (SKIP.has(name) || name.startsWith(".")) continue;
1611
- const path = join8(dir, name);
1612
- if (entry.isDirectory()) {
1613
- walk(path);
1614
- continue;
1615
- }
1616
- files++;
1617
- const json2 = isTokenJson(path);
1618
- if (!entry.isFile() || !(json2 || isTokenSass(path))) continue;
1619
- let stat2;
1620
- try {
1621
- stat2 = statSync4(path);
1622
- } catch {
1623
- continue;
1624
- }
1625
- if (stat2.size > MAX_FILE_BYTES2) continue;
1626
- const before = known.get(path);
1627
- const file = relative3(root, path);
1628
- const cached = before && before.mtime === stat2.mtimeMs ? before : { mtime: stat2.mtimeMs, tokens: read3(path, file, json2) };
1629
- now.set(path, cached);
1630
- out.push(...cached.tokens);
1631
- }
1632
- };
1633
- walk(root);
1634
- cache2.set(root, now);
1635
- return out;
1636
- }
1637
- function read3(path, file, json2) {
1638
- let text;
1639
- try {
1640
- text = readFileSync6(path, "utf8");
1641
- } catch {
1642
- return [];
1643
- }
1644
- return json2 ? jsonTokens(text, file) : sassTokens(text, file);
1645
- }
1646
- function jsonTokens(text, file) {
1647
- let data;
1648
- try {
1649
- data = JSON.parse(text);
1650
- } catch {
1651
- return [];
1652
- }
1653
- const raw = /* @__PURE__ */ new Map();
1654
- const walk = (node, path) => {
1655
- if (!node || typeof node !== "object" || Array.isArray(node)) return;
1656
- const n = node;
1657
- const value = "$value" in n ? n.$value : "value" in n && typeof n.value !== "object" ? n.value : void 0;
1658
- if (value !== void 0) {
1659
- if ((typeof value === "string" || typeof value === "number") && path.length) raw.set(path.join("."), String(value));
1660
- return;
1661
- }
1662
- for (const [key, child] of Object.entries(n)) if (!key.startsWith("$")) walk(child, [...path, key]);
1663
- };
1664
- walk(data, []);
1665
- const lines = text.split("\n");
1666
- const out = [];
1667
- for (const [name, value] of raw) {
1668
- const resolved = resolve2(value, (ref) => raw.get(ref), /\{([^{}]+)\}/g);
1669
- if (resolved === null) continue;
1670
- const last = name.split(".").at(-1);
1671
- const at = lines.findIndex((l) => l.includes(`"${last}"`));
1672
- out.push({ name, value: resolved, file, ...at >= 0 ? { line: at + 1 } : {} });
1673
- }
1674
- return out;
1675
- }
1676
- function sassTokens(text, file) {
1677
- const raw = /* @__PURE__ */ new Map();
1678
- text.split("\n").forEach((line, i) => {
1679
- const m = /^\s*\$([\w-]+)\s*:\s*([^;]+?)\s*(?:!default|!global)*\s*;/.exec(line);
1680
- if (m && !raw.has(m[1])) raw.set(m[1], { value: m[2], line: i + 1 });
1681
- });
1682
- const out = [];
1683
- for (const [name, { value, line }] of raw) {
1684
- if (/[\w-]\([^)]*\$|map-get|\bif\(|^\(/.test(value)) continue;
1685
- const resolved = resolve2(value, (ref) => raw.get(ref)?.value, /\$([\w-]+)/g);
1686
- if (resolved === null || resolved.includes("$")) continue;
1687
- out.push({ name: `$${name}`, value: resolved, file, line });
1688
- }
1689
- return out;
1690
- }
1691
- function resolve2(value, get, pattern) {
1692
- let v = value;
1693
- for (let depth = 0; depth < 8; depth++) {
1694
- let missing = false;
1695
- const next = v.replace(pattern, (_, ref) => {
1696
- const found = get(ref);
1697
- if (found === void 0) missing = true;
1698
- return found ?? "";
1699
- });
1700
- if (missing) return null;
1701
- if (next === v) return v.trim();
1702
- v = next;
1703
- }
1704
- return null;
1705
- }
1706
-
1707
- // src/hub.ts
1708
- import { randomUUID } from "crypto";
1709
- var AGENT_TTL = 3e4;
1710
- var Hub = class {
1711
- constructor(now = Date.now) {
1712
- this.now = now;
1713
- }
1714
- now;
1715
- agents = /* @__PURE__ */ new Map();
1716
- pages = /* @__PURE__ */ new Set();
1717
- jobs = /* @__PURE__ */ new Map();
1718
- waiters = [];
1719
- checks = /* @__PURE__ */ new Map();
1720
- // Agents
1721
- /** An agent works on pages of `origin` (again: also how a remote one says it's alive). */
1722
- register(info, origin) {
1723
- const key = originKey(origin);
1724
- const known = this.agents.get(info.id);
1725
- const { folder, kind, ...shown } = info;
1726
- this.agents.set(info.id, {
1727
- info: shown,
1728
- origin: key,
1729
- seen: this.now(),
1730
- folder: folder ?? known?.folder,
1731
- kind: isAgentKind(kind) ? kind : known?.kind
1732
- });
1733
- if (!known || known.origin !== key) {
1734
- if (known) this.notifyAgents(known.origin);
1735
- this.notifyAgents(key);
1736
- }
1737
- }
1738
- /**
1739
- * The agent is gone (its process ended or it stopped pinging): its waits
1740
- * end, and the jobs it was working on go back to the queue, for another
1741
- * chat (or this one, back), instead of staying "working" for nobody.
1742
- */
1743
- unregister(agentId) {
1744
- const agent = this.agents.get(agentId);
1745
- if (!agent) return;
1746
- this.agents.delete(agentId);
1747
- for (const w of this.waiters.filter((w2) => w2.agentId === agentId)) this.endWait(w, null);
1748
- for (const job of this.jobs.values()) {
1749
- if (job.status === "working" && job.agent?.id === agentId) this.update(job, { status: "queued", takenAt: void 0 });
1750
- }
1751
- this.notifyAgents(agent.origin);
1752
- this.dispatch(agent.origin);
1753
- }
1754
- /** An agent's info as pages see it (no folder). */
1755
- shown(info) {
1756
- return this.agents.get(info.id)?.info ?? { id: info.id, label: info.label };
1757
- }
1758
- /** The project folders of the agents working on pages of `origin`: where its components are read from. */
1759
- folders(origin) {
1760
- const key = originKey(origin);
1761
- return [...new Set([...this.agents.values()].filter((a) => a.origin === key && a.folder).map((a) => a.folder))];
1762
- }
1763
- /** Where the agents working on pages of `origin` read their skills from (each agent's own folders, skills.ts): for the `/` list. */
1764
- skillFolders(origin) {
1765
- const key = originKey(origin);
1766
- const agents = [...this.agents.values()].filter((a) => a.origin === key && a.folder && a.kind);
1767
- return [...new Set(agents.flatMap((a) => skillFolders2(AGENTS[a.kind], a.folder)))];
1768
- }
1769
- /** Drops agents not heard from in AGENT_TTL (`keep`: the ones in this process, always alive). */
1770
- sweep(keep = /* @__PURE__ */ new Set()) {
1771
- const cutoff = this.now() - AGENT_TTL;
1772
- for (const [id, agent] of this.agents) {
1773
- if (!keep.has(id) && agent.seen < cutoff && !this.waiters.some((w) => w.agentId === id)) this.unregister(id);
1774
- }
1775
- }
1776
- /**
1777
- * The designer closed Pilot on `origin` (the whole site): its open pages
1778
- * close it too. Nothing else: jobs aren't touched (a run on one finishes),
1779
- * and Pilot keeps running for the site, so the shortcut opens it again.
1780
- */
1781
- quit(origin) {
1782
- this.sendTo(originKey(origin), { type: "quit" });
1783
- }
1784
- /**
1785
- * The pages with Pilot open in a browser now, each site and project once,
1786
- * leaving out the sites Pilot already runs for: where `npx usepilot` looks
1787
- * for its own project's pages (by their project's name), without a URL.
1788
- */
1789
- openPages() {
1790
- const seen = /* @__PURE__ */ new Map();
1791
- for (const page of this.pages) {
1792
- if (this.hasAgents(page.origin)) continue;
1793
- seen.set(`${page.origin} ${page.project ?? ""}`, { origin: page.origin, ...page.project ? { project: page.project } : {} });
1794
- }
1795
- return [...seen.values()];
1796
- }
1797
- /** Pilot started for a site (`npx usepilot`): registers it and tells the open pages of `origin` to launch Pilot. Returns how many pages got it. */
1798
- launch(info, origin) {
1799
- this.register(info, origin);
1800
- return this.sendTo(originKey(origin), { type: "launch", agent: this.shown(info) });
1801
- }
1802
- /**
1803
- * The agent's next job for its origin: the oldest queued one right away, or
1804
- * the next one posted within `timeoutMs` (null after that, or when `signal`
1805
- * aborts). Taking a job marks it working, by this agent.
1806
- */
1807
- wait(info, origin, timeoutMs, signal) {
1808
- this.register(info, origin);
1809
- const key = originKey(origin);
1810
- const queued = this.oldestQueued(key);
1811
- if (queued) return Promise.resolve({ job: this.take(queued, this.shown(info)) });
1812
- return new Promise((resolve3) => {
1813
- const waiter = {
1814
- agentId: info.id,
1815
- origin: key,
1816
- resolve: (job) => {
1817
- clearTimeout(timer);
1818
- signal?.removeEventListener("abort", onAbort);
1819
- resolve3({ job });
1820
- }
1821
- };
1822
- const timer = setTimeout(() => this.endWait(waiter, null), timeoutMs);
1823
- const onAbort = () => this.endWait(waiter, null);
1824
- signal?.addEventListener("abort", onAbort, { once: true });
1825
- this.waiters.push(waiter);
1826
- this.notifyAgents(key);
1827
- });
1828
- }
1829
- /**
1830
- * The agent applied a job: done, with its notes, and its `question` for
1831
- * the designer if it asked one (the page shows it and holds the job until
1832
- * the answer, see answer). A job asks once: a question on an answered job
1833
- * is dropped. Null for a job the hub doesn't know.
1834
- */
1835
- done(agentId, jobId, notes, question, props, extra = {}) {
1836
- const job = this.jobs.get(jobId);
1837
- if (!job || job.status === "cancelled") return null;
1838
- const agent = this.agents.get(agentId)?.info ?? job.agent;
1839
- const asks = question && !job.answer ? { question } : {};
1840
- const listed = props?.length && job.changeSet.request?.kind === "props" ? { props } : {};
1841
- this.update(job, {
1842
- status: "done",
1843
- agent,
1844
- notes: notes?.trim() || void 0,
1845
- doneAt: new Date(this.now()).toISOString(),
1846
- ...asks,
1847
- ...listed,
1848
- // The session to resume for its follow-up (kept from the first run when a later one has none), and the run's error or none.
1849
- session: extra.session ?? job.session,
1850
- error: extra.error
1851
- });
1852
- return job;
1853
- }
1854
- /**
1855
- * The designer answered a done job's question: the job goes back to the
1856
- * queue with the answer, preferably to the agent that asked. Null when it
1857
- * can't (not done, no question, or answered already).
1858
- */
1859
- answer(origin, jobId, answer) {
1860
- const job = this.jobs.get(jobId);
1861
- if (!job || job.origin !== originKey(origin) || job.status !== "done" || !job.question || job.answer) return null;
1862
- this.update(job, { status: "queued", answer, notes: void 0 });
1863
- this.dispatch(job.origin);
1864
- return job;
1865
- }
1866
- /**
1867
- * An agent asks for Pilot's width check of a task's element: the open
1868
- * pages of the job's origin get a `check` event, and the one that has the
1869
- * job measures it and posts the answer (checkResult). Null when no page
1870
- * is open, the hub doesn't know the job, or no answer comes in `timeoutMs`.
1871
- */
1872
- check(jobId, timeoutMs) {
1873
- const job = this.jobs.get(jobId);
1874
- if (!job) return Promise.resolve(null);
1875
- const requestId = randomUUID();
1876
- return new Promise((resolve3) => {
1877
- const timer = setTimeout(() => finish(null), timeoutMs);
1878
- const finish = (check) => {
1879
- clearTimeout(timer);
1880
- this.checks.delete(requestId);
1881
- resolve3(check);
1882
- };
1883
- this.checks.set(requestId, { origin: job.origin, resolve: finish });
1884
- if (!this.sendTo(job.origin, { type: "check", requestId, jobId })) finish(null);
1885
- });
1886
- }
1887
- /** A page's answer to a width check: false when nothing waits for it from that origin. */
1888
- checkResult(origin, requestId, check) {
1889
- const pending = this.checks.get(requestId);
1890
- if (!pending || pending.origin !== originKey(origin)) return false;
1891
- pending.resolve(check);
1892
- return true;
1893
- }
1894
- // Pages
1895
- addPage(page) {
1896
- const conn = { ...page, origin: originKey(page.origin) };
1897
- this.pages.add(conn);
1898
- conn.send(this.agentsEvent(conn.origin));
1899
- for (const job of this.jobs.values()) {
1900
- if (job.origin === conn.origin) conn.send({ type: "job", job: structuredClone(job) });
1901
- }
1902
- return () => this.pages.delete(conn);
1903
- }
1904
- /** Whether any agent works on pages of `origin`: only then does the hub take jobs from it. */
1905
- hasAgents(origin) {
1906
- const key = originKey(origin);
1907
- return [...this.agents.values()].some((a) => a.origin === key);
1908
- }
1909
- /**
1910
- * A job from a page: new ones are queued (and go to a waiting agent);
1911
- * posting one the hub already has changes nothing, so a page can post its
1912
- * unfinished jobs again whenever it connects. One the page knows as working,
1913
- * by an agent still here, stays that agent's.
1914
- */
1915
- postJob(origin, post) {
1916
- const key = originKey(origin);
1917
- const known = this.jobs.get(post.id);
1918
- if (known) return known;
1919
- const at = new Date(this.now()).toISOString();
1920
- const stillWorking = post.status === "working" && post.agent && this.agents.has(post.agent.id);
1921
- const job = {
1922
- id: post.id,
1923
- origin: key,
1924
- changeSet: post.changeSet,
1925
- status: stillWorking ? "working" : "queued",
1926
- // A follow-up (or an answered question) keeps its agent as the one to prefer (see dispatch).
1927
- agent: stillWorking || post.attempt === 2 || post.answer ? post.agent : void 0,
1928
- attempt: post.attempt ?? 1,
1929
- differences: post.differences,
1930
- issues: post.issues,
1931
- question: post.question,
1932
- answer: post.answer,
1933
- session: post.session,
1934
- createdAt: at,
1935
- updatedAt: at
1936
- };
1937
- this.jobs.set(job.id, job);
1938
- this.sendTo(key, { type: "job", job });
1939
- if (job.status === "queued") this.dispatch(key);
1940
- return job;
1941
- }
1942
- /** The designer took a job back before it was done. */
1943
- cancel(origin, jobId) {
1944
- const job = this.jobs.get(jobId);
1945
- if (!job || job.origin !== originKey(origin) || job.status === "done") return null;
1946
- this.update(job, { status: "cancelled" });
1947
- return job;
1948
- }
1949
- /**
1950
- * Some changes of a done job didn't come out as the designer set them (or
1951
- * a task's width check found problems, `issues`): the job goes back to
1952
- * the queue once, as a follow-up with the `differences`,
1953
- * preferably to the agent that did it. Null when it can't (not done, or
1954
- * already a follow-up: then the page takes what the code gives).
1955
- */
1956
- retry(origin, jobId, differences, issues) {
1957
- const job = this.jobs.get(jobId);
1958
- if (!job || job.origin !== originKey(origin) || job.status !== "done" || (job.attempt ?? 1) >= 2) return null;
1959
- this.update(job, { status: "queued", attempt: 2, differences, issues, notes: void 0 });
1960
- this.dispatch(job.origin);
1961
- return job;
1962
- }
1963
- job(id) {
1964
- return this.jobs.get(id);
1965
- }
1966
- // Internals
1967
- oldestQueued(origin) {
1968
- return [...this.jobs.values()].filter((j) => j.origin === origin && j.status === "queued").sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0];
1969
- }
1970
- take(job, agent) {
1971
- this.update(job, { status: "working", agent, takenAt: new Date(this.now()).toISOString() });
1972
- return job;
1973
- }
1974
- /**
1975
- * Gives the oldest queued job of `origin` to the agent waiting longest
1976
- * there; a follow-up to the agent that did the job, if it's waiting.
1977
- */
1978
- dispatch(origin) {
1979
- const job = this.oldestQueued(origin);
1980
- const waiters = this.waiters.filter((w) => w.origin === origin);
1981
- const waiter = waiters.find((w) => w.agentId === job?.agent?.id) ?? waiters[0];
1982
- const agent = waiter && this.agents.get(waiter.agentId);
1983
- if (!waiter || !job || !agent) return;
1984
- this.endWait(waiter, this.take(job, agent.info));
1985
- }
1986
- endWait(waiter, job) {
1987
- const i = this.waiters.indexOf(waiter);
1988
- if (i < 0) return;
1989
- this.waiters.splice(i, 1);
1990
- waiter.resolve(job);
1991
- this.notifyAgents(waiter.origin);
1992
- }
1993
- update(job, patch) {
1994
- Object.assign(job, patch, { updatedAt: new Date(this.now()).toISOString() });
1995
- this.sendTo(job.origin, { type: "job", job });
1996
- }
1997
- agentsEvent(origin) {
1998
- const agents = [...this.agents.values()].filter((a) => a.origin === origin).map((a) => a.info);
1999
- const waiting = new Set(this.waiters.filter((w) => w.origin === origin).map((w) => w.agentId)).size;
2000
- return { type: "agents", agents, waiting };
2001
- }
2002
- notifyAgents(origin) {
2003
- this.sendTo(origin, this.agentsEvent(origin));
2004
- }
2005
- sendTo(origin, event) {
2006
- let n = 0;
2007
- for (const page of this.pages) {
2008
- if (page.origin !== origin) continue;
2009
- page.send(structuredClone(event));
2010
- n++;
2011
- }
2012
- return n;
2013
- }
2014
- };
2015
-
2016
- // src/server.ts
2017
- function startHub(port, hub = new Hub(), options = {}) {
2018
- const attachments = options.attachments ?? attachmentsDir();
2019
- void sweepAttachments(attachments);
2020
- const server = createServer((req, res) => {
2021
- handle(hub, req, res, attachments).catch((error) => {
2022
- if (!res.headersSent) json(res, 500, { error: String(error) });
2023
- });
2024
- });
2025
- const sweep = setInterval(() => hub.sweep(localAgents), 5e3);
2026
- sweep.unref();
2027
- return new Promise((resolve3, reject) => {
2028
- server.once("error", (error) => {
2029
- clearInterval(sweep);
2030
- reject(error);
2031
- });
2032
- server.listen(port, "127.0.0.1", () => {
2033
- const address = server.address();
2034
- resolve3({
2035
- hub,
2036
- server,
2037
- port: typeof address === "object" && address ? address.port : port,
2038
- close: () => new Promise((done) => {
2039
- clearInterval(sweep);
2040
- server.closeAllConnections?.();
2041
- server.close(() => done());
2042
- })
2043
- });
2044
- });
2045
- });
2046
- }
2047
- var localAgents = /* @__PURE__ */ new Set();
2048
- async function handle(hub, req, res, attachments) {
2049
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
2050
- const origin = req.headers.origin;
2051
- const path = url.pathname;
2052
- if (path === "/health") return json(res, 200, { pilot: true, version: BRIDGE_VERSION });
2053
- if (path.startsWith("/agents/")) {
2054
- if (origin) return json(res, 403, { error: "agents only" });
2055
- if (req.method !== "POST") return json(res, 405, { error: "POST only" });
2056
- return handleAgent(hub, path.slice("/agents/".length), await body(req), req, res);
2057
- }
2058
- if (!origin || originKey(origin) === "null") return json(res, 400, { error: "no origin" });
2059
- res.setHeader("Access-Control-Allow-Origin", origin);
2060
- res.setHeader("Vary", "Origin");
2061
- if (req.method === "OPTIONS") {
2062
- res.setHeader("Access-Control-Allow-Methods", "POST, GET");
2063
- res.setHeader("Access-Control-Allow-Headers", "content-type");
2064
- res.setHeader("Access-Control-Allow-Private-Network", "true");
2065
- res.writeHead(204).end();
2066
- return;
2067
- }
2068
- if (path === "/events" && req.method === "GET") return events(hub, origin, req, res, projectNameOf(url.searchParams.get("project")));
2069
- if (path === "/quit" && req.method === "POST") {
2070
- hub.quit(origin);
2071
- return json(res, 200, { ok: true });
2072
- }
2073
- if (req.method !== "POST") return json(res, 405, { error: "POST only" });
2074
- if (!hub.hasAgents(origin)) return json(res, 403, { error: "Pilot isn't running for this site: run npx usepilot in your project" });
2075
- if (path === "/components") return json(res, 200, { components: projectComponents(hub.folders(origin)) });
2076
- if (path === "/tokens") return json(res, 200, { tokens: fileTokens(hub.folders(origin)) });
2077
- if (path === "/skills") return json(res, 200, { skills: findSkills(hub.skillFolders(origin)) });
2078
- if (path === "/attachments") {
2079
- const type = req.headers["content-type"] ?? "";
2080
- if (!extensionOf(type)) return json(res, 415, { error: "images (png, jpeg, gif, webp), text files (txt, md, csv, json) and PDFs only" });
2081
- const bytes = await rawBody(req, MAX_ATTACHMENT_BYTES);
2082
- if (!bytes) return json(res, 413, { error: `files up to ${MAX_ATTACHMENT_BYTES / 1e6} MB` });
2083
- const id = await saveAttachment(bytes, type, attachments);
2084
- return id ? json(res, 201, { id }) : json(res, 400, { error: "not a file of that type" });
2085
- }
2086
- const data = await body(req);
2087
- if (path === "/jobs") {
2088
- const post = data;
2089
- if (typeof post?.id !== "string" || !post.changeSet) return json(res, 400, { error: "job needs id and changeSet" });
2090
- return json(res, 202, { job: hub.postJob(origin, withAttachmentPaths({ ...post, session: sessionOf(post.session) }, attachments)) });
2091
- }
2092
- const jobRoute = path.match(/^\/jobs\/([^/]+)\/(cancel|retry|answer)$/);
2093
- if (jobRoute) {
2094
- const [, id, action] = jobRoute;
2095
- const answer = data.answer;
2096
- if (action === "answer" && (typeof answer !== "string" || !answer.trim())) return json(res, 400, { error: "answer needed" });
2097
- const job = action === "cancel" ? hub.cancel(origin, decodeURIComponent(id)) : action === "answer" ? hub.answer(origin, decodeURIComponent(id), answer.trim().slice(0, 2e3)) : hub.retry(
2098
- origin,
2099
- decodeURIComponent(id),
2100
- (data.differences ?? []).slice(0, 200),
2101
- stringsOf(data.issues)
2102
- );
2103
- return job ? json(res, 200, { job }) : json(res, 409, { error: `can't ${action} this job` });
2104
- }
2105
- const checkRoute = path.match(/^\/checks\/([^/]+)$/);
2106
- if (checkRoute) {
2107
- const check = data.check;
2108
- if (!check || !Array.isArray(check.widths)) return json(res, 400, { error: "check needed" });
2109
- return hub.checkResult(origin, decodeURIComponent(checkRoute[1]), check) ? json(res, 200, { ok: true }) : json(res, 409, { error: "no check waits for this" });
2110
- }
2111
- return json(res, 404, { error: "not found" });
2112
- }
2113
- function events(hub, origin, req, res, project) {
2114
- res.writeHead(200, {
2115
- "Content-Type": "text/event-stream",
2116
- "Cache-Control": "no-cache",
2117
- Connection: "keep-alive"
2118
- });
2119
- res.write("retry: 2000\n\n");
2120
- const send = (event) => res.write(`data: ${JSON.stringify(event)}
2121
-
2122
- `);
2123
- const remove = hub.addPage({ origin, project, send });
2124
- const ping = setInterval(() => res.write(": ping\n\n"), 15e3);
2125
- req.on("close", () => {
2126
- clearInterval(ping);
2127
- remove();
2128
- });
2129
- }
2130
- async function handleAgent(hub, action, data, req, res) {
2131
- const d = data;
2132
- if (!d?.agent?.id) return json(res, 400, { error: "agent needed" });
2133
- switch (action) {
2134
- case "register":
2135
- if (!d.origin) return json(res, 400, { error: "origin needed" });
2136
- hub.register(d.agent, d.origin);
2137
- return json(res, 200, { ok: true });
2138
- case "pages":
2139
- return json(res, 200, { pages: hub.openPages() });
2140
- case "launch":
2141
- if (!d.origin) return json(res, 400, { error: "origin needed" });
2142
- return json(res, 200, { pages: hub.launch(d.agent, d.origin) });
2143
- case "wait": {
2144
- if (!d.origin) return json(res, 400, { error: "origin needed" });
2145
- const aborted = new AbortController();
2146
- res.on("close", () => aborted.abort());
2147
- const result = await hub.wait(d.agent, d.origin, Math.min(d.timeoutMs ?? 6e4, 15 * 6e4), aborted.signal);
2148
- if (!res.writableEnded && !res.destroyed) json(res, 200, result);
2149
- return;
2150
- }
2151
- case "done":
2152
- if (!d.jobId) return json(res, 400, { error: "jobId needed" });
2153
- return json(res, 200, {
2154
- job: hub.done(d.agent.id, d.jobId, d.notes, questionOf(d.question), propsOf(d.props), { session: sessionOf(d.session), error: jobErrorOf(d.error) })
2155
- });
2156
- case "job":
2157
- if (!d.jobId) return json(res, 400, { error: "jobId needed" });
2158
- return json(res, 200, { job: hub.job(d.jobId) ?? null });
2159
- case "check": {
2160
- if (!d.jobId) return json(res, 400, { error: "jobId needed" });
2161
- const check = await hub.check(d.jobId, Math.min(d.timeoutMs ?? CHECK_TIMEOUT, 2 * 6e4));
2162
- return json(res, 200, { check });
2163
- }
2164
- case "leave":
2165
- hub.unregister(d.agent.id);
2166
- return json(res, 200, { ok: true });
2167
- default:
2168
- return json(res, 404, { error: "not found" });
2169
- }
2170
- }
2171
- var CHECK_TIMEOUT = 6e4;
2172
- function stringsOf(value) {
2173
- if (!Array.isArray(value)) return void 0;
2174
- return value.filter((v) => typeof v === "string").slice(0, 100).map((v) => v.slice(0, 2e3));
2175
- }
2176
- function json(res, status, data) {
2177
- res.writeHead(status, { "Content-Type": "application/json" });
2178
- res.end(JSON.stringify(data));
2179
- }
2180
- function rawBody(req, max) {
2181
- return new Promise((resolve3, reject) => {
2182
- const chunks = [];
2183
- let size = 0;
2184
- let over = false;
2185
- req.on("data", (chunk) => {
2186
- if (over) return;
2187
- size += chunk.length;
2188
- if (size > max) {
2189
- over = true;
2190
- resolve3(null);
2191
- req.resume();
2192
- return;
2193
- }
2194
- chunks.push(chunk);
2195
- });
2196
- req.on("end", () => {
2197
- if (!over) resolve3(Buffer.concat(chunks));
2198
- });
2199
- req.on("error", reject);
2200
- });
2201
- }
2202
- function body(req) {
2203
- return new Promise((resolve3, reject) => {
2204
- let text = "";
2205
- req.setEncoding("utf8");
2206
- req.on("data", (chunk) => {
2207
- text += chunk;
2208
- if (text.length > 5e6) reject(new Error("body too large"));
2209
- });
2210
- req.on("end", () => {
2211
- try {
2212
- resolve3(text ? JSON.parse(text) : {});
2213
- } catch {
2214
- resolve3({});
2215
- }
2216
- });
2217
- req.on("error", reject);
2218
- });
2219
- }
2220
-
2221
- // src/agent.ts
2222
- var LocalApi = class {
2223
- constructor(hub) {
2224
- this.hub = hub;
2225
- }
2226
- hub;
2227
- async register(agent, origin) {
2228
- localAgents.add(agent.id);
2229
- this.hub.register(agent, origin);
2230
- }
2231
- async launch(agent, origin) {
2232
- localAgents.add(agent.id);
2233
- return this.hub.launch(agent, origin);
2234
- }
2235
- async pages() {
2236
- return this.hub.openPages();
2237
- }
2238
- wait(agent, origin, timeoutMs, signal) {
2239
- localAgents.add(agent.id);
2240
- return this.hub.wait(agent, origin, timeoutMs, signal);
2241
- }
2242
- async done(agent, jobId, notes, question, props, extra) {
2243
- return this.hub.done(agent.id, jobId, notes, question, props, extra);
2244
- }
2245
- async job(_agent, jobId) {
2246
- return this.hub.job(jobId) ?? null;
2247
- }
2248
- check(_agent, jobId, timeoutMs) {
2249
- return this.hub.check(jobId, timeoutMs);
2250
- }
2251
- async leave(agent) {
2252
- localAgents.delete(agent.id);
2253
- this.hub.unregister(agent.id);
2254
- }
2255
- };
2256
- var RemoteApi = class {
2257
- constructor(port) {
2258
- this.port = port;
2259
- }
2260
- port;
2261
- async post(action, data, signal) {
2262
- const res = await fetch(`http://127.0.0.1:${this.port}/agents/${action}`, {
2263
- method: "POST",
2264
- headers: { "content-type": "application/json" },
2265
- body: JSON.stringify(data),
2266
- signal
2267
- });
2268
- if (!res.ok) throw new Error(`Pilot bridge: ${action} failed (${res.status})`);
2269
- return await res.json();
2270
- }
2271
- async register(agent, origin) {
2272
- await this.post("register", { agent, origin });
2273
- }
2274
- async launch(agent, origin) {
2275
- return (await this.post("launch", { agent, origin })).pages;
2276
- }
2277
- async pages() {
2278
- try {
2279
- return (await this.post("pages", {})).pages ?? [];
2280
- } catch (error) {
2281
- if (isConnectionError(error)) throw error;
2282
- return [];
2283
- }
2284
- }
2285
- wait(agent, origin, timeoutMs, signal) {
2286
- return this.post("wait", { agent, origin, timeoutMs }, signal);
2287
- }
2288
- async done(agent, jobId, notes, question, props, extra) {
2289
- return (await this.post("done", { agent, jobId, notes, question, props, ...extra })).job;
2290
- }
2291
- async job(agent, jobId) {
2292
- return (await this.post("job", { agent, jobId })).job;
2293
- }
2294
- async check(agent, jobId, timeoutMs) {
2295
- return (await this.post("check", { agent, jobId, timeoutMs })).check;
2296
- }
2297
- async leave(agent) {
2298
- await this.post("leave", { agent });
2299
- }
2300
- };
2301
- var HEARTBEAT = 1e4;
2302
- var Bridge = class {
2303
- constructor(agent, port) {
2304
- this.agent = agent;
2305
- this.port = port;
2306
- }
2307
- agent;
2308
- port;
2309
- api = null;
2310
- server = null;
2311
- connecting = null;
2312
- heartbeat = null;
2313
- /** The origin this agent works on, once it launched: re-registered after a takeover. */
2314
- origin = null;
2315
- /** Whether this process runs the hub. */
2316
- get isHub() {
2317
- return !!this.server;
2318
- }
2319
- async launch(origin) {
2320
- this.origin = origin;
2321
- const pages = await this.call((api) => api.launch(this.agent, origin));
2322
- this.startHeartbeat();
2323
- return pages;
2324
- }
2325
- /** The sites with Pilot open in a browser (their origins). */
2326
- pages() {
2327
- return this.call((api) => api.pages());
2328
- }
2329
- /** Waits up to `timeoutMs` for a job; survives the hub moving to another process mid-wait. */
2330
- async wait(origin, timeoutMs, signal) {
2331
- this.origin = origin;
2332
- const until = Date.now() + timeoutMs;
2333
- for (; ; ) {
2334
- try {
2335
- const api = await this.connect();
2336
- return await api.wait(this.agent, origin, Math.max(0, until - Date.now()), signal);
2337
- } catch (error) {
2338
- if (signal?.aborted) return { job: null };
2339
- if (!isConnectionError(error) || Date.now() >= until) throw error;
2340
- this.reset();
2341
- }
2342
- }
2343
- }
2344
- done(jobId, notes, question, props, extra) {
2345
- return this.call((api) => api.done(this.agent, jobId, notes, question, props, extra));
2346
- }
2347
- /** A job as the hub has it now (null: it doesn't know it). */
2348
- job(jobId) {
2349
- return this.call((api) => api.job(this.agent, jobId));
2350
- }
2351
- /** Pilot's width check of a task's element, measured by the page (null: no page answered). */
2352
- check(jobId, timeoutMs = CHECK_TIMEOUT) {
2353
- return this.call((api) => api.check(this.agent, jobId, timeoutMs));
2354
- }
2355
- async close() {
2356
- if (this.heartbeat) clearInterval(this.heartbeat);
2357
- try {
2358
- await this.api?.leave(this.agent);
2359
- } catch {
2360
- }
2361
- await this.server?.close();
2362
- this.server = null;
2363
- this.api = null;
2364
- }
2365
- /** Runs `fn` against the hub, reconnecting (or taking over) once if it went away. */
2366
- async call(fn) {
2367
- try {
2368
- return await fn(await this.connect());
2369
- } catch (error) {
2370
- if (!isConnectionError(error)) throw error;
2371
- this.reset();
2372
- return fn(await this.connect());
2373
- }
2374
- }
2375
- connect() {
2376
- if (this.api) return Promise.resolve(this.api);
2377
- this.connecting ??= this.elect().finally(() => {
2378
- this.connecting = null;
2379
- });
2380
- return this.connecting;
2381
- }
2382
- /** Runs the hub here, or joins the one already on the port. */
2383
- async elect() {
2384
- for (let attempt = 0; attempt < 5; attempt++) {
2385
- try {
2386
- this.server = await startHub(this.port);
2387
- this.api = new LocalApi(this.server.hub);
2388
- } catch (error) {
2389
- if (error.code !== "EADDRINUSE") throw error;
2390
- const health = await checkHealth(this.port);
2391
- if (!health) {
2392
- await new Promise((r) => setTimeout(r, 200));
2393
- continue;
2394
- }
2395
- if (!health.pilot) throw new Error(`Port ${this.port} is used by another program. Set PILOT_PORT to use another port.`);
2396
- if (health.version !== BRIDGE_VERSION) {
2397
- throw new Error(
2398
- `Another Pilot version (bridge ${health.version}) runs on port ${this.port}. Each version has its own port, so this one was set by hand (PILOT_PORT): unset it, or use the same Pilot version everywhere.`
2399
- );
2400
- }
2401
- this.api = new RemoteApi(this.port);
2402
- }
2403
- if (this.origin) await this.api.register(this.agent, this.origin);
2404
- return this.api;
2405
- }
2406
- throw new Error(`Pilot bridge: couldn't start or reach the hub on port ${this.port}.`);
2407
- }
2408
- reset() {
2409
- this.api = null;
2410
- }
2411
- startHeartbeat() {
2412
- if (this.heartbeat) return;
2413
- this.heartbeat = setInterval(() => {
2414
- if (!this.origin || this.server) return;
2415
- this.call((api) => api.register(this.agent, this.origin)).catch(() => {
2416
- });
2417
- }, HEARTBEAT);
2418
- this.heartbeat.unref();
2419
- }
2420
- };
2421
- async function checkHealth(port) {
2422
- let res;
2423
- try {
2424
- res = await fetch(`http://127.0.0.1:${port}/health`);
2425
- } catch {
2426
- return null;
2427
- }
2428
- try {
2429
- return await res.json();
2430
- } catch {
2431
- return {};
2432
- }
2433
- }
2434
- function isConnectionError(error) {
2435
- const e = error;
2436
- const code = e?.code ?? e?.cause?.code;
2437
- return code === "ECONNREFUSED" || code === "ECONNRESET" || code === "UND_ERR_SOCKET" || /fetch failed|socket hang up|other side closed/i.test(e?.message ?? "");
2438
- }
2439
-
2440
- // src/locate.ts
2441
- import { existsSync as existsSync6, readdirSync as readdirSync5, readFileSync as readFileSync7, statSync as statSync5 } from "fs";
2442
- import { basename as basename5, extname as extname3, isAbsolute, join as join9, relative as relative4 } from "path";
2443
- var SKIP2 = /* @__PURE__ */ new Set([
2444
- "node_modules",
2445
- "dist",
2446
- "build",
2447
- "out",
2448
- "coverage",
2449
- "vendor",
2450
- ".git",
2451
- ".next",
2452
- ".nuxt",
2453
- ".svelte-kit",
2454
- ".output",
2455
- ".vercel",
2456
- ".turbo",
2457
- ".cache"
2458
- ]);
2459
- var EXTENSIONS2 = /* @__PURE__ */ new Set([
2460
- ".html",
2461
- ".htm",
2462
- ".jsx",
2463
- ".tsx",
2464
- ".js",
2465
- ".ts",
2466
- ".mjs",
2467
- ".vue",
2468
- ".svelte",
2469
- ".astro",
2470
- ".mdx",
2471
- ".php",
2472
- ".erb",
2473
- ".hbs",
2474
- ".njk",
2475
- ".liquid",
2476
- ".twig"
2477
- ]);
2478
- var MAX_FILES3 = 4e3;
2479
- var MAX_FILE_BYTES3 = 512e3;
2480
- var BUDGET_MS3 = 800;
2481
- var cache3 = null;
2482
- function sourceFiles(root) {
2483
- if (cache3 && cache3.root === root && Date.now() - cache3.at < 3e4) return cache3.files;
2484
- const files = [];
2485
- const walk = (dir) => {
2486
- let names;
2487
- try {
2488
- names = readdirSync5(dir);
2489
- } catch {
2490
- return;
2491
- }
2492
- for (const name of names) {
2493
- if (files.length >= MAX_FILES3) return;
2494
- if (SKIP2.has(name) || name.startsWith(".") && name !== ".") continue;
2495
- const path = join9(dir, name);
2496
- let stat2;
2497
- try {
2498
- stat2 = statSync5(path);
2499
- } catch {
2500
- continue;
2501
- }
2502
- if (stat2.isDirectory()) walk(path);
2503
- else if (EXTENSIONS2.has(extname3(name)) && stat2.size <= MAX_FILE_BYTES3) files.push(path);
2504
- }
2505
- };
2506
- walk(root);
2507
- cache3 = { root, at: Date.now(), files };
2508
- return files;
2509
- }
2510
- function searchable(cwd) {
2511
- return existsSync6(join9(cwd, "package.json")) || existsSync6(join9(cwd, ".git"));
2512
- }
2513
- var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2514
- function needles(target) {
2515
- const text = target.text?.replace(/…$/, "").trim();
2516
- const words = text?.split(/\s+/) ?? [];
2517
- return {
2518
- id: target.id ? new RegExp(`\\bid\\s*=\\s*[{"']*${escape(target.id)}["'}]`) : null,
2519
- // The whole text when it's short; else its first words (the rest may be split across lines or tags).
2520
- text: text && text.length >= 3 && text.length <= 60 ? text : null,
2521
- lead: words.length >= 3 ? words.slice(0, 3).join(" ") : null,
2522
- classes: target.classes.filter((c) => c.length >= 2).map((c) => new RegExp(`(^|[\\s"'\`{])${escape(c)}($|[\\s"'\`}])`)),
2523
- tag: new RegExp(`<${escape(target.tag)}[\\s>/]`, "i")
2524
- };
2525
- }
2526
- function locate(target, root, deadline = Date.now() + BUDGET_MS3) {
2527
- const n = needles(target);
2528
- const known = target.source?.file && target.source.line ? sourcePath(target.source.file, root) : null;
2529
- if (known && target.source?.line) {
2530
- try {
2531
- const lines = readFileSync7(join9(root, known), "utf8").split("\n");
2532
- const from = target.source.line - 1;
2533
- const own = bestLine(n, lines, from);
2534
- const index = own && own.score >= 2 ? own.index : from;
2535
- return { file: known, line: index + 1, snippet: snippetAt(lines, index) };
2536
- } catch {
2537
- }
2538
- }
2539
- if (!n.id && !n.text && !n.lead && n.classes.length < 3) return null;
2540
- let best = null;
2541
- for (const file of sourceFiles(root)) {
2542
- if (Date.now() > deadline) break;
2543
- let content;
2544
- try {
2545
- content = readFileSync7(file, "utf8");
2546
- } catch {
2547
- continue;
2548
- }
2549
- if (!(n.id && content.includes(target.id)) && !(n.text && content.includes(n.text)) && !(n.lead && content.includes(n.lead))) {
2550
- if (n.classes.length < 3) continue;
2551
- }
2552
- const lines = content.split("\n");
2553
- const found = bestLine(n, lines);
2554
- if (found && (!best || found.score > best.score)) best = { file, line: found.index, score: found.score, lines };
2555
- }
2556
- const enough = best && (best.score >= 6 || n.classes.length >= 3 && best.score >= n.classes.length + 2);
2557
- if (!best || !enough) return null;
2558
- return { file: relative4(root, best.file), line: best.line + 1, snippet: snippetAt(best.lines, best.line) };
2559
- }
2560
- function bestLine(n, lines, from = 0) {
2561
- const classesOn = (i) => lines[i] === void 0 ? 0 : n.classes.filter((re) => re.test(lines[i])).length;
2562
- let best = null;
2563
- for (let i = from; i < lines.length; i++) {
2564
- const line = lines[i];
2565
- let score = 0;
2566
- if (n.id?.test(line)) score += 8;
2567
- if (n.text && line.includes(n.text)) score += 6;
2568
- else if (n.lead && line.includes(n.lead)) score += 4;
2569
- let classes = 0;
2570
- for (let j = Math.max(from, i - 3); j <= i; j++) classes = Math.max(classes, classesOn(j));
2571
- score += classes;
2572
- if (n.classes.length && classes === n.classes.length) score += 2;
2573
- if (n.tag.test(line)) score += 1;
2574
- if (!best || score > best.score) best = { index: i, score };
2575
- }
2576
- return best;
2577
- }
2578
- function snippetAt(lines, index) {
2579
- return lines.slice(Math.max(0, index - 2), index + 3).map((l) => l.length > 160 ? `${l.slice(0, 159)}\u2026` : l).join("\n");
2580
- }
2581
- function sourcePath(file, root) {
2582
- const rel = isAbsolute(file) ? relative4(root, file) : file.replace(/^\.\//, "");
2583
- if (rel.startsWith("..") || isAbsolute(rel)) return null;
2584
- return existsSync6(join9(root, rel)) ? rel : null;
2585
- }
2586
- function componentFile(name, root, deadline = Date.now() + BUDGET_MS3, within) {
2587
- if (!/^[A-Za-z_$][\w$]*$/.test(name)) return null;
2588
- const declaration = new RegExp(
2589
- `^\\s*(export\\s+(?:default\\s+)?)?(?:(?:async\\s+)?function\\s*\\*?\\s+${name}\\b|class\\s+${name}\\b|(?:const|let|var)\\s+${name}\\s*[:=])`
2590
- );
2591
- let best = null;
2592
- const files = within ? [join9(root, within)] : sourceFiles(root);
2593
- for (const file of files) {
2594
- if (Date.now() > deadline) break;
2595
- if (!/\.[jt]sx?$|\.mjs$/.test(file)) continue;
2596
- let content;
2597
- try {
2598
- content = readFileSync7(file, "utf8");
2599
- } catch {
2600
- continue;
2601
- }
2602
- if (!content.includes(name)) continue;
2603
- const lines = content.split("\n");
2604
- for (let i = 0; i < lines.length; i++) {
2605
- const m = declaration.exec(lines[i]);
2606
- if (!m) continue;
2607
- const score = (basename5(file).replace(/\.[^.]+$/, "") === name ? 2 : 0) + (m[1] ? 1 : 0);
2608
- if (!best || score > best.score) best = { file, line: i + 1, score };
2609
- break;
2610
- }
2611
- }
2612
- return best ? { file: relative4(root, best.file), line: best.line } : null;
2613
- }
2614
- function withComponentFiles(job, root) {
2615
- if (!searchable(root)) return job;
2616
- const deadline = Date.now() + BUDGET_MS3;
2617
- const fill = (target) => {
2618
- const source = target.source;
2619
- if (!source?.component || source.line) return target;
2620
- const known = source.file ? sourcePath(source.file, root) : null;
2621
- if (source.file && !known) return target;
2622
- const found = componentFile(source.component, root, deadline, known ?? void 0);
2623
- return found ? { ...target, source: { ...source, file: found.file, line: found.line } } : target;
2624
- };
2625
- const workspace = workspaceRoot(root);
2626
- const declared = (name) => {
2627
- const found = componentFile(name, workspace, deadline);
2628
- return found ? { file: relative4(root, join9(workspace, found.file)), line: found.line } : null;
2629
- };
2630
- const local = (file) => {
2631
- const path = join9(workspace, file);
2632
- return existsSync6(path) ? relative4(root, path) : file;
2633
- };
2634
- const mention = (r) => {
2635
- if (r.kind === "token") return r.source ? { ...r, source: { ...r.source, file: local(r.source.file) } } : r;
2636
- if (r.kind === "element") return { ...r, target: fill(r.target) };
2637
- if (r.kind === "unlisted") {
2638
- const source2 = declared(r.name);
2639
- return source2 ? { kind: "component", name: r.name, source: source2 } : r;
2640
- }
2641
- if (r.kind !== "component") return r;
2642
- if (r.source) {
2643
- const path = join9(workspace, r.source.file);
2644
- return existsSync6(path) ? { ...r, source: { ...r.source, file: relative4(root, path) } } : r;
2645
- }
2646
- if (r.target?.source?.file) return { ...r, target: fill(r.target) };
2647
- const source = declared(r.name);
2648
- return source ? { ...r, source } : r;
2649
- };
2650
- const mentions = (refs) => refs?.length ? { references: refs.map(mention) } : {};
2651
- const { changeSet } = job;
2652
- const request = changeSet.request;
2653
- return {
2654
- ...job,
2655
- changeSet: {
2656
- ...changeSet,
2657
- edits: changeSet.edits.map((e) => ({ ...e, target: fill(e.target) })),
2658
- ...changeSet.fileTokens ? { fileTokens: changeSet.fileTokens.map((t) => ({ ...t, file: local(t.file) })) } : {},
2659
- ...request ? {
2660
- request: {
2661
- ...request,
2662
- target: fill(request.target),
2663
- ...request.others ? { others: request.others.map(fill) } : {},
2664
- ...request.kind === "comment" ? { thread: request.thread.map((m) => ({ ...m, ...mentions(m.references) })) } : mentions(request.references)
2665
- }
2666
- } : {}
2667
- }
2668
- };
2669
- }
2670
- function whereSection(job, root) {
2671
- if (!searchable(root)) return "";
2672
- const targets = job.changeSet.request ? requestTargets(job.changeSet.request) : job.changeSet.edits.map((e) => e.target);
2673
- const deadline = Date.now() + BUDGET_MS3;
2674
- const found = [];
2675
- for (const target of targets) {
2676
- const at = locate(target, root, deadline);
2677
- if (!at) continue;
2678
- const lang = extname3(at.file).slice(1) || "text";
2679
- found.push(
2680
- `- \`${target.path}\` \u2192 \`${at.file}:${at.line}\`:`,
2681
- "",
2682
- ` \`\`\`${lang}`,
2683
- ...at.snippet.split("\n").map((l) => ` ${l}`),
2684
- " ```"
2685
- );
2686
- }
2687
- if (!found.length) return "";
2688
- return [
2689
- "## Where the code probably is",
2690
- "",
2691
- "Pilot searched the project for these elements (by component, id, text and classes). Start there; if it isn't the right place (the text comes from a prop, a translation, a CMS), search as usual.",
2692
- "",
2693
- ...found
2694
- ].join("\n");
2695
- }
2696
-
2697
- // src/prompt.ts
2698
- function jobPrompt(job, where = "") {
2699
- const body2 = job.attempt === 2 && job.issues?.length ? taskFollowUp(job) : job.attempt === 2 && job.differences?.length ? followUp(job) : job.answer && job.question ? answered(job) : formatPrompt(job.changeSet);
2700
- return `${body2}${where ? `
2701
- ${where}
2702
- ` : ""}
2703
- ---
2704
- ${runFooter(job)}
2705
- `;
2706
- }
2707
- function runFooter(job) {
2708
- const props = job.changeSet.request?.kind === "props";
2709
- return [
2710
- skillOf(job) ? `When you're done, reply with your notes for the designer: ${notesFor(job)}. Pilot shows them to the designer in the element's thread.` : `When you're done, reply with your notes for the designer: ${notesFor(job)}. Concise, no headings ("Done." when there's nothing to add): Pilot shows them to the designer in a small box, and checks the page itself, so don't open a browser, start a dev server, or run builds or tests.`,
2711
- "",
2712
- props ? "Put the props in a block at the very end of your reply, after your notes, as JSON:" : "If you ask the designer a question (only where this job says to), put it in a block at the very end of your reply, after your notes, as JSON:",
2713
- "",
2714
- "```pilot",
2715
- props ? `{"props": [{"name": "tone", "type": "options", "options": ["light", "dark"], "default": "light", "description": "a few words, when the name doesn't say"}]}` : '{"question": {"text": "One short sentence?", "choices": ["Your suggestion", "Another"]}}',
2716
- "```",
2717
- ...props ? ["", "`type` is one of `options`, `boolean`, `text`, `number`; `options` only for `options`."] : []
2718
- ].join("\n");
2719
- }
2720
- function answered(job) {
2721
- const meaning = job.answer ? sharedChoiceMeaning(job.answer) : null;
2722
- return [
2723
- "# Pilot: the designer answered your question",
2724
- "",
2725
- `You did this job and asked the designer: ${job.question?.text}`,
2726
- "",
2727
- "Their answer:",
2728
- "",
2729
- job.answer?.trim().split("\n").map((l) => `> ${l}`).join("\n"),
2730
- "",
2731
- ...meaning ? [`What that means for the code: ${meaning}`, ""] : [],
2732
- "Do what's left of the job the way they answered, then reply with your notes. Pilot then checks it like any job. (Don't ask again: say anything still open in your notes.)",
2733
- "",
2734
- "The job, for reference:",
2735
- "",
2736
- formatPrompt(job.changeSet)
2737
- ].join("\n");
2738
- }
2739
- function followUp(job) {
2740
- const lines = [
2741
- "# Pilot design edits: follow-up",
2742
- "",
2743
- "You applied this job, but Pilot checked the page and these changes don't give the designer's value yet (the values are what the browser computes for the element):",
2744
- ""
2745
- ];
2746
- for (const d of job.differences ?? []) {
2747
- const edit = job.changeSet.edits.find((e) => e.target.selector === d.selector);
2748
- const where = edit ? `\`${edit.target.path}\` (selector \`${d.selector}\`${edit.target.text ? `, text "${edit.target.text}"` : ""})` : `\`${d.selector}\``;
2749
- lines.push(`- ${where}: \`${d.property}\` should be \`${d.expected}\`, the page gives \`${d.actual ?? "?"}\`.`);
2750
- }
2751
- lines.push(
2752
- "",
2753
- "Fix them: the usual causes are a rule that overrides yours (more specific, later, or in a media query), an edit in the wrong file or component, or a missed change. If you chose a different value on purpose (a token or the nearest step in the project's scale), keep it and say so in your notes. Pilot takes what the code gives after this."
2754
- );
2755
- return lines.join("\n");
2756
- }
2757
- function notesFor(job) {
2758
- switch (job.changeSet.request?.kind) {
2759
- case "comment":
2760
- return skillOf(job) ? "your reply in the designer's comment thread, as the skill you used says to report (as long as it needs to be; Markdown shows)" : "your reply in the designer's comment thread, a small chat box: concise, like a chat message, a few short sentences at most, with what you changed or your answer";
2761
- case "responsive":
2762
- return "what changed at which widths, anything left for the designer";
2763
- case "break-and-fix":
2764
- return "what broke and how you fixed it, anything for the designer to decide";
2765
- case "props":
2766
- return "one short sentence for the designer, like a chat message; the props go in `props`";
2767
- default:
2768
- return "values you approximated, anything you did differently";
2769
- }
2770
- }
2771
- function taskFollowUp(job) {
2772
- const request = job.changeSet.request;
2773
- const target = `\`${request?.target.path ?? "the element"}\``;
2774
- if (request?.kind === "comment")
2775
- return [
2776
- "# Pilot: props, follow-up",
2777
- "",
2778
- `You set the props the designer picked on ${target}, but Pilot read the instance on the page after hot reload, and these aren't what they picked yet:`,
2779
- "",
2780
- ...(job.issues ?? []).map((i) => `- ${i}`),
2781
- "",
2782
- "Fix them where this instance is written: the usual causes are another instance's line, a value the parent passes from a variable or data, or a default the prop falls back to. If one can't be set there, say why in your notes. Pilot takes what the code gives after this.",
2783
- "",
2784
- "The comment, for reference:",
2785
- "",
2786
- formatPrompt(job.changeSet)
2787
- ].join("\n");
2788
- const breakFix = request?.kind === "break-and-fix";
2789
- const lines = [
2790
- breakFix ? "# Pilot: break and fix, follow-up" : "# Pilot: make responsive, follow-up",
2791
- "",
2792
- breakFix ? `You stress-tested ${target} and reported it done, but Pilot's width check (the page with its usual content, measured at each width) finds these problems. If one comes from test content still in the code, remove it:` : `You made ${target} responsive, but Pilot's width check (the page measured at each width) still finds these problems:`,
2793
- "",
2794
- ...(job.issues ?? []).map((i) => `- ${i}`),
2795
- "",
2796
- "Fix them from the code (no browser). If one is deliberate, keep it and say why in your notes. Pilot takes what the code gives after this.",
2797
- "",
2798
- "The task, for reference:",
2799
- "",
2800
- formatPrompt(job.changeSet)
2801
- ];
2802
- return lines.join("\n");
2803
- }
2804
- function skillOf(job) {
2805
- const request = job.changeSet.request;
2806
- if (request?.kind !== "comment" || job.attempt === 2 || job.answer) return void 0;
2807
- const skill = request.thread.at(-1)?.skill;
2808
- return skill && SKILL_NAME.test(skill) ? skill : void 0;
2809
- }
2810
-
2811
- // src/run.ts
2812
- var SLOTS = 3;
2813
- var CANCEL_POLL_MS = 2e3;
2814
- var RUN_TIMEOUT_MS = 20 * 6e4;
2815
- var WAIT_MS = 10 * 6e4;
2816
- var RunnerError = class extends Error {
2817
- };
2818
- async function startRunner(options) {
2819
- const out = options.out ?? ((line) => process.stdout.write(`${line}
2820
- `));
2821
- const choose2 = options.choose ?? (async () => 0);
2822
- const project = options.cwd;
2823
- if (!searchable(project)) {
2824
- throw new RunnerError(`${project} isn't a project folder (no package.json or .git). Run npx usepilot in your project's folder.`);
2825
- }
2826
- const { cli, bin } = await pickAgent(options, choose2, out);
2827
- const agent = { id: randomUUID2(), label: `${cli.label} \xB7 ${basename6(project)}`, folder: project, kind: cli.kind };
2828
- const bridge = new Bridge(agent, options.port ?? (Number(process.env.PILOT_PORT) || DEFAULT_BRIDGE_PORT));
2829
- const origin = await pickSite(bridge, options, out);
2830
- await bridge.launch(origin);
2831
- out(`Pilot is on ${origin}, every page, with ${cli.label}. Send from the toolbar; jobs show here. Ctrl+C stops.`);
2832
- const stop = new AbortController();
2833
- const runs = /* @__PURE__ */ new Set();
2834
- const slots = options.slots ?? SLOTS;
2835
- for (let i = 0; i < slots; i++) {
2836
- const loop = (async () => {
2837
- while (!stop.signal.aborted) {
2838
- let job = null;
2839
- try {
2840
- ({ job } = await bridge.wait(origin, WAIT_MS, stop.signal));
2841
- } catch (error) {
2842
- if (stop.signal.aborted) break;
2843
- out(`The hub is unreachable (${error.message}); trying again.`);
2844
- await sleep(2e3, stop.signal);
2845
- continue;
2846
- }
2847
- if (job && !stop.signal.aborted) await runJob(job, { bridge, cli, bin, project, out, signal: stop.signal });
2848
- }
2849
- })();
2850
- runs.add(loop);
2851
- }
2852
- return {
2853
- origin,
2854
- agent: cli,
2855
- async close() {
2856
- stop.abort();
2857
- await Promise.allSettled(runs);
2858
- await bridge.close();
2859
- }
2860
- };
2861
- }
2862
- async function pickAgent(options, choose2, out) {
2863
- const wanted = options.agent ?? savedAgent(options.cwd, options.configFile);
2864
- if (wanted && options.bin) return { cli: AGENTS[wanted], bin: options.bin };
2865
- const found = await (options.detect ?? detectAgents)();
2866
- if (wanted) {
2867
- const cli = AGENTS[wanted];
2868
- const it = found.find((a) => a.kind === wanted);
2869
- if (!it) throw new RunnerError(`${cli.label}'s command-line tool isn't installed. Install it (${cli.install}), sign in (${cli.signIn}), then run npx usepilot again.`);
2870
- if (!it.signedIn) throw new RunnerError(`${cli.label} isn't signed in. Run ${cli.signIn}, then npx usepilot again.`);
2871
- if (options.agent) saveAgent(options.cwd, wanted, options.configFile);
2872
- return { cli, bin: it.bin };
2873
- }
2874
- const ready = found.filter((a) => a.signedIn);
2875
- if (!ready.length) {
2876
- const installed = found.map((a) => `${AGENTS[a.kind].label} isn't signed in: run ${AGENTS[a.kind].signIn}.`);
2877
- throw new RunnerError(
2878
- [
2879
- "Pilot runs your coding agent's command-line tool, and none is ready here.",
2880
- ...installed.length ? installed : Object.values(AGENTS).map((cli) => `- ${cli.label}: ${cli.install}, then ${cli.signIn}`),
2881
- "Then run npx usepilot again."
2882
- ].join("\n")
2883
- );
2884
- }
2885
- const index = ready.length > 1 ? await choose2("Which agent should Pilot run for this project?", ready.map((a) => AGENTS[a.kind].label)) : 0;
2886
- const picked = ready[index] ?? ready[0];
2887
- saveAgent(options.cwd, picked.kind, options.configFile);
2888
- if (ready.length > 1) out(`${AGENTS[picked.kind].label} it is, for this project (npx usepilot --agent <name> changes it).`);
2889
- return { cli: AGENTS[picked.kind], bin: options.bin ?? picked.bin };
2890
- }
2891
- async function pickSite(bridge, options, out) {
2892
- if (options.url) {
2893
- const origin = originOf(options.url);
2894
- if (!origin) throw new RunnerError(`"${options.url}" isn't a page address. Pass your dev server's, e.g. http://localhost:5173.`);
2895
- return originKey(origin);
2896
- }
2897
- const name = projectName(options.cwd);
2898
- const told = /* @__PURE__ */ new Set();
2899
- const say = (key, line) => {
2900
- if (told.has(key)) return;
2901
- told.add(key);
2902
- out(line);
2903
- };
2904
- for (; ; ) {
2905
- const local = (await bridge.pages()).filter((p) => {
2906
- try {
2907
- return isLocalHost(new URL(p.origin).hostname);
2908
- } catch {
2909
- return false;
2910
- }
2911
- });
2912
- const mine = local.find((p) => p.project === name);
2913
- if (mine) return mine.origin;
2914
- for (const page of local) {
2915
- if (page.project)
2916
- say(`${page.origin} ${page.project}`, `Pilot is open on ${page.origin} for ${page.project}, not ${name}: run npx usepilot in that project's folder for it.`);
2917
- else
2918
- say(
2919
- page.origin,
2920
- `Pilot is open on ${page.origin}, but its loader doesn't say which project it is (set up before 0.15). If it's this one, ask your agent to run npx usepilot@latest update here, or start with npx usepilot --url ${page.origin}.`
2921
- );
2922
- }
2923
- say("none", `Waiting for a page of ${name}: open your app in the browser (with its dev server running).`);
2924
- await sleep(1e3);
2925
- }
2926
- }
2927
- async function runJob(job, ctx) {
2928
- const { bridge, cli, out } = ctx;
2929
- const started = Date.now();
2930
- out(`\u25B8 ${describeJob(job)}`);
2931
- const stop = new AbortController();
2932
- const onStop = () => stop.abort();
2933
- ctx.signal.addEventListener("abort", onStop, { once: true });
2934
- const watch = setInterval(() => {
2935
- bridge.job(job.id).then((j) => {
2936
- if (j?.status === "cancelled") stop.abort();
2937
- }).catch(() => {
2938
- });
2939
- }, CANCEL_POLL_MS);
2940
- try {
2941
- const prompt = await promptFor(job, ctx.project, cli);
2942
- const resume = sessionToResume(job, cli.kind);
2943
- const images = newAttachments(job).map((f) => f.path).filter((p) => /\.(png|jpe?g|gif|webp)$/i.test(p));
2944
- let result = await runAgent(ctx, prompt, { resume, images, signal: stop.signal });
2945
- if (!stop.signal.aborted && !result.reply && !signInProblem(result.error)) {
2946
- result = await runAgent(ctx, prompt, { images, signal: stop.signal });
2947
- }
2948
- if (stop.signal.aborted) {
2949
- out(`\u25A0 Stopped: ${describeJob(job)}`);
2950
- return;
2951
- }
2952
- const seconds = Math.round((Date.now() - started) / 1e3);
2953
- if (!result.reply) {
2954
- const error = errorFor(cli, result.error);
2955
- await bridge.done(job.id, void 0, void 0, void 0, { error });
2956
- out(`\u2717 ${error.title}. ${error.detail}${result.error && !signInProblem(result.error) ? `
2957
- ${result.error.split("\n")[0]}` : ""}`);
2958
- return;
2959
- }
2960
- const reply = replyOf(result.reply);
2961
- const session = result.session ? { agent: cli.kind, id: result.session } : void 0;
2962
- await bridge.done(job.id, reply.notes, reply.question, reply.props, { session });
2963
- out(`\u2713 ${seconds}s \xB7 ${firstLine(reply.notes) || "Done."}`);
2964
- } catch (error) {
2965
- if (!stop.signal.aborted) {
2966
- const jobError = { title: `Pilot couldn't run ${cli.label}`, detail: error.message };
2967
- await bridge.done(job.id, void 0, void 0, void 0, { error: jobError }).catch(() => {
2968
- });
2969
- out(`\u2717 ${jobError.title}: ${jobError.detail}`);
2970
- }
2971
- } finally {
2972
- clearInterval(watch);
2973
- ctx.signal.removeEventListener("abort", onStop);
2974
- }
2975
- }
2976
- async function runAgent(ctx, prompt, options) {
2977
- const { cli } = ctx;
2978
- if (!existsSync7(ctx.bin)) return { error: `${cli.label}'s command-line tool isn't installed any more.` };
2979
- const run2 = await exec(ctx.bin, cli.args({ resume: options.resume, readDirs: [attachmentsDir()], images: options.images }), {
2980
- cwd: ctx.project,
2981
- input: prompt,
2982
- signal: options.signal,
2983
- timeoutMs: RUN_TIMEOUT_MS
2984
- });
2985
- const parsed = cli.parse(run2.stdout);
2986
- if (!parsed.reply && !parsed.error) parsed.error = run2.stderr.trim().split("\n").slice(-3).join("\n") || `exit code ${run2.code}`;
2987
- if (!parsed.reply && run2.stderr && !parsed.error?.includes(run2.stderr.trim().slice(0, 40))) parsed.error = `${parsed.error}
2988
- ${run2.stderr.trim().slice(-500)}`;
2989
- return parsed;
2990
- }
2991
- async function promptFor(job, project, cli) {
2992
- const j = withComponentFiles(job, project);
2993
- const where = j.attempt === 2 ? "" : whereSection(j, project);
2994
- const texts = (await attachmentBlocks(j)).flatMap((b) => b.type === "text" ? [b.text] : []);
2995
- const skill = skillOf(j);
2996
- return [...skill ? [cli.invokeSkill(skill)] : [], jobPrompt(j, where), ...texts].join("\n\n");
2997
- }
2998
- function sessionToResume(job, agent) {
2999
- const request = job.changeSet.request;
3000
- const own = sessionOf(job.session);
3001
- const thread = request?.kind === "comment" ? sessionOf(request.session) : void 0;
3002
- const session = (job.attempt === 2 || job.answer ? own : void 0) ?? thread ?? own;
3003
- return session?.agent === agent ? session.id : void 0;
3004
- }
3005
- function replyOf(reply) {
3006
- const blocks = [...reply.matchAll(/```pilot\s*\n([\s\S]*?)```/g)];
3007
- const last = blocks.at(-1);
3008
- let notes = reply;
3009
- let data = {};
3010
- if (last) {
3011
- notes = reply.replace(last[0], "");
3012
- try {
3013
- data = JSON.parse(last[1] ?? "");
3014
- } catch {
3015
- }
3016
- }
3017
- notes = notes.trim();
3018
- return { notes: notes || void 0, question: questionOf(data.question), props: propsOf(data.props) };
3019
- }
3020
- function signInProblem(error) {
3021
- return !!error && /not (logged|signed) in|log ?in required|please (run )?\/?login|authenticat|unauthori[sz]ed|\b401\b|api key/i.test(error);
3022
- }
3023
- function errorFor(cli, error) {
3024
- if (signInProblem(error)) return { title: `${cli.label} isn't signed in`, detail: `Run ${cli.signIn} in a terminal, then send again.` };
3025
- return {
3026
- title: `${cli.label} couldn't do this job`,
3027
- detail: `${(error ?? "It stopped without a reply.").split("\n")[0]?.slice(0, 300)} The terminal running npx usepilot has the details. Send again to retry.`
3028
- };
3029
- }
3030
- function describeJob(job) {
3031
- const request = job.changeSet.request;
3032
- const follow = job.attempt === 2 ? "follow-up: " : job.answer ? "answer: " : "";
3033
- if (request?.kind === "comment") {
3034
- const latest = request.thread.at(-1)?.text.trim().replace(/\s+/g, " ") ?? "";
3035
- return `${follow}comment on ${nameOf(request.target)}: "${latest.length > 60 ? `${latest.slice(0, 60)}\u2026` : latest}"`;
3036
- }
3037
- if (request) return `${follow}${request.kind} on ${requestTargets(request).map(nameOf).join(", ")}`;
3038
- const changes = job.changeSet.edits.reduce((n, e) => n + e.changes.length + (e.texts?.length ?? 0), 0);
3039
- return `${follow}${changes} change${changes === 1 ? "" : "s"} on ${job.changeSet.edits.map((e) => nameOf(e.target)).join(", ")}`;
3040
- }
3041
- function firstLine(text) {
3042
- const line = text?.trim().split("\n")[0]?.trim() ?? "";
3043
- return line.length > 160 ? `${line.slice(0, 160)}\u2026` : line;
3044
- }
3045
- function nameOf(target) {
3046
- return target.text ? `${target.tag} "${target.text.length > 30 ? `${target.text.slice(0, 30)}\u2026` : target.text}"` : target.tag;
3047
- }
3048
- function sleep(ms, signal) {
3049
- return new Promise((resolve3) => {
3050
- const timer = setTimeout(resolve3, ms);
3051
- signal?.addEventListener(
3052
- "abort",
3053
- () => {
3054
- clearTimeout(timer);
3055
- resolve3();
3056
- },
3057
- { once: true }
3058
- );
3059
- });
3060
- }
3061
-
3062
- // src/update.ts
3063
- import { spawnSync as spawnSync2 } from "child_process";
3064
- import { existsSync as existsSync8, readFileSync as readFileSync8 } from "fs";
3065
- import { homedir as homedir5 } from "os";
3066
- import { dirname as dirname7, join as join10 } from "path";
3067
- async function update(options = {}) {
3068
- const cwd = options.cwd ?? process.cwd();
3069
- const run2 = options.run ?? runCommand2;
3070
- const home = options.home ?? homedir5();
3071
- const pkg = readJson3(join10(cwd, "package.json"));
3072
- const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
3073
- if (!pkg || !deps.usepilot) {
3074
- return `# Pilot isn't installed here
3075
-
3076
- Run this in your app's folder, the one where Pilot was set up. To set Pilot up in this one, run \`npx usepilot@latest init\` instead.
3077
- `;
3078
- }
3079
- const root = projectRoot(cwd);
3080
- const before = installedVersion(cwd, root);
3081
- const oldBridge = bridgeOf(cwd, root);
3082
- const pm = packageManager(cwd, root);
3083
- const args = installArgs(pm, "usepilot@latest");
3084
- const installed = run2(pm, args, cwd);
3085
- const after = installed ? installedVersion(cwd, root) ?? VERSION : before;
3086
- const removed = installed ? await removeOldSetup(root, home, options.platform ?? process.platform, run2) : [];
3087
- if (!installed) {
3088
- return `# Pilot: not updated
3089
-
3090
- Installing the latest Pilot didn't work (the output is above). Run this in ${cwd}, then \`npx usepilot@latest update\` again:
3091
-
3092
- \`\`\`
3093
- ${pm} ${args.join(" ")}
3094
- \`\`\`
3095
- `;
3096
- }
3097
- const loader = detectFramework(cwd, deps).loads;
3098
- const unnamed = loader ? !!namingStep(loader, cwd) : oldBridge !== null && oldBridge < 8;
3099
- const bumped = !!before && !!after && olderThan(before, after);
3100
- const changed = bumped || removed.length > 0 || unnamed;
3101
- const steps = [
3102
- ...unnamed ? ["Ask your agent to run `npx usepilot@latest init` in the app's folder: it names this project in Pilot's loader, so `npx usepilot` knows the app's pages are this project's (new in 0.15)."] : [],
3103
- "Restart your app's dev server, so the page loads the new Pilot.",
3104
- "Restart `npx usepilot` in the app's folder (Ctrl+C, then run it again), so Pilot runs the new version."
3105
- ];
3106
- if (oldBridge !== null && oldBridge !== BRIDGE_VERSION) {
3107
- steps.push(
3108
- "Update Pilot in your other projects too (`npx usepilot@latest update` in each): this version can't share its connection with older ones."
3109
- );
3110
- }
3111
- const headline = bumped ? `# Pilot updated: ${before} \u2192 ${after}` : `# Pilot is up to date (${after ?? VERSION})`;
3112
- const removedLine = removed.length ? `
3113
- Pilot's old chat setup is removed (${removed.map((r) => `\`${r}\``).join(", ")}): Pilot runs your agent itself now. Run \`npx usepilot\` in your app's folder, beside its dev server, instead of \`/pilot\` in a chat.
3114
- ` : "";
3115
- return `${headline}
3116
- ${removedLine}
3117
- ${changed ? `Next:
3118
- ${steps.map((s, i) => `${i + 1}. ${s}`).join("\n")}
3119
- ` : "Nothing else to do.\n"}`;
3120
- }
3121
- function bridgeOf(cwd, root) {
3122
- for (let dir = cwd; ; dir = dirname7(dir)) {
3123
- const file = join10(dir, "node_modules", "usepilot", "cli", "index.js");
3124
- if (existsSync8(file)) {
3125
- const match = /BRIDGE_VERSION = (\d+)/.exec(readFileSync8(file, "utf8"));
3126
- return match ? Number(match[1]) : null;
3127
- }
3128
- if (dir === root || dirname7(dir) === dir) return null;
3129
- }
3130
- }
3131
- function readJson3(file) {
3132
- try {
3133
- return JSON.parse(readFileSync8(file, "utf8"));
3134
- } catch {
3135
- return null;
3136
- }
3137
- }
3138
- function runCommand2(command2, args, cwd) {
3139
- const result = spawnSync2(command2, args, { cwd, stdio: ["ignore", "inherit", "inherit"], shell: process.platform === "win32" });
3140
- return result.status === 0;
651
+ function runCommand2(command2, args, cwd) {
652
+ const result = spawnSync2(command2, args, { cwd, stdio: ["ignore", "inherit", "inherit"], shell: process.platform === "win32" });
653
+ return result.status === 0;
3141
654
  }
3142
655
 
3143
656
  // src/index.ts
@@ -3151,6 +664,10 @@ Usage: npx usepilot [command]
3151
664
  in), and shows the jobs here. Ctrl+C stops it.
3152
665
  --agent <claude|codex|cursor>: which agent (saved for the project)
3153
666
  --url <address>: your app's address, when Pilot can't tell
667
+ dev Start your dev server with Pilot: usepilot dev -- <your dev command>
668
+ (in package.json: "dev": "usepilot dev -- vite"). Pilot starts with it
669
+ and stops with it, so there's no npx usepilot to run. Vite and Next.js
670
+ have their own way (usepilot/vite, usepilot/next): init sets it up.
3154
671
  init Set Pilot up in this project: installs it, checks your agent's
3155
672
  command-line tool, removes Pilot's old chat setup, and prints
3156
673
  what's left (loading Pilot in the app). Ask your agent to run it.
@@ -3159,6 +676,8 @@ Usage: npx usepilot [command]
3159
676
  update Update Pilot in this project to the latest, and remove its old
3160
677
  chat setup. Prints what's left (restart the app and npx usepilot).
3161
678
  Run it in the app's folder.
679
+ guide Print Pilot's guide: how to do each thing in Pilot, for this
680
+ version (also in node_modules/usepilot/GUIDE.md)
3162
681
  help Show this message
3163
682
  `;
3164
683
  var MCP_GONE = `Pilot no longer runs inside your agent's chat: it runs your agent itself.
@@ -3205,6 +724,28 @@ async function run() {
3205
724
  process.on("SIGINT", close);
3206
725
  process.on("SIGTERM", close);
3207
726
  }
727
+ async function dev() {
728
+ const args = process.argv.slice(process.argv.indexOf("dev") + 1);
729
+ const commandLine = args[0] === "--" ? args.slice(1) : args;
730
+ if (!commandLine.length) {
731
+ process.stderr.write('usepilot dev runs your dev server with Pilot: usepilot dev -- <your dev command> (in package.json: "dev": "usepilot dev -- vite").\n');
732
+ process.exitCode = 1;
733
+ return;
734
+ }
735
+ const runner = startWithDevServer({ cwd: process.cwd() });
736
+ const child = commandLine.length === 1 && /\s/.test(commandLine[0]) ? spawn(commandLine[0], { stdio: "inherit", shell: true }) : process.platform === "win32" ? spawn(commandLine.map((a) => /^[\w\-.:\\/=,@]+$/.test(a) ? a : `"${a.replace(/"/g, '""')}"`).join(" "), { stdio: "inherit", shell: true }) : spawn(commandLine[0], commandLine.slice(1), { stdio: "inherit" });
737
+ process.on("SIGINT", () => {
738
+ });
739
+ process.on("SIGTERM", () => child.kill("SIGTERM"));
740
+ child.on("error", (error) => {
741
+ process.stderr.write(`usepilot dev: couldn't start ${commandLine[0]}: ${error.message}
742
+ `);
743
+ });
744
+ child.on("close", async (code, signal) => {
745
+ await runner?.close();
746
+ process.exit(code ?? (signal ? 1 : 0));
747
+ });
748
+ }
3208
749
  switch (command) {
3209
750
  case "run":
3210
751
  try {
@@ -3216,11 +757,17 @@ switch (command) {
3216
757
  process.exitCode = 1;
3217
758
  }
3218
759
  break;
760
+ case "dev":
761
+ await dev();
762
+ break;
3219
763
  case "help":
3220
764
  case "--help":
3221
765
  case "-h":
3222
766
  process.stdout.write(HELP);
3223
767
  break;
768
+ case "guide":
769
+ process.stdout.write(GUIDE_default);
770
+ break;
3224
771
  case "mcp":
3225
772
  process.stderr.write(MCP_GONE);
3226
773
  process.exitCode = 1;