usepilot 0.16.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.
@@ -0,0 +1,4577 @@
1
+ import { createRequire as __pilotRequire } from "node:module"; const require = __pilotRequire(import.meta.url);
2
+
3
+ // src/agents.ts
4
+ import { spawn, spawnSync } from "child_process";
5
+ import { statSync } from "fs";
6
+ import { homedir } from "os";
7
+ import { delimiter, join } from "path";
8
+ var AGENT_KINDS = ["claude", "codex", "cursor"];
9
+ var NOTHING_PRINTED = "The agent printed nothing.";
10
+ function refusedOf(value) {
11
+ if (!Array.isArray(value)) return [];
12
+ return value.flatMap((v) => {
13
+ const r = v;
14
+ const text = (k) => typeof r?.[k] === "string" && r[k].trim() ? r[k].trim().slice(0, 200) : null;
15
+ const mcp = text("mcp");
16
+ const command = text("command");
17
+ const web = text("web");
18
+ const tool = text("tool");
19
+ return mcp ? [{ mcp }] : command ? [{ command }] : web ? [{ web }] : tool ? [{ tool }] : [];
20
+ });
21
+ }
22
+ function denialOf(d) {
23
+ if (typeof d?.tool_name !== "string") return [];
24
+ const input = d.tool_input && typeof d.tool_input === "object" ? d.tool_input : {};
25
+ const mcp = /^mcp__(.+?)__/.exec(d.tool_name);
26
+ if (mcp?.[1]) return [{ mcp: mcp[1] }];
27
+ if (d.tool_name === "Bash" && typeof input.command === "string" && input.command.trim()) return [{ command: input.command.trim() }];
28
+ const host = typeof input.url === "string" ? /^https?:\/\/([^/:]+)/.exec(input.url)?.[1] : void 0;
29
+ if (d.tool_name === "WebFetch" && host) return [{ web: host }];
30
+ return [{ tool: d.tool_name }];
31
+ }
32
+ function parseStream(stdout) {
33
+ let session;
34
+ let reply;
35
+ let error;
36
+ let refused;
37
+ for (const line of stdout.split("\n")) {
38
+ const event = jsonLine(line);
39
+ if (!event) continue;
40
+ if (typeof event.session_id === "string") session = event.session_id;
41
+ if (event.type === "assistant") {
42
+ const text = textOf(event.message);
43
+ if (text.trim()) reply = text.trim();
44
+ }
45
+ if (event.type === "result") {
46
+ if (event.is_error) error = String(event.result ?? event.error ?? "The agent stopped with an error.");
47
+ else if (!reply && typeof event.result === "string" && event.result.trim()) reply = event.result.trim();
48
+ if (Array.isArray(event.permission_denials)) refused = event.permission_denials.flatMap(denialOf);
49
+ }
50
+ }
51
+ if (!session && !reply && !error) error = lastLines(stdout) || NOTHING_PRINTED;
52
+ return { session, reply, error, ...refused?.length ? { refused } : {} };
53
+ }
54
+ function parseCodex(stdout) {
55
+ let session;
56
+ let reply;
57
+ let error;
58
+ for (const line of stdout.split("\n")) {
59
+ const event = jsonLine(line);
60
+ if (!event) continue;
61
+ if (event.type === "thread.started" && typeof event.thread_id === "string") session = event.thread_id;
62
+ const item = event.item;
63
+ if (event.type === "item.completed" && item?.type === "agent_message" && item.text?.trim()) reply = item.text.trim();
64
+ if (event.type === "error" || event.type === "turn.failed") {
65
+ const e = event.error;
66
+ error = String(event.message ?? e?.message ?? "The agent stopped with an error.");
67
+ }
68
+ }
69
+ if (!session && !reply && !error) error = lastLines(stdout) || NOTHING_PRINTED;
70
+ return { session, reply, error };
71
+ }
72
+ function refusedNote(cli, refused) {
73
+ const servers = /* @__PURE__ */ new Set();
74
+ const sites = /* @__PURE__ */ new Set();
75
+ const programs = /* @__PURE__ */ new Set();
76
+ const files = /* @__PURE__ */ new Set();
77
+ for (const r of refused ?? []) {
78
+ if ("mcp" in r) servers.add(r.mcp);
79
+ else if ("web" in r) sites.add(r.web);
80
+ else if ("command" in r) programs.add(program(r.command));
81
+ else files.add(FILE_TOOLS[r.tool] ?? `using ${r.tool}`);
82
+ }
83
+ const allowable = [
84
+ ...[...servers].map((m) => ({ ask: `the ${m} MCP server`, said: `the \`${m}\` MCP server` })),
85
+ ...[...sites].map((w) => ({ ask: `fetching ${w}`, said: `fetching \`${w}\`` }))
86
+ ];
87
+ const said = [...allowable.map((a) => a.said), ...programs.size ? [`running ${list([...programs].map((p) => `\`${p}\``))}`] : [], ...files];
88
+ if (!said.length) return null;
89
+ const head = `**Not allowed in this run** (${cli.label} can't ask you here, as in its chat): ${list(said)}.`;
90
+ if (!allowable.length) return { note: head };
91
+ const them = allowable.length > 1 ? "them" : "it";
92
+ return {
93
+ note: `${head} To allow ${allowable.length > 1 ? "the MCP servers and sites" : servers.size ? "the MCP server" : "the site"}, copy the instructions for ${cli.label}.`,
94
+ allow: `Allow ${list(allowable.map((a) => a.ask))} in this project's ${cli.label} settings (${cli.projectSettings}), so Pilot's runs here can use ${them}.`
95
+ };
96
+ }
97
+ var FILE_TOOLS = {
98
+ Write: "writing files outside the project",
99
+ Edit: "editing files outside the project",
100
+ MultiEdit: "editing files outside the project",
101
+ NotebookEdit: "editing files outside the project",
102
+ Read: "reading files outside the project"
103
+ };
104
+ function list(items) {
105
+ return items.length < 2 ? items[0] ?? "" : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
106
+ }
107
+ function program(command) {
108
+ const words = command.trim().split(/\s+/);
109
+ const first = words.find((w) => !/^[A-Za-z_]\w*=/.test(w)) ?? words[0] ?? command;
110
+ return (first.split("/").pop() || first).replace(/^["']|["']$/g, "").slice(0, 40);
111
+ }
112
+ var AGENTS = {
113
+ claude: {
114
+ kind: "claude",
115
+ label: "Claude Code",
116
+ bins: ["claude"],
117
+ install: "curl -fsSL https://claude.ai/install.sh | bash",
118
+ installWindows: "irm https://claude.ai/install.ps1 | iex",
119
+ signIn: "claude auth login",
120
+ login: ["auth", "login"],
121
+ update: "claude update",
122
+ help: ["--help"],
123
+ status: { args: ["auth", "status"], ok: (out) => /"loggedIn"\s*:\s*true/.test(out) },
124
+ // The designer's own settings (allow rules, MCP servers, skills), edits in the project accepted.
125
+ // A run can't prompt: `-p` refuses what would ask (checked; `--permission-prompts none` says the
126
+ // same, but older versions don't know it). Reading the user's skills is allowed, read-only: its
127
+ // chat would ask before a skill reads its other files there, and a run can't answer.
128
+ // Partial messages: its output comes while it thinks too, so Pilot sees a long think isn't a stalled run (Job.activeAt).
129
+ args: ({ resume, readDirs = [] }) => [
130
+ "-p",
131
+ "--output-format",
132
+ "stream-json",
133
+ "--verbose",
134
+ "--include-partial-messages",
135
+ "--permission-mode",
136
+ "acceptEdits",
137
+ "--allowedTools",
138
+ "Read(~/.claude/skills/**)",
139
+ ...readDirs.flatMap((d) => ["--add-dir", d]),
140
+ ...resume ? ["--resume", resume] : []
141
+ ],
142
+ parse: parseStream,
143
+ skills: { project: [".claude/skills"], home: [".claude/skills"] },
144
+ invokeSkill: (name) => `/${name}`,
145
+ projectSettings: ".claude/settings.local.json"
146
+ },
147
+ codex: {
148
+ kind: "codex",
149
+ label: "Codex",
150
+ bins: ["codex"],
151
+ install: "npm install -g @openai/codex",
152
+ signIn: "codex login",
153
+ login: ["login"],
154
+ update: "npm install -g @openai/codex@latest",
155
+ help: ["exec", "--help"],
156
+ status: { args: ["login", "status"], ok: (_out, code) => code === 0 },
157
+ // Its sandbox in the mode its chat uses for a project (writes in the project), with the designer's
158
+ // own settings for the rest (network, web search, rules). `exec` never asks: what would is refused.
159
+ // On Windows the sandbox needs a mode, or a run is read-only; "unelevated" needs no admin rights.
160
+ args: ({ resume, images = [], platform = process.platform }) => [
161
+ "exec",
162
+ "--json",
163
+ "-s",
164
+ "workspace-write",
165
+ ...platform === "win32" ? ["-c", 'windows.sandbox="unelevated"'] : [],
166
+ "--skip-git-repo-check",
167
+ ...images.flatMap((i) => ["-i", i]),
168
+ ...resume ? ["resume", resume] : [],
169
+ "-"
170
+ ],
171
+ parse: parseCodex,
172
+ skills: { project: [".agents/skills"], home: [".agents/skills", ".codex/skills"] },
173
+ invokeSkill: (name) => "$" + name,
174
+ projectSettings: ".codex/config.toml"
175
+ },
176
+ cursor: {
177
+ kind: "cursor",
178
+ label: "Cursor",
179
+ bins: ["cursor-agent", "agent"],
180
+ install: "curl https://cursor.com/install -fsS | bash",
181
+ installWindows: "irm 'https://cursor.com/install?win32=true' | iex",
182
+ signIn: "cursor-agent login",
183
+ login: ["login"],
184
+ update: "cursor-agent update",
185
+ help: ["--help"],
186
+ status: { args: ["status"], ok: (out) => /logged in/i.test(out) && !/not logged in/i.test(out) },
187
+ keyEnv: "CURSOR_API_KEY",
188
+ // Its allowlist mode, not its sandbox: the sandbox doesn't exist on Windows and fails on Ubuntu's
189
+ // default AppArmor settings. Without `--force`, a run is refused what the user's allowlist doesn't
190
+ // allow (it can't ask): writes outside the project, web fetches, shell commands. Checked on all three.
191
+ args: ({ resume }) => ["-p", "--output-format", "stream-json", "--trust", "--sandbox", "disabled", ...resume ? ["--resume", resume] : []],
192
+ parse: parseStream,
193
+ skills: { project: [".agents/skills", ".cursor/skills"], home: [".cursor/skills"] },
194
+ invokeSkill: (name) => `/${name}`,
195
+ projectSettings: ".cursor/cli.json"
196
+ }
197
+ };
198
+ function installCommand(cli, platform = process.platform) {
199
+ return platform === "win32" && cli.installWindows ? cli.installWindows : cli.install;
200
+ }
201
+ function isAgentKind(value) {
202
+ return typeof value === "string" && AGENT_KINDS.includes(value);
203
+ }
204
+ function findBin(names, env = process.env, platform = process.platform, home = homedir()) {
205
+ const win = platform === "win32";
206
+ const exts = win ? (env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";").filter(Boolean).map((e) => e.toLowerCase()) : [""];
207
+ const dirs = [...(env.PATH ?? env.Path ?? "").split(win ? ";" : delimiter), join(home, ".local", "bin")].filter(Boolean);
208
+ for (const name of names) {
209
+ for (const dir of dirs) {
210
+ for (const ext of exts) {
211
+ const file = join(dir, name + ext);
212
+ try {
213
+ if (statSync(file).isFile()) return file;
214
+ } catch {
215
+ }
216
+ }
217
+ }
218
+ }
219
+ return null;
220
+ }
221
+ function agentFromEnv(env = process.env) {
222
+ if (env.CLAUDECODE || env.CLAUDE_CODE_ENTRYPOINT) return "claude";
223
+ if (env.CURSOR_AGENT || env.CURSOR_TRACE_ID) return "cursor";
224
+ if (env.CODEX_SANDBOX || env.CODEX_SANDBOX_NETWORK_DISABLED || env.CODEX_MANAGED_BY_NPM || env.CODEX_THREAD_ID) return "codex";
225
+ return null;
226
+ }
227
+ async function missingFlags(cli, bin, run = exec) {
228
+ const flags = [...new Set(cli.args({ resume: "session", readDirs: ["dir"], images: ["image.png"] }).filter((a) => a.startsWith("--")))];
229
+ let help;
230
+ try {
231
+ help = await run(bin, cli.help, { timeoutMs: 15e3 });
232
+ } catch {
233
+ return null;
234
+ }
235
+ const text = `${help.stdout}
236
+ ${help.stderr}`;
237
+ if (help.killed || !text.trim() || !flags.some((f) => listed(text, f))) return null;
238
+ return flags.filter((f) => !listed(text, f));
239
+ }
240
+ function listed(text, flag) {
241
+ return new RegExp(`(^|[^\\w-])${flag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\w-])`).test(text);
242
+ }
243
+ async function detectAgents(kinds = AGENT_KINDS) {
244
+ const found = await Promise.all(
245
+ kinds.map(async (kind) => {
246
+ const cli = AGENTS[kind];
247
+ const bin = findBin(cli.bins);
248
+ if (!bin) return null;
249
+ if (cli.keyEnv && process.env[cli.keyEnv]) return { kind, bin, signedIn: true };
250
+ const { stdout, stderr, code } = await exec(bin, cli.status.args, { timeoutMs: 15e3 });
251
+ return { kind, bin, signedIn: cli.status.ok(stdout + stderr, code) };
252
+ })
253
+ );
254
+ return found.filter((a) => !!a);
255
+ }
256
+ function exec(bin, args, options = {}) {
257
+ return new Promise((resolve5) => {
258
+ const shell = process.platform === "win32" && /\.(cmd|bat)$/i.test(bin);
259
+ 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() });
260
+ let stdout = "";
261
+ let stderr = "";
262
+ let killed = false;
263
+ const kill = () => {
264
+ killed = true;
265
+ if (process.platform === "win32" && child.pid) spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" });
266
+ else child.kill();
267
+ };
268
+ child.stdout?.on("data", (d) => {
269
+ const text = d.toString();
270
+ stdout += text;
271
+ options.onStdout?.(text);
272
+ });
273
+ child.stderr?.on("data", (d) => {
274
+ const text = d.toString();
275
+ stderr += text;
276
+ options.onStderr?.(text);
277
+ });
278
+ const timer = options.timeoutMs ? setTimeout(kill, options.timeoutMs) : null;
279
+ options.signal?.addEventListener("abort", kill, { once: true });
280
+ const finish = (code) => {
281
+ if (timer) clearTimeout(timer);
282
+ options.signal?.removeEventListener("abort", kill);
283
+ resolve5({ stdout, stderr, code, killed });
284
+ };
285
+ child.on("error", (e) => {
286
+ stderr += String(e);
287
+ finish(-1);
288
+ });
289
+ child.on("close", finish);
290
+ child.stdin?.on("error", () => {
291
+ });
292
+ child.stdin?.end(options.input ?? "");
293
+ });
294
+ }
295
+ function quoteForCmd(arg) {
296
+ return /^[\w\-.:\\/=,]+$/.test(arg) ? arg : `"${arg.replace(/"/g, '""')}"`;
297
+ }
298
+ function childEnv(env = process.env) {
299
+ const { CLAUDECODE: _a, CLAUDE_CODE_ENTRYPOINT: _b, ...rest } = env;
300
+ return rest;
301
+ }
302
+ function jsonLine(line) {
303
+ const text = line.trim();
304
+ if (!text.startsWith("{")) return null;
305
+ try {
306
+ return JSON.parse(text);
307
+ } catch {
308
+ return null;
309
+ }
310
+ }
311
+ function textOf(message) {
312
+ const content = message?.content;
313
+ if (typeof content === "string") return content;
314
+ if (!Array.isArray(content)) return "";
315
+ return content.filter((c) => c?.type === "text" && typeof c.text === "string").map((c) => c.text).join("");
316
+ }
317
+ function lastLines(text) {
318
+ return text.trim().split("\n").slice(-3).join("\n").slice(0, 500);
319
+ }
320
+
321
+ // src/run.ts
322
+ import { randomUUID as randomUUID2 } from "crypto";
323
+ import { existsSync as existsSync7 } from "fs";
324
+ import { basename as basename7 } from "path";
325
+
326
+ // ../protocol/src/types.ts
327
+ function mentionText(reference) {
328
+ return reference.kind === "token" ? reference.name : `@${reference.name}`;
329
+ }
330
+ var ATTACHMENT_TYPES = {
331
+ png: "image/png",
332
+ jpg: "image/jpeg",
333
+ gif: "image/gif",
334
+ webp: "image/webp",
335
+ pdf: "application/pdf",
336
+ txt: "text/plain",
337
+ md: "text/markdown",
338
+ csv: "text/csv",
339
+ json: "application/json"
340
+ };
341
+ var ATTACHMENT_ID = /^[a-f0-9]{64}\.(png|jpg|gif|webp|pdf|txt|md|csv|json)$/;
342
+ function attachmentKind(name) {
343
+ const ext = name.split(".").pop()?.toLowerCase();
344
+ return ext === "pdf" ? "pdf" : ext === "png" || ext === "jpg" || ext === "jpeg" || ext === "gif" || ext === "webp" ? "image" : "text";
345
+ }
346
+ var BY_EXTENSION = {
347
+ png: "image/png",
348
+ jpg: "image/jpeg",
349
+ jpeg: "image/jpeg",
350
+ gif: "image/gif",
351
+ webp: "image/webp",
352
+ pdf: "application/pdf",
353
+ txt: "text/plain",
354
+ log: "text/plain",
355
+ text: "text/plain",
356
+ md: "text/markdown",
357
+ markdown: "text/markdown",
358
+ csv: "text/csv",
359
+ json: "application/json"
360
+ };
361
+ var ATTACHMENT_ACCEPT = [...new Set(Object.values(ATTACHMENT_TYPES))].join(",") + "," + Object.keys(BY_EXTENSION).map((e) => `.${e}`).join(",");
362
+ function requestTargets(request) {
363
+ return [request.target, ...request.others ?? []];
364
+ }
365
+
366
+ // ../protocol/src/format.ts
367
+ function formatPrompt(changeSet, options = {}) {
368
+ if (changeSet.request?.kind === "responsive") return formatResponsive(changeSet, changeSet.request);
369
+ if (changeSet.request?.kind === "break-and-fix") return formatBreakFix(changeSet, changeSet.request);
370
+ if (changeSet.request?.kind === "comment") return formatComment(changeSet, changeSet.request);
371
+ if (changeSet.request?.kind === "props") return formatProps(changeSet, changeSet.request);
372
+ const { page, edits, note } = changeSet;
373
+ const lines = [
374
+ "# Pilot design edits",
375
+ "",
376
+ "A designer adjusted the UI below in the browser with Pilot. Apply these changes to the source code.",
377
+ "",
378
+ ...options.guidelinesKnown ? ["Guidelines: the same as for the earlier edits in this session (design intent, the project's own conventions, no builds or browser)."] : ["Guidelines:", ...editGuidelines()],
379
+ "",
380
+ `Page: ${page.url} (${page.title || "untitled"}) at ${page.viewport.width}x${page.viewport.height}`
381
+ ];
382
+ if (note?.trim()) {
383
+ lines.push("", `Designer note: ${note.trim()}`);
384
+ }
385
+ edits.forEach((edit, index) => {
386
+ lines.push("", ...formatEdit(edit, index + 1));
387
+ });
388
+ lines.push(...fileTokenLines(changeSet.fileTokens));
389
+ return `${lines.join("\n")}
390
+ `;
391
+ }
392
+ function fileTokenLines(tokens) {
393
+ if (!tokens?.length) return [];
394
+ return [
395
+ "",
396
+ "## The project's tokens in these values",
397
+ "",
398
+ "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:",
399
+ "",
400
+ ...tokens.map((t) => `- \`var(${t.variable})\` is \`${t.name}\` in \`${t.file}${t.line ? `:${t.line}` : ""}\` (\`${t.value}\`)`)
401
+ ];
402
+ }
403
+ function advancedTask() {
404
+ 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.";
405
+ }
406
+ 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.";
407
+ var PRODUCTION_CODE = "No inline styles, no `!important`, no hard-coded values where a token or utility fits.";
408
+ var SHARED_CHOICES = {
409
+ all: { label: "All of them", means: "change the component (or the shared code) itself, so every instance gets it." },
410
+ one: {
411
+ label: "Only this",
412
+ 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."
413
+ },
414
+ variant: {
415
+ label: "New variant",
416
+ 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."
417
+ }
418
+ };
419
+ function sharedChoiceMeaning(answer) {
420
+ const said = answer.trim().toLowerCase();
421
+ const choice = Object.values(SHARED_CHOICES).find((c) => c.label.toLowerCase() === said);
422
+ return choice ? `**${choice.label}**: ${choice.means}` : null;
423
+ }
424
+ function sharedCode() {
425
+ return [
426
+ `**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). Start it by saying that part hasn't changed yet (the page shows nothing new for it until they answer), and ask about what the designer did: "only this one" for a comment or a task, "only the ones you changed" for their edits ("Not changed yet: every **FeatureCard**, or only this one?"). Their answer comes back to you as this job. You can ask once per job: when it changes some copies of several components (or several parts that repeat), ask one question naming each in **bold** ("Not changed yet: every **PlanCard** and **FeatureCard**, or only the ones you changed?"), leave all those parts until the answer, and apply it to each.`,
427
+ ...Object.values(SHARED_CHOICES).map((c) => `**${c.label}**: ${c.means}`),
428
+ `Don't ask when the designer already said (in the comment or note: "only here", "every card", "as a variant"), or when nothing else uses that code: just change it.`,
429
+ `**Every copy in the job:** an element's "Every instance" line means the designer picked every instance of its component on the page together (with Pilot's Select similar, or one by one): they mean the component. Change the component itself, in its own file, so the change reaches wherever it's used, other pages included: not each instance where it's used, not a new variant, and don't ask. An "Every copy" line (no component: copies Pilot matched by the page's structure, plain HTML) means every one on this page only: change them here; if the only way is code other pages share too (a class in a global stylesheet, a partial or include), ask first, with the three choices above, before changing it there.`
430
+ ].join(" ");
431
+ }
432
+ var UNCLEAR_ASK = '**Unclear, or already done:** if the comment could mean more than one thing ("make this square": square corners, or a 1:1 shape?), or the element already seems to be what it asks, don\'t search for what the designer meant and don\'t guess: leave that part, and ask them in your notes, in one short sentence naming the options ("Square corners, or a 1:1 shape?"). Their answer comes back as their next comment in this thread. (Your notes, not the `pilot` block: that one is for the shared-code question below.) What they meant is in the comment, the elements above and the code, nowhere else: not in git history, other agent sessions or the web.';
433
+ var COMMENT_WINS = `**The comment was written after these edits, so it wins:** where it asks for something else for the same property (an edit sets a margin, the comment says "10\xD7 the spacing"), do what the comment asks for that property and say so in your notes. Pilot's check may then find the edit's value missing and send it back once: keep what the comment asked.`;
434
+ function editGuidelines() {
435
+ return [
436
+ `- ${DESIGN_INTENT}`,
437
+ `- ${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.`,
438
+ "- Find each element by its selector, DOM path and text, then the component that renders it. Change only the listed elements.",
439
+ `- ${sharedCode()}`,
440
+ "- A removed property means the element shouldn't declare it at all: not `0` or `none`, the declaration gone.",
441
+ "- No screenshots, builds or tests for these edits: hot reload shows them, and Pilot checks the page itself.",
442
+ `- 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. "Base" is the element's base value: change it where it's declared without a media query or a state (its From and source above), and keep the project's media queries, states and conditions for that property as they are: they still win where they apply, as they did before. A change for some widths or a state builds on them too: change the project's own rule for that breakpoint or state where it has one, else add one in its usual form (its breakpoints' order: a larger "from" width still wins above it), and keep the others. Build on what's there; don't flatten it.`,
443
+ "- 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.",
444
+ "- 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).",
445
+ "- `dark` and `light` in States: the change is only for that color scheme, the rest of the time as it is. Use the project's own dark mode, whichever it is (Tailwind's `dark:`, `@media (prefers-color-scheme: dark)`, a `.dark` class or a `data-theme` attribute on the root): change its rule for that mode where it has one, else add one in that form. Light-only styles take the project's `light:` variant if it has one, else the same mechanism for light (`@media (prefers-color-scheme: light)`, or what isn't dark: `:not(.dark)`); say which.",
446
+ "- `before`, `after` and `placeholder` in States: the change is for that pseudo-element, not the element itself (`::before`, Tailwind's `before:`), together with any other state (\"hover, before\": its `::before` while hovered). A `::before` or `::after` only shows with a `content`: keep the one it has, and add `content: ''` (Tailwind's `before:content-['']`) if it has none."
447
+ ];
448
+ }
449
+ 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}`;
450
+ var ACTION_ASKED = {
451
+ responsive: "asked you to make it responsive",
452
+ "break-and-fix": "asked you to break and fix it",
453
+ props: "asked for the component's props"
454
+ };
455
+ function propValue(value) {
456
+ return value === void 0 ? "*not set*" : `\`${typeof value === "string" ? JSON.stringify(value) : String(value)}\``;
457
+ }
458
+ function formatProps(changeSet, request) {
459
+ const { page, note } = changeSet;
460
+ const current = Object.entries(request.current);
461
+ const lines = [
462
+ "# Pilot: props",
463
+ "",
464
+ `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.**`,
465
+ "",
466
+ `Page: ${page.url} (${page.title || "untitled"}), seen at ${page.viewport.width}x${page.viewport.height}`,
467
+ "",
468
+ ...elementsSection(request),
469
+ ...request.usedIn ? [`- This instance is written in: \`${request.usedIn}\``] : [],
470
+ "",
471
+ "## Its props now (read from the page)",
472
+ "",
473
+ ...current.length ? current.map(([name, value]) => `- \`${name}\`: ${propValue(value)}`) : ["None that Pilot could read (it reads strings, numbers and on-off values)."],
474
+ ...note?.trim() ? ["", `Designer note: ${note.trim()}`] : [],
475
+ ...request.attachments?.length ? ["", ...attachmentLines(request.attachments, `The designer attached ${countFiles(request.attachments.length)}:`)] : [],
476
+ ...request.references?.length ? ["", ...referenceLines(request.references)] : [],
477
+ "",
478
+ "## What to list",
479
+ "",
480
+ "- **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.",
481
+ "- **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, with what it takes when its type doesn't say (a number's range, `how full the bar is, 0\u2013100`; a text's form, `the fill, a Tailwind bg class`).",
482
+ "- The most useful first (the main variant, then the size, then the rest); 12 at most.",
483
+ "",
484
+ 'Reply with one short sentence for the designer, like a chat message ("Button has 3 props you can change"), without describing them (Pilot lists them right under it), and the list as `props` in your reply\'s `pilot` block. Pilot lists the props under your sentence, each with its value on this instance and what it takes; the designer changes one by replying with a `name: value` line (`tone: dark`), which comes back to you as their comment, to set where this instance is written. If none is worth listing, say so and leave the block out.'
485
+ ];
486
+ return `${lines.join("\n")}
487
+ `;
488
+ }
489
+ function formatBreakFix(changeSet, request) {
490
+ const { page, note } = changeSet;
491
+ const { breakpoints } = request;
492
+ const several = requestTargets(request).length;
493
+ const widths = breakpoints.length ? breakpoints.map((b) => `${b}px`).join(", ") : "none found (it may use container queries, or none yet)";
494
+ const lines = [
495
+ "# Pilot: break and fix",
496
+ "",
497
+ 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.",
498
+ "",
499
+ `Page: ${page.url} (${page.title || "untitled"}), seen at ${page.viewport.width}x${page.viewport.height}`,
500
+ `The page's breakpoints (the widths its media queries test): ${widths}`,
501
+ "",
502
+ advancedTask()
503
+ ];
504
+ if (note?.trim()) lines.push("", `Designer note: ${note.trim()}`);
505
+ if (request.attachments?.length)
506
+ lines.push("", ...attachmentLines(request.attachments, `The designer attached ${countFiles(request.attachments.length)}:`));
507
+ if (request.references?.length) lines.push("", ...referenceLines(request.references));
508
+ lines.push(
509
+ "",
510
+ ...elementsSection(request),
511
+ "",
512
+ "## How to do it",
513
+ "",
514
+ "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.",
515
+ "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.",
516
+ "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.",
517
+ "4. **Fix what breaks, without changing how it looks with its usual content**, the way this project does it (its utilities, its components):",
518
+ " - **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).",
519
+ " - **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.",
520
+ " - **Long words:** `overflow-wrap: anywhere` (`break-words`) where text must wrap.",
521
+ " - **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.",
522
+ " - **Missing parts:** no gap or empty box left behind; a simple empty state only where one is clearly needed.",
523
+ " In the check, an ellipsis on your deliberately long text is the fix working, not a problem.",
524
+ "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.",
525
+ `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.`,
526
+ "",
527
+ 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.",
528
+ "",
529
+ PROJECT_CODE
530
+ );
531
+ return `${lines.join("\n")}
532
+ `;
533
+ }
534
+ function formatResponsive(changeSet, request) {
535
+ const { page, note } = changeSet;
536
+ const { breakpoints } = request;
537
+ const several = requestTargets(request).length;
538
+ const widths = breakpoints.length ? breakpoints.map((b) => `${b}px`).join(", ") : "none found (it may use container queries, or none yet)";
539
+ const lines = [
540
+ "# Pilot: make responsive",
541
+ "",
542
+ 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.",
543
+ "",
544
+ `Page: ${page.url} (${page.title || "untitled"}), seen at ${page.viewport.width}x${page.viewport.height}`,
545
+ `The page's breakpoints (the widths its media queries test): ${widths}`,
546
+ "",
547
+ advancedTask()
548
+ ];
549
+ if (note?.trim()) lines.push("", `Designer note: ${note.trim()}`);
550
+ if (request.attachments?.length)
551
+ lines.push("", ...attachmentLines(request.attachments, `The designer attached ${countFiles(request.attachments.length)}:`));
552
+ if (request.references?.length) lines.push("", ...referenceLines(request.references));
553
+ lines.push(
554
+ "",
555
+ ...elementsSection(request),
556
+ "",
557
+ "## How to do it",
558
+ "",
559
+ "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.",
560
+ "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.",
561
+ "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.",
562
+ "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.",
563
+ "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.",
564
+ `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.`,
565
+ "",
566
+ 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).",
567
+ "",
568
+ sharedCode(),
569
+ "",
570
+ PROJECT_CODE
571
+ );
572
+ return `${lines.join("\n")}
573
+ `;
574
+ }
575
+ function formatComment(changeSet, request) {
576
+ const { page, edits } = changeSet;
577
+ const { thread, breakpoints } = request;
578
+ const several = requestTargets(request).length;
579
+ const latest = thread.at(-1);
580
+ const earlier = thread.slice(0, -1);
581
+ const widths = breakpoints.length ? breakpoints.map((b) => `${b}px`).join(", ") : "none found (it may use container queries, or none yet)";
582
+ const lines = [
583
+ "# Pilot: comment",
584
+ "",
585
+ 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).",
586
+ "",
587
+ `Page: ${page.url} (${page.title || "untitled"}), seen at ${page.viewport.width}x${page.viewport.height}`,
588
+ `The page's breakpoints (the widths its media queries test): ${widths}`,
589
+ "",
590
+ ...elementsSection(request),
591
+ "",
592
+ "## The comment",
593
+ "",
594
+ // Props set from the thread, with no words: the props are the comment.
595
+ ...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)
596
+ ];
597
+ if (latest?.skill) {
598
+ lines.push(
599
+ "",
600
+ "## The skill to use",
601
+ "",
602
+ `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.`
603
+ );
604
+ }
605
+ if (latest?.props?.set.length) {
606
+ const { component, usedIn, set } = latest.props;
607
+ lines.push(
608
+ "",
609
+ "## Props to set",
610
+ "",
611
+ `The designer picked new values for this \`${component}\` instance's props from the list you gave (the \`name: value\` lines in their comment):`,
612
+ "",
613
+ ...set.map((c) => `- \`${c.name}\`: ${propValue(c.from)} \u2192 ${propValue(c.to)}`),
614
+ "",
615
+ `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.`
616
+ );
617
+ }
618
+ if (edits.length) {
619
+ lines.push(
620
+ "",
621
+ "## The designer's edits, sent with the comment",
622
+ "",
623
+ `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.`,
624
+ "",
625
+ COMMENT_WINS,
626
+ "",
627
+ "Guidelines:",
628
+ ...editGuidelines()
629
+ );
630
+ edits.forEach((edit, index) => lines.push("", ...formatEdit(edit, index + 1).map((l) => l.startsWith("## ") ? `#${l}` : l)));
631
+ lines.push(...fileTokenLines(changeSet.fileTokens));
632
+ }
633
+ if (earlier.length) {
634
+ lines.push("", "## The thread so far (you already did what it asked)", "");
635
+ for (const m of earlier) {
636
+ const files = m.attachments?.length ? ` (${countFiles(m.attachments.length)})` : "";
637
+ const action = m.action ? ` (${ACTION_ASKED[m.action]})` : m.skill ? ` (with the skill \`${m.skill}\`)` : "";
638
+ lines.push(`- **${m.from === "designer" ? "Designer" : "You"}:**${action}${files} ${m.text.replace(/\s*\n\s*/g, " ")}`.trimEnd());
639
+ }
640
+ }
641
+ lines.push(
642
+ "",
643
+ "## How to do it",
644
+ "",
645
+ "- **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.",
646
+ "- **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.",
647
+ `- ${UNCLEAR_ASK}`,
648
+ `- 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 change the base value, keeping the project's breakpoints as they are.`,
649
+ `- ${PROJECT_CODE}`,
650
+ several > 1 ? "- Change only what the comment is about, on each of these elements." : "- Change only what the comment is about.",
651
+ `- ${sharedCode()}`,
652
+ "- **A question, not a change:** answer it, and change nothing.",
653
+ 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."
654
+ );
655
+ return `${lines.join("\n")}
656
+ `;
657
+ }
658
+ function commentLines(message) {
659
+ const text = message?.text.trim() ?? "";
660
+ const files = message?.attachments ?? [];
661
+ const out = text ? [quote(text)] : [];
662
+ const references = message?.references ?? [];
663
+ if (references.length) out.push("", ...referenceLines(references));
664
+ if (!files.length) return out.length ? out : ["> (empty)"];
665
+ const one = files.length === 1;
666
+ if (out.length) out.push("");
667
+ out.push(
668
+ 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.`,
669
+ "",
670
+ ...attachmentLines(files)
671
+ );
672
+ return out;
673
+ }
674
+ function referenceLines(references) {
675
+ const picked = references.some((r) => r.kind !== "unlisted");
676
+ return [
677
+ 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:",
678
+ "",
679
+ ...references.map(referenceLine)
680
+ ];
681
+ }
682
+ function referenceLine(reference) {
683
+ const as = `- \`${mentionText(reference)}\`:`;
684
+ if (reference.kind === "token" && reference.source)
685
+ 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.`;
686
+ if (reference.kind === "token")
687
+ 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).`;
688
+ if (reference.kind === "breakpoint")
689
+ return `${as} one of the page's breakpoints: its media queries change the layout at ${reference.width}px. Use the project's own name for it (\`md\`, a \`$breakpoint\` variable\u2026), from its config, or that width if it has none.`;
690
+ if (reference.kind === "unlisted")
691
+ 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.`;
692
+ if (reference.kind === "component") {
693
+ const t = reference.target;
694
+ const source = reference.source ?? (t?.source?.file ? { file: t.source.file, line: t.source.line } : void 0);
695
+ 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)`;
696
+ 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.`;
697
+ }
698
+ const el = reference.target;
699
+ const component = el.source?.component ? `, inside the \`${el.source.component}\` component` : "";
700
+ return `${as} an element on the page: \`${el.path}\`, selector \`${el.selector}\`${el.text ? `, text "${el.text}"` : ""}${component}.`;
701
+ }
702
+ function attachmentLines(files, intro) {
703
+ const lines = files.map((file) => {
704
+ const kind = attachmentKind(file.id);
705
+ 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";
706
+ return `- ${file.name ? `${file.name} ` : ""}(${how}): \`${file.path ?? file.id}\``;
707
+ });
708
+ return intro ? [intro, "", ...lines] : lines;
709
+ }
710
+ function countFiles(n) {
711
+ return n === 1 ? "a file" : `${n} files`;
712
+ }
713
+ function quote(text) {
714
+ return text.trim().split("\n").map((l) => `> ${l}`).join("\n");
715
+ }
716
+ function firstChecked() {
717
+ return "Pilot's width check after you're done measures the first of them; read the code for the others.";
718
+ }
719
+ function elementsSection(request) {
720
+ const targets = requestTargets(request);
721
+ if (targets.length === 1) return [`## \`${request.target.path}\``, "", ...targetLines(request.target)];
722
+ const out = [`## The elements (${targets.length})`];
723
+ targets.forEach((target, i) => out.push("", `### ${i + 1}. \`${target.path}\``, "", ...targetLines(target)));
724
+ return out;
725
+ }
726
+ function targetLines(target) {
727
+ const out = [`- Selector: \`${target.selector}\``];
728
+ if (target.text) out.push(`- Text: "${target.text}"`);
729
+ if (target.source?.component || target.source?.file) {
730
+ const { component, file, line } = target.source;
731
+ const where = [component && `\`${component}\``, file && `\`${file}${line ? `:${line}` : ""}\``].filter(Boolean).join(", in ");
732
+ out.push(`- Component: ${where}`);
733
+ }
734
+ if (target.lookAlikes) {
735
+ const of = target.lookAlikesOf ? `other instances of \`${target.lookAlikesOf}\`, the same part of each` : "the same part of other copies";
736
+ out.push(`- Look-alikes: ${target.lookAlikes} more on the page (${of}), not in this job`);
737
+ }
738
+ if (target.everyCopy) {
739
+ out.push(
740
+ target.everyCopy.of ? `- Every instance of \`${target.everyCopy.of}\` on the page is in this job (the same part of each): change the component itself, wherever it's used` : "- Every copy on the page is in this job (the same part of each, matched by the page's structure; no component): keep the change to this page"
741
+ );
742
+ }
743
+ if (target.style?.length) out.push("- Its style now, as the page has it (no need to look it up; what each comes to after `=`):", ...target.style.map((st) => ` - ${styleLine(st)}`));
744
+ return out;
745
+ }
746
+ function styleLine(st) {
747
+ const value = `\`${st.property}: ${st.value}\`${st.computed ? ` = \`${st.computed}\`` : ""}`;
748
+ const source = st.source;
749
+ if (!source) return value;
750
+ if (source.kind === "inherited") return `${value}, inherited`;
751
+ if (source.kind === "inline") return `${value}, in its \`style\` attribute`;
752
+ const shared = source.elements && source.elements > 1 ? `, which matches ${source.elements} elements` : "";
753
+ return `${value}, from \`${source.selector}\`${source.media ? ` in \`@media ${source.media}\`` : ""}${shared}`;
754
+ }
755
+ function formatEdit(edit, n) {
756
+ const { target, changes, texts } = edit;
757
+ const out = [`## ${n}. \`${target.path}\``, "", ...targetLines(target)];
758
+ if (texts?.length) out.push("", "Text (from \u2192 to):", "", ...texts.map((t) => `- ${JSON.stringify(t.from)} \u2192 ${JSON.stringify(t.to)}`));
759
+ if (!changes.length) return out;
760
+ const withStates = changes.some((c) => c.states?.length);
761
+ out.push(
762
+ "",
763
+ withStates ? "| Property | From | To | Widths | State |" : "| Property | From | To | Widths |",
764
+ withStates ? "| --- | --- | --- | --- | --- |" : "| --- | --- | --- | --- |"
765
+ );
766
+ for (const c of changes) {
767
+ const to = c.removed ? "*removed*" : `\`${c.to}\``;
768
+ const from = c.from ? `\`${c.from}\`` : "*not set*";
769
+ const widths = c.widths ? describeWidths(c.widths) : "base";
770
+ out.push(`| \`${c.property}\` | ${from} | ${to} | ${widths} |${withStates ? ` ${describeStates(c.states)} |` : ""}`);
771
+ }
772
+ const notes = changes.flatMap((c) => [c.removed && removalNote(c), mediaNote(c), equivalentsNote(c)].filter((n2) => !!n2));
773
+ if (notes.length) out.push("", ...notes.map((n2) => `- ${n2}`));
774
+ return out;
775
+ }
776
+ function describeStates(states) {
777
+ return states?.length ? states.join(", ") : "\u2014";
778
+ }
779
+ function describeWidths({ min, max }) {
780
+ if (min !== void 0 && min === max) return `${min}px only`;
781
+ if (min !== void 0 && max !== void 0) return `${min}\u2013${max}px`;
782
+ if (min !== void 0) return `from ${min}px`;
783
+ if (max !== void 0) return `to ${max}px`;
784
+ return "every width";
785
+ }
786
+ function mediaNote(c) {
787
+ const media = c.source?.kind === "rule" ? c.source.media : void 0;
788
+ if (!media) return null;
789
+ const today = `\`${c.property}\` is set inside \`@media ${media}\` today.`;
790
+ return c.widths ? `${today} The change is for ${describeWidths(c.widths)}.` : `${today} The change has no width: set it without a media query, and keep that one as it is.`;
791
+ }
792
+ function equivalentsNote(c) {
793
+ const e = c.equivalents;
794
+ if (!e || !e.tokens.length && !e.classes.length) return null;
795
+ const code = (list2) => list2.map((x) => `\`${x}\``).join(", ");
796
+ const parts = [
797
+ e.tokens.length ? `the page's ${e.tokens.length > 1 ? "tokens" : "token"} ${code(e.tokens)}${e.fluid ? " (fluid: equal at the page's current width only, so check it's the one meant)" : ""}` : "",
798
+ e.classes.length ? `${e.classes.length > 1 ? "the classes" : "the class"} ${code(e.classes)}, which set${e.classes.length > 1 ? "" : "s"} just \`${c.property}\`` : ""
799
+ ].filter(Boolean);
800
+ return `\`${c.property}: ${c.to}\` is ${parts.join(", and ")}: use one where it fits, as this project writes it.`;
801
+ }
802
+ function removalNote(c) {
803
+ 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).`;
804
+ const source = c.source;
805
+ if (!source) return note;
806
+ if (source.kind === "inline") return `${note} It's set in the element's own \`style\` attribute.`;
807
+ 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` : "";
808
+ const also = source.also?.length ? `, and from ${source.also.map((s) => `\`${s}\``).join(", ")}, which declare${source.also.length > 1 ? "" : "s"} the same value: remove it from ${source.also.length > 1 ? "them" : "it"} too` : "";
809
+ return `${note} It comes from \`${source.selector}\`${shared}${also}.`;
810
+ }
811
+
812
+ // ../protocol/src/bridge.ts
813
+ var BRIDGE_VERSION = 9;
814
+ var DEFAULT_BRIDGE_PORT = 4747 + BRIDGE_VERSION;
815
+ var SKILL_NAME = /^[A-Za-z0-9][\w.:-]{0,63}$/;
816
+ var MAX_CHOICES = 4;
817
+ function questionOf(value) {
818
+ const q = value;
819
+ if (typeof q?.text !== "string" || !q.text.trim()) return void 0;
820
+ 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);
821
+ const element = Number.isInteger(q.element) && q.element >= 1 && q.element <= 1e3 ? q.element : void 0;
822
+ return { text: q.text.trim().slice(0, 500), ...choices.length ? { choices } : {}, ...element ? { element } : {} };
823
+ }
824
+ function sessionOf(value) {
825
+ const s = value;
826
+ if (typeof s?.agent !== "string" || !/^[a-z]{1,20}$/.test(s.agent)) return void 0;
827
+ if (typeof s.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9-]{7,99}$/.test(s.id)) return void 0;
828
+ return { agent: s.agent, id: s.id };
829
+ }
830
+ function allowOf(value) {
831
+ if (typeof value !== "string") return void 0;
832
+ const text = value.replace(/\s+/g, " ").trim();
833
+ return text ? text.slice(0, 500) : void 0;
834
+ }
835
+ function jobErrorOf(value) {
836
+ const e = value;
837
+ if (typeof e?.title !== "string" || !e.title.trim()) return void 0;
838
+ return { title: e.title.trim().slice(0, 200), detail: typeof e.detail === "string" ? e.detail.trim().slice(0, 1e3) : "" };
839
+ }
840
+ var SETUP_STATES = ["not-installed", "not-signed-in", "signing-in"];
841
+ function setupOf(value) {
842
+ const s = value;
843
+ if (!s || !SETUP_STATES.includes(s.state) || typeof s.command !== "string") return void 0;
844
+ const text = (v, max) => typeof v === "string" && v.trim() ? v.trim().slice(0, max) : void 0;
845
+ const agent = text(s.agent, 60);
846
+ const url = text(s.url, 2e3);
847
+ const error = text(s.error, 500);
848
+ return {
849
+ state: s.state,
850
+ command: s.command.trim().slice(0, 500),
851
+ ...agent ? { agent } : {},
852
+ ...s.canSignIn === true ? { canSignIn: true } : {},
853
+ ...url && /^https:\/\/[^\s"'<>]+$/.test(url) ? { url } : {},
854
+ ...error ? { error } : {}
855
+ };
856
+ }
857
+ var MAX_PROPS = 20;
858
+ function propsOf(value) {
859
+ if (!Array.isArray(value)) return void 0;
860
+ const scalar = (v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean";
861
+ const props = value.flatMap((p) => {
862
+ const name = typeof p?.name === "string" ? p.name.trim().slice(0, 60) : "";
863
+ const type = ["options", "boolean", "text", "number"].includes(p?.type) ? p.type : null;
864
+ if (!name || !type) return [];
865
+ const options = Array.isArray(p.options) ? [...new Set(p.options.filter(scalar).map(String))].slice(0, 30) : [];
866
+ if (type === "options" && !options.length) return [];
867
+ return [
868
+ {
869
+ name,
870
+ type,
871
+ ...type === "options" ? { options } : {},
872
+ ...scalar(p.default) ? { default: p.default } : {},
873
+ ...typeof p.description === "string" && p.description.trim() ? { description: p.description.trim().slice(0, 120) } : {}
874
+ }
875
+ ];
876
+ });
877
+ return props.length ? props.slice(0, MAX_PROPS) : void 0;
878
+ }
879
+ function projectNameOf(value) {
880
+ return typeof value === "string" && /^[\w@./-]{1,120}$/.test(value.trim()) ? value.trim() : void 0;
881
+ }
882
+ function originOf(url) {
883
+ try {
884
+ const u = new URL(url.includes("://") ? url : `http://${url}`);
885
+ return u.protocol === "http:" || u.protocol === "https:" ? u.origin : null;
886
+ } catch {
887
+ return null;
888
+ }
889
+ }
890
+ function isLocalHost(hostname) {
891
+ const h = hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
892
+ if (!h) return false;
893
+ if (h === "localhost" || h === "0.0.0.0" || h === "::1" || h === "::") return true;
894
+ if (/\.(localhost|local|test|internal|lan|home\.arpa)$/.test(h)) return true;
895
+ const v4 = /^(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/.exec(h);
896
+ if (v4) {
897
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
898
+ return a === 127 || a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 169 && b === 254;
899
+ }
900
+ if (h.includes(":")) return /^f[cd][0-9a-f]{2}:/.test(h) || /^fe[89ab][0-9a-f]:/.test(h);
901
+ return !h.includes(".");
902
+ }
903
+ function originKey(origin) {
904
+ return origin.replace(/^(https?:\/\/)(?:127\.0\.0\.1|\[::1\])(?=[:/]|$)/, "$1localhost").replace(/\/$/, "");
905
+ }
906
+
907
+ // src/server.ts
908
+ import { createServer } from "http";
909
+
910
+ // src/attachments.ts
911
+ import { createHash } from "crypto";
912
+ import { existsSync } from "fs";
913
+ import { mkdir, readdir, readFile, rm, stat, writeFile } from "fs/promises";
914
+ import { tmpdir } from "os";
915
+ import { basename, dirname, join as join2 } from "path";
916
+ var FOLDER = "pilot-attachments";
917
+ var MAX_ATTACHMENT_BYTES = 1e7;
918
+ var MAX_INLINE_IMAGE = 35e5;
919
+ var MAX_INLINE_TEXT = 1e5;
920
+ var KEEP_MS = 7 * 24 * 60 * 60 * 1e3;
921
+ function attachmentsDir(base = tmpdir()) {
922
+ return join2(base, FOLDER);
923
+ }
924
+ function extensionOf(type) {
925
+ const given = type.split(";")[0]?.trim().toLowerCase();
926
+ const found = Object.entries(ATTACHMENT_TYPES).find(([, t]) => t === given);
927
+ return found ? found[0] : null;
928
+ }
929
+ function looksLike(bytes, ext) {
930
+ const starts = (...sig) => sig.every((b, i) => bytes[i] === b);
931
+ switch (ext) {
932
+ case "png":
933
+ return starts(137, 80, 78, 71);
934
+ case "jpg":
935
+ return starts(255, 216, 255);
936
+ case "gif":
937
+ return starts(71, 73, 70, 56);
938
+ case "webp":
939
+ return starts(82, 73, 70, 70) && bytes.subarray(8, 12).toString("latin1") === "WEBP";
940
+ case "pdf":
941
+ return bytes.subarray(0, 5).toString("latin1") === "%PDF-";
942
+ default:
943
+ if (bytes.includes(0)) return false;
944
+ try {
945
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes);
946
+ return true;
947
+ } catch {
948
+ return false;
949
+ }
950
+ }
951
+ }
952
+ async function saveAttachment(bytes, type, dir = attachmentsDir()) {
953
+ const ext = extensionOf(type);
954
+ if (!ext || bytes.length === 0 || bytes.length > MAX_ATTACHMENT_BYTES || !looksLike(bytes, ext)) return null;
955
+ const id = `${createHash("sha256").update(bytes).digest("hex")}.${ext}`;
956
+ await mkdir(dir, { recursive: true });
957
+ const path = join2(dir, id);
958
+ if (!existsSync(path)) await writeFile(path, bytes);
959
+ return id;
960
+ }
961
+ function withAttachmentPaths(job, dir = attachmentsDir()) {
962
+ const request = job.changeSet.request;
963
+ const kept = (files) => {
964
+ if (!Array.isArray(files)) return void 0;
965
+ const valid = files.filter((file) => typeof file?.id === "string" && ATTACHMENT_ID.test(file.id) && existsSync(join2(dir, file.id))).slice(0, 20).map((file) => ({
966
+ id: file.id,
967
+ name: typeof file.name === "string" ? file.name.slice(0, 200) : void 0,
968
+ path: join2(dir, file.id)
969
+ }));
970
+ return valid.length ? valid : void 0;
971
+ };
972
+ if (request && request.kind !== "comment")
973
+ return { ...job, changeSet: { ...job.changeSet, request: { ...request, attachments: kept(request.attachments) } } };
974
+ if (request?.kind !== "comment") return job;
975
+ const thread = request.thread.map((message) => message.attachments ? { ...message, attachments: kept(message.attachments) } : message);
976
+ return { ...job, changeSet: { ...job.changeSet, request: { ...request, thread } } };
977
+ }
978
+ function newAttachments(job) {
979
+ const request = job.changeSet.request;
980
+ let files;
981
+ if (request && request.kind !== "comment") files = request.attachments ?? [];
982
+ else if (request?.kind === "comment") {
983
+ const lastReply = request.thread.map((m) => m.from).lastIndexOf("agent");
984
+ files = request.thread.slice(lastReply + 1).flatMap((m) => m.attachments ?? []);
985
+ } else return [];
986
+ return files.filter((f) => !!f.path && basename(dirname(f.path)) === FOLDER && ATTACHMENT_ID.test(basename(f.path)));
987
+ }
988
+ async function attachmentBlocks(job) {
989
+ const blocks = [];
990
+ for (const file of newAttachments(job)) {
991
+ const path = file.path;
992
+ const kind = attachmentKind(path);
993
+ if (kind === "pdf") continue;
994
+ try {
995
+ const size = (await stat(path)).size;
996
+ if (kind === "image") {
997
+ if (size > MAX_INLINE_IMAGE) continue;
998
+ const ext = basename(path).split(".").pop();
999
+ blocks.push({ type: "image", data: (await readFile(path)).toString("base64"), mimeType: ATTACHMENT_TYPES[ext] });
1000
+ } else {
1001
+ if (size > MAX_INLINE_TEXT) continue;
1002
+ const name = file.name ?? basename(path);
1003
+ blocks.push({
1004
+ type: "text",
1005
+ text: `Attached file ${name}, as the designer sent it:
1006
+
1007
+ ${await readFile(path, "utf8")}
1008
+
1009
+ (end of ${name})`
1010
+ });
1011
+ }
1012
+ } catch {
1013
+ }
1014
+ }
1015
+ return blocks;
1016
+ }
1017
+ async function sweepAttachments(dir = attachmentsDir(), now = Date.now()) {
1018
+ try {
1019
+ for (const name of await readdir(dir)) {
1020
+ if (!ATTACHMENT_ID.test(name)) continue;
1021
+ const path = join2(dir, name);
1022
+ if (now - (await stat(path)).mtimeMs > KEEP_MS) await rm(path, { force: true });
1023
+ }
1024
+ } catch {
1025
+ }
1026
+ }
1027
+
1028
+ // src/components.ts
1029
+ import { existsSync as existsSync2, readdirSync, readFileSync, statSync as statSync2 } from "fs";
1030
+ import { basename as basename2, dirname as dirname2, extname, join as join3 } from "path";
1031
+
1032
+ // src/paths.ts
1033
+ import { relative, sep } from "path";
1034
+ function shownPath(path) {
1035
+ return sep === "\\" ? path.replaceAll("\\", "/") : path;
1036
+ }
1037
+ function relPath(from, to) {
1038
+ return shownPath(relative(from, to));
1039
+ }
1040
+
1041
+ // src/components.ts
1042
+ var SKIP = /* @__PURE__ */ new Set([
1043
+ "node_modules",
1044
+ "dist",
1045
+ "build",
1046
+ "out",
1047
+ "coverage",
1048
+ "vendor",
1049
+ ".git",
1050
+ ".next",
1051
+ ".nuxt",
1052
+ ".svelte-kit",
1053
+ ".output",
1054
+ ".vercel",
1055
+ ".turbo",
1056
+ ".cache",
1057
+ "storybook-static",
1058
+ "__tests__",
1059
+ "__mocks__"
1060
+ ]);
1061
+ var EXTENSIONS = /* @__PURE__ */ new Set([".jsx", ".tsx", ".js", ".vue", ".svelte"]);
1062
+ var NOT_COMPONENTS = /\.(test|spec|stories|story|d)\.[jt]sx?$/;
1063
+ var ROUTE_FILES = /^(page|layout|template|loading|error|not-found|default|route|_app|_document)\.[jt]sx?$/;
1064
+ var MAX_FILES = 8e3;
1065
+ var MAX_FILE_BYTES = 512e3;
1066
+ var BUDGET_MS = 1500;
1067
+ var cache = /* @__PURE__ */ new Map();
1068
+ function projectComponents(folders) {
1069
+ const roots = [...new Set(folders.map(workspaceRoot))];
1070
+ const out = [];
1071
+ const seen = /* @__PURE__ */ new Set();
1072
+ const deadline = Date.now() + BUDGET_MS;
1073
+ for (const root of roots) {
1074
+ for (const c of scan(root, deadline)) {
1075
+ const key = `${c.name} ${c.file}`;
1076
+ if (!seen.has(key)) {
1077
+ seen.add(key);
1078
+ out.push(c);
1079
+ }
1080
+ }
1081
+ }
1082
+ return out;
1083
+ }
1084
+ function workspaceRoot(folder) {
1085
+ let dir = folder;
1086
+ for (; ; ) {
1087
+ if (isWorkspace(dir)) return dir;
1088
+ const parent = dirname2(dir);
1089
+ if (existsSync2(join3(dir, ".git")) || parent === dir) return folder;
1090
+ dir = parent;
1091
+ }
1092
+ }
1093
+ function isWorkspace(dir) {
1094
+ if (["pnpm-workspace.yaml", "lerna.json", "nx.json", "turbo.json"].some((f) => existsSync2(join3(dir, f)))) return true;
1095
+ try {
1096
+ return "workspaces" in JSON.parse(readFileSync(join3(dir, "package.json"), "utf8"));
1097
+ } catch {
1098
+ return false;
1099
+ }
1100
+ }
1101
+ function scan(root, deadline) {
1102
+ const known = cache.get(root) ?? /* @__PURE__ */ new Map();
1103
+ const now = /* @__PURE__ */ new Map();
1104
+ const out = [];
1105
+ const walk = (dir) => {
1106
+ let entries;
1107
+ try {
1108
+ entries = readdirSync(dir, { withFileTypes: true });
1109
+ } catch {
1110
+ return;
1111
+ }
1112
+ for (const entry of entries) {
1113
+ if (now.size >= MAX_FILES || Date.now() > deadline) return;
1114
+ const name = entry.name;
1115
+ if (SKIP.has(name) || name.startsWith(".")) continue;
1116
+ const path = join3(dir, name);
1117
+ if (entry.isDirectory()) {
1118
+ walk(path);
1119
+ continue;
1120
+ }
1121
+ if (!entry.isFile() || !EXTENSIONS.has(extname(name)) || NOT_COMPONENTS.test(name) || ROUTE_FILES.test(name)) continue;
1122
+ let stat2;
1123
+ try {
1124
+ stat2 = statSync2(path);
1125
+ } catch {
1126
+ continue;
1127
+ }
1128
+ if (stat2.size > MAX_FILE_BYTES) continue;
1129
+ const before = known.get(path);
1130
+ const cached = before && before.mtime === stat2.mtimeMs ? before : { mtime: stat2.mtimeMs, components: read(path) };
1131
+ now.set(path, cached);
1132
+ const file = relPath(root, path);
1133
+ for (const c of cached.components) out.push({ name: c.name, file, line: c.line });
1134
+ }
1135
+ };
1136
+ walk(root);
1137
+ cache.set(root, now);
1138
+ return out;
1139
+ }
1140
+ function fileComponentName(path) {
1141
+ return basename2(path, extname(path)).split(/[-_.\s]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join("");
1142
+ }
1143
+ var NAME = "[A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*";
1144
+ var FUNCTION = new RegExp(`^\\s*(export\\s+)?(?:default\\s+)?(?:async\\s+)?function\\s+(${NAME})\\b`);
1145
+ var CONSTANT = new RegExp(`^\\s*(export\\s+)?(?:const|let|var)\\s+(${NAME})\\s*(?::[^=]+)?=\\s*(.*)$`);
1146
+ var COMPONENT_VALUE = /^(?:\(|async\s*\(|function\b|[A-Za-z_$][\w$]*\s*=>|(?:React\.)?(?:forwardRef|memo|lazy)\b|styled[.(]|defineComponent\b|component\$)/;
1147
+ function read(path) {
1148
+ const ext = extname(path);
1149
+ if (ext === ".vue" || ext === ".svelte") return [{ name: fileComponentName(path), line: 1 }];
1150
+ let source;
1151
+ try {
1152
+ source = readFileSync(path, "utf8");
1153
+ } catch {
1154
+ return [];
1155
+ }
1156
+ if (!/<[A-Za-z]|styled[.(]/.test(source)) return [];
1157
+ const found = [];
1158
+ const lines = source.split("\n");
1159
+ for (let i = 0; i < lines.length; i++) {
1160
+ const line = lines[i];
1161
+ const fn = FUNCTION.exec(line);
1162
+ const constant = fn ? null : CONSTANT.exec(line);
1163
+ const m = fn ?? constant;
1164
+ if (!m) continue;
1165
+ const name = m[2];
1166
+ if (constant && !COMPONENT_VALUE.test((constant[3] ?? "").trim())) continue;
1167
+ const exported = !!m[1] || new RegExp(`export\\s+default\\s+${name}\\b|export\\s*\\{[^}]*\\b${name}\\b[^}]*\\}`).test(source);
1168
+ if (exported && !found.some((f) => f.name === name)) found.push({ name, line: i + 1 });
1169
+ }
1170
+ return found;
1171
+ }
1172
+
1173
+ // src/skills.ts
1174
+ import { existsSync as existsSync3, readdirSync as readdirSync2, readFileSync as readFileSync2, statSync as statSync3 } from "fs";
1175
+ import { homedir as homedir2 } from "os";
1176
+ import { dirname as dirname3, join as join4 } from "path";
1177
+ function skillFolders(cli, project, home = homedir2()) {
1178
+ const folders = [...projectRoots(project).flatMap((dir) => cli.skills.project.map((rel) => join4(dir, rel))), ...cli.skills.home.map((rel) => join4(home, rel))];
1179
+ return [...new Set(folders)];
1180
+ }
1181
+ function projectRoots(project) {
1182
+ const roots = [project];
1183
+ let dir = project;
1184
+ while (!existsSync3(join4(dir, ".git"))) {
1185
+ const up = dirname3(dir);
1186
+ if (up === dir) return [project];
1187
+ dir = up;
1188
+ roots.push(dir);
1189
+ }
1190
+ return roots;
1191
+ }
1192
+ function findSkills(folders) {
1193
+ const found = /* @__PURE__ */ new Map();
1194
+ for (const folder of folders) {
1195
+ let entries;
1196
+ try {
1197
+ entries = readdirSync2(folder);
1198
+ } catch {
1199
+ continue;
1200
+ }
1201
+ for (const entry of entries.sort()) {
1202
+ if (entry.startsWith(".")) continue;
1203
+ const meta = readSkill(join4(folder, entry, "SKILL.md"));
1204
+ if (!meta) continue;
1205
+ const name = meta.name || entry;
1206
+ if (!SKILL_NAME.test(name) || found.has(name)) continue;
1207
+ found.set(name, { name, ...meta.description ? { description: meta.description } : {}, ...meta.author ? { author: meta.author } : {} });
1208
+ }
1209
+ }
1210
+ return [...found.values()].sort((a, b) => a.name.localeCompare(b.name));
1211
+ }
1212
+ var MAX_SKILL_BYTES = 256e3;
1213
+ var MAX_DESCRIPTION = 300;
1214
+ var MAX_AUTHOR = 60;
1215
+ function readSkill(file) {
1216
+ try {
1217
+ if (statSync3(file).size > MAX_SKILL_BYTES) return null;
1218
+ const text = readFileSync2(file, "utf8");
1219
+ const meta = frontmatter(text);
1220
+ const description = meta.description?.replace(/\s+/g, " ").trim();
1221
+ const author = (meta.author ?? metadataValue(text, "author"))?.replace(/\s+/g, " ").trim().slice(0, MAX_AUTHOR);
1222
+ return {
1223
+ name: meta.name?.trim(),
1224
+ description: description && description.length > MAX_DESCRIPTION ? `${description.slice(0, MAX_DESCRIPTION - 1).trimEnd()}\u2026` : description,
1225
+ ...author ? { author } : {}
1226
+ };
1227
+ } catch {
1228
+ return null;
1229
+ }
1230
+ }
1231
+ function frontmatter(text) {
1232
+ const block = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text)?.[1];
1233
+ if (block === void 0) return {};
1234
+ const lines = block.split(/\r?\n/);
1235
+ const out = {};
1236
+ for (let i = 0; i < lines.length; i++) {
1237
+ const pair = /^([A-Za-z][\w-]*):[ \t]*(.*)$/.exec(lines[i]);
1238
+ if (!pair) continue;
1239
+ const key = pair[1];
1240
+ let value = pair[2].trim();
1241
+ const more = [];
1242
+ while (i + 1 < lines.length && (/^[ \t]+\S/.test(lines[i + 1]) || !lines[i + 1].trim())) more.push(lines[++i].trim());
1243
+ if (/^[>|][+-]?$/.test(value)) value = more.filter(Boolean).join(value.startsWith("|") ? "\n" : " ");
1244
+ else if (more.some(Boolean)) value = [value, ...more].filter(Boolean).join(" ");
1245
+ out[key] = unquote(value);
1246
+ }
1247
+ return out;
1248
+ }
1249
+ function metadataValue(text, key) {
1250
+ const block = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text)?.[1];
1251
+ if (block === void 0) return void 0;
1252
+ const lines = block.split(/\r?\n/);
1253
+ const start = lines.findIndex((l) => /^metadata:[ \t]*$/.test(l));
1254
+ if (start < 0) return void 0;
1255
+ for (const line of lines.slice(start + 1)) {
1256
+ if (!/^[ \t]+\S/.test(line)) break;
1257
+ const pair = new RegExp(`^[ \\t]+${key}:[ \\t]*(.+)$`).exec(line);
1258
+ if (pair) return unquote(pair[1].trim());
1259
+ }
1260
+ return void 0;
1261
+ }
1262
+ function unquote(value) {
1263
+ if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) return value.slice(1, -1).replace(/''/g, "'");
1264
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) return value.slice(1, -1).replace(/\\(["\\])/g, "$1").replace(/\\n/g, "\n");
1265
+ return value;
1266
+ }
1267
+
1268
+ // src/tokenFiles.ts
1269
+ import { readdirSync as readdirSync3, readFileSync as readFileSync3, statSync as statSync4 } from "fs";
1270
+ import { basename as basename3, dirname as dirname4, join as join5 } from "path";
1271
+ var MAX_FILES2 = 8e3;
1272
+ var MAX_FILE_BYTES2 = 512e3;
1273
+ var MAX_TOKENS = 1e3;
1274
+ var BUDGET_MS2 = 1500;
1275
+ function isTokenJson(path) {
1276
+ const name = basename3(path).toLowerCase();
1277
+ if (!name.endsWith(".json") || name === "package.json" || name.startsWith("tsconfig")) return false;
1278
+ return /(^|[.-])(design-)?tokens?\.json$/.test(name) || /(^|[\\/])(design-)?tokens?$/.test(dirname4(path).toLowerCase());
1279
+ }
1280
+ function isTokenSass(path) {
1281
+ const name = basename3(path).toLowerCase();
1282
+ return /\.s[ac]ss$/.test(name) && /(token|variable|vars?\b|theme|colou?r|spacing|typograph|radius|radii|shadow|breakpoint)/.test(name);
1283
+ }
1284
+ var cache2 = /* @__PURE__ */ new Map();
1285
+ function fileTokens(folders) {
1286
+ const out = [];
1287
+ const seen = /* @__PURE__ */ new Set();
1288
+ const deadline = Date.now() + BUDGET_MS2;
1289
+ for (const root of new Set(folders.map(workspaceRoot))) {
1290
+ for (const t of scan2(root, deadline)) {
1291
+ if (out.length >= MAX_TOKENS) return out;
1292
+ if (!seen.has(t.name)) {
1293
+ seen.add(t.name);
1294
+ out.push(t);
1295
+ }
1296
+ }
1297
+ }
1298
+ return out;
1299
+ }
1300
+ function scan2(root, deadline) {
1301
+ const known = cache2.get(root) ?? /* @__PURE__ */ new Map();
1302
+ const now = /* @__PURE__ */ new Map();
1303
+ const out = [];
1304
+ let files = 0;
1305
+ const walk = (dir) => {
1306
+ let entries;
1307
+ try {
1308
+ entries = readdirSync3(dir, { withFileTypes: true });
1309
+ } catch {
1310
+ return;
1311
+ }
1312
+ for (const entry of entries) {
1313
+ if (files >= MAX_FILES2 || Date.now() > deadline) return;
1314
+ const name = entry.name;
1315
+ if (SKIP.has(name) || name.startsWith(".")) continue;
1316
+ const path = join5(dir, name);
1317
+ if (entry.isDirectory()) {
1318
+ walk(path);
1319
+ continue;
1320
+ }
1321
+ files++;
1322
+ const json2 = isTokenJson(path);
1323
+ if (!entry.isFile() || !(json2 || isTokenSass(path))) continue;
1324
+ let stat2;
1325
+ try {
1326
+ stat2 = statSync4(path);
1327
+ } catch {
1328
+ continue;
1329
+ }
1330
+ if (stat2.size > MAX_FILE_BYTES2) continue;
1331
+ const before = known.get(path);
1332
+ const file = relPath(root, path);
1333
+ const cached = before && before.mtime === stat2.mtimeMs ? before : { mtime: stat2.mtimeMs, tokens: read2(path, file, json2) };
1334
+ now.set(path, cached);
1335
+ out.push(...cached.tokens);
1336
+ }
1337
+ };
1338
+ walk(root);
1339
+ cache2.set(root, now);
1340
+ return out;
1341
+ }
1342
+ function read2(path, file, json2) {
1343
+ let text;
1344
+ try {
1345
+ text = readFileSync3(path, "utf8");
1346
+ } catch {
1347
+ return [];
1348
+ }
1349
+ return json2 ? jsonTokens(text, file) : sassTokens(text, file);
1350
+ }
1351
+ function jsonTokens(text, file) {
1352
+ let data;
1353
+ try {
1354
+ data = JSON.parse(text);
1355
+ } catch {
1356
+ return [];
1357
+ }
1358
+ const raw = /* @__PURE__ */ new Map();
1359
+ const walk = (node, path) => {
1360
+ if (!node || typeof node !== "object" || Array.isArray(node)) return;
1361
+ const n = node;
1362
+ const value = "$value" in n ? n.$value : "value" in n && typeof n.value !== "object" ? n.value : void 0;
1363
+ if (value !== void 0) {
1364
+ if ((typeof value === "string" || typeof value === "number") && path.length) raw.set(path.join("."), String(value));
1365
+ return;
1366
+ }
1367
+ for (const [key, child] of Object.entries(n)) if (!key.startsWith("$")) walk(child, [...path, key]);
1368
+ };
1369
+ walk(data, []);
1370
+ const lines = text.split("\n");
1371
+ const out = [];
1372
+ for (const [name, value] of raw) {
1373
+ const resolved = resolve(value, (ref) => raw.get(ref), /\{([^{}]+)\}/g);
1374
+ if (resolved === null) continue;
1375
+ const last = name.split(".").at(-1);
1376
+ const at = lines.findIndex((l) => l.includes(`"${last}"`));
1377
+ out.push({ name, value: resolved, file, ...at >= 0 ? { line: at + 1 } : {} });
1378
+ }
1379
+ return out;
1380
+ }
1381
+ function sassTokens(text, file) {
1382
+ const raw = /* @__PURE__ */ new Map();
1383
+ text.split("\n").forEach((line, i) => {
1384
+ const m = /^\s*\$([\w-]+)\s*:\s*([^;]+?)\s*(?:!default|!global)*\s*;/.exec(line);
1385
+ if (m && !raw.has(m[1])) raw.set(m[1], { value: m[2], line: i + 1 });
1386
+ });
1387
+ const out = [];
1388
+ for (const [name, { value, line }] of raw) {
1389
+ if (/[\w-]\([^)]*\$|map-get|\bif\(|^\(/.test(value)) continue;
1390
+ const resolved = resolve(value, (ref) => raw.get(ref)?.value, /\$([\w-]+)/g);
1391
+ if (resolved === null || resolved.includes("$")) continue;
1392
+ out.push({ name: `$${name}`, value: resolved, file, line });
1393
+ }
1394
+ return out;
1395
+ }
1396
+ function resolve(value, get, pattern) {
1397
+ let v = value;
1398
+ for (let depth = 0; depth < 8; depth++) {
1399
+ let missing = false;
1400
+ const next = v.replace(pattern, (_, ref) => {
1401
+ const found = get(ref);
1402
+ if (found === void 0) missing = true;
1403
+ return found ?? "";
1404
+ });
1405
+ if (missing) return null;
1406
+ if (next === v) return v.trim();
1407
+ v = next;
1408
+ }
1409
+ return null;
1410
+ }
1411
+
1412
+ // src/hub.ts
1413
+ import { randomUUID } from "crypto";
1414
+ var AGENT_TTL = 3e4;
1415
+ var Hub = class {
1416
+ constructor(now = Date.now) {
1417
+ this.now = now;
1418
+ }
1419
+ now;
1420
+ agents = /* @__PURE__ */ new Map();
1421
+ pages = /* @__PURE__ */ new Set();
1422
+ jobs = /* @__PURE__ */ new Map();
1423
+ waiters = [];
1424
+ checks = /* @__PURE__ */ new Map();
1425
+ // Agents
1426
+ /** An agent works on pages of `origin` (again: also how a remote one says it's alive). */
1427
+ register(info, origin) {
1428
+ const key = originKey(origin);
1429
+ const known = this.agents.get(info.id);
1430
+ const { folder, kind, setup: rawSetup, ...rest } = info;
1431
+ const setup = setupOf(rawSetup);
1432
+ const shown = { ...rest, ...setup ? { setup } : {} };
1433
+ this.agents.set(info.id, {
1434
+ info: shown,
1435
+ origin: key,
1436
+ seen: this.now(),
1437
+ folder: folder ?? known?.folder,
1438
+ kind: isAgentKind(kind) ? kind : known?.kind,
1439
+ // A sign-in asked for stays asked until the runner takes it, or the agent no longer needs one.
1440
+ ...known?.signIn && setup?.canSignIn ? { signIn: true } : {}
1441
+ });
1442
+ if (!known || known.origin !== key) {
1443
+ if (known) this.notifyAgents(known.origin);
1444
+ this.notifyAgents(key);
1445
+ } else if (JSON.stringify(known.info) !== JSON.stringify(shown)) {
1446
+ this.notifyAgents(key);
1447
+ }
1448
+ }
1449
+ /**
1450
+ * The designer asked to sign in from the page of `origin`: each agent there
1451
+ * that can start its sign-in (AgentSetup.canSignIn) gets the request, which
1452
+ * its runner takes (takeSignIn). How many got it: 0 when none can.
1453
+ */
1454
+ requestSignIn(origin) {
1455
+ const key = originKey(origin);
1456
+ let n = 0;
1457
+ for (const agent of this.agents.values()) {
1458
+ if (agent.origin !== key || !agent.info.setup?.canSignIn) continue;
1459
+ agent.signIn = true;
1460
+ n++;
1461
+ }
1462
+ return n;
1463
+ }
1464
+ /** Whether the designer asked agent `agentId` to sign in (requestSignIn) since it last asked: the request is taken. */
1465
+ takeSignIn(agentId) {
1466
+ const agent = this.agents.get(agentId);
1467
+ if (!agent?.signIn) return false;
1468
+ agent.signIn = false;
1469
+ return true;
1470
+ }
1471
+ /**
1472
+ * The agent is gone (its process ended or it stopped pinging): its waits
1473
+ * end, and the jobs it was working on go back to the queue, for another
1474
+ * chat (or this one, back), instead of staying "working" for nobody.
1475
+ */
1476
+ unregister(agentId) {
1477
+ const agent = this.agents.get(agentId);
1478
+ if (!agent) return;
1479
+ this.agents.delete(agentId);
1480
+ for (const w of this.waiters.filter((w2) => w2.agentId === agentId)) this.endWait(w, null);
1481
+ for (const job of this.jobs.values()) {
1482
+ if (job.status === "working" && job.agent?.id === agentId) this.update(job, { status: "queued", takenAt: void 0, activeAt: void 0 });
1483
+ }
1484
+ this.notifyAgents(agent.origin);
1485
+ this.dispatch(agent.origin);
1486
+ }
1487
+ /** An agent's info as pages see it (no folder). */
1488
+ shown(info) {
1489
+ return this.agents.get(info.id)?.info ?? { id: info.id, label: info.label };
1490
+ }
1491
+ /** The project folders of the agents working on pages of `origin`: where its components are read from. */
1492
+ folders(origin) {
1493
+ const key = originKey(origin);
1494
+ return [...new Set([...this.agents.values()].filter((a) => a.origin === key && a.folder).map((a) => a.folder))];
1495
+ }
1496
+ /** Where the agents working on pages of `origin` read their skills from (each agent's own folders, skills.ts): for the `/` list. */
1497
+ skillFolders(origin) {
1498
+ const key = originKey(origin);
1499
+ const agents = [...this.agents.values()].filter((a) => a.origin === key && a.folder && a.kind);
1500
+ return [...new Set(agents.flatMap((a) => skillFolders(AGENTS[a.kind], a.folder)))];
1501
+ }
1502
+ /** Drops agents not heard from in AGENT_TTL (`keep`: the ones in this process, always alive). */
1503
+ sweep(keep = /* @__PURE__ */ new Set()) {
1504
+ const cutoff = this.now() - AGENT_TTL;
1505
+ for (const [id, agent] of this.agents) {
1506
+ if (!keep.has(id) && agent.seen < cutoff && !this.waiters.some((w) => w.agentId === id)) this.unregister(id);
1507
+ }
1508
+ }
1509
+ /**
1510
+ * The designer closed Pilot on `origin` (the whole site): its open pages
1511
+ * close it too. Nothing else: jobs aren't touched (a run on one finishes),
1512
+ * and Pilot keeps running for the site, so the shortcut opens it again.
1513
+ */
1514
+ quit(origin) {
1515
+ this.sendTo(originKey(origin), { type: "quit" });
1516
+ }
1517
+ /**
1518
+ * The pages with Pilot open in a browser now, each site and project once,
1519
+ * leaving out the sites Pilot already runs for: where `npx usepilot` looks
1520
+ * for its own project's pages (by their project's name), without a URL.
1521
+ */
1522
+ openPages() {
1523
+ const seen = /* @__PURE__ */ new Map();
1524
+ for (const page of this.pages) {
1525
+ if (this.hasAgents(page.origin)) continue;
1526
+ seen.set(`${page.origin} ${page.project ?? ""}`, { origin: page.origin, ...page.project ? { project: page.project } : {} });
1527
+ }
1528
+ return [...seen.values()];
1529
+ }
1530
+ /** 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. */
1531
+ launch(info, origin) {
1532
+ this.register(info, origin);
1533
+ return this.sendTo(originKey(origin), { type: "launch", agent: this.shown(info) });
1534
+ }
1535
+ /**
1536
+ * The agent's next job for its origin: the oldest queued one right away, or
1537
+ * the next one posted within `timeoutMs` (null after that, or when `signal`
1538
+ * aborts). Taking a job marks it working, by this agent.
1539
+ */
1540
+ wait(info, origin, timeoutMs, signal) {
1541
+ this.register(info, origin);
1542
+ const key = originKey(origin);
1543
+ const queued = this.oldestQueued(key);
1544
+ if (queued) return Promise.resolve({ job: this.take(queued, this.shown(info)) });
1545
+ return new Promise((resolve5) => {
1546
+ const waiter = {
1547
+ agentId: info.id,
1548
+ origin: key,
1549
+ resolve: (job) => {
1550
+ clearTimeout(timer);
1551
+ signal?.removeEventListener("abort", onAbort);
1552
+ resolve5({ job });
1553
+ }
1554
+ };
1555
+ const timer = setTimeout(() => this.endWait(waiter, null), timeoutMs);
1556
+ const onAbort = () => this.endWait(waiter, null);
1557
+ signal?.addEventListener("abort", onAbort, { once: true });
1558
+ this.waiters.push(waiter);
1559
+ this.notifyAgents(key);
1560
+ });
1561
+ }
1562
+ /**
1563
+ * The agent applied a job: done, with its notes, and its `question` for
1564
+ * the designer if it asked one (the page shows it and holds the job until
1565
+ * the answer, see answer). A job asks once: a question on an answered job
1566
+ * is dropped. Null for a job the hub doesn't know.
1567
+ */
1568
+ done(agentId, jobId, notes, question, props, extra = {}) {
1569
+ const job = this.jobs.get(jobId);
1570
+ if (!job || job.status === "cancelled") return null;
1571
+ const agent = this.agents.get(agentId)?.info ?? job.agent;
1572
+ const asks = question && !job.answer ? { question } : {};
1573
+ const listed2 = props?.length && job.changeSet.request?.kind === "props" ? { props } : {};
1574
+ this.update(job, {
1575
+ status: "done",
1576
+ agent,
1577
+ notes: notes?.trim() || void 0,
1578
+ doneAt: new Date(this.now()).toISOString(),
1579
+ ...asks,
1580
+ ...listed2,
1581
+ // 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.
1582
+ session: extra.session ?? job.session,
1583
+ error: extra.error,
1584
+ allow: extra.allow
1585
+ });
1586
+ return job;
1587
+ }
1588
+ /**
1589
+ * The designer answered a done job's question: the job goes back to the
1590
+ * queue with the answer, preferably to the agent that asked. Null when it
1591
+ * can't (not done, no question, or answered already).
1592
+ */
1593
+ answer(origin, jobId, answer) {
1594
+ const job = this.jobs.get(jobId);
1595
+ if (!job || job.origin !== originKey(origin) || job.status !== "done" || !job.question || job.answer) return null;
1596
+ this.update(job, { status: "queued", answer, notes: void 0 });
1597
+ this.dispatch(job.origin);
1598
+ return job;
1599
+ }
1600
+ /**
1601
+ * An agent asks for Pilot's width check of a task's element: the open
1602
+ * pages of the job's origin get a `check` event, and the one that has the
1603
+ * job measures it and posts the answer (checkResult). Null when no page
1604
+ * is open, the hub doesn't know the job, or no answer comes in `timeoutMs`.
1605
+ */
1606
+ check(jobId, timeoutMs) {
1607
+ const job = this.jobs.get(jobId);
1608
+ if (!job) return Promise.resolve(null);
1609
+ const requestId = randomUUID();
1610
+ return new Promise((resolve5) => {
1611
+ const timer = setTimeout(() => finish(null), timeoutMs);
1612
+ const finish = (check) => {
1613
+ clearTimeout(timer);
1614
+ this.checks.delete(requestId);
1615
+ resolve5(check);
1616
+ };
1617
+ this.checks.set(requestId, { origin: job.origin, resolve: finish });
1618
+ if (!this.sendTo(job.origin, { type: "check", requestId, jobId })) finish(null);
1619
+ });
1620
+ }
1621
+ /** A page's answer to a width check: false when nothing waits for it from that origin. */
1622
+ checkResult(origin, requestId, check) {
1623
+ const pending = this.checks.get(requestId);
1624
+ if (!pending || pending.origin !== originKey(origin)) return false;
1625
+ pending.resolve(check);
1626
+ return true;
1627
+ }
1628
+ // Pages
1629
+ addPage(page) {
1630
+ const conn = { ...page, origin: originKey(page.origin) };
1631
+ this.pages.add(conn);
1632
+ conn.send(this.agentsEvent(conn.origin));
1633
+ for (const job of this.jobs.values()) {
1634
+ if (job.origin === conn.origin) conn.send({ type: "job", job: structuredClone(job) });
1635
+ }
1636
+ return () => this.pages.delete(conn);
1637
+ }
1638
+ /** Whether any agent works on pages of `origin`: only then does the hub take jobs from it. */
1639
+ hasAgents(origin) {
1640
+ const key = originKey(origin);
1641
+ return [...this.agents.values()].some((a) => a.origin === key);
1642
+ }
1643
+ /**
1644
+ * A job from a page: new ones are queued (and go to a waiting agent);
1645
+ * posting one the hub already has changes nothing, so a page can post its
1646
+ * unfinished jobs again whenever it connects. One the page knows as working,
1647
+ * by an agent still here, stays that agent's.
1648
+ */
1649
+ postJob(origin, post) {
1650
+ const key = originKey(origin);
1651
+ const known = this.jobs.get(post.id);
1652
+ if (known) return known;
1653
+ const at = new Date(this.now()).toISOString();
1654
+ const stillWorking = post.status === "working" && post.agent && this.agents.has(post.agent.id);
1655
+ const job = {
1656
+ id: post.id,
1657
+ origin: key,
1658
+ changeSet: post.changeSet,
1659
+ status: stillWorking ? "working" : "queued",
1660
+ // A follow-up (or an answered question) keeps its agent as the one to prefer (see dispatch).
1661
+ agent: stillWorking || post.attempt === 2 || post.answer ? post.agent : void 0,
1662
+ attempt: post.attempt ?? 1,
1663
+ differences: post.differences,
1664
+ issues: post.issues,
1665
+ question: post.question,
1666
+ answer: post.answer,
1667
+ session: post.session,
1668
+ createdAt: at,
1669
+ updatedAt: at
1670
+ };
1671
+ this.jobs.set(job.id, job);
1672
+ this.sendTo(key, { type: "job", job });
1673
+ if (job.status === "queued") this.dispatch(key);
1674
+ return job;
1675
+ }
1676
+ /** The designer took a job back before it was done. */
1677
+ cancel(origin, jobId) {
1678
+ const job = this.jobs.get(jobId);
1679
+ if (!job || job.origin !== originKey(origin) || job.status === "done") return null;
1680
+ this.update(job, { status: "cancelled" });
1681
+ return job;
1682
+ }
1683
+ /**
1684
+ * Some changes of a done job didn't come out as the designer set them (or
1685
+ * a task's width check found problems, `issues`): the job goes back to
1686
+ * the queue once, as a follow-up with the `differences`,
1687
+ * preferably to the agent that did it. Null when it can't (not done, or
1688
+ * already a follow-up: then the page takes what the code gives).
1689
+ */
1690
+ retry(origin, jobId, differences, issues) {
1691
+ const job = this.jobs.get(jobId);
1692
+ if (!job || job.origin !== originKey(origin) || job.status !== "done" || (job.attempt ?? 1) >= 2) return null;
1693
+ this.update(job, { status: "queued", attempt: 2, differences, issues, notes: void 0 });
1694
+ this.dispatch(job.origin);
1695
+ return job;
1696
+ }
1697
+ job(id) {
1698
+ return this.jobs.get(id);
1699
+ }
1700
+ // Internals
1701
+ oldestQueued(origin) {
1702
+ return [...this.jobs.values()].filter((j) => j.origin === origin && j.status === "queued").sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0];
1703
+ }
1704
+ take(job, agent) {
1705
+ this.update(job, { status: "working", agent, takenAt: new Date(this.now()).toISOString(), activeAt: void 0 });
1706
+ return job;
1707
+ }
1708
+ /** The agent running `jobId` is at work (its output came): the page sees the run isn't quiet. Ignored for another agent's job, or one not running. */
1709
+ activity(agentId, jobId) {
1710
+ const job = this.jobs.get(jobId);
1711
+ if (!job || job.status !== "working" || job.agent?.id !== agentId) return;
1712
+ this.update(job, { activeAt: new Date(this.now()).toISOString() });
1713
+ }
1714
+ /**
1715
+ * Gives the oldest queued job of `origin` to the agent waiting longest
1716
+ * there; a follow-up to the agent that did the job, if it's waiting.
1717
+ */
1718
+ dispatch(origin) {
1719
+ const job = this.oldestQueued(origin);
1720
+ const waiters = this.waiters.filter((w) => w.origin === origin);
1721
+ const waiter = waiters.find((w) => w.agentId === job?.agent?.id) ?? waiters[0];
1722
+ const agent = waiter && this.agents.get(waiter.agentId);
1723
+ if (!waiter || !job || !agent) return;
1724
+ this.endWait(waiter, this.take(job, agent.info));
1725
+ }
1726
+ endWait(waiter, job) {
1727
+ const i = this.waiters.indexOf(waiter);
1728
+ if (i < 0) return;
1729
+ this.waiters.splice(i, 1);
1730
+ waiter.resolve(job);
1731
+ this.notifyAgents(waiter.origin);
1732
+ }
1733
+ update(job, patch) {
1734
+ Object.assign(job, patch, { updatedAt: new Date(this.now()).toISOString() });
1735
+ this.sendTo(job.origin, { type: "job", job });
1736
+ }
1737
+ agentsEvent(origin) {
1738
+ const agents = [...this.agents.values()].filter((a) => a.origin === origin).map((a) => a.info);
1739
+ const waiting = new Set(this.waiters.filter((w) => w.origin === origin).map((w) => w.agentId)).size;
1740
+ return { type: "agents", agents, waiting };
1741
+ }
1742
+ notifyAgents(origin) {
1743
+ this.sendTo(origin, this.agentsEvent(origin));
1744
+ }
1745
+ sendTo(origin, event) {
1746
+ let n = 0;
1747
+ for (const page of this.pages) {
1748
+ if (page.origin !== origin) continue;
1749
+ page.send(structuredClone(event));
1750
+ n++;
1751
+ }
1752
+ return n;
1753
+ }
1754
+ };
1755
+
1756
+ // src/server.ts
1757
+ function startHub(port, hub = new Hub(), options = {}) {
1758
+ const attachments = options.attachments ?? attachmentsDir();
1759
+ void sweepAttachments(attachments);
1760
+ const server = createServer((req, res) => {
1761
+ handle(hub, req, res, attachments).catch((error) => {
1762
+ if (!res.headersSent) json(res, 500, { error: String(error) });
1763
+ });
1764
+ });
1765
+ const sweep = setInterval(() => hub.sweep(localAgents), 5e3);
1766
+ sweep.unref();
1767
+ return new Promise((resolve5, reject) => {
1768
+ server.once("error", (error) => {
1769
+ clearInterval(sweep);
1770
+ reject(error);
1771
+ });
1772
+ server.listen(port, "127.0.0.1", () => {
1773
+ const address = server.address();
1774
+ resolve5({
1775
+ hub,
1776
+ server,
1777
+ port: typeof address === "object" && address ? address.port : port,
1778
+ close: () => new Promise((done) => {
1779
+ clearInterval(sweep);
1780
+ server.closeAllConnections?.();
1781
+ server.close(() => done());
1782
+ })
1783
+ });
1784
+ });
1785
+ });
1786
+ }
1787
+ var localAgents = /* @__PURE__ */ new Set();
1788
+ async function handle(hub, req, res, attachments) {
1789
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
1790
+ const origin = req.headers.origin;
1791
+ const path = url.pathname;
1792
+ if (path === "/health") return json(res, 200, { pilot: true, version: BRIDGE_VERSION });
1793
+ if (path.startsWith("/agents/")) {
1794
+ if (origin) return json(res, 403, { error: "agents only" });
1795
+ if (req.method !== "POST") return json(res, 405, { error: "POST only" });
1796
+ return handleAgent(hub, path.slice("/agents/".length), await body(req), req, res);
1797
+ }
1798
+ if (!origin || originKey(origin) === "null") return json(res, 400, { error: "no origin" });
1799
+ res.setHeader("Access-Control-Allow-Origin", origin);
1800
+ res.setHeader("Vary", "Origin");
1801
+ if (req.method === "OPTIONS") {
1802
+ res.setHeader("Access-Control-Allow-Methods", "POST, GET");
1803
+ res.setHeader("Access-Control-Allow-Headers", "content-type");
1804
+ res.setHeader("Access-Control-Allow-Private-Network", "true");
1805
+ res.writeHead(204).end();
1806
+ return;
1807
+ }
1808
+ if (path === "/events" && req.method === "GET") return events(hub, origin, req, res, projectNameOf(url.searchParams.get("project")));
1809
+ if (path === "/quit" && req.method === "POST") {
1810
+ hub.quit(origin);
1811
+ return json(res, 200, { ok: true });
1812
+ }
1813
+ if (req.method !== "POST") return json(res, 405, { error: "POST only" });
1814
+ if (!hub.hasAgents(origin)) return json(res, 403, { error: "Pilot isn't running for this site: run npx usepilot in your project" });
1815
+ if (path === "/components") return json(res, 200, { components: projectComponents(hub.folders(origin)) });
1816
+ if (path === "/tokens") return json(res, 200, { tokens: fileTokens(hub.folders(origin)) });
1817
+ if (path === "/skills") return json(res, 200, { skills: findSkills(hub.skillFolders(origin)) });
1818
+ if (path === "/attachments") {
1819
+ const type = req.headers["content-type"] ?? "";
1820
+ if (!extensionOf(type)) return json(res, 415, { error: "images (png, jpeg, gif, webp), text files (txt, md, csv, json) and PDFs only" });
1821
+ const bytes = await rawBody(req, MAX_ATTACHMENT_BYTES);
1822
+ if (!bytes) return json(res, 413, { error: `files up to ${MAX_ATTACHMENT_BYTES / 1e6} MB` });
1823
+ const id = await saveAttachment(bytes, type, attachments);
1824
+ return id ? json(res, 201, { id }) : json(res, 400, { error: "not a file of that type" });
1825
+ }
1826
+ if (path === "/setup/sign-in") {
1827
+ const agents = hub.requestSignIn(origin);
1828
+ return agents ? json(res, 202, { agents }) : json(res, 409, { error: "no agent here can sign in from the page" });
1829
+ }
1830
+ const data = await body(req);
1831
+ if (path === "/jobs") {
1832
+ const post = data;
1833
+ if (typeof post?.id !== "string" || !post.changeSet) return json(res, 400, { error: "job needs id and changeSet" });
1834
+ return json(res, 202, { job: hub.postJob(origin, withAttachmentPaths({ ...post, session: sessionOf(post.session) }, attachments)) });
1835
+ }
1836
+ const jobRoute = path.match(/^\/jobs\/([^/]+)\/(cancel|retry|answer)$/);
1837
+ if (jobRoute) {
1838
+ const [, id, action] = jobRoute;
1839
+ const answer = data.answer;
1840
+ if (action === "answer" && (typeof answer !== "string" || !answer.trim())) return json(res, 400, { error: "answer needed" });
1841
+ const job = action === "cancel" ? hub.cancel(origin, decodeURIComponent(id)) : action === "answer" ? hub.answer(origin, decodeURIComponent(id), answer.trim().slice(0, 2e3)) : hub.retry(
1842
+ origin,
1843
+ decodeURIComponent(id),
1844
+ (data.differences ?? []).slice(0, 200),
1845
+ stringsOf(data.issues)
1846
+ );
1847
+ return job ? json(res, 200, { job }) : json(res, 409, { error: `can't ${action} this job` });
1848
+ }
1849
+ const checkRoute = path.match(/^\/checks\/([^/]+)$/);
1850
+ if (checkRoute) {
1851
+ const check = data.check;
1852
+ if (!check || !Array.isArray(check.widths)) return json(res, 400, { error: "check needed" });
1853
+ return hub.checkResult(origin, decodeURIComponent(checkRoute[1]), check) ? json(res, 200, { ok: true }) : json(res, 409, { error: "no check waits for this" });
1854
+ }
1855
+ return json(res, 404, { error: "not found" });
1856
+ }
1857
+ function events(hub, origin, req, res, project) {
1858
+ res.writeHead(200, {
1859
+ "Content-Type": "text/event-stream",
1860
+ "Cache-Control": "no-cache",
1861
+ Connection: "keep-alive"
1862
+ });
1863
+ res.write("retry: 2000\n\n");
1864
+ const send = (event) => res.write(`data: ${JSON.stringify(event)}
1865
+
1866
+ `);
1867
+ const remove = hub.addPage({ origin, project, send });
1868
+ const ping = setInterval(() => res.write(": ping\n\n"), 15e3);
1869
+ req.on("close", () => {
1870
+ clearInterval(ping);
1871
+ remove();
1872
+ });
1873
+ }
1874
+ async function handleAgent(hub, action, data, req, res) {
1875
+ const d = data;
1876
+ if (!d?.agent?.id) return json(res, 400, { error: "agent needed" });
1877
+ switch (action) {
1878
+ case "register":
1879
+ if (!d.origin) return json(res, 400, { error: "origin needed" });
1880
+ hub.register(d.agent, d.origin);
1881
+ return json(res, 200, { ok: true });
1882
+ case "pages":
1883
+ return json(res, 200, { pages: hub.openPages() });
1884
+ case "launch":
1885
+ if (!d.origin) return json(res, 400, { error: "origin needed" });
1886
+ return json(res, 200, { pages: hub.launch(d.agent, d.origin) });
1887
+ case "wait": {
1888
+ if (!d.origin) return json(res, 400, { error: "origin needed" });
1889
+ const aborted = new AbortController();
1890
+ res.on("close", () => aborted.abort());
1891
+ const result = await hub.wait(d.agent, d.origin, Math.min(d.timeoutMs ?? 6e4, 15 * 6e4), aborted.signal);
1892
+ if (!res.writableEnded && !res.destroyed) json(res, 200, result);
1893
+ return;
1894
+ }
1895
+ case "done":
1896
+ if (!d.jobId) return json(res, 400, { error: "jobId needed" });
1897
+ return json(res, 200, {
1898
+ job: hub.done(d.agent.id, d.jobId, d.notes, questionOf(d.question), propsOf(d.props), { session: sessionOf(d.session), error: jobErrorOf(d.error), allow: allowOf(d.allow) })
1899
+ });
1900
+ case "activity":
1901
+ if (!d.jobId) return json(res, 400, { error: "jobId needed" });
1902
+ hub.activity(d.agent.id, d.jobId);
1903
+ return json(res, 200, {});
1904
+ case "job":
1905
+ if (!d.jobId) return json(res, 400, { error: "jobId needed" });
1906
+ return json(res, 200, { job: hub.job(d.jobId) ?? null });
1907
+ case "check": {
1908
+ if (!d.jobId) return json(res, 400, { error: "jobId needed" });
1909
+ const check = await hub.check(d.jobId, Math.min(d.timeoutMs ?? CHECK_TIMEOUT, 2 * 6e4));
1910
+ return json(res, 200, { check });
1911
+ }
1912
+ case "setup":
1913
+ return json(res, 200, { signIn: hub.takeSignIn(d.agent.id) });
1914
+ case "leave":
1915
+ hub.unregister(d.agent.id);
1916
+ return json(res, 200, { ok: true });
1917
+ default:
1918
+ return json(res, 404, { error: "not found" });
1919
+ }
1920
+ }
1921
+ var CHECK_TIMEOUT = 6e4;
1922
+ function stringsOf(value) {
1923
+ if (!Array.isArray(value)) return void 0;
1924
+ return value.filter((v) => typeof v === "string").slice(0, 100).map((v) => v.slice(0, 2e3));
1925
+ }
1926
+ function json(res, status, data) {
1927
+ res.writeHead(status, { "Content-Type": "application/json" });
1928
+ res.end(JSON.stringify(data));
1929
+ }
1930
+ function rawBody(req, max) {
1931
+ return new Promise((resolve5, reject) => {
1932
+ const chunks = [];
1933
+ let size = 0;
1934
+ let over = false;
1935
+ req.on("data", (chunk) => {
1936
+ if (over) return;
1937
+ size += chunk.length;
1938
+ if (size > max) {
1939
+ over = true;
1940
+ resolve5(null);
1941
+ req.resume();
1942
+ return;
1943
+ }
1944
+ chunks.push(chunk);
1945
+ });
1946
+ req.on("end", () => {
1947
+ if (!over) resolve5(Buffer.concat(chunks));
1948
+ });
1949
+ req.on("error", reject);
1950
+ });
1951
+ }
1952
+ function body(req) {
1953
+ return new Promise((resolve5, reject) => {
1954
+ let text = "";
1955
+ req.setEncoding("utf8");
1956
+ req.on("data", (chunk) => {
1957
+ text += chunk;
1958
+ if (text.length > 5e6) reject(new Error("body too large"));
1959
+ });
1960
+ req.on("end", () => {
1961
+ try {
1962
+ resolve5(text ? JSON.parse(text) : {});
1963
+ } catch {
1964
+ resolve5({});
1965
+ }
1966
+ });
1967
+ req.on("error", reject);
1968
+ });
1969
+ }
1970
+
1971
+ // src/agent.ts
1972
+ var LocalApi = class {
1973
+ constructor(hub) {
1974
+ this.hub = hub;
1975
+ }
1976
+ hub;
1977
+ async register(agent, origin) {
1978
+ localAgents.add(agent.id);
1979
+ this.hub.register(agent, origin);
1980
+ }
1981
+ async launch(agent, origin) {
1982
+ localAgents.add(agent.id);
1983
+ return this.hub.launch(agent, origin);
1984
+ }
1985
+ async pages() {
1986
+ return this.hub.openPages();
1987
+ }
1988
+ wait(agent, origin, timeoutMs, signal) {
1989
+ localAgents.add(agent.id);
1990
+ return this.hub.wait(agent, origin, timeoutMs, signal);
1991
+ }
1992
+ async done(agent, jobId, notes, question, props, extra) {
1993
+ return this.hub.done(agent.id, jobId, notes, question, props, extra);
1994
+ }
1995
+ async job(_agent, jobId) {
1996
+ return this.hub.job(jobId) ?? null;
1997
+ }
1998
+ async activity(agent, jobId) {
1999
+ this.hub.activity(agent.id, jobId);
2000
+ }
2001
+ check(_agent, jobId, timeoutMs) {
2002
+ return this.hub.check(jobId, timeoutMs);
2003
+ }
2004
+ async setup(agent) {
2005
+ return { signIn: this.hub.takeSignIn(agent.id) };
2006
+ }
2007
+ async leave(agent) {
2008
+ localAgents.delete(agent.id);
2009
+ this.hub.unregister(agent.id);
2010
+ }
2011
+ };
2012
+ var RemoteApi = class {
2013
+ constructor(port) {
2014
+ this.port = port;
2015
+ }
2016
+ port;
2017
+ async post(action, data, signal) {
2018
+ const res = await fetch(`http://127.0.0.1:${this.port}/agents/${action}`, {
2019
+ method: "POST",
2020
+ headers: { "content-type": "application/json" },
2021
+ body: JSON.stringify(data),
2022
+ signal
2023
+ });
2024
+ if (!res.ok) throw new Error(`Pilot bridge: ${action} failed (${res.status})`);
2025
+ return await res.json();
2026
+ }
2027
+ async register(agent, origin) {
2028
+ await this.post("register", { agent, origin });
2029
+ }
2030
+ async launch(agent, origin) {
2031
+ return (await this.post("launch", { agent, origin })).pages;
2032
+ }
2033
+ async pages() {
2034
+ try {
2035
+ return (await this.post("pages", {})).pages ?? [];
2036
+ } catch (error) {
2037
+ if (isConnectionError(error)) throw error;
2038
+ return [];
2039
+ }
2040
+ }
2041
+ wait(agent, origin, timeoutMs, signal) {
2042
+ return this.post("wait", { agent, origin, timeoutMs }, signal);
2043
+ }
2044
+ async done(agent, jobId, notes, question, props, extra) {
2045
+ return (await this.post("done", { agent, jobId, notes, question, props, ...extra })).job;
2046
+ }
2047
+ async job(agent, jobId) {
2048
+ return (await this.post("job", { agent, jobId })).job;
2049
+ }
2050
+ async activity(agent, jobId) {
2051
+ try {
2052
+ await this.post("activity", { agent, jobId });
2053
+ } catch (error) {
2054
+ if (isConnectionError(error)) throw error;
2055
+ }
2056
+ }
2057
+ async check(agent, jobId, timeoutMs) {
2058
+ return (await this.post("check", { agent, jobId, timeoutMs })).check;
2059
+ }
2060
+ async setup(agent) {
2061
+ return { signIn: !!(await this.post("setup", { agent })).signIn };
2062
+ }
2063
+ async leave(agent) {
2064
+ await this.post("leave", { agent });
2065
+ }
2066
+ };
2067
+ var HEARTBEAT = 1e4;
2068
+ var Bridge = class {
2069
+ constructor(agent, port) {
2070
+ this.agent = agent;
2071
+ this.port = port;
2072
+ }
2073
+ agent;
2074
+ port;
2075
+ api = null;
2076
+ server = null;
2077
+ connecting = null;
2078
+ heartbeat = null;
2079
+ /** The origin this agent works on, once it launched: re-registered after a takeover. */
2080
+ origin = null;
2081
+ /** Whether this process runs the hub. */
2082
+ get isHub() {
2083
+ return !!this.server;
2084
+ }
2085
+ async launch(origin) {
2086
+ this.origin = origin;
2087
+ const pages = await this.call((api) => api.launch(this.agent, origin));
2088
+ this.startHeartbeat();
2089
+ return pages;
2090
+ }
2091
+ /** The sites with Pilot open in a browser (their origins). */
2092
+ pages() {
2093
+ return this.call((api) => api.pages());
2094
+ }
2095
+ /** Tells the hub how the agent stands now (its `setup` changed): the pages show it at once. */
2096
+ async register() {
2097
+ if (!this.origin) return;
2098
+ const origin = this.origin;
2099
+ await this.call((api) => api.register(this.agent, origin));
2100
+ }
2101
+ /** Whether the designer asked, from the page, to sign the agent in (see Hub.requestSignIn). */
2102
+ async signInAsked() {
2103
+ return (await this.call((api) => api.setup(this.agent))).signIn;
2104
+ }
2105
+ /** Waits up to `timeoutMs` for a job; survives the hub moving to another process mid-wait. */
2106
+ async wait(origin, timeoutMs, signal) {
2107
+ this.origin = origin;
2108
+ const until = Date.now() + timeoutMs;
2109
+ for (; ; ) {
2110
+ try {
2111
+ const api = await this.connect();
2112
+ return await api.wait(this.agent, origin, Math.max(0, until - Date.now()), signal);
2113
+ } catch (error) {
2114
+ if (signal?.aborted) return { job: null };
2115
+ if (!isConnectionError(error) || Date.now() >= until) throw error;
2116
+ this.reset();
2117
+ }
2118
+ }
2119
+ }
2120
+ done(jobId, notes, question, props, extra) {
2121
+ return this.call((api) => api.done(this.agent, jobId, notes, question, props, extra));
2122
+ }
2123
+ /** A job as the hub has it now (null: it doesn't know it). */
2124
+ job(jobId) {
2125
+ return this.call((api) => api.job(this.agent, jobId));
2126
+ }
2127
+ /** The agent is at work on `jobId`: its output came (see Job.activeAt). */
2128
+ activity(jobId) {
2129
+ return this.call((api) => api.activity(this.agent, jobId));
2130
+ }
2131
+ /** Pilot's width check of a task's element, measured by the page (null: no page answered). */
2132
+ check(jobId, timeoutMs = CHECK_TIMEOUT) {
2133
+ return this.call((api) => api.check(this.agent, jobId, timeoutMs));
2134
+ }
2135
+ async close() {
2136
+ if (this.heartbeat) clearInterval(this.heartbeat);
2137
+ try {
2138
+ await this.api?.leave(this.agent);
2139
+ } catch {
2140
+ }
2141
+ await this.server?.close();
2142
+ this.server = null;
2143
+ this.api = null;
2144
+ }
2145
+ /** Runs `fn` against the hub, reconnecting (or taking over) once if it went away. */
2146
+ async call(fn) {
2147
+ try {
2148
+ return await fn(await this.connect());
2149
+ } catch (error) {
2150
+ if (!isConnectionError(error)) throw error;
2151
+ this.reset();
2152
+ return fn(await this.connect());
2153
+ }
2154
+ }
2155
+ connect() {
2156
+ if (this.api) return Promise.resolve(this.api);
2157
+ this.connecting ??= this.elect().finally(() => {
2158
+ this.connecting = null;
2159
+ });
2160
+ return this.connecting;
2161
+ }
2162
+ /** Runs the hub here, or joins the one already on the port. */
2163
+ async elect() {
2164
+ for (let attempt = 0; attempt < 5; attempt++) {
2165
+ try {
2166
+ this.server = await startHub(this.port);
2167
+ this.api = new LocalApi(this.server.hub);
2168
+ } catch (error) {
2169
+ if (error.code !== "EADDRINUSE") throw error;
2170
+ const health = await checkHealth(this.port);
2171
+ if (!health) {
2172
+ await new Promise((r) => setTimeout(r, 200));
2173
+ continue;
2174
+ }
2175
+ if (!health.pilot) throw new Error(`Port ${this.port} is used by another program. Set PILOT_PORT to use another port.`);
2176
+ if (health.version !== BRIDGE_VERSION) {
2177
+ throw new Error(
2178
+ `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.`
2179
+ );
2180
+ }
2181
+ this.api = new RemoteApi(this.port);
2182
+ }
2183
+ if (this.origin) await this.api.register(this.agent, this.origin);
2184
+ return this.api;
2185
+ }
2186
+ throw new Error(`Pilot bridge: couldn't start or reach the hub on port ${this.port}.`);
2187
+ }
2188
+ reset() {
2189
+ this.api = null;
2190
+ }
2191
+ startHeartbeat() {
2192
+ if (this.heartbeat) return;
2193
+ this.heartbeat = setInterval(() => {
2194
+ if (!this.origin || this.server) return;
2195
+ this.call((api) => api.register(this.agent, this.origin)).catch(() => {
2196
+ });
2197
+ }, HEARTBEAT);
2198
+ this.heartbeat.unref();
2199
+ }
2200
+ };
2201
+ async function checkHealth(port) {
2202
+ let res;
2203
+ try {
2204
+ res = await fetch(`http://127.0.0.1:${port}/health`);
2205
+ } catch {
2206
+ return null;
2207
+ }
2208
+ try {
2209
+ return await res.json();
2210
+ } catch {
2211
+ return {};
2212
+ }
2213
+ }
2214
+ function isConnectionError(error) {
2215
+ const e = error;
2216
+ const code = e?.code ?? e?.cause?.code;
2217
+ return code === "ECONNREFUSED" || code === "ECONNRESET" || code === "UND_ERR_SOCKET" || /fetch failed|socket hang up|other side closed/i.test(e?.message ?? "");
2218
+ }
2219
+
2220
+ // src/config.ts
2221
+ import { mkdirSync, readFileSync as readFileSync4, realpathSync, writeFileSync } from "fs";
2222
+ import { homedir as homedir3 } from "os";
2223
+ import { basename as basename4, dirname as dirname5, join as join6, resolve as resolve2 } from "path";
2224
+ function configFile(env = process.env, platform = process.platform, home = homedir3()) {
2225
+ const base = platform === "win32" ? env.APPDATA ?? join6(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME ?? join6(home, ".config");
2226
+ return join6(base, "usepilot", "projects.json");
2227
+ }
2228
+ function read3(file) {
2229
+ try {
2230
+ const data = JSON.parse(readFileSync4(file, "utf8"));
2231
+ return data && typeof data === "object" ? data : {};
2232
+ } catch {
2233
+ return {};
2234
+ }
2235
+ }
2236
+ function savedAgent(folder, file = configFile()) {
2237
+ const agent = read3(file)[resolve2(folder)]?.agent;
2238
+ return isAgentKind(agent) ? agent : void 0;
2239
+ }
2240
+ function saveAgent(folder, agent, file = configFile()) {
2241
+ const projects = read3(file);
2242
+ projects[resolve2(folder)] = { ...projects[resolve2(folder)], agent };
2243
+ mkdirSync(dirname5(file), { recursive: true });
2244
+ writeFileSync(file, `${JSON.stringify(projects, null, 2)}
2245
+ `);
2246
+ }
2247
+ function isSetUp(folder, file = configFile()) {
2248
+ const here = canonical(folder);
2249
+ return Object.entries(read3(file)).some(
2250
+ ([key, project]) => !!project && (project.setUp === true || isAgentKind(project.agent)) && canonical(key) === here
2251
+ );
2252
+ }
2253
+ function canonical(folder, platform = process.platform) {
2254
+ let path = resolve2(folder);
2255
+ try {
2256
+ path = realpathSync.native(path);
2257
+ } catch {
2258
+ }
2259
+ return platform === "win32" ? path.toLowerCase() : path;
2260
+ }
2261
+ function markSetUp(folder, file = configFile()) {
2262
+ const projects = read3(file);
2263
+ if (projects[resolve2(folder)]?.setUp) return;
2264
+ projects[resolve2(folder)] = { ...projects[resolve2(folder)], setUp: true };
2265
+ mkdirSync(dirname5(file), { recursive: true });
2266
+ writeFileSync(file, `${JSON.stringify(projects, null, 2)}
2267
+ `);
2268
+ }
2269
+ function savedSessions(folder, file = configFile()) {
2270
+ const list2 = read3(file)[resolve2(folder)]?.editor;
2271
+ return Array.isArray(list2) ? list2.filter((s) => s && isAgentKind(s.agent) && typeof s.id === "string") : [];
2272
+ }
2273
+ function saveSessions(folder, sessions, file = configFile()) {
2274
+ const projects = read3(file);
2275
+ projects[resolve2(folder)] = { ...projects[resolve2(folder)], editor: sessions };
2276
+ mkdirSync(dirname5(file), { recursive: true });
2277
+ writeFileSync(file, `${JSON.stringify(projects, null, 2)}
2278
+ `);
2279
+ }
2280
+ function projectName(folder) {
2281
+ try {
2282
+ const name = projectNameOf(JSON.parse(readFileSync4(join6(folder, "package.json"), "utf8")).name);
2283
+ if (name) return name;
2284
+ } catch {
2285
+ }
2286
+ return projectNameOf(basename4(resolve2(folder))) ?? "project";
2287
+ }
2288
+
2289
+ // src/facts.ts
2290
+ import { existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
2291
+ import { dirname as dirname6, join as join9, relative as relative2, resolve as resolve4, sep as sep2 } from "path";
2292
+
2293
+ // src/sources.ts
2294
+ import { readdirSync as readdirSync4, readFileSync as readFileSync5, statSync as statSync5 } from "fs";
2295
+ import { extname as extname3, join as join7 } from "path";
2296
+ var SKIP2 = /* @__PURE__ */ new Set([
2297
+ "node_modules",
2298
+ "dist",
2299
+ "build",
2300
+ "out",
2301
+ "coverage",
2302
+ "vendor",
2303
+ "bower_components",
2304
+ ".git",
2305
+ ".next",
2306
+ ".nuxt",
2307
+ ".svelte-kit",
2308
+ ".output",
2309
+ ".vercel",
2310
+ ".turbo",
2311
+ ".cache"
2312
+ ]);
2313
+ var EXTENSIONS2 = /* @__PURE__ */ new Set([
2314
+ ".html",
2315
+ ".htm",
2316
+ ".jsx",
2317
+ ".tsx",
2318
+ ".js",
2319
+ ".ts",
2320
+ ".mjs",
2321
+ ".vue",
2322
+ ".svelte",
2323
+ ".astro",
2324
+ ".mdx",
2325
+ ".php",
2326
+ ".erb",
2327
+ ".hbs",
2328
+ ".njk",
2329
+ ".liquid",
2330
+ ".twig"
2331
+ ]);
2332
+ var STYLESHEETS = /* @__PURE__ */ new Set([".css", ".scss", ".sass", ".less", ".styl"]);
2333
+ var MAX_FILES3 = 5e4;
2334
+ var MAX_FILE_BYTES3 = 512e3;
2335
+ var FRESH_MS = 2e3;
2336
+ var Index = class {
2337
+ constructor(root) {
2338
+ this.root = root;
2339
+ }
2340
+ root;
2341
+ entries = /* @__PURE__ */ new Map();
2342
+ /** Every walked file, markup or not (componentFile looks at all scripts). */
2343
+ paths = [];
2344
+ /** Every stylesheet walked (not read): CSS, Sass, Less, Stylus. */
2345
+ styles = [];
2346
+ /** How many lines of the markup files hold each word, and how many lines they have. */
2347
+ counts = /* @__PURE__ */ new Map();
2348
+ lines = 0;
2349
+ walkedAt = 0;
2350
+ get sources() {
2351
+ const out = [];
2352
+ for (const e of this.entries.values()) if (e.source) out.push(e.source);
2353
+ return out;
2354
+ }
2355
+ refresh() {
2356
+ if (Date.now() - this.walkedAt < FRESH_MS) return;
2357
+ const seen = /* @__PURE__ */ new Set();
2358
+ const paths = [];
2359
+ const styles = [];
2360
+ const walk = (dir) => {
2361
+ let names;
2362
+ try {
2363
+ names = readdirSync4(dir);
2364
+ } catch {
2365
+ return;
2366
+ }
2367
+ for (const name of names) {
2368
+ if (paths.length >= MAX_FILES3) return;
2369
+ if (SKIP2.has(name) || name.startsWith(".")) continue;
2370
+ const path = join7(dir, name);
2371
+ let stat2;
2372
+ try {
2373
+ stat2 = statSync5(path);
2374
+ } catch {
2375
+ continue;
2376
+ }
2377
+ if (stat2.isDirectory()) {
2378
+ walk(path);
2379
+ continue;
2380
+ }
2381
+ if (STYLESHEETS.has(extname3(name)) && stat2.size <= MAX_FILE_BYTES3) styles.push(path);
2382
+ if (!EXTENSIONS2.has(extname3(name)) || stat2.size > MAX_FILE_BYTES3) continue;
2383
+ paths.push(path);
2384
+ seen.add(path);
2385
+ const known = this.entries.get(path);
2386
+ if (known && known.mtime === stat2.mtimeMs && known.size === stat2.size) continue;
2387
+ if (known?.source) this.count(known.source, -1);
2388
+ const source = this.read(path);
2389
+ if (source) this.count(source, 1);
2390
+ this.entries.set(path, { mtime: stat2.mtimeMs, size: stat2.size, source });
2391
+ }
2392
+ };
2393
+ walk(this.root);
2394
+ for (const [path, e] of this.entries) {
2395
+ if (seen.has(path)) continue;
2396
+ if (e.source) this.count(e.source, -1);
2397
+ this.entries.delete(path);
2398
+ }
2399
+ this.paths = paths;
2400
+ this.styles = styles;
2401
+ this.walkedAt = Date.now();
2402
+ }
2403
+ read(path) {
2404
+ let content;
2405
+ try {
2406
+ content = readFileSync5(path, "utf8");
2407
+ } catch {
2408
+ return null;
2409
+ }
2410
+ if (!/<[A-Za-z][\w.:-]*[\s>/]/.test(content)) return null;
2411
+ const lines = content.split("\n");
2412
+ const lineCounts = /* @__PURE__ */ new Map();
2413
+ for (const line of lines) for (const w of new Set(wordsOf(line))) lineCounts.set(w, (lineCounts.get(w) ?? 0) + 1);
2414
+ return { path, rel: relPath(this.root, path), content, lines, words: new Set(lineCounts.keys()), lineCounts };
2415
+ }
2416
+ count(source, by) {
2417
+ this.lines += by * source.lines.length;
2418
+ for (const [w, lines] of source.lineCounts) {
2419
+ const n = (this.counts.get(w) ?? 0) + by * lines;
2420
+ if (n > 0) this.counts.set(w, n);
2421
+ else this.counts.delete(w);
2422
+ }
2423
+ }
2424
+ };
2425
+ function wordsOf(text) {
2426
+ return text.split(/[\s"'`<>{}=]+/).filter((w) => w.length > 0);
2427
+ }
2428
+ var indexes = /* @__PURE__ */ new Map();
2429
+ function indexOf(root) {
2430
+ let index = indexes.get(root);
2431
+ if (!index) {
2432
+ index = new Index(root);
2433
+ indexes.set(root, index);
2434
+ }
2435
+ index.refresh();
2436
+ return index;
2437
+ }
2438
+ function markupSources(root) {
2439
+ const index = indexOf(root);
2440
+ const scale2 = 6 / Math.log2(index.lines + 2);
2441
+ return {
2442
+ sources: index.sources,
2443
+ rarity: (word) => Math.max(0, Math.min(6, Math.log2((index.lines + 2) / ((index.counts.get(word) ?? 0) + 1)) * scale2))
2444
+ };
2445
+ }
2446
+ function styleFiles(root) {
2447
+ return indexOf(root).styles;
2448
+ }
2449
+ function sourceFiles(root) {
2450
+ return indexOf(root).paths;
2451
+ }
2452
+ function warmSources(root) {
2453
+ indexOf(root);
2454
+ }
2455
+
2456
+ // src/styles.ts
2457
+ import { existsSync as existsSync4, readFileSync as readFileSync6, statSync as statSync6 } from "fs";
2458
+ import { basename as basename5, extname as extname4, join as join8 } from "path";
2459
+ var STYLE_EXTENSIONS = /* @__PURE__ */ new Set([".css", ".scss", ".sass", ".less", ".styl"]);
2460
+ var PREPROCESSED = /* @__PURE__ */ new Set([".scss", ".sass", ".less", ".styl"]);
2461
+ var TEMPLATES = /^@(mixin|function|each|for|while|if|else|keyframes|-webkit-keyframes|font-face|property|page|counter-style|theme|utility|variant|custom-variant)\b/;
2462
+ var parsed = /* @__PURE__ */ new Map();
2463
+ function rulesOf(path, root) {
2464
+ let stat2;
2465
+ try {
2466
+ stat2 = statSync6(path);
2467
+ } catch {
2468
+ return [];
2469
+ }
2470
+ const known = parsed.get(path);
2471
+ if (known && known.mtime === stat2.mtimeMs && known.size === stat2.size) return known.rules;
2472
+ let rules = [];
2473
+ try {
2474
+ const text = readFileSync6(path, "utf8");
2475
+ if (!text.split("\n", 50).some((l) => l.length > 3e3)) rules = parseStylesheet(text, relPath(root, path));
2476
+ } catch {
2477
+ }
2478
+ parsed.set(path, { mtime: stat2.mtimeMs, size: stat2.size, rules });
2479
+ return rules;
2480
+ }
2481
+ function withoutComments(text, lineComments) {
2482
+ let out = "";
2483
+ let quote2 = "";
2484
+ for (let i = 0; i < text.length; i++) {
2485
+ const ch = text[i];
2486
+ if (quote2) {
2487
+ out += ch;
2488
+ if (ch === "\\") out += text[++i] ?? "";
2489
+ else if (ch === quote2) quote2 = "";
2490
+ continue;
2491
+ }
2492
+ if (ch === '"' || ch === "'") {
2493
+ quote2 = ch;
2494
+ out += ch;
2495
+ continue;
2496
+ }
2497
+ if (ch === "/" && text[i + 1] === "*") {
2498
+ const end = text.indexOf("*/", i + 2);
2499
+ const stop = end < 0 ? text.length : end + 2;
2500
+ out += text.slice(i, stop).replace(/[^\n]/g, " ");
2501
+ i = stop - 1;
2502
+ continue;
2503
+ }
2504
+ if (lineComments && ch === "/" && text[i + 1] === "/" && text[i - 1] !== ":") {
2505
+ const end = text.indexOf("\n", i);
2506
+ const stop = end < 0 ? text.length : end;
2507
+ out += " ".repeat(stop - i);
2508
+ i = stop - 1;
2509
+ continue;
2510
+ }
2511
+ out += ch;
2512
+ }
2513
+ return out;
2514
+ }
2515
+ function splitTopLevel(text, sep3) {
2516
+ const out = [];
2517
+ let depth = 0;
2518
+ let start = 0;
2519
+ for (let i = 0; i < text.length; i++) {
2520
+ const ch = text[i];
2521
+ if (ch === "(" || ch === "[") depth++;
2522
+ else if (ch === ")" || ch === "]") depth--;
2523
+ else if (ch === sep3 && depth === 0) {
2524
+ out.push(text.slice(start, i));
2525
+ start = i + 1;
2526
+ }
2527
+ }
2528
+ out.push(text.slice(start));
2529
+ return out.map((s) => s.trim()).filter(Boolean);
2530
+ }
2531
+ function normalSelector(selector) {
2532
+ return selector.replace(/\s+/g, " ").replace(/\s*([>+~])\s*/g, "$1").replace(/\[\s*([\w-]+)\s*([~|^$*]?=)\s*(["'])([\w-]+)\3\s*\]/g, "[$1$2$4]").replace(/\[\s*([\w-]+)\s*\]/g, "[$1]").trim();
2533
+ }
2534
+ function resolve3(parents, own) {
2535
+ if (!parents.length) return own;
2536
+ const out = [];
2537
+ for (const p of parents) for (const s of own) out.push(s.includes("&") ? s.replaceAll("&", p) : `${p} ${s}`);
2538
+ return out;
2539
+ }
2540
+ function parseStylesheet(text, file) {
2541
+ const ext = extname4(file);
2542
+ const css = withoutComments(text, ext !== ".css");
2543
+ const rules = [];
2544
+ const stack = [];
2545
+ let start = 0;
2546
+ let line = 1;
2547
+ let startLine = 1;
2548
+ const top = () => stack[stack.length - 1];
2549
+ const inTemplate = () => stack.some((b) => b.template);
2550
+ for (let i = 0; i < css.length; i++) {
2551
+ const ch = css[i];
2552
+ if (ch === "\n") line++;
2553
+ if (ch === "{" && css[i - 1] === "#") {
2554
+ const close = css.indexOf("}", i);
2555
+ if (close > 0) {
2556
+ line += (css.slice(i, close).match(/\n/g) ?? []).length;
2557
+ i = close;
2558
+ }
2559
+ continue;
2560
+ }
2561
+ if (ch === "{") {
2562
+ const prelude = css.slice(start, i).trim();
2563
+ const preludeLine = startLine + (css.slice(start, i).match(/^\s*/)?.[0].match(/\n/g) ?? []).length;
2564
+ const parent = top();
2565
+ if (prelude.startsWith("@")) {
2566
+ const own = /^@media\s+(.+)$/.exec(prelude)?.[1]?.trim();
2567
+ const media = own && parent?.media ? `${parent.media} and ${own}` : own ?? parent?.media;
2568
+ const template = TEMPLATES.test(prelude);
2569
+ const rule = parent?.rule && own ? { file, line: preludeLine, selectors: parent.selectors, declarations: [], ...media ? { media } : {} } : parent?.rule;
2570
+ if (rule && rule !== parent?.rule && !template && !inTemplate()) rules.push(rule);
2571
+ stack.push({ selectors: parent?.selectors ?? [], ...rule ? { rule } : {}, ...media ? { media } : {}, template });
2572
+ } else {
2573
+ const selectors = resolve3(parent?.selectors ?? [], splitTopLevel(prelude, ",")).map(normalSelector);
2574
+ const rule = { file, line: preludeLine, selectors, declarations: [], ...parent?.media ? { media: parent.media } : {} };
2575
+ if (!inTemplate() && !/^(from|to|\d+%)$/.test(prelude)) rules.push(rule);
2576
+ stack.push({ selectors, rule, ...parent?.media ? { media: parent.media } : {} });
2577
+ }
2578
+ start = i + 1;
2579
+ startLine = line;
2580
+ continue;
2581
+ }
2582
+ if (ch === ";" || ch === "}") {
2583
+ const statement = css.slice(start, i);
2584
+ const m = /^\s*(-?[A-Za-z][\w-]*|--[\w-]+)\s*:(?!:)\s*([\s\S]+?)\s*$/.exec(statement);
2585
+ const block = top();
2586
+ if (m && block?.rule && !inTemplate()) {
2587
+ const at = startLine + (statement.match(/^\s*/)?.[0].match(/\n/g) ?? []).length;
2588
+ block.rule.declarations.push({ property: m[1].toLowerCase(), value: m[2].replace(/\s+/g, " "), line: at });
2589
+ }
2590
+ if (ch === "}") stack.pop();
2591
+ start = i + 1;
2592
+ startLine = line;
2593
+ }
2594
+ }
2595
+ return rules;
2596
+ }
2597
+ function componentStyles(path, root) {
2598
+ let text;
2599
+ try {
2600
+ text = readFileSync6(path, "utf8");
2601
+ } catch {
2602
+ return [];
2603
+ }
2604
+ const out = [];
2605
+ for (const m of text.matchAll(/<style\b([^>]*)>([\s\S]*?)<\/style>/g)) {
2606
+ const before = text.slice(0, m.index + m[0].indexOf(">") + 1);
2607
+ const offset = (before.match(/\n/g) ?? []).length;
2608
+ const lang = /lang=["'](\w+)["']/.exec(m[1])?.[1] ?? "css";
2609
+ const file = relPath(root, path);
2610
+ for (const r of parseStylesheet(m[2], `${file}.${lang}`))
2611
+ out.push({ ...r, file, line: r.line + offset, declarations: r.declarations.map((d) => ({ ...d, line: d.line + offset })) });
2612
+ }
2613
+ return out;
2614
+ }
2615
+ function moduleClass(hashed) {
2616
+ let m = /^([A-Za-z][\w-]*?)_([\w-]+?)__[\w-]{5,}$/.exec(hashed);
2617
+ if (m) return { file: m[1], local: m[2] };
2618
+ m = /^_([\w-]+?)_[a-z0-9]{5,}(_\d+)?$/.exec(hashed);
2619
+ if (m) return { local: m[1] };
2620
+ return null;
2621
+ }
2622
+ function asWritten(selector) {
2623
+ let module;
2624
+ let hashed = false;
2625
+ const out = selector.replace(/\.(-?[_A-Za-z][\w-]*)/g, (whole, cls) => {
2626
+ const m = moduleClass(cls);
2627
+ if (!m) return whole;
2628
+ hashed = true;
2629
+ module = module ?? m.file;
2630
+ return `.${m.local}`;
2631
+ });
2632
+ return { selector: normalSelector(out), ...module ? { module } : {}, hashed };
2633
+ }
2634
+ function warmStyles(root) {
2635
+ for (const path of styleFiles(root)) if (STYLE_EXTENSIONS.has(extname4(path))) rulesOf(path, root);
2636
+ }
2637
+ function ruleSource(selector, property, root, near = [], media) {
2638
+ const wanted = asWritten(selector);
2639
+ const files = styleFiles(root);
2640
+ const found = [];
2641
+ const consider = (rules) => {
2642
+ for (const rule of rules) {
2643
+ if (!rule.selectors.includes(wanted.selector)) continue;
2644
+ const declaration = [...rule.declarations].reverse().find((d) => d.property === property || shorthandOf(property).includes(d.property));
2645
+ found.push({ rule, ...declaration ? { declaration } : {} });
2646
+ }
2647
+ };
2648
+ const sources = new Set(files.filter((f) => PREPROCESSED.has(extname4(f))).map((f) => basename5(f).replace(/^_/, "").replace(/\.\w+$/, "")));
2649
+ for (const path of files) {
2650
+ const ext = extname4(path);
2651
+ if (!STYLE_EXTENSIONS.has(ext)) continue;
2652
+ if (ext === ".css" && compiled(path, sources)) continue;
2653
+ if (wanted.hashed && !/\.module\.\w+$/.test(path)) continue;
2654
+ if (wanted.module && !basename5(path).startsWith(`${wanted.module}.`)) continue;
2655
+ consider(rulesOf(path, root));
2656
+ }
2657
+ if (!found.length && !wanted.hashed) {
2658
+ for (const path of sourceFiles(root)) if (/\.(vue|svelte|astro)$/.test(path)) consider(componentStyles(path, root));
2659
+ }
2660
+ const sites = new Set(near.map((f) => siteOf(f, root)));
2661
+ const kept = sites.size ? found.filter((s) => sites.has(siteOf(s.rule.file, root))) : found;
2662
+ if (!kept.length) return null;
2663
+ if (!sites.size && new Set(kept.map((s) => siteOf(s.rule.file, root))).size > 1) return null;
2664
+ const score = (s) => {
2665
+ const ext = extname4(s.rule.file);
2666
+ const dir = s.rule.file.split(/[\\/]/).slice(0, -1);
2667
+ const shared = Math.max(
2668
+ 0,
2669
+ ...near.map((f) => {
2670
+ const parts = f.split(/[\\/]/);
2671
+ let n = 0;
2672
+ while (n < dir.length && dir[n] === parts[n]) n++;
2673
+ return n;
2674
+ })
2675
+ );
2676
+ return (PREPROCESSED.has(ext) || !STYLE_EXTENSIONS.has(ext) ? 100 : 0) + (s.declaration ? 50 : 0) + ((s.rule.media ?? "") === (media ?? "") ? 20 : 0) + shared;
2677
+ };
2678
+ return kept.sort((a, b) => score(b) - score(a))[0];
2679
+ }
2680
+ var SITE_FILES = ["index.html", "index.htm", "index.php", "package.json"];
2681
+ var siteCache = /* @__PURE__ */ new Map();
2682
+ function siteOf(file, root) {
2683
+ const parts = file.split(/[\\/]/).slice(0, -1);
2684
+ for (let n = parts.length; n > 0; n--) {
2685
+ const dir = parts.slice(0, n).join("/");
2686
+ const key = `${root}\0${dir}`;
2687
+ let site = siteCache.get(key);
2688
+ if (site === void 0) {
2689
+ site = SITE_FILES.some((f) => existsSync4(join8(root, dir, f))) ? dir : "";
2690
+ siteCache.set(key, site);
2691
+ }
2692
+ if (site) return site;
2693
+ }
2694
+ return "";
2695
+ }
2696
+ function compiled(path, sources) {
2697
+ if (existsSync4(`${path}.map`)) return true;
2698
+ if (sources.has(basename5(path, ".css"))) return true;
2699
+ try {
2700
+ const text = readFileSync6(path, "utf8");
2701
+ return /\/\*#\s*sourceMappingURL=/.test(text.slice(-500));
2702
+ } catch {
2703
+ return false;
2704
+ }
2705
+ }
2706
+ function shorthandOf(property) {
2707
+ const out = [];
2708
+ const m = /^(padding|margin|inset|border|border-radius|gap|flex|grid|font|background|outline|transition|animation)/.exec(property);
2709
+ if (m && m[1] !== property) out.push(m[1]);
2710
+ if (/^(row|column)-gap$/.test(property)) out.push("gap");
2711
+ if (/^(padding|margin)-(inline|block)/.test(property)) out.push(property.replace(/-(start|end)$/, ""));
2712
+ if (property === "background-color") out.push("background");
2713
+ return out;
2714
+ }
2715
+
2716
+ // src/facts.ts
2717
+ var REM = 16;
2718
+ var DEFAULTS = new Map(
2719
+ Object.entries({
2720
+ spacing: "0.25rem",
2721
+ ...prefixed("breakpoint", { sm: "40rem", md: "48rem", lg: "64rem", xl: "80rem", "2xl": "96rem" }),
2722
+ ...prefixed("container", {
2723
+ "3xs": "16rem",
2724
+ "2xs": "18rem",
2725
+ xs: "20rem",
2726
+ sm: "24rem",
2727
+ md: "28rem",
2728
+ lg: "32rem",
2729
+ xl: "36rem",
2730
+ "2xl": "42rem",
2731
+ "3xl": "48rem",
2732
+ "4xl": "56rem",
2733
+ "5xl": "64rem",
2734
+ "6xl": "72rem",
2735
+ "7xl": "80rem"
2736
+ }),
2737
+ ...prefixed("text", {
2738
+ xs: "0.75rem",
2739
+ sm: "0.875rem",
2740
+ base: "1rem",
2741
+ lg: "1.125rem",
2742
+ xl: "1.25rem",
2743
+ "2xl": "1.5rem",
2744
+ "3xl": "1.875rem",
2745
+ "4xl": "2.25rem",
2746
+ "5xl": "3rem",
2747
+ "6xl": "3.75rem",
2748
+ "7xl": "4.5rem",
2749
+ "8xl": "6rem",
2750
+ "9xl": "8rem"
2751
+ }),
2752
+ ...prefixed("font-weight", {
2753
+ thin: "100",
2754
+ extralight: "200",
2755
+ light: "300",
2756
+ normal: "400",
2757
+ medium: "500",
2758
+ semibold: "600",
2759
+ bold: "700",
2760
+ extrabold: "800",
2761
+ black: "900"
2762
+ }),
2763
+ ...prefixed("tracking", { tighter: "-0.05em", tight: "-0.025em", normal: "0em", wide: "0.025em", wider: "0.05em", widest: "0.1em" }),
2764
+ ...prefixed("leading", { tight: "1.25", snug: "1.375", normal: "1.5", relaxed: "1.625", loose: "2" }),
2765
+ ...prefixed("radius", { xs: "0.125rem", sm: "0.25rem", md: "0.375rem", lg: "0.5rem", xl: "0.75rem", "2xl": "1rem", "3xl": "1.5rem", "4xl": "2rem" })
2766
+ })
2767
+ );
2768
+ function prefixed(namespace, values) {
2769
+ return Object.fromEntries(Object.entries(values).map(([k, v]) => [`${namespace}-${k}`, v]));
2770
+ }
2771
+ function tailwindOf(root, near = [], url) {
2772
+ const entries = styleFiles(root).filter((f) => importsTailwind(f));
2773
+ if (!entries.length) return null;
2774
+ const route = routeParts(url);
2775
+ const closeness = (entry2) => {
2776
+ const dir = relative2(root, dirname6(entry2)).split(sep2).filter(Boolean);
2777
+ const shared = (file) => {
2778
+ const parts = file.split(/[\\/]/);
2779
+ let n = 0;
2780
+ while (n < dir.length && dir[n] === parts[n]) n++;
2781
+ return n;
2782
+ };
2783
+ return Math.max(0, ...near.map(shared)) * 10 + (route.includes(dir[0] ?? "") ? 1 : 0);
2784
+ };
2785
+ const entry = [...entries].sort((a, b) => closeness(b) - closeness(a))[0];
2786
+ const pkg = nearestPackage(dirname6(entry), root);
2787
+ const version = installedVersion(dirname6(entry), root) ?? declaredVersion(pkg);
2788
+ if (version && !version.replace(/^[^\d]*/, "").startsWith("4")) return null;
2789
+ const theme = /* @__PURE__ */ new Map();
2790
+ const defaults = findUp(dirname6(entry), root, join9("node_modules", "tailwindcss", "theme.css"));
2791
+ if (defaults) readTheme(defaults, theme, 0);
2792
+ else for (const [k, v] of DEFAULTS) theme.set(k, v);
2793
+ const own = /* @__PURE__ */ new Set();
2794
+ readTheme(entry, theme, 0, own);
2795
+ return { entry: relPath(root, entry), ...version ? { version } : {}, theme, own };
2796
+ }
2797
+ function importsTailwind(file) {
2798
+ try {
2799
+ return /@import\s+(url\()?["']tailwindcss["']/.test(readFileSync7(file, "utf8"));
2800
+ } catch {
2801
+ return false;
2802
+ }
2803
+ }
2804
+ function routeParts(url) {
2805
+ try {
2806
+ return url ? new URL(url).pathname.split("/").filter(Boolean) : [];
2807
+ } catch {
2808
+ return [];
2809
+ }
2810
+ }
2811
+ function findUp(dir, root, name) {
2812
+ for (let d = resolve4(dir); ; d = dirname6(d)) {
2813
+ const path = join9(d, name);
2814
+ if (existsSync5(path)) return path;
2815
+ if (d === resolve4(root) || d === dirname6(d)) return null;
2816
+ }
2817
+ }
2818
+ function nearestPackage(dir, root) {
2819
+ return findUp(dir, root, "package.json");
2820
+ }
2821
+ function installedVersion(dir, root) {
2822
+ const pkg = findUp(dir, root, join9("node_modules", "tailwindcss", "package.json"));
2823
+ try {
2824
+ return pkg ? JSON.parse(readFileSync7(pkg, "utf8")).version : void 0;
2825
+ } catch {
2826
+ return void 0;
2827
+ }
2828
+ }
2829
+ function declaredVersion(pkg) {
2830
+ try {
2831
+ if (!pkg) return void 0;
2832
+ const p = JSON.parse(readFileSync7(pkg, "utf8"));
2833
+ return p.dependencies?.tailwindcss ?? p.devDependencies?.tailwindcss;
2834
+ } catch {
2835
+ return void 0;
2836
+ }
2837
+ }
2838
+ function readTheme(file, theme, depth, own) {
2839
+ let css;
2840
+ try {
2841
+ css = readFileSync7(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "");
2842
+ } catch {
2843
+ return;
2844
+ }
2845
+ if (depth < 3)
2846
+ for (const m of css.matchAll(/@import\s+(?:url\()?["'](\.{1,2}\/[^"']+\.css)["']/g)) readTheme(resolve4(dirname6(file), m[1]), theme, depth + 1, own);
2847
+ for (const block of themeBlocks(css)) {
2848
+ for (const m of block.matchAll(/--([\w-]+|\*)(-\*)?\s*:\s*([^;]+);/g)) {
2849
+ const name = m[1];
2850
+ const value = m[3].replace(/\s+/g, " ").trim();
2851
+ if (value === "initial" && (m[2] || name === "*")) {
2852
+ for (const key of [...theme.keys()]) if (name === "*" || key.startsWith(`${name}-`)) theme.delete(key);
2853
+ own?.add(`${name}-*`);
2854
+ continue;
2855
+ }
2856
+ theme.set(name, value);
2857
+ own?.add(name);
2858
+ }
2859
+ }
2860
+ }
2861
+ function themeBlocks(css) {
2862
+ const blocks = [];
2863
+ for (const m of css.matchAll(/@theme\b[^{]*\{/g)) {
2864
+ let depth = 1;
2865
+ let i = m.index + m[0].length;
2866
+ const start = i;
2867
+ for (; i < css.length && depth; i++) {
2868
+ if (css[i] === "{") depth++;
2869
+ else if (css[i] === "}") depth--;
2870
+ }
2871
+ blocks.push(css.slice(start, i - 1));
2872
+ }
2873
+ return blocks;
2874
+ }
2875
+ function rebuildOf(pkg, root) {
2876
+ const read4 = (file) => {
2877
+ try {
2878
+ return file ? JSON.parse(readFileSync7(file, "utf8")) : {};
2879
+ } catch {
2880
+ return {};
2881
+ }
2882
+ };
2883
+ const escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2884
+ for (const file of [.../* @__PURE__ */ new Set([pkg, join9(root, "package.json")])]) {
2885
+ const p = read4(file);
2886
+ const scripts = p.scripts ?? {};
2887
+ const where = file && file !== join9(root, "package.json") ? ` in \`${relPath(root, dirname6(file))}\`` : "";
2888
+ const runner = (name) => Object.entries(scripts).find(([other, cmd]) => other !== name && new RegExp(`(npm run|pnpm( run)?|yarn|bun run|npm:)\\s*${escape2(name)}\\b`).test(cmd))?.[0];
2889
+ const said = (name) => {
2890
+ const by = runner(name);
2891
+ return by ? `\`npm run ${by}\`${where} (its \`${name}\`)` : `\`npm run ${name}\`${where}`;
2892
+ };
2893
+ const gulpWatches = (() => {
2894
+ try {
2895
+ return /\bwatch\s*\(/.test(readFileSync7(join9(file ? dirname6(file) : root, "gulpfile.js"), "utf8"));
2896
+ } catch {
2897
+ return false;
2898
+ }
2899
+ })();
2900
+ const watch = Object.entries(scripts).find(
2901
+ ([, cmd]) => /\b(tailwindcss|sass|node-sass|postcss|lessc|stylus)\b/.test(cmd) && /(--watch|\s-w)\b/.test(cmd) || /\bgulp\b/.test(cmd) && (/\bwatch\b/.test(cmd) || gulpWatches)
2902
+ );
2903
+ if (watch) return { by: said(watch[0]), css: true };
2904
+ const server = Object.entries(scripts).find(([, cmd]) => /\b(vite|next dev|nuxt|astro dev|svelte-kit|remix|react-router dev|webpack serve|webpack-dev-server|parcel|eleventy --serve|ng serve|vue-cli-service serve)\b/.test(cmd));
2905
+ if (server) return { by: `its dev server (${said(server[0])})`, css: false };
2906
+ const deps = { ...p.dependencies, ...p.devDependencies };
2907
+ if (deps["@tailwindcss/vite"] || deps["@tailwindcss/postcss"]) return { by: "its dev server", css: false };
2908
+ }
2909
+ return void 0;
2910
+ }
2911
+ function toPx(value, theme, depth = 0) {
2912
+ const v = value.trim();
2913
+ if (depth > 5) return null;
2914
+ let m = /^(-?[\d.]+)(px|rem)?$/.exec(v);
2915
+ if (m) return m[2] === "rem" ? Number(m[1]) * REM : m[2] === "px" || Number(m[1]) === 0 ? Number(m[1]) : null;
2916
+ m = /^var\(--([\w-]+)(?:\s*,\s*(.+))?\)$/.exec(v);
2917
+ if (m) {
2918
+ const own = theme.get(m[1]);
2919
+ return own !== void 0 ? toPx(own, theme, depth + 1) : m[2] ? toPx(m[2], theme, depth + 1) : null;
2920
+ }
2921
+ m = /^calc\((.+)\)$/.exec(v);
2922
+ if (m) {
2923
+ const parts = m[1].split(/\s*([*/])\s*/);
2924
+ let px2 = null;
2925
+ let factor = 1;
2926
+ for (let i = 0; i < parts.length; i += 2) {
2927
+ const part = parts[i].trim();
2928
+ const op = i ? parts[i - 1] : "*";
2929
+ const resolved = /^var\(/.test(part) ? theme.get(/^var\(--([\w-]+)/.exec(part)?.[1] ?? "") ?? /,\s*(.+)\)$/.exec(part)?.[1] ?? "" : part;
2930
+ const n = /^-?[\d.]+$/.test(resolved.trim()) ? Number(resolved) : null;
2931
+ const len = n === null ? toPx(resolved, theme, depth + 1) : null;
2932
+ if (n !== null) factor = op === "/" ? factor / n : factor * n;
2933
+ else if (len !== null && px2 === null && op === "*") px2 = len;
2934
+ else return null;
2935
+ }
2936
+ return px2 === null ? null : px2 * factor;
2937
+ }
2938
+ return null;
2939
+ }
2940
+ function rgbOf(value) {
2941
+ const v = value.trim().toLowerCase();
2942
+ let m = /^#([0-9a-f]{3,8})$/.exec(v);
2943
+ if (m) {
2944
+ let h = m[1];
2945
+ if (h.length === 3 || h.length === 4) h = [...h].map((c) => c + c).join("");
2946
+ if (h.length !== 6 && h.length !== 8) return null;
2947
+ return { hex: `#${h.slice(0, 6)}`, alpha: h.length === 8 ? Number.parseInt(h.slice(6), 16) / 255 : 1 };
2948
+ }
2949
+ m = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/.exec(v);
2950
+ if (m) {
2951
+ const hex = `#${[m[1], m[2], m[3]].map((c) => Math.round(Number(c)).toString(16).padStart(2, "0")).join("")}`;
2952
+ const a = m[4] ? m[4].endsWith("%") ? Number(m[4].slice(0, -1)) / 100 : Number(m[4]) : 1;
2953
+ return { hex, alpha: a };
2954
+ }
2955
+ return null;
2956
+ }
2957
+ var normal = (s) => s.toLowerCase().replace(/\s+/g, " ").trim();
2958
+ var SPACING = {
2959
+ padding: "p",
2960
+ "padding-top": "pt",
2961
+ "padding-right": "pr",
2962
+ "padding-bottom": "pb",
2963
+ "padding-left": "pl",
2964
+ "padding-inline": "px",
2965
+ "padding-block": "py",
2966
+ "padding-inline-start": "ps",
2967
+ "padding-inline-end": "pe",
2968
+ margin: "m",
2969
+ "margin-top": "mt",
2970
+ "margin-right": "mr",
2971
+ "margin-bottom": "mb",
2972
+ "margin-left": "ml",
2973
+ "margin-inline": "mx",
2974
+ "margin-block": "my",
2975
+ "margin-inline-start": "ms",
2976
+ "margin-inline-end": "me",
2977
+ gap: "gap",
2978
+ "row-gap": "gap-y",
2979
+ "column-gap": "gap-x",
2980
+ width: "w",
2981
+ height: "h",
2982
+ "min-width": "min-w",
2983
+ "max-width": "max-w",
2984
+ "min-height": "min-h",
2985
+ "max-height": "max-h",
2986
+ inset: "inset",
2987
+ "inset-inline": "inset-x",
2988
+ "inset-block": "inset-y",
2989
+ top: "top",
2990
+ right: "right",
2991
+ bottom: "bottom",
2992
+ left: "left",
2993
+ "text-indent": "indent"
2994
+ };
2995
+ var COLORS = {
2996
+ color: "text",
2997
+ "background-color": "bg",
2998
+ "border-color": "border",
2999
+ "border-top-color": "border-t",
3000
+ "border-right-color": "border-r",
3001
+ "border-bottom-color": "border-b",
3002
+ "border-left-color": "border-l",
3003
+ "outline-color": "outline",
3004
+ fill: "fill",
3005
+ stroke: "stroke",
3006
+ "text-decoration-color": "decoration",
3007
+ "accent-color": "accent",
3008
+ "caret-color": "caret"
3009
+ };
3010
+ var NAMED = {
3011
+ "border-radius": ["rounded", "radius"],
3012
+ "border-top-left-radius": ["rounded-tl", "radius"],
3013
+ "border-top-right-radius": ["rounded-tr", "radius"],
3014
+ "border-bottom-right-radius": ["rounded-br", "radius"],
3015
+ "border-bottom-left-radius": ["rounded-bl", "radius"],
3016
+ "font-size": ["text", "text"],
3017
+ "font-weight": ["font", "font-weight"],
3018
+ "letter-spacing": ["tracking", "tracking"],
3019
+ "line-height": ["leading", "leading"],
3020
+ "box-shadow": ["shadow", "shadow"]
3021
+ };
3022
+ function scale(theme, namespace) {
3023
+ const out = [];
3024
+ for (const [key, value] of theme) {
3025
+ if (!key.startsWith(`${namespace}-`) || key.includes("--")) continue;
3026
+ const name = key.slice(namespace.length + 1);
3027
+ if (namespace === "text" && /^shadow/.test(name)) continue;
3028
+ out.push([name, value]);
3029
+ }
3030
+ return out;
3031
+ }
3032
+ var px = (n) => `${Math.round(n * 100) / 100}px`;
3033
+ function classFor(property, value, theme) {
3034
+ const v = value.trim();
3035
+ if (!v) return null;
3036
+ const variable = /^var\(--([\w-]+)\)$/.exec(v)?.[1];
3037
+ const spacingUtility = SPACING[property];
3038
+ if (spacingUtility) {
3039
+ if (v === "auto") return { exact: `${spacingUtility}-auto` };
3040
+ if (v === "100%" && /^(w|h|min-w|max-w|min-h|max-h|inset|top|right|bottom|left)/.test(spacingUtility)) return { exact: `${spacingUtility}-full` };
3041
+ const frac = /^([\d.]+)%$/.exec(v);
3042
+ if (frac && /^[wh]$/.test(spacingUtility)) {
3043
+ const f = Number(frac[1]) / 100;
3044
+ for (let q = 2; q <= 12; q++) for (let p = 1; p < q; p++) if (Math.abs(p / q - f) < 5e-4) return { exact: `${spacingUtility}-${p}/${q}` };
3045
+ }
3046
+ if (spacingUtility === "max-w") {
3047
+ const named2 = scale(theme, "container").find(([, size]) => toPx(size, theme) === toPx(v, theme));
3048
+ if (named2) return { exact: `max-w-${named2[0]}` };
3049
+ }
3050
+ const n2 = toPx(v, theme);
3051
+ const step = toPx(theme.get("spacing") ?? "0.25rem", theme);
3052
+ if (n2 === null || !step) return null;
3053
+ const negative = n2 < 0 && /^(m|inset|top|right|bottom|left)/.test(spacingUtility) ? "-" : "";
3054
+ const steps = Math.abs(n2) / step;
3055
+ if (Math.abs(n2) === 1 && step !== 1) return { exact: `${negative}${spacingUtility}-px` };
3056
+ if (Math.abs(steps * 4 - Math.round(steps * 4)) < 1e-6) return { exact: `${negative}${spacingUtility}-${Math.round(steps * 100) / 100}` };
3057
+ return { exact: `${negative}${spacingUtility}-[${px(Math.abs(n2))}]` };
3058
+ }
3059
+ const colorUtility = COLORS[property];
3060
+ if (colorUtility) {
3061
+ if (variable?.startsWith("color-")) return { exact: `${colorUtility}-${variable.slice(6)}` };
3062
+ if (/^(transparent|currentcolor|inherit)$/i.test(v)) return { exact: `${colorUtility}-${v.toLowerCase() === "currentcolor" ? "current" : v.toLowerCase()}` };
3063
+ const rgb = rgbOf(v);
3064
+ for (const [name, color] of scale(theme, "color")) {
3065
+ const own = rgbOf(color);
3066
+ if (rgb && own && own.hex === rgb.hex) {
3067
+ const alpha = Math.round(rgb.alpha * 100);
3068
+ return { exact: `${colorUtility}-${name}${alpha < 100 ? `/${alpha}` : ""}` };
3069
+ }
3070
+ if (!rgb && normal(color) === normal(v)) return { exact: `${colorUtility}-${name}` };
3071
+ }
3072
+ return { exact: `${colorUtility}-[${v.replace(/\s+/g, "_")}]`, note: "no color of the theme" };
3073
+ }
3074
+ if (property === "opacity") {
3075
+ const n2 = /^([\d.]+)(%)?$/.exec(v);
3076
+ if (n2) return { exact: `opacity-${Math.round(Number(n2[1]) * (n2[2] ? 1 : 100))}` };
3077
+ return null;
3078
+ }
3079
+ if (property === "z-index" && /^-?\d+$/.test(v)) return { exact: `${v.startsWith("-") ? "-" : ""}z-${v.replace("-", "")}` };
3080
+ if (property === "font-family") {
3081
+ const first = normal(v.split(",")[0]).replace(/["']/g, "");
3082
+ const named2 = scale(theme, "font").find(([name, family]) => !name.startsWith("weight") && normal(family.split(",")[0]).replace(/["']/g, "") === first);
3083
+ return named2 ? { exact: `font-${named2[0]}` } : null;
3084
+ }
3085
+ const named = NAMED[property];
3086
+ if (!named) return null;
3087
+ const [utility, namespace] = named;
3088
+ if (variable?.startsWith(`${namespace}-`)) return { exact: `${utility}-${variable.slice(namespace.length + 1)}` };
3089
+ const values = scale(theme, namespace);
3090
+ if (namespace === "shadow") {
3091
+ const same = values.find(([, s]) => normal(s) === normal(v));
3092
+ return same ? { exact: `shadow-${same[0]}` } : null;
3093
+ }
3094
+ if (namespace === "radius") {
3095
+ if (/^(0|0px)$/.test(v)) return { exact: `${utility}-none` };
3096
+ if (/^(9999px|calc\(infinity \* 1px\)|50%)$/.test(v)) return { exact: `${utility}-full` };
3097
+ }
3098
+ if (namespace === "tracking") {
3099
+ const same = values.find(([, s]) => s.trim() === v || /^-?0(em)?$/.test(s.trim()) && /^-?0(em|px)?$/.test(v));
3100
+ return same ? { exact: `tracking-${same[0]}` } : { exact: `tracking-[${v}]` };
3101
+ }
3102
+ if (namespace === "font-weight" || namespace === "leading") {
3103
+ const same = values.find(([, s]) => s.trim() === v);
3104
+ if (same) return { exact: `${utility}-${same[0]}` };
3105
+ if (namespace === "font-weight") return /^\d+$/.test(v) ? { exact: `font-[${v}]` } : null;
3106
+ const n2 = toPx(v, theme);
3107
+ const step = toPx(theme.get("spacing") ?? "0.25rem", theme);
3108
+ if (n2 !== null && step && Math.abs(n2 / step * 4 - Math.round(n2 / step * 4)) < 1e-6) return { exact: `leading-${Math.round(n2 / step * 100) / 100}` };
3109
+ return { exact: `leading-[${v}]` };
3110
+ }
3111
+ const n = toPx(v, theme);
3112
+ if (n === null) return null;
3113
+ let best = null;
3114
+ for (const [name, size] of values) {
3115
+ const p = toPx(size, theme);
3116
+ if (p === null) continue;
3117
+ if (Math.abs(p - n) < 0.01) return { exact: `${utility}-${name}` };
3118
+ if (!best || Math.abs(p - n) < Math.abs(best.px - n)) best = { name, px: p };
3119
+ }
3120
+ const arbitrary = `${utility}-[${px(n)}]`;
3121
+ return best ? { exact: arbitrary, closest: { cls: `${utility}-${best.name}`, px: best.px } } : { exact: arbitrary };
3122
+ }
3123
+ function prefixFor(change, theme) {
3124
+ const widths = change.widths;
3125
+ const points = scale(theme, "breakpoint").map(([name, size]) => ({ name, px: toPx(size, theme) })).filter((b) => b.px !== null);
3126
+ let prefix = "";
3127
+ if (widths?.min !== void 0) prefix += `${points.find((b) => b.px === widths.min)?.name ?? `min-[${widths.min}px]`}:`;
3128
+ if (widths?.max !== void 0) {
3129
+ const at = points.find((b) => b.px === widths.max + 1);
3130
+ prefix += `max-${at ? at.name : `[${widths.max + 1}px]`}:`;
3131
+ }
3132
+ for (const s of change.states ?? []) prefix += `${s}:`;
3133
+ return prefix;
3134
+ }
3135
+ function factsSection(job, root, near = []) {
3136
+ const lines = [];
3137
+ const seen = /* @__PURE__ */ new Set();
3138
+ const add = (line) => {
3139
+ if (!seen.has(line)) lines.push(line);
3140
+ seen.add(line);
3141
+ };
3142
+ let tw = null;
3143
+ try {
3144
+ tw = tailwindOf(root, near, job.changeSet.page?.url);
3145
+ } catch {
3146
+ }
3147
+ if (tw) {
3148
+ const step = toPx(tw.theme.get("spacing") ?? "0.25rem", tw.theme);
3149
+ add(`- Tailwind CSS ${tw.version?.replace(/^[^\d]*/, "") ?? "4"}, its theme in \`${tw.entry}\` (\`@theme\`) and Tailwind's defaults; spacing steps of ${step ? px(step) : "0.25rem"} (\`--spacing\`).`);
3150
+ }
3151
+ for (const edit of job.changeSet.edits) {
3152
+ for (const change of edit.changes) {
3153
+ if (tw && !change.removed) {
3154
+ const cls = classFor(change.property, change.to, tw.theme);
3155
+ if (cls) {
3156
+ const prefix = prefixFor(change, tw.theme);
3157
+ add(
3158
+ `- \`${change.property}: ${change.to}\`${prefix ? ` (${prefix.slice(0, -1).replaceAll(":", ", ")})` : ""} is \`${prefix}${cls.exact}\`${cls.closest ? `, no step of the scale; its closest is \`${prefix}${cls.closest.cls}\` (${px(cls.closest.px)})` : ""}${cls.note ? ` (${cls.note})` : ""}.`
3159
+ );
3160
+ }
3161
+ }
3162
+ const source = change.source;
3163
+ if (source?.kind !== "rule") continue;
3164
+ let at = null;
3165
+ try {
3166
+ at = ruleSource(source.selector, change.property, root, near, source.media);
3167
+ } catch {
3168
+ }
3169
+ if (!at) continue;
3170
+ const d = at.declaration;
3171
+ add(
3172
+ d ? `- \`${change.property}\` is set by \`${source.selector}\` in \`${at.rule.file}:${d.line}\`: \`${d.property}: ${d.value};\`.` : `- \`${change.property}\` is set by \`${source.selector}\`, the rule at \`${at.rule.file}:${at.rule.line}\` (not written in it as is: a mixin or an include gives it).`
3173
+ );
3174
+ }
3175
+ }
3176
+ const request = job.changeSet.request;
3177
+ if (request && request.kind !== "props") {
3178
+ for (const target of [request.target, ...request.others ?? []]) {
3179
+ for (const st of target.style ?? []) {
3180
+ if (st.source?.kind !== "rule") continue;
3181
+ let at = null;
3182
+ try {
3183
+ at = ruleSource(st.source.selector, st.property, root, near, st.source.media);
3184
+ } catch {
3185
+ }
3186
+ if (at?.declaration) add(`- \`${target.path}\`'s \`${st.property}\` is set in \`${at.rule.file}:${at.declaration.line}\`: \`${at.declaration.property}: ${at.declaration.value};\`.`);
3187
+ }
3188
+ }
3189
+ if (tw) lines.push(...tailwindScales(tw));
3190
+ else lines.push(...tokenScales(job.changeSet.tokens ?? []));
3191
+ }
3192
+ const pkg = near.length ? nearestPackage(dirname6(join9(root, near[0])), root) : null;
3193
+ const rebuild = rebuildOf(pkg ?? (tw ? nearestPackage(dirname6(join9(root, tw.entry)), root) : null), root);
3194
+ if (rebuild)
3195
+ add(
3196
+ rebuild.css ? `- Its CSS is rebuilt on save by ${rebuild.by}, so a change works at once: don't build it or check the compiled CSS.` : `- ${rebuild.by[0]?.toUpperCase()}${rebuild.by.slice(1)} updates the page on save: don't build it or check the compiled output.`
3197
+ );
3198
+ return lines.length ? ["## The project", "", ...lines].join("\n") : "";
3199
+ }
3200
+ var MAX_STEPS = 16;
3201
+ var MAX_SCALES = 14;
3202
+ function scaleLine(tw, namespace, label) {
3203
+ const steps = scale(tw.theme, namespace).filter(([name]) => !(namespace === "font" && name.startsWith("weight")));
3204
+ if (!steps.length) return null;
3205
+ const shown = steps.slice(0, MAX_STEPS).map(([name, value]) => {
3206
+ const n = /rem$|^calc\(/.test(value) ? toPx(value, tw.theme) : null;
3207
+ const v = namespace === "font" ? value.split(",")[0].replace(/["']/g, "").trim() : n !== null ? px(n) : value;
3208
+ return `\`${name}\` ${v}`;
3209
+ });
3210
+ return ` - ${label}: ${shown.join(", ")}${steps.length > MAX_STEPS ? ", \u2026" : ""}`;
3211
+ }
3212
+ function tailwindScales(tw) {
3213
+ const colors = scale(tw.theme, "color").filter(([name]) => tw.own.has(`color-${name}`));
3214
+ const lines = [
3215
+ scaleLine(tw, "tracking", "letter spacing (`tracking-`)"),
3216
+ scaleLine(tw, "font-weight", "font weight (`font-`)"),
3217
+ scaleLine(tw, "text", "font size (`text-`)"),
3218
+ scaleLine(tw, "leading", "line height (`leading-`)"),
3219
+ scaleLine(tw, "radius", "radius (`rounded-`)"),
3220
+ scaleLine(tw, "font", "font family (`font-`)"),
3221
+ scaleLine(tw, "breakpoint", "breakpoints"),
3222
+ colors.length ? ` - the project's colors (\`text-\`, \`bg-\`\u2026): ${colors.slice(0, 24).map(([name, value]) => `\`${name}\` ${value}`).join(", ")}${colors.length > 24 ? ", \u2026" : ""}` : null
3223
+ ].filter((l) => !!l);
3224
+ return lines.length ? ["- Its theme's scales (only these exist, with the spacing steps above and Tailwind's palette):", ...lines] : [];
3225
+ }
3226
+ function tokenScales(tokens) {
3227
+ const groups = /* @__PURE__ */ new Map();
3228
+ for (const t of tokens) {
3229
+ const m = /^(--[\w-]*?)-?([\w]+)$/.exec(t.name);
3230
+ const group = m && m[1] && m[1] !== "--" ? `${m[1]}-*` : t.name;
3231
+ const step = m && m[1] && m[1] !== "--" ? m[2] : "";
3232
+ const value = t.now ?? (t.value.length > 40 ? `${t.value.slice(0, 39)}\u2026` : t.value);
3233
+ groups.set(group, [...groups.get(group) ?? [], step ? `${step} ${value}` : value]);
3234
+ }
3235
+ const lines = [...groups].filter(([, steps]) => steps.length > 1).slice(0, MAX_SCALES).map(([group, steps]) => ` - \`${group}\`: ${steps.slice(0, MAX_STEPS).join(", ")}${steps.length > MAX_STEPS ? ", \u2026" : ""}`);
3236
+ return lines.length ? ["- The page's tokens, by scale (what each comes to at this width): use these rather than raw values", ...lines] : [];
3237
+ }
3238
+
3239
+ // src/locate.ts
3240
+ import { existsSync as existsSync6, readdirSync as readdirSync5, readFileSync as readFileSync8, statSync as statSync7 } from "fs";
3241
+ import { basename as basename6, extname as extname5, isAbsolute, join as join10 } from "path";
3242
+ var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3243
+ var BUDGET_MS3 = 800;
3244
+ var CANDIDATE_FILES = 60;
3245
+ var PARENT_LINES = 400;
3246
+ var BODY_LINES = 80;
3247
+ var NEAR_LINES = 30;
3248
+ function searchable(cwd) {
3249
+ return existsSync6(join10(cwd, "package.json")) || existsSync6(join10(cwd, ".git"));
3250
+ }
3251
+ var ENTITIES = {
3252
+ amp: "&",
3253
+ nbsp: " ",
3254
+ quot: '"',
3255
+ apos: "'",
3256
+ lt: "<",
3257
+ gt: ">",
3258
+ rsquo: "'",
3259
+ lsquo: "'",
3260
+ ldquo: '"',
3261
+ rdquo: '"',
3262
+ mdash: "\u2014",
3263
+ ndash: "\u2013",
3264
+ hellip: "\u2026",
3265
+ copy: "\xA9",
3266
+ reg: "\xAE",
3267
+ trade: "\u2122",
3268
+ times: "\xD7",
3269
+ middot: "\xB7",
3270
+ rarr: "\u2192",
3271
+ larr: "\u2190"
3272
+ };
3273
+ function plain(s) {
3274
+ return s.replace(/&(#\d+|#x[0-9a-f]+|[a-z]+);/gi, (m, e) => {
3275
+ if (e[0] === "#") {
3276
+ const code = e[1] === "x" || e[1] === "X" ? Number.parseInt(e.slice(2), 16) : Number(e.slice(1));
3277
+ return Number.isFinite(code) ? String.fromCodePoint(code) : m;
3278
+ }
3279
+ return ENTITIES[e.toLowerCase()] ?? m;
3280
+ }).replace(/[‘’]/g, "'").replace(/[“”]/g, '"').replace(/\s+/g, " ");
3281
+ }
3282
+ function* tagsOn(line) {
3283
+ const re = /<([A-Za-z][\w.:-]*)(?=[\s>/]|$)/g;
3284
+ for (let m = re.exec(line); m; m = re.exec(line)) yield { name: m[1], column: m.index };
3285
+ }
3286
+ var indentOf = (line) => /^\s*/.exec(line)[0].length;
3287
+ var isPlain = (name) => name === name.toLowerCase() && !name.includes(".");
3288
+ function needlesOf(target, url, root, rarity) {
3289
+ const own = target.text?.replace(/…$/, "").trim();
3290
+ const texts = [];
3291
+ const usable = (t) => {
3292
+ const text = t ? plain(t).trim() : "";
3293
+ return text.length >= 2 && text.length <= 80 ? text : void 0;
3294
+ };
3295
+ for (const t of [own, ...target.context?.texts ?? []]) {
3296
+ const text = usable(t);
3297
+ if (text && !texts.includes(text)) texts.push(text);
3298
+ }
3299
+ let route = [];
3300
+ try {
3301
+ if (url)
3302
+ route = new URL(url).pathname.split("/").map((p) => decodeURIComponent(p).replace(/\.[a-z]+$/i, "")).filter((p) => p && p !== "index");
3303
+ } catch {
3304
+ }
3305
+ const served = route.find((p) => !/[\\/]|^\.+$/.test(p) && isFolder(join10(root, p)));
3306
+ const otherSites = /* @__PURE__ */ new Set();
3307
+ if (served) {
3308
+ for (const name of safeList(root))
3309
+ if (name !== served && INDEX_FILES.some((f) => existsSync6(join10(root, name, f)))) otherSites.add(name);
3310
+ }
3311
+ const before = usable(target.context?.before);
3312
+ const after = usable(target.context?.after);
3313
+ const heading = usable(target.context?.heading);
3314
+ return {
3315
+ tag: target.tag.toLowerCase(),
3316
+ ...target.id ? { id: target.id } : {},
3317
+ classes: target.classes.filter((c) => c.length >= 2),
3318
+ texts,
3319
+ attrs: (target.context?.attrs ?? []).map(plain),
3320
+ ...before ? { before } : {},
3321
+ ...after ? { after } : {},
3322
+ ...heading ? { heading } : {},
3323
+ parents: target.context?.parents ?? [],
3324
+ route,
3325
+ ...served ? { served } : {},
3326
+ otherSites,
3327
+ empty: !own && !texts.length && !!target.context,
3328
+ ...own && !target.text?.endsWith("\u2026") ? { own: plain(own).trim() } : {},
3329
+ rarity
3330
+ };
3331
+ }
3332
+ function textWeight(n, text) {
3333
+ const words = wordsOf(text);
3334
+ if (!words.length) return 0;
3335
+ const rarest = Math.max(...words.map(n.rarity));
3336
+ return Math.min(8, Math.max(0.5, rarest) + Math.min(3, (words.length - 1) * 0.5));
3337
+ }
3338
+ function textFound(body2, text) {
3339
+ if (body2.includes(text)) return 1;
3340
+ const words = text.split(" ");
3341
+ if (words.length < 6) return 0;
3342
+ const run = (from) => words.slice(from, from + 5).join(" ");
3343
+ return body2.includes(run(1)) || body2.includes(run(words.length - 6)) || body2.includes(run(words.length >> 1)) ? 0.7 : 0;
3344
+ }
3345
+ function writtenText(code) {
3346
+ return plain(
3347
+ code.replace(/<\?[\s\S]*?(\?>|$)|<%[\s\S]*?(%>|$)|\{\{[\s\S]*?\}\}|\{%[\s\S]*?%\}|\{[^}]*\}/g, " ").replace(/<!--[\s\S]*?-->/g, " ").replace(/<\/?[A-Za-z][^>]*>?/g, " ")
3348
+ ).trim();
3349
+ }
3350
+ function openingAt(lines, index, column) {
3351
+ let text = "";
3352
+ let quote2 = "";
3353
+ let braces = 0;
3354
+ for (let j = index; j < Math.min(lines.length, index + 16); j++) {
3355
+ const line = j === index ? lines[j].slice(column) : lines[j];
3356
+ for (let k = j === index ? 1 : 0; k < line.length; k++) {
3357
+ const ch = line[k];
3358
+ if (ch === "<" && (line[k + 1] === "?" || line[k + 1] === "%")) {
3359
+ const close = line.indexOf(line[k + 1] === "?" ? "?>" : "%>", k + 2);
3360
+ if (close < 0) break;
3361
+ k = close + 1;
3362
+ continue;
3363
+ }
3364
+ if (quote2) {
3365
+ if (ch === quote2) quote2 = "";
3366
+ } else if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
3367
+ else if (ch === "{") braces++;
3368
+ else if (ch === "}") braces = Math.max(0, braces - 1);
3369
+ else if (ch === ">" && !braces) return { text: text + line.slice(0, k + 1), end: j };
3370
+ }
3371
+ text += `${line}
3372
+ `;
3373
+ }
3374
+ return { text, end: index };
3375
+ }
3376
+ function classAttrOf(opening) {
3377
+ const re = /(?<![\w-]):?(?:class|className)\s*=\s*(?:"([^"]*)"|'([^']*)'|`([^`]*)`|\{([\s\S]*?)\}(?=\s|\/?>|$))/g;
3378
+ let words = null;
3379
+ let dynamic = false;
3380
+ for (let m = re.exec(opening); m; m = re.exec(opening)) {
3381
+ const quoted = m[1] ?? m[2] ?? m[3];
3382
+ let value;
3383
+ if (quoted !== void 0 && !m[0].startsWith(":")) {
3384
+ value = quoted.replace(/<\?[\s\S]*?\?>|<%[\s\S]*?%>|\{\{[\s\S]*?\}\}|\{%[\s\S]*?%\}|\$\{[^}]*\}|\{[^}]*\}/g, () => {
3385
+ dynamic = true;
3386
+ return " ";
3387
+ });
3388
+ } else {
3389
+ dynamic = true;
3390
+ value = [...(quoted ?? m[4] ?? "").matchAll(/["'`]([^"'`]*)["'`]/g)].map((s) => s[1]).join(" ");
3391
+ }
3392
+ words = [...words ?? [], ...wordsOf(value)];
3393
+ }
3394
+ return words ? { words, dynamic } : null;
3395
+ }
3396
+ function classesScore(n, classes, opening) {
3397
+ const facts = [];
3398
+ if (!classes.length) return { score: 0, clear: false, facts };
3399
+ const words = new Set(wordsOf(opening));
3400
+ let matched = 0;
3401
+ let score = 0;
3402
+ for (const c of classes) {
3403
+ if (!words.has(c)) continue;
3404
+ matched++;
3405
+ facts.push(`class:${c}`);
3406
+ score += Math.max(0.2, n.rarity(c));
3407
+ }
3408
+ if (!matched) return { score: 0, clear: false, facts };
3409
+ const attr = classAttrOf(opening);
3410
+ let consistent = false;
3411
+ if (attr?.words.length) {
3412
+ const extras = attr.words.filter((c) => !classes.includes(c));
3413
+ const extra = extras.length;
3414
+ for (const c of extras) facts.push(`-class:${c}`);
3415
+ if (!attr.dynamic) {
3416
+ if (extra && classes.length - matched >= 2) return { score: -8, clear: false, facts: [...facts, "-classes"] };
3417
+ score -= Math.min(9, extra * 3);
3418
+ if (!extra && matched === classes.length) {
3419
+ score += 3;
3420
+ facts.push("classes-exact");
3421
+ }
3422
+ } else if (extra > attr.words.length / 2) score -= Math.min(4, extra);
3423
+ consistent = extra === 0;
3424
+ }
3425
+ const clear = matched >= Math.ceil(classes.length * 0.6) || consistent && attr?.dynamic === true || score >= 6;
3426
+ return { score, clear, facts };
3427
+ }
3428
+ function bodyEnd(lines, index, openingEnd) {
3429
+ const indent = indentOf(lines[index]);
3430
+ const last = Math.min(lines.length - 1, index + BODY_LINES);
3431
+ for (let j = openingEnd + 1; j <= last; j++) {
3432
+ const line = lines[j];
3433
+ if (!line.trim()) continue;
3434
+ const ind = indentOf(line);
3435
+ if (ind < indent) return j - 1;
3436
+ if (ind === indent) return /^\s*<\//.test(line) ? j : j - 1;
3437
+ }
3438
+ return last;
3439
+ }
3440
+ function scoreAt(n, file, beside, index, column, name) {
3441
+ const lower = name.toLowerCase();
3442
+ if (lower !== n.tag && isPlain(name)) return null;
3443
+ const { lines } = file;
3444
+ const opening = openingAt(lines, index, column);
3445
+ const kinds = /* @__PURE__ */ new Set();
3446
+ const facts = new Set(lower === n.tag ? ["tag"] : []);
3447
+ let score = lower === n.tag ? 1 : 0;
3448
+ if (n.id && opening.text.includes(n.id) && new RegExp(`\\bid\\s*=\\s*[{"'\`]*${escape(n.id)}["'\`}]`).test(opening.text)) {
3449
+ score += 8;
3450
+ kinds.add("id");
3451
+ facts.add("id");
3452
+ }
3453
+ const classes = classesScore(n, n.classes, opening.text);
3454
+ if (classes.clear) kinds.add("classes");
3455
+ for (const f of classes.facts) facts.add(f);
3456
+ score += classes.score;
3457
+ if (n.classes.length && !classes.score && !kinds.has("id") && classAttrOf(opening.text)?.words.length) return null;
3458
+ const end = bodyEnd(lines, index, opening.end);
3459
+ if (!n.texts.length && !n.empty) {
3460
+ } else if (n.empty) {
3461
+ const code = [lines[index].slice(column), ...lines.slice(index + 1, end + 1)].join("\n");
3462
+ if (writtenText(code).length >= 2) {
3463
+ score -= 4;
3464
+ facts.add("-text");
3465
+ }
3466
+ }
3467
+ if (n.texts.length || n.attrs.length) {
3468
+ const code = [lines[index].slice(column), ...lines.slice(index + 1, end + 1)].join("\n");
3469
+ const body2 = plain(code);
3470
+ let texts = 0;
3471
+ for (const t of n.texts) {
3472
+ const found = textFound(body2, t);
3473
+ if (found) facts.add(`text:${t}`);
3474
+ texts += found * textWeight(n, t);
3475
+ }
3476
+ if (texts) {
3477
+ score += Math.min(14, texts);
3478
+ kinds.add("text");
3479
+ }
3480
+ const written = n.texts.length ? writtenText(code) : "";
3481
+ if (written && n.own && written.length <= 120 && !n.own.includes(written) && !body2.includes(n.own)) {
3482
+ score -= 4;
3483
+ facts.add("-text");
3484
+ }
3485
+ let attrs = 0;
3486
+ for (const a of n.attrs)
3487
+ if (body2.includes(a)) {
3488
+ facts.add(`attr:${a}`);
3489
+ attrs += Math.min(6, Math.max(1, textWeight(n, a)));
3490
+ }
3491
+ if (attrs) {
3492
+ score += Math.min(10, attrs);
3493
+ kinds.add("attrs");
3494
+ }
3495
+ }
3496
+ let near = 0;
3497
+ const within = (at, from, to) => at.some((i) => i >= from && i <= to);
3498
+ if (n.before && (within(beside.before, index - NEAR_LINES, index - 1) || beside.before.includes(index) && plain(lines[index].slice(0, column)).includes(n.before))) {
3499
+ near += Math.min(5, textWeight(n, n.before));
3500
+ facts.add("before");
3501
+ }
3502
+ if (n.after && within(beside.after, end, end + NEAR_LINES)) {
3503
+ near += Math.min(5, textWeight(n, n.after));
3504
+ facts.add("after");
3505
+ }
3506
+ if (n.heading) {
3507
+ let h = -1;
3508
+ for (const i of beside.headings) if (i < index) h = i;
3509
+ let last = h;
3510
+ while (h >= 0 && last < Math.min(h + 2, index - 1) && !/<\/h[1-6]>/i.test(lines[last])) last++;
3511
+ if (h >= 0 && plain(lines.slice(h, last + 1).join(" ")).includes(n.heading)) {
3512
+ near += Math.min(4, textWeight(n, n.heading));
3513
+ facts.add("heading");
3514
+ }
3515
+ }
3516
+ if (near) {
3517
+ score += near;
3518
+ kinds.add("near");
3519
+ }
3520
+ const parents = parentsScore(n, lines, index, column);
3521
+ if (parents.score) {
3522
+ score += parents.score;
3523
+ kinds.add("parents");
3524
+ for (let i = 0; i < parents.found; i++) facts.add(`parent:${i}`);
3525
+ }
3526
+ return { file, index, column, score, classScore: classes.score, kinds, facts };
3527
+ }
3528
+ var VOID = /* @__PURE__ */ new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
3529
+ function selfClosing(lines, index, column) {
3530
+ const rest = lines[index].slice(column);
3531
+ const end = rest.indexOf(">");
3532
+ if (end > 0 && !/["'`{]/.test(rest.slice(0, end))) return rest[end - 1] === "/";
3533
+ return /\/>$/.test(openingAt(lines, index, column).text);
3534
+ }
3535
+ function parentOf(lines, index, column) {
3536
+ const open = [];
3537
+ for (let j = index; j >= Math.max(0, index - PARENT_LINES); j--) {
3538
+ const line = j === index ? lines[j].slice(0, column) : lines[j];
3539
+ if (!line.includes("<")) continue;
3540
+ const tags = [...line.matchAll(/<(\/?)([A-Za-z][\w.:-]*)(?=[\s>/]|$)/g)];
3541
+ for (let t = tags.length - 1; t >= 0; t--) {
3542
+ const m = tags[t];
3543
+ const name = m[2].toLowerCase();
3544
+ if (m[1]) {
3545
+ open.push(name);
3546
+ continue;
3547
+ }
3548
+ if (VOID.has(name) || selfClosing(lines, j, m.index)) continue;
3549
+ const closed = open.lastIndexOf(name);
3550
+ if (closed >= 0) {
3551
+ open.length = closed;
3552
+ continue;
3553
+ }
3554
+ return { index: j, column: m.index, name: m[2] };
3555
+ }
3556
+ }
3557
+ return null;
3558
+ }
3559
+ function parentsScore(n, lines, index, column) {
3560
+ let score = 0;
3561
+ let found = 0;
3562
+ let at = { index, column };
3563
+ for (const p of n.parents) {
3564
+ const parent = parentOf(lines, at.index, at.column);
3565
+ if (!parent || isPlain(parent.name) && parent.name !== p.tag) break;
3566
+ const opening = openingAt(lines, parent.index, parent.column).text;
3567
+ if (p.id && opening.includes(p.id)) score += 4;
3568
+ else if (p.classes.length) {
3569
+ const classes = classesScore(n, p.classes, opening);
3570
+ if (!classes.clear) break;
3571
+ score += Math.min(4, 1 + Math.max(0, classes.score) / 2);
3572
+ } else if (classAttrOf(opening)?.words.length) break;
3573
+ else score += 0.5;
3574
+ at = parent;
3575
+ found++;
3576
+ }
3577
+ return { score, found };
3578
+ }
3579
+ function routeOf(n, rel) {
3580
+ if (!n.route.length) return { score: 0, facts: [] };
3581
+ const parts = rel.split(/[\\/]/);
3582
+ const names = new Set(parts.map((p) => p.replace(/\.[a-z]+$/i, "")));
3583
+ const like = n.route.filter((p) => names.has(p));
3584
+ const score = Math.min(5, like.length * 2.5);
3585
+ const facts = like.map((p) => `route:${p}`);
3586
+ if (parts.length > 1 && n.otherSites.has(parts[0])) return { score: score - 20, facts: [...facts, "-site"] };
3587
+ if (n.served && parts.length > 1 && parts[0] !== n.served) return { score: score - 3, facts: [...facts, "-folder"] };
3588
+ return { score, facts };
3589
+ }
3590
+ var INDEX_FILES = ["index.php", "index.html", "index.htm"];
3591
+ var safeList = (dir) => {
3592
+ try {
3593
+ return readdirSync5(dir).filter((name) => !name.startsWith(".") && isFolder(join10(dir, name)));
3594
+ } catch {
3595
+ return [];
3596
+ }
3597
+ };
3598
+ var isFolder = (path) => {
3599
+ try {
3600
+ return statSync7(path).isDirectory();
3601
+ } catch {
3602
+ return false;
3603
+ }
3604
+ };
3605
+ function fileScore(n, file) {
3606
+ let score = 0;
3607
+ if (n.id && file.words.has(n.id)) score += 8;
3608
+ for (const c of n.classes) if (file.words.has(c)) score += n.rarity(c);
3609
+ for (const t of [...n.texts, ...n.attrs]) {
3610
+ const words = wordsOf(t);
3611
+ if (words.length && words.every((w) => file.words.has(w))) score += textWeight(n, t);
3612
+ }
3613
+ return score;
3614
+ }
3615
+ function besideOf(n, file) {
3616
+ const beside = { before: [], after: [], headings: [] };
3617
+ const lead = (t) => t?.split(" ")[0];
3618
+ const firstBefore = lead(n.before);
3619
+ const firstAfter = lead(n.after);
3620
+ file.lines.forEach((line, i) => {
3621
+ if (n.heading && /<h[1-6][\s>]/i.test(line)) beside.headings.push(i);
3622
+ if (firstBefore && line.includes(firstBefore) && plain(line).includes(n.before)) beside.before.push(i);
3623
+ if (firstAfter && line.includes(firstAfter) && plain(line).includes(n.after)) beside.after.push(i);
3624
+ });
3625
+ return beside;
3626
+ }
3627
+ function scoreFile(n, file, from = 0, to = file.lines.length) {
3628
+ const out = [];
3629
+ const beside = besideOf(n, file);
3630
+ for (let i = from; i < Math.min(to, file.lines.length); i++) {
3631
+ const line = file.lines[i];
3632
+ if (!line.includes("<")) continue;
3633
+ for (const { name, column } of tagsOn(line)) {
3634
+ const found = scoreAt(n, file, beside, i, column, name);
3635
+ if (found?.kinds.size) out.push(found);
3636
+ }
3637
+ }
3638
+ return out;
3639
+ }
3640
+ function convincing(c) {
3641
+ if (c.kinds.has("id")) return c.score >= 9;
3642
+ if (c.kinds.size >= 2) return c.score >= 10;
3643
+ return c.kinds.has("classes") && c.classScore >= 12;
3644
+ }
3645
+ var MARGIN = 4;
3646
+ function locate(target, root, options = {}) {
3647
+ const found = candidates(target, root, options);
3648
+ if (!found) return null;
3649
+ if ("known" in found) return found.known;
3650
+ const all = found.list;
3651
+ const best = all[0];
3652
+ if (!best || !convincing(best)) return null;
3653
+ const at = (c) => ({ file: c.file.rel, line: c.index + 1, snippet: snippetAt(c.file.lines, c.index) });
3654
+ const apart = (a, b) => a.file !== b.file || a.index !== b.index || a.column !== b.column;
3655
+ const elsewhere = all.filter((c) => apart(c, best));
3656
+ const second = elsewhere[0];
3657
+ if (!second || clearlyAhead(best, second)) return at(best);
3658
+ const third = elsewhere.find((c) => apart(c, second));
3659
+ if (convincing(second) && (!third || clearlyAhead(best, third))) return { ...at(best), also: at(second) };
3660
+ return null;
3661
+ }
3662
+ function clearlyAhead(best, other) {
3663
+ const diff = best.score - other.score;
3664
+ if (diff >= MARGIN) return true;
3665
+ if (diff <= 0) return false;
3666
+ const pro = (c) => [...c.facts].filter((f) => !f.startsWith("-"));
3667
+ const con = (c) => [...c.facts].filter((f) => f.startsWith("-"));
3668
+ return pro(other).every((f) => best.facts.has(f)) && con(best).every((f) => other.facts.has(f)) && pro(best).length + con(other).length > pro(other).length + con(best).length;
3669
+ }
3670
+ function candidates(target, root, options = {}) {
3671
+ const { sources, rarity } = markupSources(root);
3672
+ const deadline = options.deadline ?? Date.now() + BUDGET_MS3;
3673
+ const n = needlesOf(target, options.url, root, rarity);
3674
+ const known = target.source?.file && target.source.line ? sourcePath(target.source.file, root) : null;
3675
+ if (known && target.source?.line) {
3676
+ const from = target.source.line - 1;
3677
+ const file = sources.find((s) => s.rel === known);
3678
+ if (file) {
3679
+ const own = scoreFile(n, file, from, from + 200).sort((a, b) => b.score - a.score)[0];
3680
+ const index = own && own.score >= 2 ? own.index : from;
3681
+ return { known: { file: known, line: index + 1, snippet: snippetAt(file.lines, index) } };
3682
+ }
3683
+ }
3684
+ if (!n.id && !n.texts.length && !n.attrs.length && !n.classes.length) return null;
3685
+ const files = sources.map((file) => ({ file, score: fileScore(n, file) })).filter((f) => f.score > 0).sort((a, b) => b.score - a.score).slice(0, CANDIDATE_FILES);
3686
+ const list2 = [];
3687
+ for (const { file } of files) {
3688
+ if (Date.now() > deadline) break;
3689
+ const route = routeOf(n, file.rel);
3690
+ for (const c of scoreFile(n, file)) list2.push({ ...c, score: c.score + route.score, facts: /* @__PURE__ */ new Set([...c.facts, ...route.facts]) });
3691
+ }
3692
+ return { list: list2.sort((a, b) => b.score - a.score) };
3693
+ }
3694
+ function snippetAt(lines, index) {
3695
+ return lines.slice(Math.max(0, index - 2), index + 3).map((l) => l.length > 160 ? `${l.slice(0, 159)}\u2026` : l).join("\n");
3696
+ }
3697
+ function sourcePath(file, root) {
3698
+ const rel = isAbsolute(file) ? relPath(root, file) : file.replace(/^\.\//, "");
3699
+ if (rel.startsWith("..") || isAbsolute(rel)) return null;
3700
+ return existsSync6(join10(root, rel)) ? rel : null;
3701
+ }
3702
+ function componentFile(name, root, deadline = Date.now() + BUDGET_MS3, within) {
3703
+ if (!/^[A-Za-z_$][\w$]*$/.test(name)) return null;
3704
+ const declaration = new RegExp(
3705
+ `^\\s*(export\\s+(?:default\\s+)?)?(?:(?:async\\s+)?function\\s*\\*?\\s+${name}\\b|class\\s+${name}\\b|(?:const|let|var)\\s+${name}\\s*[:=])`
3706
+ );
3707
+ let best = null;
3708
+ const files = within ? [join10(root, within)] : sourceFiles(root);
3709
+ for (const file of files) {
3710
+ if (Date.now() > deadline) break;
3711
+ if (!/\.[jt]sx?$|\.mjs$/.test(file)) continue;
3712
+ let content;
3713
+ try {
3714
+ content = readFileSync8(file, "utf8");
3715
+ } catch {
3716
+ continue;
3717
+ }
3718
+ if (!content.includes(name)) continue;
3719
+ const lines = content.split("\n");
3720
+ for (let i = 0; i < lines.length; i++) {
3721
+ const m = declaration.exec(lines[i]);
3722
+ if (!m) continue;
3723
+ const score = (basename6(file).replace(/\.[^.]+$/, "") === name ? 2 : 0) + (m[1] ? 1 : 0);
3724
+ if (!best || score > best.score) best = { file, line: i + 1, score };
3725
+ break;
3726
+ }
3727
+ }
3728
+ return best ? { file: relPath(root, best.file), line: best.line } : null;
3729
+ }
3730
+ function withComponentFiles(job, root) {
3731
+ if (!searchable(root)) return job;
3732
+ const deadline = Date.now() + BUDGET_MS3;
3733
+ const fill = (target) => {
3734
+ const source = target.source;
3735
+ if (!source?.component || source.line) return target;
3736
+ const known = source.file ? sourcePath(source.file, root) : null;
3737
+ if (source.file && !known) return target;
3738
+ const found = componentFile(source.component, root, deadline, known ?? void 0);
3739
+ return found ? { ...target, source: { ...source, file: found.file, line: found.line } } : target;
3740
+ };
3741
+ const workspace = workspaceRoot(root);
3742
+ const declared = (name) => {
3743
+ const found = componentFile(name, workspace, deadline);
3744
+ return found ? { file: relPath(root, join10(workspace, found.file)), line: found.line } : null;
3745
+ };
3746
+ const local = (file) => {
3747
+ const path = join10(workspace, file);
3748
+ return existsSync6(path) ? relPath(root, path) : file;
3749
+ };
3750
+ const mention = (r) => {
3751
+ if (r.kind === "token") return r.source ? { ...r, source: { ...r.source, file: local(r.source.file) } } : r;
3752
+ if (r.kind === "element") return { ...r, target: fill(r.target) };
3753
+ if (r.kind === "unlisted") {
3754
+ const source2 = declared(r.name);
3755
+ return source2 ? { kind: "component", name: r.name, source: source2 } : r;
3756
+ }
3757
+ if (r.kind !== "component") return r;
3758
+ if (r.source) {
3759
+ const path = join10(workspace, r.source.file);
3760
+ return existsSync6(path) ? { ...r, source: { ...r.source, file: relPath(root, path) } } : r;
3761
+ }
3762
+ if (r.target?.source?.file) return { ...r, target: fill(r.target) };
3763
+ const source = declared(r.name);
3764
+ return source ? { ...r, source } : r;
3765
+ };
3766
+ const mentions = (refs) => refs?.length ? { references: refs.map(mention) } : {};
3767
+ const { changeSet } = job;
3768
+ const request = changeSet.request;
3769
+ return {
3770
+ ...job,
3771
+ changeSet: {
3772
+ ...changeSet,
3773
+ edits: changeSet.edits.map((e) => ({ ...e, target: fill(e.target) })),
3774
+ ...changeSet.fileTokens ? { fileTokens: changeSet.fileTokens.map((t) => ({ ...t, file: local(t.file) })) } : {},
3775
+ ...request ? {
3776
+ request: {
3777
+ ...request,
3778
+ target: fill(request.target),
3779
+ ...request.others ? { others: request.others.map(fill) } : {},
3780
+ ...request.kind === "comment" ? { thread: request.thread.map((m) => ({ ...m, ...mentions(m.references) })) } : mentions(request.references)
3781
+ }
3782
+ } : {}
3783
+ }
3784
+ };
3785
+ }
3786
+ function jobLocations(job, root) {
3787
+ if (!searchable(root)) return [];
3788
+ const targets = job.changeSet.request ? requestTargets(job.changeSet.request) : job.changeSet.edits.map((e) => e.target);
3789
+ markupSources(root);
3790
+ const deadline = Date.now() + BUDGET_MS3;
3791
+ const found = [];
3792
+ for (const target of targets) {
3793
+ const at = locate(target, root, { url: job.changeSet.page?.url, deadline });
3794
+ if (at) found.push({ target, at });
3795
+ }
3796
+ return found;
3797
+ }
3798
+ function whereSection(job, root, located = jobLocations(job, root)) {
3799
+ if (!searchable(root)) return "";
3800
+ const found = [];
3801
+ for (const { target, at } of located) {
3802
+ const snippet = (place) => [
3803
+ "",
3804
+ ` \`\`\`${extname5(place.file).slice(1) || "text"}`,
3805
+ ...place.snippet.split("\n").map((l) => ` ${l}`),
3806
+ " ```"
3807
+ ];
3808
+ if (at.also)
3809
+ found.push(
3810
+ `- \`${target.path}\` \u2192 one of these two (the same markup in both; the page doesn't say which):`,
3811
+ "",
3812
+ ` \`${at.file}:${at.line}\`:`,
3813
+ ...snippet(at),
3814
+ "",
3815
+ ` \`${at.also.file}:${at.also.line}\`:`,
3816
+ ...snippet(at.also)
3817
+ );
3818
+ else found.push(`- \`${target.path}\` \u2192 \`${at.file}:${at.line}\`:`, ...snippet(at));
3819
+ }
3820
+ if (!found.length) return "";
3821
+ return [
3822
+ "## Where the code probably is",
3823
+ "",
3824
+ "Pilot searched the project for these elements (by component, and by their classes, texts, attributes and parents together). Start there; if it isn't the right place (the text comes from a prop, a translation, a CMS), search as usual.",
3825
+ "",
3826
+ ...found
3827
+ ].join("\n");
3828
+ }
3829
+
3830
+ // src/pool.ts
3831
+ var MAX_JOBS = 20;
3832
+ var MAX_AGE_MS = 24 * 60 * 60 * 1e3;
3833
+ var SessionPool = class {
3834
+ constructor(folder, agent, file, now = Date.now) {
3835
+ this.folder = folder;
3836
+ this.agent = agent;
3837
+ this.file = file;
3838
+ this.now = now;
3839
+ this.sessions = this.fresh(savedSessions(folder, file).filter((s) => s.agent === agent));
3840
+ }
3841
+ folder;
3842
+ agent;
3843
+ file;
3844
+ now;
3845
+ sessions;
3846
+ busy = /* @__PURE__ */ new Set();
3847
+ waiters = /* @__PURE__ */ new Map();
3848
+ /** The sessions still usable (not retired), for tests and the log. */
3849
+ get kept() {
3850
+ return this.sessions;
3851
+ }
3852
+ /** A free session for a new job, else none (a new one starts). */
3853
+ take() {
3854
+ this.sessions = this.fresh(this.sessions);
3855
+ const free = this.sessions.find((s) => !this.busy.has(s.id));
3856
+ if (free) this.busy.add(free.id);
3857
+ return this.leaseOf(free?.id);
3858
+ }
3859
+ /** The session `id` for a follow-up of its job: when another job has it, once it's free. Not one of the pool's: just a lease on it. */
3860
+ async takeOwn(id) {
3861
+ while (this.busy.has(id)) await new Promise((resolve5) => this.waiters.set(id, [...this.waiters.get(id) ?? [], resolve5]));
3862
+ this.busy.add(id);
3863
+ return this.leaseOf(id);
3864
+ }
3865
+ leaseOf(resume) {
3866
+ let released = false;
3867
+ return {
3868
+ ...resume ? { resume } : {},
3869
+ release: (session) => {
3870
+ if (released) return;
3871
+ released = true;
3872
+ if (resume) this.free(resume);
3873
+ if (resume && session !== resume) this.sessions = this.sessions.filter((s) => s.id !== resume);
3874
+ if (session) {
3875
+ const known = this.sessions.find((s) => s.id === session);
3876
+ if (known) known.jobs++;
3877
+ else this.sessions.push({ agent: this.agent, id: session, jobs: 1, since: this.now() });
3878
+ }
3879
+ this.sessions = this.fresh(this.sessions);
3880
+ this.save();
3881
+ }
3882
+ };
3883
+ }
3884
+ free(id) {
3885
+ this.busy.delete(id);
3886
+ const next = this.waiters.get(id)?.shift();
3887
+ if (next) next();
3888
+ }
3889
+ /** Without the retired ones. */
3890
+ fresh(sessions) {
3891
+ return sessions.filter((s) => s.jobs < MAX_JOBS && this.now() - s.since < MAX_AGE_MS);
3892
+ }
3893
+ save() {
3894
+ try {
3895
+ const others = savedSessions(this.folder, this.file).filter((s) => s.agent !== this.agent);
3896
+ saveSessions(this.folder, [...others, ...this.sessions], this.file);
3897
+ } catch {
3898
+ }
3899
+ }
3900
+ };
3901
+
3902
+ // src/prompt.ts
3903
+ function jobPrompt(job, where = "", options = {}) {
3904
+ 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, options);
3905
+ return `${body2}${where ? `
3906
+ ${where}
3907
+ ` : ""}
3908
+ ---
3909
+ ${runFooter(job)}
3910
+ `;
3911
+ }
3912
+ function runFooter(job) {
3913
+ const props = job.changeSet.request?.kind === "props";
3914
+ const { request, edits } = job.changeSet;
3915
+ const several = (request ? requestTargets(request) : edits).length > 1;
3916
+ return [
3917
+ 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, and don't check your edit afterwards (no git diff, script or second read of the file): Pilot does.`,
3918
+ "",
3919
+ 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:",
3920
+ "",
3921
+ "```pilot",
3922
+ props ? `{"props": [{"name": "tone", "type": "options", "options": ["light", "dark"], "default": "light", "description": "a few words, when the name doesn't say"}]}` : several ? '{"question": {"text": "One short sentence?", "choices": ["Your suggestion", "Another"], "element": 2}}' : '{"question": {"text": "One short sentence?", "choices": ["Your suggestion", "Another"]}}',
3923
+ "```",
3924
+ ...props ? ["", "`type` is one of `options`, `boolean`, `text`, `number`; `options` only for `options`."] : [],
3925
+ ...!props && several ? ["", "`element`: the number of the element it's about (its heading's), so the designer sees it there; leave it out when it's about all of them."] : [],
3926
+ "",
3927
+ // What runs were refused most, for nothing (a skill's checks): reading with `cat`, fetching the page with `curl`.
3928
+ "Read and search files with your own file tools, not shell commands (`cat`, `cd`, `grep`), and don't fetch or open the page (`curl`, a browser): Pilot checks it itself.",
3929
+ "",
3930
+ // Refused stays refused however it's put: a run tried `git show` five ways, a model round each.
3931
+ "If you were refused something you needed (a tool, a command, a website: it would have asked the designer, and no one can answer in this run), list it in that block as `refused`, and do without it: it stays refused however you put it, so don't retry it another way. Pilot tells the designer how to allow it, so don't explain that yourself:",
3932
+ "",
3933
+ "```pilot",
3934
+ `{"refused": [{"mcp": "the MCP server's name"}, {"command": "the command, as you ran it"}, {"web": "the site's domain"}, {"tool": "any other tool's name"}]}`,
3935
+ "```"
3936
+ ].join("\n");
3937
+ }
3938
+ function answered(job) {
3939
+ const meaning = job.answer ? sharedChoiceMeaning(job.answer) : null;
3940
+ return [
3941
+ "# Pilot: the designer answered your question",
3942
+ "",
3943
+ `You did this job and asked the designer: ${job.question?.text}`,
3944
+ "",
3945
+ "Their answer:",
3946
+ "",
3947
+ job.answer?.trim().split("\n").map((l) => `> ${l}`).join("\n"),
3948
+ "",
3949
+ ...meaning ? [`What that means for the code: ${meaning}`, ""] : [],
3950
+ "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.)",
3951
+ "",
3952
+ "The job, for reference:",
3953
+ "",
3954
+ formatPrompt(job.changeSet)
3955
+ ].join("\n");
3956
+ }
3957
+ function followUp(job) {
3958
+ const lines = [
3959
+ "# Pilot design edits: follow-up",
3960
+ "",
3961
+ "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):",
3962
+ ""
3963
+ ];
3964
+ for (const d of job.differences ?? []) {
3965
+ const edit = job.changeSet.edits.find((e) => e.target.selector === d.selector);
3966
+ const where = edit ? `\`${edit.target.path}\` (selector \`${d.selector}\`${edit.target.text ? `, text "${edit.target.text}"` : ""})` : `\`${d.selector}\``;
3967
+ lines.push(`- ${where}: \`${d.property}\` should be \`${d.expected}\`, the page gives \`${d.actual ?? "?"}\`.`);
3968
+ }
3969
+ lines.push(
3970
+ "",
3971
+ "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. A media query, state or condition the project already had for a base change is meant to win where it applies (Pilot checks a base change only where it doesn't): keep it, don't flatten it. 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."
3972
+ );
3973
+ if (job.changeSet.request?.kind === "comment")
3974
+ lines.push(
3975
+ "",
3976
+ "These edits came with the designer's comment, which was written after them. Where you did what the comment asked instead of an edit's value, that's right: keep it, don't switch to the edit's value, and say so in your notes."
3977
+ );
3978
+ return lines.join("\n");
3979
+ }
3980
+ function notesFor(job) {
3981
+ switch (job.changeSet.request?.kind) {
3982
+ case "comment":
3983
+ 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";
3984
+ case "responsive":
3985
+ return "what changed at which widths, anything left for the designer";
3986
+ case "break-and-fix":
3987
+ return "what broke and how you fixed it, anything for the designer to decide";
3988
+ case "props":
3989
+ return "one short sentence for the designer, like a chat message; the props go in `props`";
3990
+ default:
3991
+ return "values you approximated, anything you did differently";
3992
+ }
3993
+ }
3994
+ function taskFollowUp(job) {
3995
+ const request = job.changeSet.request;
3996
+ const target = `\`${request?.target.path ?? "the element"}\``;
3997
+ if (request?.kind === "comment")
3998
+ return [
3999
+ "# Pilot: props, follow-up",
4000
+ "",
4001
+ `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:`,
4002
+ "",
4003
+ ...(job.issues ?? []).map((i) => `- ${i}`),
4004
+ "",
4005
+ "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.",
4006
+ "",
4007
+ "The comment, for reference:",
4008
+ "",
4009
+ formatPrompt(job.changeSet)
4010
+ ].join("\n");
4011
+ const breakFix = request?.kind === "break-and-fix";
4012
+ const lines = [
4013
+ breakFix ? "# Pilot: break and fix, follow-up" : "# Pilot: make responsive, follow-up",
4014
+ "",
4015
+ 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:`,
4016
+ "",
4017
+ ...(job.issues ?? []).map((i) => `- ${i}`),
4018
+ "",
4019
+ "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.",
4020
+ "",
4021
+ "The task, for reference:",
4022
+ "",
4023
+ formatPrompt(job.changeSet)
4024
+ ];
4025
+ return lines.join("\n");
4026
+ }
4027
+ function skillOf(job) {
4028
+ const request = job.changeSet.request;
4029
+ if (request?.kind !== "comment" || job.attempt === 2 || job.answer) return void 0;
4030
+ const skill = request.thread.at(-1)?.skill;
4031
+ return skill && SKILL_NAME.test(skill) ? skill : void 0;
4032
+ }
4033
+
4034
+ // src/run.ts
4035
+ var SLOTS = 5;
4036
+ var CANCEL_POLL_MS = 2e3;
4037
+ var ACTIVITY_EVERY_MS = 15e3;
4038
+ var RUN_TIMEOUT_MS = 20 * 6e4;
4039
+ var WAIT_MS = 10 * 6e4;
4040
+ var RunnerError = class extends Error {
4041
+ };
4042
+ var RunnerStopped = class extends Error {
4043
+ };
4044
+ async function startRunner(options) {
4045
+ const out = options.out ?? ((line) => process.stdout.write(`${line}
4046
+ `));
4047
+ const choose = options.choose ?? (async () => 0);
4048
+ const project = options.cwd;
4049
+ if (!searchable(project)) {
4050
+ throw new RunnerError(`${project} isn't a project folder (no package.json or .git). Run npx usepilot in your project's folder.`);
4051
+ }
4052
+ if (!options.waitForAgent) markSetUp(project, options.configFile);
4053
+ let state = options.waitForAgent ? await readiness(options, choose) : { ready: await pickAgent(options, choose, out) };
4054
+ const first = state.ready?.cli ?? state.target;
4055
+ const agent = {
4056
+ id: randomUUID2(),
4057
+ label: `${first?.label ?? "Pilot"} \xB7 ${basename7(project)}`,
4058
+ folder: project,
4059
+ ...first ? { kind: first.kind } : {},
4060
+ ...state.ready ? {} : { setup: state.setup }
4061
+ };
4062
+ const bridge = new Bridge(agent, options.port ?? (Number(process.env.PILOT_PORT) || DEFAULT_BRIDGE_PORT));
4063
+ let origin;
4064
+ try {
4065
+ origin = await pickSite(bridge, options, out);
4066
+ if (options.signal?.aborted) throw new RunnerStopped("stopped");
4067
+ } catch (error) {
4068
+ await bridge.close();
4069
+ throw error;
4070
+ }
4071
+ await bridge.launch(origin);
4072
+ out(
4073
+ state.ready ? `Pilot is on ${origin}, every page, with ${state.ready.cli.label}. Send from the toolbar; jobs show here. Ctrl+C stops.` : `Pilot is on ${origin}, every page. ${setupLine(state.setup)}`
4074
+ );
4075
+ setImmediate(() => {
4076
+ warmSources(project);
4077
+ warmStyles(project);
4078
+ });
4079
+ const stop = new AbortController();
4080
+ const runs = /* @__PURE__ */ new Set();
4081
+ let picked = state.ready ?? null;
4082
+ const start = ({ cli, bin }) => {
4083
+ const checkFlags = options.bin ? void 0 : () => missingFlags(cli, bin).catch(() => null);
4084
+ void checkFlags?.().then((missing) => {
4085
+ if (missing?.length) out(outdatedNote(cli, missing));
4086
+ });
4087
+ const pool = new SessionPool(project, cli.kind, options.configFile);
4088
+ const slots = options.slots ?? SLOTS;
4089
+ for (let i = 0; i < slots; i++) {
4090
+ const loop = (async () => {
4091
+ while (!stop.signal.aborted) {
4092
+ let job = null;
4093
+ try {
4094
+ ({ job } = await bridge.wait(origin, WAIT_MS, stop.signal));
4095
+ } catch (error) {
4096
+ if (stop.signal.aborted) break;
4097
+ out(`The hub is unreachable (${error.message}); trying again.`);
4098
+ await sleep(2e3, stop.signal);
4099
+ continue;
4100
+ }
4101
+ if (job && !stop.signal.aborted) await runJob(job, { bridge, cli, bin, project, out, signal: stop.signal, pool, checkFlags });
4102
+ }
4103
+ })();
4104
+ runs.add(loop);
4105
+ }
4106
+ };
4107
+ let ready;
4108
+ if (state.ready) {
4109
+ start(state.ready);
4110
+ ready = Promise.resolve();
4111
+ } else {
4112
+ const waiting = (async () => {
4113
+ const poll = options.setupPollMs ?? SETUP_TICK_MS;
4114
+ let signingIn = null;
4115
+ let url;
4116
+ let signInError;
4117
+ const say = async (setup) => {
4118
+ const shown = signingIn ? { ...setup, state: "signing-in", canSignIn: false, ...url ? { url } : {} } : { ...setup, ...signInError ? { error: signInError } : {} };
4119
+ const label = `${state.target?.label ?? "Pilot"} \xB7 ${basename7(project)}`;
4120
+ if (JSON.stringify(agent.setup) === JSON.stringify(shown) && agent.label === label) return;
4121
+ const before = agent.setup;
4122
+ agent.setup = shown;
4123
+ agent.label = label;
4124
+ if (state.target) agent.kind = state.target.kind;
4125
+ else delete agent.kind;
4126
+ if (before?.state !== shown.state || before?.agent !== shown.agent || before?.error !== shown.error) out(setupLine(shown));
4127
+ await bridge.register().catch(() => {
4128
+ });
4129
+ };
4130
+ const lookEvery = options.setupPollMs ? 1 : Math.round(SETUP_POLL_MS / SETUP_TICK_MS);
4131
+ for (let tick = 1; !stop.signal.aborted && !state.ready; tick++) {
4132
+ await sleep(poll, stop.signal);
4133
+ if (stop.signal.aborted) return;
4134
+ const asked = !signingIn && state.setup?.canSignIn && state.target ? await bridge.signInAsked().catch(() => false) : false;
4135
+ if (asked && state.target && state.bin) {
4136
+ const cli2 = state.target;
4137
+ out(`Signing in to ${cli2.label}: its page opens in your browser.`);
4138
+ url = void 0;
4139
+ signInError = void 0;
4140
+ signingIn = (options.signIn ?? signIn)(cli2, state.bin, (u) => {
4141
+ url = u;
4142
+ if (state.setup) void say(state.setup);
4143
+ }).catch(() => {
4144
+ }).finally(() => {
4145
+ signingIn = null;
4146
+ signInError = `The sign-in didn't finish. Run ${cli2.signIn} in a terminal, then send again.`;
4147
+ });
4148
+ }
4149
+ if (!asked && tick % lookEvery !== 0) continue;
4150
+ state = await readiness(options, choose);
4151
+ if (state.ready) break;
4152
+ if (state.setup) await say(state.setup);
4153
+ }
4154
+ if (stop.signal.aborted || !state.ready) return;
4155
+ picked = state.ready;
4156
+ const { cli } = state.ready;
4157
+ agent.label = `${cli.label} \xB7 ${basename7(project)}`;
4158
+ agent.kind = cli.kind;
4159
+ delete agent.setup;
4160
+ await bridge.register().catch(() => {
4161
+ });
4162
+ out(`${cli.label} is ready: Pilot runs it for each job (the ones that waited go now).`);
4163
+ start(state.ready);
4164
+ })();
4165
+ runs.add(waiting);
4166
+ ready = waiting;
4167
+ }
4168
+ return {
4169
+ origin,
4170
+ get agent() {
4171
+ return picked?.cli ?? null;
4172
+ },
4173
+ ready,
4174
+ async close() {
4175
+ stop.abort();
4176
+ await Promise.allSettled(runs);
4177
+ await bridge.close();
4178
+ }
4179
+ };
4180
+ }
4181
+ var SETUP_POLL_MS = 3e3;
4182
+ var SETUP_TICK_MS = 1e3;
4183
+ var SIGN_IN_TIMEOUT_MS = 5 * 6e4;
4184
+ async function readiness(options, choose) {
4185
+ const wanted = options.agent ?? savedAgent(options.cwd, options.configFile);
4186
+ if (wanted && options.bin) return { ready: { cli: AGENTS[wanted], bin: options.bin } };
4187
+ const found = await (options.detect ?? detectAgents)();
4188
+ const waitFor = (cli, it) => ({ target: cli, ...it ? { bin: it.bin } : {}, setup: setupFor(cli, it) });
4189
+ if (wanted) {
4190
+ const it = found.find((a) => a.kind === wanted);
4191
+ if (it?.signedIn) {
4192
+ if (options.agent) saveAgent(options.cwd, wanted, options.configFile);
4193
+ return { ready: { cli: AGENTS[wanted], bin: it.bin } };
4194
+ }
4195
+ return waitFor(AGENTS[wanted], it);
4196
+ }
4197
+ const signedIn = found.filter((a) => a.signedIn);
4198
+ if (signedIn.length) {
4199
+ const index = signedIn.length > 1 ? await choose("Which agent should Pilot run for this project?", signedIn.map((a) => AGENTS[a.kind].label)) : 0;
4200
+ const it = signedIn[index] ?? signedIn[0];
4201
+ saveAgent(options.cwd, it.kind, options.configFile);
4202
+ return { ready: { cli: AGENTS[it.kind], bin: options.bin ?? it.bin } };
4203
+ }
4204
+ const installed = found[0];
4205
+ if (installed) return waitFor(AGENTS[installed.kind], installed);
4206
+ return {
4207
+ setup: {
4208
+ state: "not-installed",
4209
+ command: `Install your coding agent's command-line tool and sign in: ${Object.values(AGENTS).map((cli) => `${cli.label}: ${installCommand(cli)}, then ${cli.signIn}`).join(". ")}.`
4210
+ }
4211
+ };
4212
+ }
4213
+ function setupFor(cli, found) {
4214
+ if (!found) return { state: "not-installed", agent: cli.label, command: `${installCommand(cli)}, then ${cli.signIn}` };
4215
+ return { state: "not-signed-in", agent: cli.label, command: cli.signIn, canSignIn: true };
4216
+ }
4217
+ function setupLine(setup) {
4218
+ if (!setup) return "";
4219
+ const name = setup.agent ?? "your coding agent";
4220
+ if (setup.state === "signing-in") return `Waiting for you to sign in to ${name} in the browser${setup.url ? ` (${setup.url})` : ""}.`;
4221
+ if (setup.error) return `! ${setup.error}`;
4222
+ if (setup.state === "not-signed-in")
4223
+ return `${name} isn't signed in: click Send in Pilot to sign in (its page opens in your browser), or run ${setup.command} in a terminal. Jobs wait until then.`;
4224
+ return setup.agent ? `${name}'s command-line tool isn't installed: ask your agent to install it, or run ${setup.command} in a terminal. Jobs wait until then.` : `${setup.command} (Or ask your agent to install its own.) Jobs wait until then.`;
4225
+ }
4226
+ async function signIn(cli, bin, onUrl) {
4227
+ let seen = "";
4228
+ const look = (chunk) => {
4229
+ seen += chunk;
4230
+ const url = /https:\/\/[^\s"'<>]+/.exec(seen)?.[0];
4231
+ if (url) onUrl(url);
4232
+ };
4233
+ await exec(bin, cli.login, { timeoutMs: SIGN_IN_TIMEOUT_MS, onStdout: look, onStderr: look });
4234
+ }
4235
+ async function pickAgent(options, choose, out) {
4236
+ const wanted = options.agent ?? savedAgent(options.cwd, options.configFile);
4237
+ if (wanted && options.bin) return { cli: AGENTS[wanted], bin: options.bin };
4238
+ const found = await (options.detect ?? detectAgents)();
4239
+ if (wanted) {
4240
+ const cli = AGENTS[wanted];
4241
+ const it = found.find((a) => a.kind === wanted);
4242
+ if (!it) throw new RunnerError(`${cli.label}'s command-line tool isn't installed. Install it (${installCommand(cli)}), sign in (${cli.signIn}), then run npx usepilot again.`);
4243
+ if (!it.signedIn) throw new RunnerError(`${cli.label} isn't signed in. Run ${cli.signIn}, then npx usepilot again.`);
4244
+ if (options.agent) saveAgent(options.cwd, wanted, options.configFile);
4245
+ return { cli, bin: it.bin };
4246
+ }
4247
+ const ready = found.filter((a) => a.signedIn);
4248
+ if (!ready.length) {
4249
+ const installed = found.map((a) => `${AGENTS[a.kind].label} isn't signed in: run ${AGENTS[a.kind].signIn}.`);
4250
+ throw new RunnerError(
4251
+ [
4252
+ "Pilot runs your coding agent's command-line tool, and none is ready here.",
4253
+ ...installed.length ? installed : Object.values(AGENTS).map((cli) => `- ${cli.label}: ${installCommand(cli)}, then ${cli.signIn}`),
4254
+ "Then run npx usepilot again."
4255
+ ].join("\n")
4256
+ );
4257
+ }
4258
+ const index = ready.length > 1 ? await choose("Which agent should Pilot run for this project?", ready.map((a) => AGENTS[a.kind].label)) : 0;
4259
+ const picked = ready[index] ?? ready[0];
4260
+ saveAgent(options.cwd, picked.kind, options.configFile);
4261
+ if (ready.length > 1) out(`${AGENTS[picked.kind].label} it is, for this project (npx usepilot --agent <name> changes it).`);
4262
+ return { cli: AGENTS[picked.kind], bin: options.bin ?? picked.bin };
4263
+ }
4264
+ async function pickSite(bridge, options, out) {
4265
+ if (options.url) {
4266
+ const origin = originOf(options.url);
4267
+ if (!origin) throw new RunnerError(`"${options.url}" isn't a page address. Pass your dev server's, e.g. http://localhost:5173.`);
4268
+ return originKey(origin);
4269
+ }
4270
+ const name = projectName(options.cwd);
4271
+ const told = /* @__PURE__ */ new Set();
4272
+ const say = (key, line) => {
4273
+ if (told.has(key)) return;
4274
+ told.add(key);
4275
+ out(line);
4276
+ };
4277
+ for (; ; ) {
4278
+ if (options.signal?.aborted) throw new RunnerStopped("stopped");
4279
+ const local = (await bridge.pages()).filter((p) => {
4280
+ try {
4281
+ return isLocalHost(new URL(p.origin).hostname);
4282
+ } catch {
4283
+ return false;
4284
+ }
4285
+ });
4286
+ const mine = local.find((p) => p.project === name);
4287
+ if (mine) return mine.origin;
4288
+ for (const page of local) {
4289
+ if (page.project)
4290
+ 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.`);
4291
+ else
4292
+ say(
4293
+ page.origin,
4294
+ `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}.`
4295
+ );
4296
+ }
4297
+ say("none", `Waiting for a page of ${name}: open your app in the browser (with its dev server running).`);
4298
+ await sleep(1e3, options.signal);
4299
+ }
4300
+ }
4301
+ function isEditorJob(job) {
4302
+ return !job.changeSet.request && !job.answer;
4303
+ }
4304
+ async function runJob(job, ctx) {
4305
+ const { bridge, cli, out } = ctx;
4306
+ const started = Date.now();
4307
+ out(`\u25B8 ${describeJob(job)}`);
4308
+ const stop = new AbortController();
4309
+ const onStop = () => stop.abort();
4310
+ ctx.signal.addEventListener("abort", onStop, { once: true });
4311
+ const watch = setInterval(() => {
4312
+ bridge.job(job.id).then((j) => {
4313
+ if (j?.status === "cancelled") stop.abort();
4314
+ }).catch(() => {
4315
+ });
4316
+ }, CANCEL_POLL_MS);
4317
+ let lease;
4318
+ let ended;
4319
+ try {
4320
+ if (ctx.pool && isEditorJob(job)) {
4321
+ const own = sessionOf(job.session);
4322
+ if (job.attempt !== 2) lease = ctx.pool.take();
4323
+ else if (own?.agent === cli.kind) lease = await ctx.pool.takeOwn(own.id);
4324
+ }
4325
+ const resume = lease ? lease.resume : sessionToResume(job, cli.kind);
4326
+ const known = !!lease?.resume && job.attempt !== 2;
4327
+ const prompt = await promptFor(job, ctx.project, cli, { guidelinesKnown: known });
4328
+ const images = newAttachments(job).map((f) => f.path).filter((p) => /\.(png|jpe?g|gif|webp)$/i.test(p));
4329
+ const active = activityOf(bridge, job.id);
4330
+ let result = await runAgent(ctx, prompt, { resume, images, signal: stop.signal, onOutput: active });
4331
+ if (!stop.signal.aborted && !result.reply && !signInProblem(result.error)) {
4332
+ result = await runAgent(ctx, known ? await promptFor(job, ctx.project, cli) : prompt, { images, signal: stop.signal, onOutput: active });
4333
+ }
4334
+ if (stop.signal.aborted) {
4335
+ ended = lease?.resume;
4336
+ out(`\u25A0 Stopped: ${describeJob(job)}`);
4337
+ return;
4338
+ }
4339
+ if (result.reply) ended = result.session;
4340
+ const seconds = Math.round((Date.now() - started) / 1e3);
4341
+ if (!result.reply) {
4342
+ const error = errorFor(cli, result.error, await ctx.checkFlags?.() ?? void 0);
4343
+ await bridge.done(job.id, void 0, void 0, void 0, { error });
4344
+ const said = (result.error ?? "").split("\n").map((l) => l.trim()).filter(Boolean).slice(-8);
4345
+ out(`\u2717 ${error.title}. ${error.detail}${said.length && !signInProblem(result.error) ? `
4346
+ ${said.map((l) => ` ${l}`).join("\n")}` : ""}`);
4347
+ return;
4348
+ }
4349
+ const reply = replyOf(result.reply);
4350
+ const session = result.session ? { agent: cli.kind, id: result.session } : void 0;
4351
+ const refused = refusedNote(cli, [...result.refused ?? [], ...reply.refused ?? []]);
4352
+ const notes = refused ? [reply.notes, refused.note].filter(Boolean).join("\n\n") : reply.notes;
4353
+ await bridge.done(job.id, notes, reply.question, reply.props, { session, ...refused?.allow ? { allow: refused.allow } : {} });
4354
+ out(`\u2713 ${seconds}s \xB7 ${firstLine(reply.notes) || "Done."}`);
4355
+ if (refused) out(`! ${[refused.note, refused.allow].filter(Boolean).join(" ").replaceAll("**", "").replaceAll("`", "")}`);
4356
+ } catch (error) {
4357
+ if (!stop.signal.aborted) {
4358
+ const jobError = { title: `Pilot couldn't run ${cli.label}`, detail: error.message };
4359
+ await bridge.done(job.id, void 0, void 0, void 0, { error: jobError }).catch(() => {
4360
+ });
4361
+ out(`\u2717 ${jobError.title}: ${jobError.detail}`);
4362
+ }
4363
+ } finally {
4364
+ lease?.release(ended);
4365
+ clearInterval(watch);
4366
+ ctx.signal.removeEventListener("abort", onStop);
4367
+ }
4368
+ }
4369
+ function activityOf(bridge, jobId, every = ACTIVITY_EVERY_MS, now = Date.now) {
4370
+ let last = Number.NEGATIVE_INFINITY;
4371
+ return () => {
4372
+ if (now() - last < every) return;
4373
+ last = now();
4374
+ bridge.activity(jobId).catch(() => {
4375
+ });
4376
+ };
4377
+ }
4378
+ async function runAgent(ctx, prompt, options) {
4379
+ const { cli } = ctx;
4380
+ if (!existsSync7(ctx.bin)) return { error: `${cli.label}'s command-line tool isn't installed any more.` };
4381
+ options.onOutput?.();
4382
+ const run = await exec(ctx.bin, cli.args({ resume: options.resume, readDirs: [attachmentsDir()], images: options.images }), {
4383
+ cwd: ctx.project,
4384
+ input: prompt,
4385
+ signal: options.signal,
4386
+ timeoutMs: RUN_TIMEOUT_MS,
4387
+ ...options.onOutput ? { onStdout: options.onOutput } : {}
4388
+ });
4389
+ const parsed2 = cli.parse(run.stdout);
4390
+ if (!parsed2.reply && !parsed2.error) parsed2.error = run.stderr.trim().split("\n").slice(-3).join("\n") || `exit code ${run.code}`;
4391
+ if (!parsed2.reply && run.stderr && !parsed2.error?.includes(run.stderr.trim().slice(0, 40))) parsed2.error = `${parsed2.error}
4392
+ ${run.stderr.trim().slice(-500)}`;
4393
+ if (!parsed2.reply && !run.stderr.trim() && parsed2.error === NOTHING_PRINTED) parsed2.error = `${NOTHING_PRINTED} (exit code ${run.code}${run.killed ? ", stopped" : ""})`;
4394
+ return parsed2;
4395
+ }
4396
+ async function promptFor(job, project, cli, options = {}) {
4397
+ const j = withComponentFiles(job, project);
4398
+ const located = j.attempt === 2 ? [] : jobLocations(j, project);
4399
+ const where = j.attempt === 2 ? "" : [whereSection(j, project, located), factsSection(j, project, located.map((l) => l.at.file))].filter(Boolean).join("\n\n");
4400
+ const texts = (await attachmentBlocks(j)).flatMap((b) => b.type === "text" ? [b.text] : []);
4401
+ const skill = skillOf(j);
4402
+ return [...skill ? [cli.invokeSkill(skill)] : [], jobPrompt(j, where, options), ...texts].join("\n\n");
4403
+ }
4404
+ function sessionToResume(job, agent) {
4405
+ const request = job.changeSet.request;
4406
+ const own = sessionOf(job.session);
4407
+ const thread = request?.kind === "comment" ? sessionOf(request.session) : void 0;
4408
+ const session = (job.attempt === 2 || job.answer ? own : void 0) ?? thread ?? own;
4409
+ return session?.agent === agent ? session.id : void 0;
4410
+ }
4411
+ function replyOf(reply) {
4412
+ const blocks = [...reply.matchAll(/```pilot\s*\n([\s\S]*?)```/g)];
4413
+ const last = blocks.at(-1);
4414
+ let notes = reply;
4415
+ let data = {};
4416
+ if (last) {
4417
+ notes = reply.replace(last[0], "");
4418
+ try {
4419
+ data = JSON.parse(last[1] ?? "");
4420
+ } catch {
4421
+ }
4422
+ }
4423
+ notes = notes.trim();
4424
+ const refused = refusedOf(data.refused);
4425
+ return { notes: notes || void 0, question: questionOf(data.question), props: propsOf(data.props), ...refused.length ? { refused } : {} };
4426
+ }
4427
+ function signInProblem(error) {
4428
+ return !!error && /not (logged|signed) in|log ?in required|please (run )?\/?login|authenticat|unauthori[sz]ed|\b401\b|api key/i.test(error);
4429
+ }
4430
+ function outdatedNote(cli, missing) {
4431
+ return [`! ${cli.label} needs an update to work with Pilot. In a terminal, run:`, ` ${cli.update}`, ` (This version doesn't support ${missing.join(", ")}, which Pilot uses.)`].join("\n");
4432
+ }
4433
+ function errorFor(cli, error, missing) {
4434
+ if (signInProblem(error)) return { title: `${cli.label} isn't signed in`, detail: `Run ${cli.signIn} in a terminal, then send again.` };
4435
+ if (missing?.length)
4436
+ return {
4437
+ title: `${cli.label} needs an update`,
4438
+ detail: `This version of ${cli.label} can't work with Pilot yet. In a terminal, run ${cli.update}, then send again.`
4439
+ };
4440
+ const lines = (error ?? "").split("\n").map((l) => l.trim()).filter(Boolean);
4441
+ const telling = lines.find((l) => !l.startsWith(NOTHING_PRINTED)) ?? lines[0] ?? "It stopped without a reply.";
4442
+ return {
4443
+ title: `${cli.label} couldn't do this job`,
4444
+ detail: `${telling.slice(0, 300)} The terminal running npx usepilot has the details. Send again to retry.`
4445
+ };
4446
+ }
4447
+ function describeJob(job) {
4448
+ const request = job.changeSet.request;
4449
+ const follow = job.attempt === 2 ? "follow-up: " : job.answer ? "answer: " : "";
4450
+ if (request?.kind === "comment") {
4451
+ const latest = request.thread.at(-1)?.text.trim().replace(/\s+/g, " ") ?? "";
4452
+ return `${follow}comment on ${nameOf(request.target)}: "${latest.length > 60 ? `${latest.slice(0, 60)}\u2026` : latest}"`;
4453
+ }
4454
+ if (request) return `${follow}${request.kind} on ${requestTargets(request).map(nameOf).join(", ")}`;
4455
+ const changes = job.changeSet.edits.reduce((n, e) => n + e.changes.length + (e.texts?.length ?? 0), 0);
4456
+ return `${follow}${changes} change${changes === 1 ? "" : "s"} on ${job.changeSet.edits.map((e) => nameOf(e.target)).join(", ")}`;
4457
+ }
4458
+ function firstLine(text) {
4459
+ const line = text?.trim().split("\n")[0]?.trim() ?? "";
4460
+ return line.length > 160 ? `${line.slice(0, 160)}\u2026` : line;
4461
+ }
4462
+ function nameOf(target) {
4463
+ return target.text ? `${target.tag} "${target.text.length > 30 ? `${target.text.slice(0, 30)}\u2026` : target.text}"` : target.tag;
4464
+ }
4465
+ function sleep(ms, signal) {
4466
+ return new Promise((resolve5) => {
4467
+ const timer = setTimeout(resolve5, ms);
4468
+ signal?.addEventListener(
4469
+ "abort",
4470
+ () => {
4471
+ clearTimeout(timer);
4472
+ resolve5();
4473
+ },
4474
+ { once: true }
4475
+ );
4476
+ });
4477
+ }
4478
+
4479
+ // src/dev.ts
4480
+ import { existsSync as existsSync8 } from "fs";
4481
+ import { dirname as dirname7, join as join11 } from "path";
4482
+ var RUNNER_ENV = "USEPILOT_RUNNER";
4483
+ var STARTED = /* @__PURE__ */ Symbol.for("usepilot.devRunner");
4484
+ var OFF_SAID_ENV = "USEPILOT_OFF_SAID";
4485
+ function devGuard(env = process.env) {
4486
+ if (env.NODE_ENV === "production") return "Pilot doesn't start: NODE_ENV is production (Pilot only runs in development).";
4487
+ if (env.CI && env.CI !== "false" && env.CI !== "0") return "Pilot doesn't start in CI.";
4488
+ return null;
4489
+ }
4490
+ function startWithDevServer(options = {}) {
4491
+ const env = options.env ?? process.env;
4492
+ const out = options.out ?? ((line) => process.stdout.write(`[pilot] ${line}
4493
+ `));
4494
+ const off = devGuard(env);
4495
+ if (off) {
4496
+ out(off);
4497
+ return null;
4498
+ }
4499
+ const global = globalThis;
4500
+ if (global[STARTED]) return global[STARTED];
4501
+ const parent = Number(env[RUNNER_ENV]);
4502
+ if (parent && parent !== process.pid && alive(parent)) return null;
4503
+ const project = projectFolder(options.cwd ?? process.cwd());
4504
+ if (!isSetUp(project, options.runner?.configFile ?? configFile(env))) {
4505
+ if (!env[OFF_SAID_ENV]) {
4506
+ out(`Pilot isn't set up for ${projectName(project)} on this computer, so it doesn't start. To use it: npx usepilot init (in ${project}).`);
4507
+ env[OFF_SAID_ENV] = "1";
4508
+ }
4509
+ return null;
4510
+ }
4511
+ env[RUNNER_ENV] = String(process.pid);
4512
+ let closed = false;
4513
+ const stop = new AbortController();
4514
+ const started = startRunner({
4515
+ cwd: project,
4516
+ out,
4517
+ waitForAgent: true,
4518
+ signal: stop.signal,
4519
+ ...options.url ? { url: options.url } : {},
4520
+ ...options.runner
4521
+ }).then(
4522
+ async (runner) => {
4523
+ if (!closed) return runner;
4524
+ await runner.close();
4525
+ return null;
4526
+ },
4527
+ (error) => {
4528
+ if (!(error instanceof RunnerStopped)) out(error instanceof RunnerError ? error.message : `Pilot couldn't start: ${error.message}`);
4529
+ return null;
4530
+ }
4531
+ );
4532
+ const handle2 = {
4533
+ started,
4534
+ async close() {
4535
+ if (closed) return;
4536
+ closed = true;
4537
+ if (global[STARTED] === handle2) delete global[STARTED];
4538
+ if (env[RUNNER_ENV] === String(process.pid)) delete env[RUNNER_ENV];
4539
+ stop.abort();
4540
+ await (await started)?.close();
4541
+ }
4542
+ };
4543
+ global[STARTED] = handle2;
4544
+ return handle2;
4545
+ }
4546
+ function projectFolder(dir) {
4547
+ for (let d = dir; ; d = dirname7(d)) {
4548
+ if (existsSync8(join11(d, "package.json"))) return d;
4549
+ if (dirname7(d) === d) return dir;
4550
+ }
4551
+ }
4552
+ function alive(pid) {
4553
+ try {
4554
+ process.kill(pid, 0);
4555
+ return true;
4556
+ } catch (error) {
4557
+ return error.code === "EPERM";
4558
+ }
4559
+ }
4560
+
4561
+ export {
4562
+ AGENTS,
4563
+ installCommand,
4564
+ isAgentKind,
4565
+ agentFromEnv,
4566
+ detectAgents,
4567
+ BRIDGE_VERSION,
4568
+ configFile,
4569
+ saveAgent,
4570
+ markSetUp,
4571
+ projectName,
4572
+ shownPath,
4573
+ relPath,
4574
+ RunnerError,
4575
+ startRunner,
4576
+ startWithDevServer
4577
+ };