usepilot 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/index.js CHANGED
@@ -3912,50 +3912,50 @@ var require_fast_uri = __commonJS({
3912
3912
  schemelessOptions.skipEscape = true;
3913
3913
  return serialize(resolved, schemelessOptions);
3914
3914
  }
3915
- function resolveComponent(base, relative, options, skipNormalization) {
3915
+ function resolveComponent(base, relative3, options, skipNormalization) {
3916
3916
  const target = {};
3917
3917
  if (!skipNormalization) {
3918
3918
  base = parse3(serialize(base, options), options);
3919
- relative = parse3(serialize(relative, options), options);
3919
+ relative3 = parse3(serialize(relative3, options), options);
3920
3920
  }
3921
3921
  options = options || {};
3922
- if (!options.tolerant && relative.scheme) {
3923
- target.scheme = relative.scheme;
3924
- target.userinfo = relative.userinfo;
3925
- target.host = relative.host;
3926
- target.port = relative.port;
3927
- target.path = removeDotSegments(relative.path || "");
3928
- target.query = relative.query;
3922
+ if (!options.tolerant && relative3.scheme) {
3923
+ target.scheme = relative3.scheme;
3924
+ target.userinfo = relative3.userinfo;
3925
+ target.host = relative3.host;
3926
+ target.port = relative3.port;
3927
+ target.path = removeDotSegments(relative3.path || "");
3928
+ target.query = relative3.query;
3929
3929
  } else {
3930
- if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) {
3931
- target.userinfo = relative.userinfo;
3932
- target.host = relative.host;
3933
- target.port = relative.port;
3934
- target.path = removeDotSegments(relative.path || "");
3935
- target.query = relative.query;
3930
+ if (relative3.userinfo !== void 0 || relative3.host !== void 0 || relative3.port !== void 0) {
3931
+ target.userinfo = relative3.userinfo;
3932
+ target.host = relative3.host;
3933
+ target.port = relative3.port;
3934
+ target.path = removeDotSegments(relative3.path || "");
3935
+ target.query = relative3.query;
3936
3936
  } else {
3937
- if (!relative.path) {
3937
+ if (!relative3.path) {
3938
3938
  target.path = base.path;
3939
- if (relative.query !== void 0) {
3940
- target.query = relative.query;
3939
+ if (relative3.query !== void 0) {
3940
+ target.query = relative3.query;
3941
3941
  } else {
3942
3942
  target.query = base.query;
3943
3943
  }
3944
3944
  } else {
3945
- if (relative.path[0] === "/") {
3946
- target.path = removeDotSegments(relative.path);
3945
+ if (relative3.path[0] === "/") {
3946
+ target.path = removeDotSegments(relative3.path);
3947
3947
  } else {
3948
3948
  const baseHasAuthority = base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0;
3949
3949
  if (baseHasAuthority && !base.path) {
3950
- target.path = "/" + relative.path;
3950
+ target.path = "/" + relative3.path;
3951
3951
  } else if (!base.path) {
3952
- target.path = relative.path;
3952
+ target.path = relative3.path;
3953
3953
  } else {
3954
- target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
3954
+ target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative3.path;
3955
3955
  }
3956
3956
  target.path = base.scheme === void 0 && !baseHasAuthority && target.path[0] !== "/" ? removeDotSegmentsRelative(target.path) : removeDotSegments(target.path);
3957
3957
  }
3958
- target.query = relative.query;
3958
+ target.query = relative3.query;
3959
3959
  }
3960
3960
  target.userinfo = base.userinfo;
3961
3961
  target.host = base.host;
@@ -3963,7 +3963,7 @@ var require_fast_uri = __commonJS({
3963
3963
  }
3964
3964
  target.scheme = base.scheme;
3965
3965
  }
3966
- target.fragment = relative.fragment;
3966
+ target.fragment = relative3.fragment;
3967
3967
  return target;
3968
3968
  }
3969
3969
  function equal(uriA, uriB, options) {
@@ -7230,8 +7230,8 @@ var require_dist = __commonJS({
7230
7230
  return ajv;
7231
7231
  }
7232
7232
  const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];
7233
- const list = opts.formats || formats_1.formatNames;
7234
- addFormats(ajv, list, formats, exportName);
7233
+ const list2 = opts.formats || formats_1.formatNames;
7234
+ addFormats(ajv, list2, formats, exportName);
7235
7235
  if (opts.keywords)
7236
7236
  (0, limit_1.default)(ajv);
7237
7237
  return ajv;
@@ -7243,11 +7243,11 @@ var require_dist = __commonJS({
7243
7243
  throw new Error(`Unknown format "${name}"`);
7244
7244
  return f;
7245
7245
  };
7246
- function addFormats(ajv, list, fs, exportName) {
7246
+ function addFormats(ajv, list2, fs, exportName) {
7247
7247
  var _a3;
7248
7248
  var _b;
7249
7249
  (_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
7250
- for (const f of list)
7250
+ for (const f of list2)
7251
7251
  ajv.addFormat(f, fs[f]);
7252
7252
  }
7253
7253
  module.exports = exports = formatsPlugin;
@@ -8733,7 +8733,7 @@ function $constructor(name, initializer3, proto, params) {
8733
8733
  Internals.prototype = zodProto;
8734
8734
  const protoMembers = proto;
8735
8735
  const initialized = protoMembers && /* @__PURE__ */ new WeakSet();
8736
- function init(inst, def) {
8736
+ function init2(inst, def) {
8737
8737
  if (!inst._zod) {
8738
8738
  _zodDesc.value = new Internals(def);
8739
8739
  try {
@@ -8773,7 +8773,7 @@ function $constructor(name, initializer3, proto, params) {
8773
8773
  Object.defineProperty(Definition, "name", { value: name });
8774
8774
  function _(def) {
8775
8775
  const inst = params?.Parent ? newError(Definition) : this;
8776
- init(inst, def);
8776
+ init2(inst, def);
8777
8777
  const deferred = inst._zod.deferred;
8778
8778
  if (deferred) {
8779
8779
  for (const fn of deferred) {
@@ -8786,7 +8786,7 @@ function $constructor(name, initializer3, proto, params) {
8786
8786
  pp(inst);
8787
8787
  return inst;
8788
8788
  }
8789
- Object.defineProperty(_, "init", { value: init });
8789
+ Object.defineProperty(_, "init", { value: init2 });
8790
8790
  Object.defineProperty(_, Symbol.hasInstance, {
8791
8791
  value: (inst) => {
8792
8792
  if (params?.Parent && inst instanceof params.Parent)
@@ -23464,8 +23464,8 @@ var contributors = {
23464
23464
  function aggregateChecks(schema) {
23465
23465
  const agg = {};
23466
23466
  const def = schema._zod.def;
23467
- const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? [];
23468
- for (const ch of list)
23467
+ const list2 = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? [];
23468
+ for (const ch of list2)
23469
23469
  contributors[ch._zod.def.check]?.(agg, ch._zod.def);
23470
23470
  const bag = schema._zod.bag;
23471
23471
  if (bag.minimum !== void 0)
@@ -28612,8 +28612,8 @@ var StdioServerTransport = class {
28612
28612
  };
28613
28613
 
28614
28614
  // src/mcp.ts
28615
- import { randomUUID } from "crypto";
28616
- import { basename } from "path";
28615
+ import { randomUUID as randomUUID2 } from "crypto";
28616
+ import { basename as basename2 } from "path";
28617
28617
 
28618
28618
  // ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v3/helpers/util.js
28619
28619
  var util;
@@ -36659,8 +36659,44 @@ var EMPTY_COMPLETION_RESULT = {
36659
36659
  }
36660
36660
  };
36661
36661
 
36662
+ // ../protocol/src/types.ts
36663
+ var ATTACHMENT_TYPES = {
36664
+ png: "image/png",
36665
+ jpg: "image/jpeg",
36666
+ gif: "image/gif",
36667
+ webp: "image/webp",
36668
+ pdf: "application/pdf",
36669
+ txt: "text/plain",
36670
+ md: "text/markdown",
36671
+ csv: "text/csv",
36672
+ json: "application/json"
36673
+ };
36674
+ var ATTACHMENT_ID = /^[a-f0-9]{64}\.(png|jpg|gif|webp|pdf|txt|md|csv|json)$/;
36675
+ function attachmentKind(name) {
36676
+ const ext = name.split(".").pop()?.toLowerCase();
36677
+ return ext === "pdf" ? "pdf" : ext === "png" || ext === "jpg" || ext === "jpeg" || ext === "gif" || ext === "webp" ? "image" : "text";
36678
+ }
36679
+ var BY_EXTENSION = {
36680
+ png: "image/png",
36681
+ jpg: "image/jpeg",
36682
+ jpeg: "image/jpeg",
36683
+ gif: "image/gif",
36684
+ webp: "image/webp",
36685
+ pdf: "application/pdf",
36686
+ txt: "text/plain",
36687
+ log: "text/plain",
36688
+ text: "text/plain",
36689
+ md: "text/markdown",
36690
+ markdown: "text/markdown",
36691
+ csv: "text/csv",
36692
+ json: "application/json"
36693
+ };
36694
+ var ATTACHMENT_ACCEPT = [...new Set(Object.values(ATTACHMENT_TYPES))].join(",") + "," + Object.keys(BY_EXTENSION).map((e) => `.${e}`).join(",");
36695
+
36662
36696
  // ../protocol/src/format.ts
36663
36697
  function formatPrompt(changeSet) {
36698
+ if (changeSet.request?.kind === "responsive") return formatResponsive(changeSet, changeSet.request);
36699
+ if (changeSet.request?.kind === "comment") return formatComment(changeSet, changeSet.request);
36664
36700
  const { page, edits, note } = changeSet;
36665
36701
  const lines = [
36666
36702
  "# Pilot design edits",
@@ -36672,6 +36708,8 @@ function formatPrompt(changeSet) {
36672
36708
  "- Prefer an existing token or utility when it matches the value (or is within a pixel or two); mention any value you had to approximate.",
36673
36709
  "- Change only the listed elements. If an element is a shared component, ask before changing every instance.",
36674
36710
  `- Widths are viewport widths in CSS px, both ends included. Use this project's breakpoints when one matches (or is within a few pixels), else a custom media query, and say which. "Every width" means no media query: the value holds at every viewport width, and no existing media query should override it.`,
36711
+ "- 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.",
36712
+ "- 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).",
36675
36713
  "",
36676
36714
  `Page: ${page.url} (${page.title || "untitled"}) at ${page.viewport.width}x${page.viewport.height}`
36677
36715
  ];
@@ -36684,24 +36722,142 @@ function formatPrompt(changeSet) {
36684
36722
  return `${lines.join("\n")}
36685
36723
  `;
36686
36724
  }
36687
- function formatEdit(edit, n) {
36688
- const { target, changes } = edit;
36689
- const out = [`## ${n}. \`${target.path}\``, "", `- Selector: \`${target.selector}\``];
36725
+ var ADVANCED_TASK = '**An advanced task: it needs judgment more than speed.** If you can hand work to a more capable model and aren\'t running on one, do: in Claude Code, unless you already run on Opus, give this whole prompt (with the job id) to a subagent with `model: "opus"` (the Agent tool), have it make the changes and run the width check, and report back; then call `pilot_done` with its notes.';
36726
+ function formatResponsive(changeSet, request) {
36727
+ const { page, note } = changeSet;
36728
+ const { target, breakpoints } = request;
36729
+ const widths = breakpoints.length ? breakpoints.map((b) => `${b}px`).join(", ") : "none found (it may use container queries, or none yet)";
36730
+ const lines = [
36731
+ "# Pilot: make responsive",
36732
+ "",
36733
+ "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.",
36734
+ "",
36735
+ `Page: ${page.url} (${page.title || "untitled"}), seen at ${page.viewport.width}x${page.viewport.height}`,
36736
+ `The page's breakpoints (the widths its media queries test): ${widths}`,
36737
+ "",
36738
+ ADVANCED_TASK
36739
+ ];
36740
+ if (note?.trim()) lines.push("", `Designer note: ${note.trim()}`);
36741
+ lines.push(
36742
+ "",
36743
+ `## \`${target.path}\``,
36744
+ "",
36745
+ ...targetLines(target),
36746
+ "",
36747
+ "## How to do it",
36748
+ "",
36749
+ "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.",
36750
+ "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.",
36751
+ "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.",
36752
+ "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.",
36753
+ "5. **Check every width with `pilot_check_widths`** (Pilot's tool, with this job's id). It loads the page at a phone width (375px), each breakpoint and 1px below it, a wide desktop (1440px) and the designer's width, measures the element in each, and reports problems as numbers: sticking out of the viewport, spilling out of its parent, clipped content, overlaps, and anything that changed at the designer's width. No screenshots needed. Fix what it finds and run it again until it finds none. Without that tool (a pasted prompt), check those widths in a browser if you have one, and say which widths you couldn't check.",
36754
+ "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.",
36755
+ "",
36756
+ "Change only this element and what its layout needs (its container, its children). If it's a shared component, ask before changing every instance."
36757
+ );
36758
+ return `${lines.join("\n")}
36759
+ `;
36760
+ }
36761
+ function formatComment(changeSet, request) {
36762
+ const { page } = changeSet;
36763
+ const { target, thread, breakpoints } = request;
36764
+ const latest = thread.at(-1);
36765
+ const earlier = thread.slice(0, -1);
36766
+ const widths = breakpoints.length ? breakpoints.map((b) => `${b}px`).join(", ") : "none found (it may use container queries, or none yet)";
36767
+ const lines = [
36768
+ "# Pilot: comment",
36769
+ "",
36770
+ "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).",
36771
+ "",
36772
+ `Page: ${page.url} (${page.title || "untitled"}), seen at ${page.viewport.width}x${page.viewport.height}`,
36773
+ `The page's breakpoints (the widths its media queries test): ${widths}`,
36774
+ "",
36775
+ `## \`${target.path}\``,
36776
+ "",
36777
+ ...targetLines(target),
36778
+ "",
36779
+ "## The comment",
36780
+ "",
36781
+ ...commentLines(latest)
36782
+ ];
36783
+ if (earlier.length) {
36784
+ lines.push("", "## The thread so far (you already did what it asked)", "");
36785
+ for (const m of earlier) {
36786
+ const files = m.attachments?.length ? ` (${countFiles(m.attachments.length)})` : "";
36787
+ lines.push(`- **${m.from === "designer" ? "Designer" : "You"}:**${files} ${m.text.replace(/\s*\n\s*/g, " ")}`.trimEnd());
36788
+ }
36789
+ }
36790
+ lines.push(
36791
+ "",
36792
+ "## How to do it",
36793
+ "",
36794
+ "- **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.",
36795
+ "- **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 and aren't running on one, do: in Claude Code, unless you already run on Opus, give this prompt (with the job id) to a subagent with `model: \"opus\"` (the Agent tool), and report back with its notes.",
36796
+ `- The designer was looking at the page ${page.viewport.width}px wide. If the comment is about how it looks at that width only, scope the change with the project's breakpoints; otherwise it's for every width.`,
36797
+ "- Change only what the comment is about. Never leave inline styles. If the element comes from a shared component, ask before changing every instance.",
36798
+ "- **A question, not a change:** answer it, and change nothing.",
36799
+ "- **Your notes are your reply in the designer's thread, a small chat box for quick design back-and-forth:** keep it to one short sentence, like a chat message (about 120 characters at most): what you changed, or your answer, or the one thing you need from them. No lists, headings or code blocks; inline `code` for a value or a file name at most. Not a report: the designer sees the result on the page."
36800
+ );
36801
+ return `${lines.join("\n")}
36802
+ `;
36803
+ }
36804
+ function commentLines(message) {
36805
+ const text = message?.text.trim() ?? "";
36806
+ const files = message?.attachments ?? [];
36807
+ const out = text ? [quote(text)] : [];
36808
+ if (!files.length) return out.length ? out : ["> (empty)"];
36809
+ const one = files.length === 1;
36810
+ if (out.length) out.push("");
36811
+ out.push(
36812
+ 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.`,
36813
+ "",
36814
+ ...files.map((file2) => {
36815
+ const kind = attachmentKind(file2.id);
36816
+ 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";
36817
+ return `- ${file2.name ? `${file2.name} ` : ""}(${how}): \`${file2.path ?? file2.id}\``;
36818
+ })
36819
+ );
36820
+ return out;
36821
+ }
36822
+ function countFiles(n) {
36823
+ return n === 1 ? "a file" : `${n} files`;
36824
+ }
36825
+ function quote(text) {
36826
+ return text.trim().split("\n").map((l) => `> ${l}`).join("\n");
36827
+ }
36828
+ function targetLines(target) {
36829
+ const out = [`- Selector: \`${target.selector}\``];
36690
36830
  if (target.text) out.push(`- Text: "${target.text}"`);
36691
36831
  if (target.source?.component || target.source?.file) {
36692
36832
  const where = [target.source.component, target.source.file && `${target.source.file}${target.source.line ? `:${target.source.line}` : ""}`].filter(Boolean).join(" in ");
36693
36833
  out.push(`- Source hint: ${where}`);
36694
36834
  }
36695
- out.push("", "| Property | From | To | Widths |", "| --- | --- | --- | --- |");
36835
+ return out;
36836
+ }
36837
+ function formatEdit(edit, n) {
36838
+ const { target, changes, texts } = edit;
36839
+ const out = [`## ${n}. \`${target.path}\``, "", ...targetLines(target)];
36840
+ if (texts?.length) out.push("", "Text (from \u2192 to):", "", ...texts.map((t) => `- ${JSON.stringify(t.from)} \u2192 ${JSON.stringify(t.to)}`));
36841
+ if (!changes.length) return out;
36842
+ const withStates = changes.some((c) => c.states?.length);
36843
+ out.push(
36844
+ "",
36845
+ withStates ? "| Property | From | To | Widths | State |" : "| Property | From | To | Widths |",
36846
+ withStates ? "| --- | --- | --- | --- | --- |" : "| --- | --- | --- | --- |"
36847
+ );
36696
36848
  for (const c of changes) {
36697
36849
  const to = c.removed ? "*removed*" : `\`${c.to}\``;
36698
36850
  const from = c.from ? `\`${c.from}\`` : "*not set*";
36699
- out.push(`| \`${c.property}\` | ${from} | ${to} | ${c.widths ? describeWidths(c.widths) : "every width"} |`);
36851
+ const widths = c.widths ? describeWidths(c.widths) : "every width";
36852
+ out.push(`| \`${c.property}\` | ${from} | ${to} | ${widths} |${withStates ? ` ${describeStates(c.states)} |` : ""}`);
36700
36853
  }
36701
36854
  const notes = changes.flatMap((c) => [c.removed && removalNote(c), mediaNote(c)].filter((n2) => !!n2));
36702
36855
  if (notes.length) out.push("", ...notes.map((n2) => `- ${n2}`));
36703
36856
  return out;
36704
36857
  }
36858
+ function describeStates(states) {
36859
+ return states?.length ? states.join(", ") : "\u2014";
36860
+ }
36705
36861
  function describeWidths({ min, max }) {
36706
36862
  if (min !== void 0 && min === max) return `${min}px only`;
36707
36863
  if (min !== void 0 && max !== void 0) return `${min}\u2013${max}px`;
@@ -36723,10 +36879,38 @@ function removalNote(c) {
36723
36879
  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` : "";
36724
36880
  return `${note} It comes from \`${source.selector}\`${shared}.`;
36725
36881
  }
36882
+ function formatWidthCheck(check2) {
36883
+ const lines = [
36884
+ check2.problems ? `Pilot's width check of \`${check2.selector}\`: ${check2.problems} ${check2.problems === 1 ? "problem" : "problems"} to fix.` : `Pilot's width check of \`${check2.selector}\`: no problems found.`,
36885
+ ""
36886
+ ];
36887
+ for (const r of check2.widths) {
36888
+ const mine = r.width === check2.designerWidth ? " (the designer's width)" : "";
36889
+ if (!r.found) {
36890
+ lines.push(`- ${r.width}px${mine}: the element isn't on the page at this width (or its selector no longer matches it).`);
36891
+ continue;
36892
+ }
36893
+ lines.push(`- ${r.width}px${mine}: ${[r.size, r.layout].filter(Boolean).join(", ")}${r.issues.length ? "" : ". OK"}`);
36894
+ for (const issue2 of r.issues) lines.push(` - Problem: ${issue2}`);
36895
+ for (const note of r.notes) lines.push(` - Note: ${note}`);
36896
+ }
36897
+ if (check2.changedAtDesignerWidth?.length) {
36898
+ lines.push("", `Changed at the designer's width (${check2.designerWidth}px), which should look as it did:`);
36899
+ for (const c of check2.changedAtDesignerWidth) lines.push(`- ${c}`);
36900
+ }
36901
+ if (check2.source === "copy") {
36902
+ lines.push(
36903
+ "",
36904
+ "Measured on a copy of the page as the designer has it, with scripts off: layout that only changes through JavaScript (a menu a script toggles, components that measure themselves) isn't reflected here."
36905
+ );
36906
+ }
36907
+ return `${lines.join("\n")}
36908
+ `;
36909
+ }
36726
36910
 
36727
36911
  // ../protocol/src/bridge.ts
36728
36912
  var DEFAULT_BRIDGE_PORT = 4747;
36729
- var BRIDGE_VERSION = 1;
36913
+ var BRIDGE_VERSION = 3;
36730
36914
  function originOf(url2) {
36731
36915
  try {
36732
36916
  const u = new URL(url2.includes("://") ? url2 : `http://${url2}`);
@@ -36742,7 +36926,118 @@ function originKey(origin) {
36742
36926
  // src/server.ts
36743
36927
  import { createServer } from "http";
36744
36928
 
36929
+ // src/attachments.ts
36930
+ import { createHash } from "crypto";
36931
+ import { existsSync } from "fs";
36932
+ import { mkdir, readdir, readFile, rm, stat, writeFile } from "fs/promises";
36933
+ import { tmpdir } from "os";
36934
+ import { basename, dirname, join } from "path";
36935
+ var FOLDER = "pilot-attachments";
36936
+ var MAX_ATTACHMENT_BYTES = 1e7;
36937
+ var MAX_INLINE_IMAGE = 35e5;
36938
+ var MAX_INLINE_TEXT = 1e5;
36939
+ var KEEP_MS = 7 * 24 * 60 * 60 * 1e3;
36940
+ function attachmentsDir(base = tmpdir()) {
36941
+ return join(base, FOLDER);
36942
+ }
36943
+ function extensionOf(type) {
36944
+ const given = type.split(";")[0]?.trim().toLowerCase();
36945
+ const found = Object.entries(ATTACHMENT_TYPES).find(([, t]) => t === given);
36946
+ return found ? found[0] : null;
36947
+ }
36948
+ function looksLike(bytes, ext) {
36949
+ const starts = (...sig) => sig.every((b, i) => bytes[i] === b);
36950
+ switch (ext) {
36951
+ case "png":
36952
+ return starts(137, 80, 78, 71);
36953
+ case "jpg":
36954
+ return starts(255, 216, 255);
36955
+ case "gif":
36956
+ return starts(71, 73, 70, 56);
36957
+ case "webp":
36958
+ return starts(82, 73, 70, 70) && bytes.subarray(8, 12).toString("latin1") === "WEBP";
36959
+ case "pdf":
36960
+ return bytes.subarray(0, 5).toString("latin1") === "%PDF-";
36961
+ default:
36962
+ if (bytes.includes(0)) return false;
36963
+ try {
36964
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes);
36965
+ return true;
36966
+ } catch {
36967
+ return false;
36968
+ }
36969
+ }
36970
+ }
36971
+ async function saveAttachment(bytes, type, dir = attachmentsDir()) {
36972
+ const ext = extensionOf(type);
36973
+ if (!ext || bytes.length === 0 || bytes.length > MAX_ATTACHMENT_BYTES || !looksLike(bytes, ext)) return null;
36974
+ const id = `${createHash("sha256").update(bytes).digest("hex")}.${ext}`;
36975
+ await mkdir(dir, { recursive: true });
36976
+ const path = join(dir, id);
36977
+ if (!existsSync(path)) await writeFile(path, bytes);
36978
+ return id;
36979
+ }
36980
+ function withAttachmentPaths(job, dir = attachmentsDir()) {
36981
+ const request = job.changeSet.request;
36982
+ if (request?.kind !== "comment") return job;
36983
+ const thread = request.thread.map((message) => {
36984
+ if (!message.attachments) return message;
36985
+ const attachments = message.attachments.filter((file2) => typeof file2?.id === "string" && ATTACHMENT_ID.test(file2.id) && existsSync(join(dir, file2.id))).slice(0, 20).map((file2) => ({
36986
+ id: file2.id,
36987
+ name: typeof file2.name === "string" ? file2.name.slice(0, 200) : void 0,
36988
+ path: join(dir, file2.id)
36989
+ }));
36990
+ return { ...message, attachments: attachments.length ? attachments : void 0 };
36991
+ });
36992
+ return { ...job, changeSet: { ...job.changeSet, request: { ...request, thread } } };
36993
+ }
36994
+ async function attachmentBlocks(job) {
36995
+ const request = job.changeSet.request;
36996
+ if (request?.kind !== "comment") return [];
36997
+ const lastReply = request.thread.map((m) => m.from).lastIndexOf("agent");
36998
+ const files = request.thread.slice(lastReply + 1).flatMap((m) => m.attachments ?? []);
36999
+ const blocks = [];
37000
+ for (const file2 of files) {
37001
+ const path = file2.path;
37002
+ if (!path || basename(dirname(path)) !== FOLDER || !ATTACHMENT_ID.test(basename(path))) continue;
37003
+ const kind = attachmentKind(path);
37004
+ if (kind === "pdf") continue;
37005
+ try {
37006
+ const size = (await stat(path)).size;
37007
+ if (kind === "image") {
37008
+ if (size > MAX_INLINE_IMAGE) continue;
37009
+ const ext = basename(path).split(".").pop();
37010
+ blocks.push({ type: "image", data: (await readFile(path)).toString("base64"), mimeType: ATTACHMENT_TYPES[ext] });
37011
+ } else {
37012
+ if (size > MAX_INLINE_TEXT) continue;
37013
+ const name = file2.name ?? basename(path);
37014
+ blocks.push({
37015
+ type: "text",
37016
+ text: `Attached file ${name}, as the designer sent it:
37017
+
37018
+ ${await readFile(path, "utf8")}
37019
+
37020
+ (end of ${name})`
37021
+ });
37022
+ }
37023
+ } catch {
37024
+ }
37025
+ }
37026
+ return blocks;
37027
+ }
37028
+ async function sweepAttachments(dir = attachmentsDir(), now = Date.now()) {
37029
+ try {
37030
+ for (const name of await readdir(dir)) {
37031
+ if (!ATTACHMENT_ID.test(name)) continue;
37032
+ const path = join(dir, name);
37033
+ if (now - (await stat(path)).mtimeMs > KEEP_MS) await rm(path, { force: true });
37034
+ }
37035
+ } catch {
37036
+ }
37037
+ }
37038
+
36745
37039
  // src/hub.ts
37040
+ import { randomUUID } from "crypto";
36746
37041
  var AGENT_TTL = 3e4;
36747
37042
  var Hub = class {
36748
37043
  constructor(now = Date.now) {
@@ -36753,6 +37048,7 @@ var Hub = class {
36753
37048
  pages = /* @__PURE__ */ new Set();
36754
37049
  jobs = /* @__PURE__ */ new Map();
36755
37050
  waiters = [];
37051
+ checks = /* @__PURE__ */ new Map();
36756
37052
  // Agents
36757
37053
  /** An agent works on pages of `origin` (again: also how a remote one says it's alive). */
36758
37054
  register(info, origin) {
@@ -36819,6 +37115,34 @@ var Hub = class {
36819
37115
  this.update(job, { status: "done", agent, notes: notes?.trim() || void 0 });
36820
37116
  return job;
36821
37117
  }
37118
+ /**
37119
+ * An agent asks for Pilot's width check of a task's element: the open
37120
+ * pages of the job's origin get a `check` event, and the one that has the
37121
+ * job measures it and posts the answer (checkResult). Null when no page
37122
+ * is open, the hub doesn't know the job, or no answer comes in `timeoutMs`.
37123
+ */
37124
+ check(jobId, timeoutMs) {
37125
+ const job = this.jobs.get(jobId);
37126
+ if (!job) return Promise.resolve(null);
37127
+ const requestId = randomUUID();
37128
+ return new Promise((resolve) => {
37129
+ const timer = setTimeout(() => finish(null), timeoutMs);
37130
+ const finish = (check2) => {
37131
+ clearTimeout(timer);
37132
+ this.checks.delete(requestId);
37133
+ resolve(check2);
37134
+ };
37135
+ this.checks.set(requestId, { origin: job.origin, resolve: finish });
37136
+ if (!this.sendTo(job.origin, { type: "check", requestId, jobId })) finish(null);
37137
+ });
37138
+ }
37139
+ /** A page's answer to a width check: false when nothing waits for it from that origin. */
37140
+ checkResult(origin, requestId, check2) {
37141
+ const pending = this.checks.get(requestId);
37142
+ if (!pending || pending.origin !== originKey(origin)) return false;
37143
+ pending.resolve(check2);
37144
+ return true;
37145
+ }
36822
37146
  // Pages
36823
37147
  addPage(page) {
36824
37148
  const conn = { ...page, origin: originKey(page.origin) };
@@ -36855,6 +37179,7 @@ var Hub = class {
36855
37179
  agent: stillWorking || post.attempt === 2 ? post.agent : void 0,
36856
37180
  attempt: post.attempt ?? 1,
36857
37181
  differences: post.differences,
37182
+ issues: post.issues,
36858
37183
  createdAt: at,
36859
37184
  updatedAt: at
36860
37185
  };
@@ -36871,15 +37196,16 @@ var Hub = class {
36871
37196
  return job;
36872
37197
  }
36873
37198
  /**
36874
- * Some changes of a done job didn't come out as the designer set them: the
36875
- * job goes back to the queue once, as a follow-up with the `differences`,
37199
+ * Some changes of a done job didn't come out as the designer set them (or
37200
+ * a task's width check found problems, `issues`): the job goes back to
37201
+ * the queue once, as a follow-up with the `differences`,
36876
37202
  * preferably to the agent that did it. Null when it can't (not done, or
36877
37203
  * already a follow-up: then the page takes what the code gives).
36878
37204
  */
36879
- retry(origin, jobId, differences) {
37205
+ retry(origin, jobId, differences, issues) {
36880
37206
  const job = this.jobs.get(jobId);
36881
37207
  if (!job || job.origin !== originKey(origin) || job.status !== "done" || (job.attempt ?? 1) >= 2) return null;
36882
- this.update(job, { status: "queued", attempt: 2, differences, notes: void 0 });
37208
+ this.update(job, { status: "queued", attempt: 2, differences, issues, notes: void 0 });
36883
37209
  this.dispatch(job.origin);
36884
37210
  return job;
36885
37211
  }
@@ -36937,9 +37263,11 @@ var Hub = class {
36937
37263
  };
36938
37264
 
36939
37265
  // src/server.ts
36940
- function startHub(port, hub = new Hub()) {
37266
+ function startHub(port, hub = new Hub(), options = {}) {
37267
+ const attachments = options.attachments ?? attachmentsDir();
37268
+ void sweepAttachments(attachments);
36941
37269
  const server = createServer((req, res) => {
36942
- handle(hub, req, res).catch((error62) => {
37270
+ handle(hub, req, res, attachments).catch((error62) => {
36943
37271
  if (!res.headersSent) json2(res, 500, { error: String(error62) });
36944
37272
  });
36945
37273
  });
@@ -36966,7 +37294,7 @@ function startHub(port, hub = new Hub()) {
36966
37294
  });
36967
37295
  }
36968
37296
  var localAgents = /* @__PURE__ */ new Set();
36969
- async function handle(hub, req, res) {
37297
+ async function handle(hub, req, res, attachments) {
36970
37298
  const url2 = new URL(req.url ?? "/", "http://127.0.0.1");
36971
37299
  const origin = req.headers.origin;
36972
37300
  const path = url2.pathname;
@@ -36989,18 +37317,37 @@ async function handle(hub, req, res) {
36989
37317
  if (path === "/events" && req.method === "GET") return events(hub, origin, req, res);
36990
37318
  if (req.method !== "POST") return json2(res, 405, { error: "POST only" });
36991
37319
  if (!hub.hasAgents(origin)) return json2(res, 403, { error: "no agent works on this page: run /pilot in your agent" });
37320
+ if (path === "/attachments") {
37321
+ const type = req.headers["content-type"] ?? "";
37322
+ if (!extensionOf(type)) return json2(res, 415, { error: "images (png, jpeg, gif, webp), text files (txt, md, csv, json) and PDFs only" });
37323
+ const bytes = await rawBody(req, MAX_ATTACHMENT_BYTES);
37324
+ if (!bytes) return json2(res, 413, { error: `files up to ${MAX_ATTACHMENT_BYTES / 1e6} MB` });
37325
+ const id = await saveAttachment(bytes, type, attachments);
37326
+ return id ? json2(res, 201, { id }) : json2(res, 400, { error: "not a file of that type" });
37327
+ }
36992
37328
  const data = await body(req);
36993
37329
  if (path === "/jobs") {
36994
37330
  const post = data;
36995
37331
  if (typeof post?.id !== "string" || !post.changeSet) return json2(res, 400, { error: "job needs id and changeSet" });
36996
- return json2(res, 202, { job: hub.postJob(origin, post) });
37332
+ return json2(res, 202, { job: hub.postJob(origin, withAttachmentPaths(post, attachments)) });
36997
37333
  }
36998
37334
  const jobRoute = path.match(/^\/jobs\/([^/]+)\/(cancel|retry)$/);
36999
37335
  if (jobRoute) {
37000
37336
  const [, id, action] = jobRoute;
37001
- const job = action === "cancel" ? hub.cancel(origin, decodeURIComponent(id)) : hub.retry(origin, decodeURIComponent(id), (data.differences ?? []).slice(0, 200));
37337
+ const job = action === "cancel" ? hub.cancel(origin, decodeURIComponent(id)) : hub.retry(
37338
+ origin,
37339
+ decodeURIComponent(id),
37340
+ (data.differences ?? []).slice(0, 200),
37341
+ stringsOf(data.issues)
37342
+ );
37002
37343
  return job ? json2(res, 200, { job }) : json2(res, 409, { error: `can't ${action} this job` });
37003
37344
  }
37345
+ const checkRoute = path.match(/^\/checks\/([^/]+)$/);
37346
+ if (checkRoute) {
37347
+ const check2 = data.check;
37348
+ if (!check2 || !Array.isArray(check2.widths)) return json2(res, 400, { error: "check needed" });
37349
+ return hub.checkResult(origin, decodeURIComponent(checkRoute[1]), check2) ? json2(res, 200, { ok: true }) : json2(res, 409, { error: "no check waits for this" });
37350
+ }
37004
37351
  return json2(res, 404, { error: "not found" });
37005
37352
  }
37006
37353
  function events(hub, origin, req, res) {
@@ -37042,6 +37389,11 @@ async function handleAgent(hub, action, data, req, res) {
37042
37389
  case "done":
37043
37390
  if (!d.jobId) return json2(res, 400, { error: "jobId needed" });
37044
37391
  return json2(res, 200, { job: hub.done(d.agent.id, d.jobId, d.notes) });
37392
+ case "check": {
37393
+ if (!d.jobId) return json2(res, 400, { error: "jobId needed" });
37394
+ const check2 = await hub.check(d.jobId, Math.min(d.timeoutMs ?? CHECK_TIMEOUT, 2 * 6e4));
37395
+ return json2(res, 200, { check: check2 });
37396
+ }
37045
37397
  case "leave":
37046
37398
  hub.unregister(d.agent.id);
37047
37399
  return json2(res, 200, { ok: true });
@@ -37049,10 +37401,37 @@ async function handleAgent(hub, action, data, req, res) {
37049
37401
  return json2(res, 404, { error: "not found" });
37050
37402
  }
37051
37403
  }
37404
+ var CHECK_TIMEOUT = 6e4;
37405
+ function stringsOf(value) {
37406
+ if (!Array.isArray(value)) return void 0;
37407
+ return value.filter((v) => typeof v === "string").slice(0, 100).map((v) => v.slice(0, 2e3));
37408
+ }
37052
37409
  function json2(res, status, data) {
37053
37410
  res.writeHead(status, { "Content-Type": "application/json" });
37054
37411
  res.end(JSON.stringify(data));
37055
37412
  }
37413
+ function rawBody(req, max) {
37414
+ return new Promise((resolve, reject) => {
37415
+ const chunks = [];
37416
+ let size = 0;
37417
+ let over = false;
37418
+ req.on("data", (chunk) => {
37419
+ if (over) return;
37420
+ size += chunk.length;
37421
+ if (size > max) {
37422
+ over = true;
37423
+ resolve(null);
37424
+ req.resume();
37425
+ return;
37426
+ }
37427
+ chunks.push(chunk);
37428
+ });
37429
+ req.on("end", () => {
37430
+ if (!over) resolve(Buffer.concat(chunks));
37431
+ });
37432
+ req.on("error", reject);
37433
+ });
37434
+ }
37056
37435
  function body(req) {
37057
37436
  return new Promise((resolve, reject) => {
37058
37437
  let text = "";
@@ -37093,6 +37472,9 @@ var LocalApi = class {
37093
37472
  async done(agent, jobId, notes) {
37094
37473
  return this.hub.done(agent.id, jobId, notes);
37095
37474
  }
37475
+ check(_agent, jobId, timeoutMs) {
37476
+ return this.hub.check(jobId, timeoutMs);
37477
+ }
37096
37478
  async leave(agent) {
37097
37479
  localAgents.delete(agent.id);
37098
37480
  this.hub.unregister(agent.id);
@@ -37125,6 +37507,9 @@ var RemoteApi = class {
37125
37507
  async done(agent, jobId, notes) {
37126
37508
  return (await this.post("done", { agent, jobId, notes })).job;
37127
37509
  }
37510
+ async check(agent, jobId, timeoutMs) {
37511
+ return (await this.post("check", { agent, jobId, timeoutMs })).check;
37512
+ }
37128
37513
  async leave(agent) {
37129
37514
  await this.post("leave", { agent });
37130
37515
  }
@@ -37171,6 +37556,10 @@ var Bridge = class {
37171
37556
  done(jobId, notes) {
37172
37557
  return this.call((api) => api.done(this.agent, jobId, notes));
37173
37558
  }
37559
+ /** Pilot's width check of a task's element, measured by the page (null: no page answered). */
37560
+ check(jobId, timeoutMs = CHECK_TIMEOUT) {
37561
+ return this.call((api) => api.check(this.agent, jobId, timeoutMs));
37562
+ }
37174
37563
  async close() {
37175
37564
  if (this.heartbeat) clearInterval(this.heartbeat);
37176
37565
  try {
@@ -37265,10 +37654,10 @@ function waitMsFor(clientName) {
37265
37654
  var PROGRESS_MS = 2e4;
37266
37655
  var INSTRUCTIONS = `Pilot lets the designer edit the running app in the browser and send the edits back to you as jobs.
37267
37656
 
37268
- The loop, when the user runs /pilot or asks to hand the design over:
37269
- 1. Call pilot_launch with the URL of the page the designer works on (the app's dev server, e.g. http://localhost:5173). Pilot opens in that page.
37657
+ The loop, when the user asks to launch or start Pilot, runs /pilot, or asks to hand the design over:
37658
+ 1. Find the page: the URL of the app's dev server, from the dev script and its config (vite.config \u2192 server.port, Next.js \u2192 3000, a --port flag\u2026) or a server already running. If it isn't running, start it in the background; if you can't tell the URL, ask. Call pilot_launch with that URL: Pilot opens in that page (if the page isn't open, tell the user to open it), then tell the user in one line that Pilot is ready: select an element, edit, press Send.
37270
37659
  2. Call pilot_wait_for_edits. It returns a job when the designer presses Send, or "no edits yet" after a while: then call it again. (In Claude Code a long wait moves to the background: the job arrives as its result.)
37271
- 3. Apply the job's edits to the source, in the project's conventions (see the job's guidelines).
37660
+ 3. Apply the job's edits to the source, in the project's conventions (see the job's guidelines). Edits are basic: every value is given, so be fast (no screenshots or browser checks: Pilot checks the page). A "make responsive" job is an advanced task: make one element work at every viewport width. Its prompt lists the steps; check the result with pilot_check_widths (numbers for every width, instead of screenshots). In Claude Code, hand advanced tasks to an Opus subagent unless you run on Opus. A "comment" job is the designer's own words about one element: do what it asks (simple asks right away, open-ended ones as advanced tasks), and your pilot_done notes are your reply in their thread: one short sentence, like a chat message, not a report.
37272
37661
  4. Call pilot_done with the job id and short notes (values you approximated, anything you did differently). Then call pilot_wait_for_edits again.
37273
37662
 
37274
37663
  Keep looping until the user interrupts you. Pilot keeps previewing each job's changes until you call pilot_done, then checks them against the page's real CSS: changes that didn't land come back once as a follow-up job with what the page gives instead.`;
@@ -37283,13 +37672,13 @@ function agentLabel(clientName, cwd) {
37283
37672
  codex: "Codex"
37284
37673
  };
37285
37674
  const app = clientName && (names[clientName.toLowerCase()] ?? clientName) || "Agent";
37286
- return `${app} \xB7 ${basename(cwd)}`;
37675
+ return `${app} \xB7 ${basename2(cwd)}`;
37287
37676
  }
37288
37677
  function jobPrompt(job) {
37289
- const body2 = job.attempt === 2 && job.differences?.length ? followUp(job) : formatPrompt(job.changeSet);
37678
+ const body2 = job.attempt === 2 && job.issues?.length ? taskFollowUp(job) : job.attempt === 2 && job.differences?.length ? followUp(job) : formatPrompt(job.changeSet);
37290
37679
  return `${body2}
37291
37680
  ---
37292
- Pilot job \`${job.id}\`. When you've applied it, call \`pilot_done\` with \`jobId: "${job.id}"\` and short notes (values you approximated, anything you did differently). Then call \`pilot_wait_for_edits\` again for the next job.
37681
+ Pilot job \`${job.id}\`. When you've applied it, call \`pilot_done\` with \`jobId: "${job.id}"\` and short notes (${notesFor(job)}). Then call \`pilot_wait_for_edits\` again for the next job.
37293
37682
  `;
37294
37683
  }
37295
37684
  function followUp(job) {
@@ -37310,12 +37699,39 @@ function followUp(job) {
37310
37699
  );
37311
37700
  return lines.join("\n");
37312
37701
  }
37702
+ function notesFor(job) {
37703
+ switch (job.changeSet.request?.kind) {
37704
+ case "comment":
37705
+ return "your reply in the designer's comment thread, a small chat box: one short sentence, about 120 characters at most, with what you changed or your answer; no lists or code blocks";
37706
+ case "responsive":
37707
+ return "what changed at which widths, anything left for the designer";
37708
+ default:
37709
+ return "values you approximated, anything you did differently";
37710
+ }
37711
+ }
37712
+ function taskFollowUp(job) {
37713
+ const target = job.changeSet.request?.target;
37714
+ const lines = [
37715
+ "# Pilot: make responsive, follow-up",
37716
+ "",
37717
+ `You made \`${target?.path ?? "the element"}\` responsive, but Pilot's width check (the page measured at each width) still finds these problems:`,
37718
+ "",
37719
+ ...(job.issues ?? []).map((i) => `- ${i}`),
37720
+ "",
37721
+ "Fix them, then run `pilot_check_widths` to confirm before `pilot_done`. If one is deliberate, keep it and say why in your notes. Pilot takes what the code gives after this.",
37722
+ "",
37723
+ "The task, for reference:",
37724
+ "",
37725
+ formatPrompt(job.changeSet)
37726
+ ];
37727
+ return lines.join("\n");
37728
+ }
37313
37729
  function createPilotServer(options = {}) {
37314
37730
  const port = options.port ?? (Number(process.env.PILOT_PORT) || DEFAULT_BRIDGE_PORT);
37315
37731
  const cwd = options.cwd ?? process.cwd();
37316
37732
  let waitMs = options.waitMs ?? waitMsFor(void 0);
37317
- const server = new McpServer({ name: "pilot", version: "0.3.0" }, { instructions: INSTRUCTIONS });
37318
- const agent = { id: randomUUID(), label: agentLabel(void 0, cwd) };
37733
+ const server = new McpServer({ name: "pilot", version: "0.5.0" }, { instructions: INSTRUCTIONS });
37734
+ const agent = { id: randomUUID2(), label: agentLabel(void 0, cwd) };
37319
37735
  const bridge = new Bridge(agent, port);
37320
37736
  let origin = null;
37321
37737
  server.server.oninitialized = () => {
@@ -37328,7 +37744,7 @@ function createPilotServer(options = {}) {
37328
37744
  "pilot_launch",
37329
37745
  {
37330
37746
  title: "Launch Pilot",
37331
- description: "Opens Pilot in the page the designer works on, and routes that page's edits to you. Call it first when the user runs /pilot. Then call pilot_wait_for_edits.",
37747
+ description: "Opens Pilot in the page the designer works on, and routes that page's edits to you. Call it first when the user asks to launch or start Pilot (or runs /pilot). Then call pilot_wait_for_edits.",
37332
37748
  inputSchema: {
37333
37749
  url: external_exports.string().describe("The page's URL on the app's dev server, e.g. http://localhost:5173 (find it in the dev server's config or output).")
37334
37750
  }
@@ -37367,7 +37783,7 @@ function createPilotServer(options = {}) {
37367
37783
  try {
37368
37784
  const { job } = await bridge.wait(origin, waitMs, extra.signal);
37369
37785
  if (!job) return text("No edits yet. Call pilot_wait_for_edits again to keep waiting (the designer can keep editing meanwhile).");
37370
- return text(jobPrompt(job));
37786
+ return { content: [{ type: "text", text: jobPrompt(job) }, ...await attachmentBlocks(job)], isError: false };
37371
37787
  } catch (error62) {
37372
37788
  return text(`Pilot's bridge failed while waiting: ${error62.message}. Call pilot_wait_for_edits again.`, true);
37373
37789
  } finally {
@@ -37395,23 +37811,55 @@ function createPilotServer(options = {}) {
37395
37811
  }
37396
37812
  }
37397
37813
  );
37814
+ server.registerTool(
37815
+ "pilot_check_widths",
37816
+ {
37817
+ title: "Check an element at every width",
37818
+ description: "For a Make responsive job: Pilot loads the page in hidden frames at a phone width, each breakpoint and just below it, a wide desktop and the designer's width, and measures the job's element in each. Returns each width's size and layout, and problems (sticking out of the viewport, spilling out of its parent, clipped content, overlaps), plus what changed at the designer's width. Use it instead of screenshots; fix the problems and run it again until it finds none.",
37819
+ inputSchema: {
37820
+ jobId: external_exports.string().describe("The Make responsive job's id, from pilot_wait_for_edits.")
37821
+ }
37822
+ },
37823
+ async ({ jobId }) => {
37824
+ try {
37825
+ const check2 = await bridge.check(jobId);
37826
+ if (!check2) {
37827
+ return text(
37828
+ `Pilot couldn't check job ${jobId}: no page answered. The page with Pilot must be open (the designer's tab), and the job must be a Make responsive one. If you can, check the widths in a browser instead.`,
37829
+ true
37830
+ );
37831
+ }
37832
+ return text(formatWidthCheck(check2));
37833
+ } catch (error62) {
37834
+ return text(`Pilot couldn't run the width check: ${error62.message}`, true);
37835
+ }
37836
+ }
37837
+ );
37398
37838
  return { server, bridge, agent };
37399
37839
  }
37400
37840
 
37841
+ // src/init.ts
37842
+ import { spawnSync } from "child_process";
37843
+ import { existsSync as existsSync3, readdirSync, readFileSync } from "fs";
37844
+ import { mkdir as mkdir3, readFile as readFile3, writeFile as writeFile3 } from "fs/promises";
37845
+ import { dirname as dirname2, join as join3, relative as relative2 } from "path";
37846
+
37401
37847
  // src/setup.ts
37402
- import { mkdir, writeFile } from "fs/promises";
37848
+ import { existsSync as existsSync2 } from "fs";
37849
+ import { lstat, mkdir as mkdir2, readFile as readFile2, unlink, writeFile as writeFile2 } from "fs/promises";
37403
37850
  import { homedir } from "os";
37404
- import { join } from "path";
37851
+ import { join as join2, relative } from "path";
37405
37852
 
37406
37853
  // ../../skills/pilot/SKILL.md
37407
- var SKILL_default = "---\nname: pilot\ndescription: Hand the UI to the designer with Pilot, then apply the design edits they send, job after job. Use when the user runs /pilot, says they want to take control of the design or edit the UI in the browser, or pastes a \"Pilot design edits\" brief.\n---\n\n# Pilot\n\nPilot lets the designer edit the running app in the browser. They select elements, change CSS properties with Pilot's editors, and press **Send**. Each Send reaches you as a **job**: plain CSS `property: from \u2192 to` on identifiable elements, for you to write into the source in this project's conventions. The designer keeps designing while you work; Pilot previews each job's changes until you report it done, then checks them against the page's real CSS.\n\n## When the user runs /pilot\n\n1. **Find the page.** Work out the URL of the app's dev server: the dev script and its config (`vite.config.*` \u2192 `server.port`, Next.js \u2192 3000, a `--port` flag\u2026), or a server already running in a terminal. If the dev server isn't running, start it in the background. If you can't tell the URL, ask.\n2. **Launch:** call `pilot_launch` with that URL. Pilot opens in the page (if the page isn't open yet, tell the designer to open it).\n3. **Tell the designer** in one line that Pilot is ready: select an element, edit, press Send.\n4. **Wait:** call `pilot_wait_for_edits`. It returns a job when the designer presses Send, or \"no edits yet\" after a while: call it again, without saying anything to the user. In Claude Code, a wait longer than two minutes moves to the background: end your turn with a short \"Waiting for your edits\", and the job arrives as the task's result.\n5. **Apply the job** (below), then call `pilot_done` with the job id and short notes, and go back to step 4.\n\nKeep looping until the user asks you to stop. Keep your messages between jobs short: a line on what you changed (and anything you approximated) is enough. If the user talks to you meanwhile, help them, and keep (or start again) a wait in the background so their next Send reaches you (queued jobs are kept).\n\n## Applying a job\n\nThe values are **intent, not code**. Translate them into this project's conventions:\n\n- **Tailwind:** the closest utility or theme value (`border-radius: 12px` \u2192 `rounded-xl`, `padding-top: 24px` \u2192 `pt-6`). Arbitrary values only when nothing fits.\n- **CSS / CSS modules / Sass:** edit the rule that styles the element. Don't add a new override.\n- **Design tokens / CSS variables:** prefer an existing token that matches. Don't hard-code its value.\n- **CSS-in-JS:** edit the styled definition or `sx` / `style` object where the component is styled.\n\nRules:\n\n- Never leave inline styles behind. Pilot's preview is only a preview.\n- Find each element by its selector, DOM path and text snippet, then the component that renders it.\n- If an element comes from a shared component, ask before changing every instance. Otherwise scope the change (a variant, a prop, a class on that use).\n- **Widths:** a change for some viewport widths goes in a media query; use the project's breakpoints when one matches (or is within a few pixels). \"Every width\" means no media query should override it.\n- **Removed:** the element shouldn't declare the property at all (not `0` or `none`).\n- If you approximated a value to fit a token or scale, say which and by how much in `pilot_done`'s notes (`22px \u2192 pt-6, 24px`). Pilot checks the page after each job: a change that doesn't give the designer's value comes back to you once as a follow-up. Fix it, or keep a deliberate choice and say why; after that, Pilot takes what the code gives.\n- Don't run builds or tests for a job unless it's needed: hot reload shows the result, and the designer is waiting to see it.\n";
37854
+ var SKILL_default = "---\nname: pilot\ndescription: Hand the UI to the designer with Pilot, then apply the design edits they send, job after job. Use when the user runs /pilot, says they want to take control of the design or edit the UI in the browser, or pastes a \"Pilot design edits\" brief.\n---\n\n# Pilot\n\nPilot lets the designer edit the running app in the browser. They select elements, change CSS properties with Pilot's editors, and press **Send**. Each Send reaches you as a **job**: plain CSS `property: from \u2192 to` (and new text, when they rewrote one) on identifiable elements, for you to write into the source in this project's conventions. The designer keeps designing while you work; Pilot previews each job's changes until you report it done, then checks them against the page's real CSS.\n\n## When the user runs /pilot\n\n1. **Find the page.** Work out the URL of the app's dev server: the dev script and its config (`vite.config.*` \u2192 `server.port`, Next.js \u2192 3000, a `--port` flag\u2026), or a server already running in a terminal. If the dev server isn't running, start it in the background. If you can't tell the URL, ask.\n2. **Launch:** call `pilot_launch` with that URL. Pilot opens in the page (if the page isn't open yet, tell the designer to open it).\n3. **Tell the designer** in one line that Pilot is ready: select an element, edit, press Send.\n4. **Wait:** call `pilot_wait_for_edits`. It returns a job when the designer presses Send, or \"no edits yet\" after a while: call it again, without saying anything to the user. In Claude Code, a wait longer than two minutes moves to the background: end your turn with a short \"Waiting for your edits\", and the job arrives as the task's result.\n5. **Apply the job** (below), then call `pilot_done` with the job id and short notes, and go back to step 4.\n\nKeep looping until the user asks you to stop. Keep your messages between jobs short: a line on what you changed (and anything you approximated) is enough. If the user talks to you meanwhile, help them, and keep (or start again) a wait in the background so their next Send reaches you (queued jobs are kept).\n\n## Applying a job\n\nJobs come in three kinds:\n\n- **Edits** (basic): the designer set every value; you only translate them. **Speed is what matters**: go straight to the code, apply, call `pilot_done`. No screenshots, browser checks, builds or tests: Pilot checks the page itself and sends back what didn't land.\n- **Comments**: the designer's own words about one element (\"make it the brand green\", \"can this be calmer?\"), with the thread so far. Do what the latest one asks: a specific, small ask right away (like an edit), an open-ended one as an advanced task (below). A question gets an answer and no change. Your `pilot_done` notes are your reply in their thread, a small chat box for quick design back-and-forth: one short sentence, like a chat message (about 120 characters), with no lists or code blocks. Not a report: they see the result on the page.\n- **Tasks** (advanced), like **Make responsive**: the designer selected an element and asked for an outcome (work at every viewport width). They need judgment more than speed. The prompt has the steps. Check the result with `pilot_check_widths` (numbers for every width, no screenshots needed). In Claude Code, unless you already run on Opus, hand the task to a subagent with `model: \"opus\"`, then call `pilot_done` with its notes. Pilot checks the widths again when you're done; problems come back once as a follow-up.\n\n### Edits\n\nThe values are **intent, not code**. Translate them into this project's conventions:\n\n- **Tailwind:** the closest utility or theme value (`border-radius: 12px` \u2192 `rounded-xl`, `padding-top: 24px` \u2192 `pt-6`). Arbitrary values only when nothing fits.\n- **CSS / CSS modules / Sass:** edit the rule that styles the element. Don't add a new override.\n- **Design tokens / CSS variables:** prefer an existing token that matches. Don't hard-code its value.\n- **CSS-in-JS:** edit the styled definition or `sx` / `style` object where the component is styled.\n\nRules:\n\n- Never leave inline styles behind. Pilot's preview is only a preview.\n- Find each element by its selector, DOM path and text snippet, then the component that renders it.\n- If an element comes from a shared component, ask before changing every instance. Otherwise scope the change (a variant, a prop, a class on that use).\n- **Widths:** a change for some viewport widths goes in a media query; use the project's breakpoints when one matches (or is within a few pixels). \"Every width\" means no media query should override it.\n- **Removed:** the element shouldn't declare the property at all (not `0` or `none`).\n- **Text:** the designer rewrote the element's copy. Change it where it comes from (the markup, a prop, a translation file), for this element only; Pilot checks that the page shows the new text.\n- If you approximated a value to fit a token or scale, say which and by how much in `pilot_done`'s notes (`22px \u2192 pt-6, 24px`). Pilot checks the page after each job: a change that doesn't give the designer's value comes back to you once as a follow-up. Fix it, or keep a deliberate choice and say why; after that, Pilot takes what the code gives.\n- Don't run builds or tests for a job unless it's needed: hot reload shows the result, and the designer is waiting to see it.\n";
37408
37855
 
37409
37856
  // src/setup.ts
37410
- async function setup() {
37411
- const dir = join(homedir(), ".claude", "skills", "pilot");
37412
- await mkdir(dir, { recursive: true });
37413
- const file2 = join(dir, "SKILL.md");
37414
- await writeFile(file2, SKILL_default);
37857
+ var MCP_SERVER = { command: "npx", args: ["-y", "usepilot", "mcp"] };
37858
+ async function setup(options = {}) {
37859
+ return options.project ? setupProject(options.cwd ?? process.cwd()) : setupMachine(options.home ?? homedir());
37860
+ }
37861
+ async function setupMachine(home) {
37862
+ const file2 = await writeSkill(join2(home, ".claude", "skills", "pilot"));
37415
37863
  return `Installed the /pilot skill: ${file2}
37416
37864
 
37417
37865
  Now register Pilot's MCP server with Claude Code, once, for every project:
@@ -37419,15 +37867,337 @@ Now register Pilot's MCP server with Claude Code, once, for every project:
37419
37867
  claude mcp add --scope user pilot -- npx -y usepilot mcp
37420
37868
 
37421
37869
  Then, in any Claude Code chat: /pilot
37870
+ (For a repo you share, run \`npx usepilot setup --project\` in it instead.)
37422
37871
  `;
37423
37872
  }
37873
+ async function setupProject(cwd) {
37874
+ const skillFile = await writeSkill(join2(cwd, ".claude", "skills", "pilot"));
37875
+ const mcpFile = join2(cwd, ".mcp.json");
37876
+ const { added } = await addMcpServer(mcpFile);
37877
+ const rel = (f) => relative(cwd, f);
37878
+ const app = existsSync2(join2(cwd, "package.json")) ? "" : "\nNo package.json here: run this in the project's root folder, where the app is.\n";
37879
+ const width = rel(skillFile).length + 2;
37880
+ return `Set up /pilot for this repo:
37881
+ ${rel(skillFile).padEnd(width)}the /pilot skill
37882
+ ${rel(mcpFile).padEnd(width)}Pilot's MCP server${added ? "" : " (it was there: updated)"}
37883
+ ${app}
37884
+ Commit both: everyone working in the repo gets /pilot in Claude Code (it asks
37885
+ each of them once to approve the project's MCP server).
37886
+
37887
+ The app needs Pilot too, in development, if it doesn't have it yet:
37888
+ npm install -D usepilot
37889
+ if (import.meta.env.DEV) import("usepilot/auto"); (in the app's entry file)
37890
+
37891
+ Then, in a Claude Code chat in this folder: /pilot
37892
+ `;
37893
+ }
37894
+ async function writeSkill(dir) {
37895
+ if (await isLink(dir)) await unlink(dir);
37896
+ await mkdir2(dir, { recursive: true });
37897
+ const file2 = join2(dir, "SKILL.md");
37898
+ await writeFile2(file2, SKILL_default);
37899
+ return file2;
37900
+ }
37901
+ async function isLink(path) {
37902
+ try {
37903
+ return (await lstat(path)).isSymbolicLink();
37904
+ } catch {
37905
+ return false;
37906
+ }
37907
+ }
37908
+ async function addMcpServer(file2) {
37909
+ let config2 = {};
37910
+ if (existsSync2(file2)) {
37911
+ const text = await readFile2(file2, "utf8");
37912
+ try {
37913
+ config2 = text.trim() ? JSON.parse(text) : {};
37914
+ } catch {
37915
+ throw new Error(`${file2} isn't valid JSON: fix it, then run setup again.`);
37916
+ }
37917
+ }
37918
+ const servers = config2.mcpServers ?? {};
37919
+ const added = !("pilot" in servers);
37920
+ config2.mcpServers = { ...servers, pilot: MCP_SERVER };
37921
+ await writeFile2(file2, `${JSON.stringify(config2, null, 2)}
37922
+ `);
37923
+ return { added };
37924
+ }
37925
+
37926
+ // src/init.ts
37927
+ var CLIENTS = [
37928
+ { name: "Claude Code", file: ".mcp.json", key: "mcpServers", entry: MCP_SERVER },
37929
+ { name: "Cursor", file: join3(".cursor", "mcp.json"), key: "mcpServers", entry: MCP_SERVER },
37930
+ { name: "VS Code", file: join3(".vscode", "mcp.json"), key: "servers", entry: { type: "stdio", ...MCP_SERVER } }
37931
+ ];
37932
+ var COMMAND = `${MCP_SERVER.command} ${MCP_SERVER.args.join(" ")}`;
37933
+ async function init(options = {}) {
37934
+ const cwd = options.cwd ?? process.cwd();
37935
+ const run = options.run ?? runCommand;
37936
+ const pkgFile = join3(cwd, "package.json");
37937
+ if (!existsSync3(pkgFile)) {
37938
+ return `# Pilot: not set up
37939
+
37940
+ There's no package.json in ${cwd}. Run \`npx usepilot@latest init\` again in the app's folder: the one with the package.json of the web app the user works on.
37941
+ `;
37942
+ }
37943
+ const pkg = readJson(pkgFile) ?? {};
37944
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
37945
+ const root = projectRoot(cwd);
37946
+ const framework = detectFramework(cwd, deps);
37947
+ if (framework.kind === "unknown" && isWorkspaceRoot(cwd, pkg)) {
37948
+ const apps = workspaceApps(cwd);
37949
+ return `# Pilot: not set up yet
37950
+
37951
+ ${cwd} is a monorepo's root, not an app. Run \`npx usepilot@latest init\` again in the folder of the web app the user works on${apps.length ? `, one of:
37952
+
37953
+ ${apps.map((a) => `- ${a}`).join("\n")}` : "."}
37954
+ `;
37955
+ }
37956
+ const done = [];
37957
+ const todo = [];
37958
+ const pm = packageManager(cwd, root);
37959
+ const installArgs = pm === "npm" ? ["install", "-D", "usepilot"] : pm === "bun" ? ["add", "-d", "usepilot"] : ["add", "-D", "usepilot"];
37960
+ const install = `${pm} ${installArgs.join(" ")}`;
37961
+ if (deps.usepilot) done.push("`usepilot` was already a dependency.");
37962
+ else if (options.install !== false && run(pm, installArgs, cwd))
37963
+ done.push(`Installed \`usepilot\` as a dev dependency (\`${install}\`).`);
37964
+ else todo.push(`Install Pilot as a dev dependency: run \`${install}\` in ${cwd}.`);
37965
+ const registered = [];
37966
+ for (const client of CLIENTS) {
37967
+ const file2 = join3(root, client.file);
37968
+ const result = await addServer(file2, client.key, client.entry);
37969
+ if (result === "invalid")
37970
+ todo.push(
37971
+ `\`${relative2(root, file2)}\` isn't valid JSON, so Pilot wasn't added to it: fix it, and add the \`pilot\` server (\`${COMMAND}\`).`
37972
+ );
37973
+ else registered.push(`${client.name} (\`${relative2(root, file2)}\`)`);
37974
+ }
37975
+ if (registered.length) done.push(`Registered Pilot's MCP server for ${list(registered)}.`);
37976
+ const skill = await writeSkill(join3(root, ".claude", "skills", "pilot"));
37977
+ done.push(`Added the \`/pilot\` command for Claude Code (\`${relative2(root, skill)}\`).`);
37978
+ if (framework.loads) done.push(`The app already loads Pilot (\`${relative2(cwd, framework.loads)}\`).`);
37979
+ else todo.push(loadStep(framework, cwd));
37980
+ todo.push(
37981
+ `**If you aren't Claude Code, Cursor or VS Code**, register Pilot's MCP server with yourself too, named \`pilot\`, running \`${COMMAND}\`. Codex: \`codex mcp add pilot -- ${COMMAND}\`. Others: their MCP settings.`,
37982
+ `**Tell the user**, in a few lines: Pilot is set up. To start, open a new chat (agents load MCP servers when a chat starts; some ask once to approve the project's server), then ask to launch Pilot (in Claude Code: \`/pilot\`). The new files (${list(
37983
+ [...CLIENTS.map((c) => `\`${c.file}\``), "`.claude/skills/pilot/`"]
37984
+ )}) can be committed, so everyone on the project gets it. Without an agent, Option+P (Alt+P) in the app opens Pilot, and Copy prompt hands the changes over.`
37985
+ );
37986
+ return `# Pilot: set up
37987
+
37988
+ Done:
37989
+ ${done.map((d) => `- ${d}`).join("\n")}
37990
+
37991
+ Left for you (the agent), in order:
37992
+ ${todo.map((t, i) => `${i + 1}. ${t}`).join("\n")}
37993
+ `;
37994
+ }
37995
+ function projectRoot(cwd) {
37996
+ for (let dir = cwd; ; dir = dirname2(dir)) {
37997
+ if (existsSync3(join3(dir, ".git"))) return dir;
37998
+ if (dirname2(dir) === dir) return cwd;
37999
+ }
38000
+ }
38001
+ function packageManager(cwd, root) {
38002
+ for (let dir = cwd; ; dir = dirname2(dir)) {
38003
+ if (existsSync3(join3(dir, "pnpm-lock.yaml"))) return "pnpm";
38004
+ if (existsSync3(join3(dir, "yarn.lock"))) return "yarn";
38005
+ if (existsSync3(join3(dir, "bun.lock")) || existsSync3(join3(dir, "bun.lockb"))) return "bun";
38006
+ if (existsSync3(join3(dir, "package-lock.json"))) return "npm";
38007
+ if (dir === root || dirname2(dir) === dir) return "npm";
38008
+ }
38009
+ }
38010
+ function detectFramework(cwd, deps) {
38011
+ const has = (name) => name in deps;
38012
+ const first = (...files) => files.map((f) => join3(cwd, f)).find((f) => existsSync3(f));
38013
+ const loads = findLoader(cwd);
38014
+ const result = (kind, file2) => ({ kind, file: file2, loads });
38015
+ if (has("next")) {
38016
+ const app = first("src/app", "app");
38017
+ if (app)
38018
+ return result(
38019
+ "next-app",
38020
+ first("src/app/layout.tsx", "src/app/layout.jsx", "src/app/layout.js", "app/layout.tsx", "app/layout.jsx", "app/layout.js")
38021
+ );
38022
+ return result(
38023
+ "next-pages",
38024
+ first("src/pages/_app.tsx", "src/pages/_app.jsx", "src/pages/_app.js", "pages/_app.tsx", "pages/_app.jsx", "pages/_app.js")
38025
+ );
38026
+ }
38027
+ if (has("nuxt")) return result("nuxt", first("plugins/pilot.client.ts", "app/plugins/pilot.client.ts"));
38028
+ if (has("@sveltejs/kit")) return result("sveltekit", first("src/hooks.client.ts", "src/hooks.client.js"));
38029
+ if (has("astro")) return result("astro");
38030
+ if (has("@react-router/dev") || has("@remix-run/react")) return result("react-router", first("app/root.tsx", "app/root.jsx"));
38031
+ if (has("vite") || Object.keys(deps).some((d) => d.startsWith("@vitejs/"))) return result("vite", viteEntry(cwd));
38032
+ if (has("react-scripts") || has("webpack")) {
38033
+ return result(
38034
+ "webpack",
38035
+ first("src/index.tsx", "src/index.ts", "src/index.jsx", "src/index.js", "src/main.tsx", "src/main.ts", "src/main.js")
38036
+ );
38037
+ }
38038
+ return { kind: "unknown", loads };
38039
+ }
38040
+ function viteEntry(cwd) {
38041
+ const html = join3(cwd, "index.html");
38042
+ if (existsSync3(html)) {
38043
+ const src = /<script[^>]*type=["']module["'][^>]*src=["']\/?([^"']+)["']/i.exec(readFileSync(html, "utf8"))?.[1];
38044
+ if (src && existsSync3(join3(cwd, src))) return join3(cwd, src);
38045
+ }
38046
+ return ["src/main.tsx", "src/main.ts", "src/main.jsx", "src/main.js", "src/index.tsx", "src/index.ts"].map((f) => join3(cwd, f)).find((f) => existsSync3(f));
38047
+ }
38048
+ var SOURCE_DIRS = ["src", "app", "pages", "plugins", "components", "lib"];
38049
+ var SOURCE_FILE = /\.(m?[jt]sx?|vue|svelte|astro|html)$/;
38050
+ function findLoader(cwd) {
38051
+ let budget = 3e3;
38052
+ const walk = (dir, depth) => {
38053
+ let names;
38054
+ try {
38055
+ names = readdirSync(dir);
38056
+ } catch {
38057
+ return void 0;
38058
+ }
38059
+ for (const name of names) {
38060
+ if (budget-- <= 0 || name === "node_modules" || name.startsWith(".")) continue;
38061
+ const path = join3(dir, name);
38062
+ if (SOURCE_FILE.test(name)) {
38063
+ if (/["']usepilot(\/auto)?["']/.test(readText(path))) return path;
38064
+ } else if (depth > 0 && !name.includes(".")) {
38065
+ const found = walk(path, depth - 1);
38066
+ if (found) return found;
38067
+ }
38068
+ }
38069
+ return void 0;
38070
+ };
38071
+ const html = join3(cwd, "index.html");
38072
+ if (existsSync3(html) && /usepilot/.test(readText(html))) return html;
38073
+ for (const dir of SOURCE_DIRS) {
38074
+ const found = walk(join3(cwd, dir), 6);
38075
+ if (found) return found;
38076
+ }
38077
+ return void 0;
38078
+ }
38079
+ function readText(file2) {
38080
+ try {
38081
+ return readFileSync(file2, "utf8");
38082
+ } catch {
38083
+ return "";
38084
+ }
38085
+ }
38086
+ function isWorkspaceRoot(cwd, pkg) {
38087
+ return !!pkg.workspaces || existsSync3(join3(cwd, "pnpm-workspace.yaml"));
38088
+ }
38089
+ function workspaceApps(cwd) {
38090
+ const found = [];
38091
+ for (const group of ["apps", "packages", "examples", "sites"]) {
38092
+ const dir = join3(cwd, group);
38093
+ if (!existsSync3(dir)) continue;
38094
+ for (const name of readdirSync(dir)) {
38095
+ const pkg = readJson(join3(dir, name, "package.json"));
38096
+ if (pkg && detectFramework(join3(dir, name), { ...pkg.dependencies, ...pkg.devDependencies }).kind !== "unknown")
38097
+ found.push(join3(group, name));
38098
+ }
38099
+ }
38100
+ return found;
38101
+ }
38102
+ function loadStep(framework, cwd) {
38103
+ const at = (file2, fallback) => `\`${file2 ? relative2(cwd, file2) : fallback}\``;
38104
+ const code = (lang, text) => `
38105
+
38106
+ \`\`\`${lang}
38107
+ ${text.replace(/^(?=.)/gm, " ")}
38108
+ \`\`\``;
38109
+ const intro = "**Load Pilot in the app, in development only** (it must never reach production), the way this project writes code.";
38110
+ switch (framework.kind) {
38111
+ case "vite":
38112
+ return `${intro} It's a Vite app: in its entry, ${at(framework.file, "src/main.ts")}, add:${code("ts", 'if (import.meta.env.DEV) import("usepilot/auto");')}`;
38113
+ case "next-app":
38114
+ return `${intro} It's Next.js (App Router): add a client component, and render it in the root layout (${at(framework.file, "app/layout.tsx")}), inside \`<body>\`:${code(
38115
+ "tsx",
38116
+ `"use client";
38117
+ import { useEffect } from "react";
38118
+
38119
+ export function Pilot() {
38120
+ useEffect(() => {
38121
+ if (process.env.NODE_ENV === "development") import("usepilot/auto");
38122
+ }, []);
38123
+ return null;
38124
+ }`
38125
+ )}`;
38126
+ case "next-pages":
38127
+ return `${intro} It's Next.js (Pages Router): in ${at(framework.file, "pages/_app.tsx")}, in the App component:${code(
38128
+ "tsx",
38129
+ `useEffect(() => {
38130
+ if (process.env.NODE_ENV === "development") import("usepilot/auto");
38131
+ }, []);`
38132
+ )}`;
38133
+ case "nuxt":
38134
+ return `${intro} It's Nuxt: add a client plugin, \`plugins/pilot.client.ts\` (\`app/plugins/\` in Nuxt 4's layout):${code(
38135
+ "ts",
38136
+ `export default defineNuxtPlugin(() => {
38137
+ if (import.meta.dev) import("usepilot/auto");
38138
+ });`
38139
+ )}`;
38140
+ case "sveltekit":
38141
+ return `${intro} It's SvelteKit: in ${at(framework.file, "src/hooks.client.ts")} (create it if there's none), add:${code("ts", 'if (import.meta.env.DEV) import("usepilot/auto");')}`;
38142
+ case "astro":
38143
+ return `${intro} It's Astro: in the layout every page uses, add:${code("astro", '<script>\n if (import.meta.env.DEV) import("usepilot/auto");\n</script>')}`;
38144
+ case "react-router":
38145
+ return `${intro} It's React Router (or Remix): in ${at(framework.file, "app/root.tsx")}, in the root component:${code(
38146
+ "tsx",
38147
+ `useEffect(() => {
38148
+ if (import.meta.env.DEV) import("usepilot/auto");
38149
+ }, []);`
38150
+ )}`;
38151
+ case "webpack":
38152
+ return `${intro} In the app's entry, ${at(framework.file, "src/index.js")}, add:${code("js", 'if (process.env.NODE_ENV === "development") import("usepilot/auto");')}`;
38153
+ default:
38154
+ return `${intro} Import \`usepilot/auto\` from code that runs in the browser, only in development (\`import.meta.env.DEV\` with Vite, \`process.env.NODE_ENV === "development"\` with webpack). It shows the toolbar when the page loads.`;
38155
+ }
38156
+ }
38157
+ async function addServer(file2, key, entry) {
38158
+ let config2 = {};
38159
+ if (existsSync3(file2)) {
38160
+ const text = await readFile3(file2, "utf8");
38161
+ try {
38162
+ config2 = text.trim() ? JSON.parse(text) : {};
38163
+ } catch {
38164
+ return "invalid";
38165
+ }
38166
+ if (typeof config2 !== "object" || config2 === null || Array.isArray(config2)) return "invalid";
38167
+ }
38168
+ const servers = config2[key] ?? {};
38169
+ const result = "pilot" in servers ? "updated" : "added";
38170
+ config2[key] = { ...servers, pilot: entry };
38171
+ await mkdir3(dirname2(file2), { recursive: true });
38172
+ await writeFile3(file2, `${JSON.stringify(config2, null, 2)}
38173
+ `);
38174
+ return result;
38175
+ }
38176
+ function readJson(file2) {
38177
+ try {
38178
+ return JSON.parse(readFileSync(file2, "utf8"));
38179
+ } catch {
38180
+ return null;
38181
+ }
38182
+ }
38183
+ function list(items) {
38184
+ return items.length < 2 ? items[0] ?? "" : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
38185
+ }
38186
+ function runCommand(command2, args, cwd) {
38187
+ const result = spawnSync(command2, args, { cwd, stdio: ["ignore", "inherit", "inherit"], shell: process.platform === "win32" });
38188
+ return result.status === 0;
38189
+ }
37424
38190
 
37425
38191
  // src/index.ts
37426
38192
  var HELP = `usepilot: take the controls from your coding agent
37427
38193
 
37428
38194
  Usage: npx usepilot <command>
37429
38195
 
37430
- setup Install the /pilot skill for Claude Code (every project)
38196
+ init Set Pilot up in this project, for any agent: installs it, registers
38197
+ its MCP server, and prints what's left for the agent (loading it in
38198
+ the app). Ask your agent to run it. --no-install: print the command.
38199
+ setup Set up /pilot in Claude Code, for every project on this machine
38200
+ (--project: for this repo, to commit, so everyone gets it)
37431
38201
  mcp Run the MCP server (stdio) agents connect to, and the bridge the
37432
38202
  page talks to. Agents start it: register it with your agent.
37433
38203
  help Show this message
@@ -37454,12 +38224,22 @@ switch (command) {
37454
38224
  await runMcp();
37455
38225
  break;
37456
38226
  case "setup":
37457
- process.stdout.write(await setup());
38227
+ try {
38228
+ process.stdout.write(await setup({ project: process.argv.includes("--project") }));
38229
+ } catch (error62) {
38230
+ process.stderr.write(`usepilot setup: ${error62.message}
38231
+ `);
38232
+ process.exitCode = 1;
38233
+ }
37458
38234
  break;
37459
38235
  case "init":
37460
- process.stderr.write(`pilot ${command}: not implemented yet.
38236
+ try {
38237
+ process.stdout.write(await init({ install: !process.argv.includes("--no-install") }));
38238
+ } catch (error62) {
38239
+ process.stderr.write(`usepilot init: ${error62.message}
37461
38240
  `);
37462
- process.exitCode = 1;
38241
+ process.exitCode = 1;
38242
+ }
37463
38243
  break;
37464
38244
  default:
37465
38245
  process.stderr.write(`Unknown command: ${command}