usepilot 0.7.2 → 0.9.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
@@ -2985,7 +2985,7 @@ var require_compile = __commonJS({
2985
2985
  const schOrFunc = root.refs[ref];
2986
2986
  if (schOrFunc)
2987
2987
  return schOrFunc;
2988
- let _sch = resolve.call(this, root, ref);
2988
+ let _sch = resolve2.call(this, root, ref);
2989
2989
  if (_sch === void 0) {
2990
2990
  const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref];
2991
2991
  const { schemaId } = this.opts;
@@ -3012,7 +3012,7 @@ var require_compile = __commonJS({
3012
3012
  function sameSchemaEnv(s1, s2) {
3013
3013
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
3014
3014
  }
3015
- function resolve(root, ref) {
3015
+ function resolve2(root, ref) {
3016
3016
  let sch;
3017
3017
  while (typeof (sch = this.refs[ref]) == "string")
3018
3018
  ref = sch;
@@ -3876,7 +3876,7 @@ var require_fast_uri = __commonJS({
3876
3876
  }
3877
3877
  return uri;
3878
3878
  }
3879
- function resolve(baseURI, relativeURI, options) {
3879
+ function resolve2(baseURI, relativeURI, options) {
3880
3880
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
3881
3881
  const {
3882
3882
  parsed: baseParsed,
@@ -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, relative4, options, skipNormalization) {
3915
+ function resolveComponent(base, relative5, options, skipNormalization) {
3916
3916
  const target = {};
3917
3917
  if (!skipNormalization) {
3918
3918
  base = parse3(serialize(base, options), options);
3919
- relative4 = parse3(serialize(relative4, options), options);
3919
+ relative5 = parse3(serialize(relative5, options), options);
3920
3920
  }
3921
3921
  options = options || {};
3922
- if (!options.tolerant && relative4.scheme) {
3923
- target.scheme = relative4.scheme;
3924
- target.userinfo = relative4.userinfo;
3925
- target.host = relative4.host;
3926
- target.port = relative4.port;
3927
- target.path = removeDotSegments(relative4.path || "");
3928
- target.query = relative4.query;
3922
+ if (!options.tolerant && relative5.scheme) {
3923
+ target.scheme = relative5.scheme;
3924
+ target.userinfo = relative5.userinfo;
3925
+ target.host = relative5.host;
3926
+ target.port = relative5.port;
3927
+ target.path = removeDotSegments(relative5.path || "");
3928
+ target.query = relative5.query;
3929
3929
  } else {
3930
- if (relative4.userinfo !== void 0 || relative4.host !== void 0 || relative4.port !== void 0) {
3931
- target.userinfo = relative4.userinfo;
3932
- target.host = relative4.host;
3933
- target.port = relative4.port;
3934
- target.path = removeDotSegments(relative4.path || "");
3935
- target.query = relative4.query;
3930
+ if (relative5.userinfo !== void 0 || relative5.host !== void 0 || relative5.port !== void 0) {
3931
+ target.userinfo = relative5.userinfo;
3932
+ target.host = relative5.host;
3933
+ target.port = relative5.port;
3934
+ target.path = removeDotSegments(relative5.path || "");
3935
+ target.query = relative5.query;
3936
3936
  } else {
3937
- if (!relative4.path) {
3937
+ if (!relative5.path) {
3938
3938
  target.path = base.path;
3939
- if (relative4.query !== void 0) {
3940
- target.query = relative4.query;
3939
+ if (relative5.query !== void 0) {
3940
+ target.query = relative5.query;
3941
3941
  } else {
3942
3942
  target.query = base.query;
3943
3943
  }
3944
3944
  } else {
3945
- if (relative4.path[0] === "/") {
3946
- target.path = removeDotSegments(relative4.path);
3945
+ if (relative5.path[0] === "/") {
3946
+ target.path = removeDotSegments(relative5.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 = "/" + relative4.path;
3950
+ target.path = "/" + relative5.path;
3951
3951
  } else if (!base.path) {
3952
- target.path = relative4.path;
3952
+ target.path = relative5.path;
3953
3953
  } else {
3954
- target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative4.path;
3954
+ target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative5.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 = relative4.query;
3958
+ target.query = relative5.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 = relative4.fragment;
3966
+ target.fragment = relative5.fragment;
3967
3967
  return target;
3968
3968
  }
3969
3969
  function equal(uriA, uriB, options) {
@@ -4267,7 +4267,7 @@ var require_fast_uri = __commonJS({
4267
4267
  var fastUri = {
4268
4268
  SCHEMES,
4269
4269
  normalize,
4270
- resolve,
4270
+ resolve: resolve2,
4271
4271
  resolveComponent,
4272
4272
  equal,
4273
4273
  serialize,
@@ -12326,7 +12326,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
12326
12326
  var NONE = 0;
12327
12327
  var ASSUMED = 1;
12328
12328
  var PROVEN = 2;
12329
- function isRecursive(inst, stack, resolve) {
12329
+ function isRecursive(inst, stack, resolve2) {
12330
12330
  const cached2 = recursive.get(inst);
12331
12331
  if (cached2 !== void 0)
12332
12332
  return cached2 ? PROVEN : NONE;
@@ -12336,7 +12336,7 @@ function isRecursive(inst, stack, resolve) {
12336
12336
  let result = NONE;
12337
12337
  const check2 = (child) => {
12338
12338
  if (result !== PROVEN && child?._zod) {
12339
- const answer = isRecursive(child, stack, resolve);
12339
+ const answer = isRecursive(child, stack, resolve2);
12340
12340
  if (answer > result)
12341
12341
  result = answer;
12342
12342
  }
@@ -12347,7 +12347,7 @@ function isRecursive(inst, stack, resolve) {
12347
12347
  const desc = Object.getOwnPropertyDescriptor(sh, key);
12348
12348
  if (spread && !desc.enumerable)
12349
12349
  continue;
12350
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;
12350
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve2) : NONE;
12351
12351
  if (child > answer)
12352
12352
  answer = child;
12353
12353
  }
@@ -12411,7 +12411,7 @@ function isRecursive(inst, stack, resolve) {
12411
12411
  break;
12412
12412
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
12413
12413
  case "lazy": {
12414
- const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : void 0);
12414
+ const inner = def._cachedInner ?? (resolve2 ? inst._zod.innerType : void 0);
12415
12415
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
12416
12416
  break;
12417
12417
  }
@@ -26761,21 +26761,21 @@ function visit(schema, fnOrHandlers) {
26761
26761
  const h = fnOrHandlers[node2._zod.def.type];
26762
26762
  return h ? h(node2, rewritten) : node2;
26763
26763
  };
26764
- const cache2 = /* @__PURE__ */ new Map();
26764
+ const cache3 = /* @__PURE__ */ new Map();
26765
26765
  function run(s) {
26766
- const cached2 = cache2.get(s);
26766
+ const cached2 = cache3.get(s);
26767
26767
  if (cached2 === RESOLVING) {
26768
26768
  return new $ZodLazy({
26769
26769
  type: "lazy",
26770
- getter: () => cache2.get(s)
26770
+ getter: () => cache3.get(s)
26771
26771
  });
26772
26772
  }
26773
26773
  if (cached2 !== void 0)
26774
26774
  return cached2;
26775
- cache2.set(s, RESOLVING);
26775
+ cache3.set(s, RESOLVING);
26776
26776
  const inner = mapInner(s);
26777
26777
  const mapped = fn(inner, inner !== s);
26778
- cache2.set(s, mapped);
26778
+ cache3.set(s, mapped);
26779
26779
  return mapped;
26780
26780
  }
26781
26781
  function mapInner(s) {
@@ -28600,12 +28600,12 @@ var StdioServerTransport = class {
28600
28600
  this.onclose?.();
28601
28601
  }
28602
28602
  send(message) {
28603
- return new Promise((resolve) => {
28603
+ return new Promise((resolve2) => {
28604
28604
  const json3 = serializeMessage(message);
28605
28605
  if (this._stdout.write(json3)) {
28606
- resolve();
28606
+ resolve2();
28607
28607
  } else {
28608
- this._stdout.once("drain", resolve);
28608
+ this._stdout.once("drain", resolve2);
28609
28609
  }
28610
28610
  });
28611
28611
  }
@@ -28613,7 +28613,9 @@ var StdioServerTransport = class {
28613
28613
 
28614
28614
  // src/mcp.ts
28615
28615
  import { randomUUID as randomUUID2 } from "crypto";
28616
- import { basename as basename2 } from "path";
28616
+ import { existsSync as existsSync6 } from "fs";
28617
+ import { basename as basename4, isAbsolute as isAbsolute2, resolve } from "path";
28618
+ import { fileURLToPath } from "url";
28617
28619
 
28618
28620
  // ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v3/helpers/util.js
28619
28621
  var util;
@@ -34589,7 +34591,7 @@ var Protocol = class {
34589
34591
  return;
34590
34592
  }
34591
34593
  const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
34592
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
34594
+ await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
34593
34595
  options?.signal?.throwIfAborted();
34594
34596
  }
34595
34597
  } catch (error62) {
@@ -34606,7 +34608,7 @@ var Protocol = class {
34606
34608
  */
34607
34609
  request(request, resultSchema, options) {
34608
34610
  const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
34609
- return new Promise((resolve, reject) => {
34611
+ return new Promise((resolve2, reject) => {
34610
34612
  const earlyReject = (error62) => {
34611
34613
  reject(error62);
34612
34614
  };
@@ -34684,7 +34686,7 @@ var Protocol = class {
34684
34686
  if (!parseResult.success) {
34685
34687
  reject(parseResult.error);
34686
34688
  } else {
34687
- resolve(parseResult.data);
34689
+ resolve2(parseResult.data);
34688
34690
  }
34689
34691
  } catch (error62) {
34690
34692
  reject(error62);
@@ -34946,12 +34948,12 @@ var Protocol = class {
34946
34948
  }
34947
34949
  } catch {
34948
34950
  }
34949
- return new Promise((resolve, reject) => {
34951
+ return new Promise((resolve2, reject) => {
34950
34952
  if (signal.aborted) {
34951
34953
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
34952
34954
  return;
34953
34955
  }
34954
- const timeoutId = setTimeout(resolve, interval);
34956
+ const timeoutId = setTimeout(resolve2, interval);
34955
34957
  signal.addEventListener("abort", () => {
34956
34958
  clearTimeout(timeoutId);
34957
34959
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
@@ -36091,7 +36093,7 @@ var McpServer = class {
36091
36093
  let task = createTaskResult.task;
36092
36094
  const pollInterval = task.pollInterval ?? 5e3;
36093
36095
  while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {
36094
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
36096
+ await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
36095
36097
  const updatedTask = await extra.taskStore.getTask(taskId);
36096
36098
  if (!updatedTask) {
36097
36099
  throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);
@@ -36660,6 +36662,9 @@ var EMPTY_COMPLETION_RESULT = {
36660
36662
  };
36661
36663
 
36662
36664
  // ../protocol/src/types.ts
36665
+ function mentionText(reference) {
36666
+ return reference.kind === "token" ? reference.name : `@${reference.name}`;
36667
+ }
36663
36668
  var ATTACHMENT_TYPES = {
36664
36669
  png: "image/png",
36665
36670
  jpg: "image/jpeg",
@@ -36700,7 +36705,8 @@ function requestTargets(request) {
36700
36705
  function formatPrompt(changeSet, options = {}) {
36701
36706
  if (changeSet.request?.kind === "responsive") return formatResponsive(changeSet, changeSet.request);
36702
36707
  if (changeSet.request?.kind === "break-and-fix") return formatBreakFix(changeSet, changeSet.request);
36703
- if (changeSet.request?.kind === "comment") return formatComment(changeSet, changeSet.request);
36708
+ if (changeSet.request?.kind === "comment") return formatComment(changeSet, changeSet.request, options);
36709
+ if (changeSet.request?.kind === "props") return formatProps(changeSet, changeSet.request);
36704
36710
  const { page, edits, note } = changeSet;
36705
36711
  const lines = [
36706
36712
  "# Pilot design edits",
@@ -36760,8 +36766,43 @@ var EDIT_GUIDELINES_REMINDER = "Follow Pilot's edit guidelines (in `pilot_wait_f
36760
36766
  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}`;
36761
36767
  var ACTION_ASKED = {
36762
36768
  responsive: "asked you to make it responsive",
36763
- "break-and-fix": "asked you to break and fix it"
36769
+ "break-and-fix": "asked you to break and fix it",
36770
+ props: "asked for the component's props"
36764
36771
  };
36772
+ function propValue(value) {
36773
+ return value === void 0 ? "*not set*" : `\`${typeof value === "string" ? JSON.stringify(value) : String(value)}\``;
36774
+ }
36775
+ function formatProps(changeSet, request) {
36776
+ const { page, note } = changeSet;
36777
+ const current = Object.entries(request.current);
36778
+ const lines = [
36779
+ "# Pilot: props",
36780
+ "",
36781
+ `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.**`,
36782
+ "",
36783
+ `Page: ${page.url} (${page.title || "untitled"}), seen at ${page.viewport.width}x${page.viewport.height}`,
36784
+ "",
36785
+ ...elementsSection(request),
36786
+ ...request.usedIn ? [`- This instance is written in: \`${request.usedIn}\``] : [],
36787
+ "",
36788
+ "## Its props now (read from the page)",
36789
+ "",
36790
+ ...current.length ? current.map(([name, value]) => `- \`${name}\`: ${propValue(value)}`) : ["None that Pilot could read (it reads strings, numbers and on-off values)."],
36791
+ ...note?.trim() ? ["", `Designer note: ${note.trim()}`] : [],
36792
+ ...request.attachments?.length ? ["", ...attachmentLines(request.attachments, `The designer attached ${countFiles(request.attachments.length)}:`)] : [],
36793
+ ...request.references?.length ? ["", ...referenceLines(request.references)] : [],
36794
+ "",
36795
+ "## What to list",
36796
+ "",
36797
+ "- **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.",
36798
+ '- **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.',
36799
+ "- The most useful first (the main variant, then the size, then the rest); 12 at most.",
36800
+ "",
36801
+ "Call `pilot_done` with this job's id, the list in `props`, and notes: one short sentence for the designer, like a chat message (\"Button has 3 props you can change\"). Pilot shows the props in the designer's thread, each with its value on this instance; what they pick comes back to you as a comment, a `name: value` line per prop (`tone: dark`), to set where this instance is written. If none is worth listing, say so in the notes and leave `props` out."
36802
+ ];
36803
+ return `${lines.join("\n")}
36804
+ `;
36805
+ }
36765
36806
  function formatBreakFix(changeSet, request) {
36766
36807
  const { page, note } = changeSet;
36767
36808
  const { breakpoints } = request;
@@ -36780,6 +36821,7 @@ function formatBreakFix(changeSet, request) {
36780
36821
  if (note?.trim()) lines.push("", `Designer note: ${note.trim()}`);
36781
36822
  if (request.attachments?.length)
36782
36823
  lines.push("", ...attachmentLines(request.attachments, `The designer attached ${countFiles(request.attachments.length)}:`));
36824
+ if (request.references?.length) lines.push("", ...referenceLines(request.references));
36783
36825
  lines.push(
36784
36826
  "",
36785
36827
  ...elementsSection(request),
@@ -36824,6 +36866,7 @@ function formatResponsive(changeSet, request) {
36824
36866
  if (note?.trim()) lines.push("", `Designer note: ${note.trim()}`);
36825
36867
  if (request.attachments?.length)
36826
36868
  lines.push("", ...attachmentLines(request.attachments, `The designer attached ${countFiles(request.attachments.length)}:`));
36869
+ if (request.references?.length) lines.push("", ...referenceLines(request.references));
36827
36870
  lines.push(
36828
36871
  "",
36829
36872
  ...elementsSection(request),
@@ -36846,8 +36889,8 @@ function formatResponsive(changeSet, request) {
36846
36889
  return `${lines.join("\n")}
36847
36890
  `;
36848
36891
  }
36849
- function formatComment(changeSet, request) {
36850
- const { page } = changeSet;
36892
+ function formatComment(changeSet, request, options = {}) {
36893
+ const { page, edits } = changeSet;
36851
36894
  const { thread, breakpoints } = request;
36852
36895
  const several = requestTargets(request).length;
36853
36896
  const latest = thread.at(-1);
@@ -36865,8 +36908,33 @@ function formatComment(changeSet, request) {
36865
36908
  "",
36866
36909
  "## The comment",
36867
36910
  "",
36868
- ...commentLines(latest)
36911
+ // Props set from the thread, with no words: the props are the comment.
36912
+ ...latest?.props && !latest.text.trim() && !latest.attachments?.length ? ["The designer set props on this instance (below), with no words."] : commentLines(latest)
36869
36913
  ];
36914
+ if (latest?.props?.set.length) {
36915
+ const { component, usedIn, set: set2 } = latest.props;
36916
+ lines.push(
36917
+ "",
36918
+ "## Props to set",
36919
+ "",
36920
+ `The designer picked new values for this \`${component}\` instance's props from the list you gave (the \`name: value\` lines in their comment):`,
36921
+ "",
36922
+ ...set2.map((c) => `- \`${c.name}\`: ${propValue(c.from)} \u2192 ${propValue(c.to)}`),
36923
+ "",
36924
+ `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 with \`pilot_done\`'s question and choices before changing it for all of them. Pilot reads the instance's props on the page when you're done.`
36925
+ );
36926
+ }
36927
+ if (edits.length) {
36928
+ lines.push(
36929
+ "",
36930
+ "## The designer's edits, sent with the comment",
36931
+ "",
36932
+ `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.`,
36933
+ "",
36934
+ ...options.guidelines === false ? [EDIT_GUIDELINES_REMINDER] : ["Guidelines:", ...EDIT_GUIDELINES]
36935
+ );
36936
+ edits.forEach((edit, index) => lines.push("", ...formatEdit(edit, index + 1).map((l) => l.startsWith("## ") ? `#${l}` : l)));
36937
+ }
36870
36938
  if (earlier.length) {
36871
36939
  lines.push("", "## The thread so far (you already did what it asked)", "");
36872
36940
  for (const m of earlier) {
@@ -36895,6 +36963,8 @@ function commentLines(message) {
36895
36963
  const text = message?.text.trim() ?? "";
36896
36964
  const files = message?.attachments ?? [];
36897
36965
  const out = text ? [quote(text)] : [];
36966
+ const references = message?.references ?? [];
36967
+ if (references.length) out.push("", ...referenceLines(references));
36898
36968
  if (!files.length) return out.length ? out : ["> (empty)"];
36899
36969
  const one = files.length === 1;
36900
36970
  if (out.length) out.push("");
@@ -36905,6 +36975,30 @@ function commentLines(message) {
36905
36975
  );
36906
36976
  return out;
36907
36977
  }
36978
+ function referenceLines(references) {
36979
+ const picked = references.some((r) => r.kind !== "unlisted");
36980
+ return [
36981
+ 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:",
36982
+ "",
36983
+ ...references.map(referenceLine)
36984
+ ];
36985
+ }
36986
+ function referenceLine(reference) {
36987
+ const as = `- \`${mentionText(reference)}\`:`;
36988
+ if (reference.kind === "token")
36989
+ 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).`;
36990
+ if (reference.kind === "unlisted")
36991
+ 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.`;
36992
+ if (reference.kind === "component") {
36993
+ const t = reference.target;
36994
+ const source = reference.source ?? (t?.source?.file ? { file: t.source.file, line: t.source.line } : void 0);
36995
+ 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)`;
36996
+ 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.`;
36997
+ }
36998
+ const el = reference.target;
36999
+ const component = el.source?.component ? `, inside the \`${el.source.component}\` component` : "";
37000
+ return `${as} an element on the page: \`${el.path}\`, selector \`${el.selector}\`${el.text ? `, text "${el.text}"` : ""}${component}.`;
37001
+ }
36908
37002
  function attachmentLines(files, intro) {
36909
37003
  const lines = files.map((file2) => {
36910
37004
  const kind = attachmentKind(file2.id);
@@ -36933,7 +37027,7 @@ function targetLines(target) {
36933
37027
  if (target.source?.component || target.source?.file) {
36934
37028
  const { component, file: file2, line } = target.source;
36935
37029
  const where = [component && `\`${component}\``, file2 && `\`${file2}${line ? `:${line}` : ""}\``].filter(Boolean).join(", in ");
36936
- out.push(`- Component: ${where} (from the framework's dev info)`);
37030
+ out.push(`- Component: ${where}`);
36937
37031
  }
36938
37032
  if (target.lookAlikes) {
36939
37033
  const of = target.lookAlikesOf ? `other instances of \`${target.lookAlikesOf}\`, the same part of each` : "the same part of other copies";
@@ -37016,7 +37110,7 @@ function formatWidthCheck(check2) {
37016
37110
  }
37017
37111
 
37018
37112
  // ../protocol/src/bridge.ts
37019
- var BRIDGE_VERSION = 4;
37113
+ var BRIDGE_VERSION = 5;
37020
37114
  var DEFAULT_BRIDGE_PORT = 4747 + BRIDGE_VERSION;
37021
37115
  var MAX_CHOICES = 4;
37022
37116
  function questionOf(value) {
@@ -37025,6 +37119,28 @@ function questionOf(value) {
37025
37119
  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);
37026
37120
  return { text: q.text.trim().slice(0, 500), ...choices.length ? { choices } : {} };
37027
37121
  }
37122
+ var MAX_PROPS = 20;
37123
+ function propsOf(value) {
37124
+ if (!Array.isArray(value)) return void 0;
37125
+ const scalar = (v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean";
37126
+ const props = value.flatMap((p) => {
37127
+ const name = typeof p?.name === "string" ? p.name.trim().slice(0, 60) : "";
37128
+ const type = ["options", "boolean", "text", "number"].includes(p?.type) ? p.type : null;
37129
+ if (!name || !type) return [];
37130
+ const options = Array.isArray(p.options) ? [...new Set(p.options.filter(scalar).map(String))].slice(0, 30) : [];
37131
+ if (type === "options" && !options.length) return [];
37132
+ return [
37133
+ {
37134
+ name,
37135
+ type,
37136
+ ...type === "options" ? { options } : {},
37137
+ ...scalar(p.default) ? { default: p.default } : {},
37138
+ ...typeof p.description === "string" && p.description.trim() ? { description: p.description.trim().slice(0, 120) } : {}
37139
+ }
37140
+ ];
37141
+ });
37142
+ return props.length ? props.slice(0, MAX_PROPS) : void 0;
37143
+ }
37028
37144
  function originOf(url2) {
37029
37145
  try {
37030
37146
  const u = new URL(url2.includes("://") ? url2 : `http://${url2}`);
@@ -37156,6 +37272,140 @@ async function sweepAttachments(dir = attachmentsDir(), now = Date.now()) {
37156
37272
  }
37157
37273
  }
37158
37274
 
37275
+ // src/components.ts
37276
+ import { existsSync as existsSync2, readdirSync, readFileSync, statSync } from "fs";
37277
+ import { basename as basename2, dirname as dirname2, extname, join as join2, relative } from "path";
37278
+ var SKIP = /* @__PURE__ */ new Set([
37279
+ "node_modules",
37280
+ "dist",
37281
+ "build",
37282
+ "out",
37283
+ "coverage",
37284
+ "vendor",
37285
+ ".git",
37286
+ ".next",
37287
+ ".nuxt",
37288
+ ".svelte-kit",
37289
+ ".output",
37290
+ ".vercel",
37291
+ ".turbo",
37292
+ ".cache",
37293
+ "storybook-static",
37294
+ "__tests__",
37295
+ "__mocks__"
37296
+ ]);
37297
+ var EXTENSIONS = /* @__PURE__ */ new Set([".jsx", ".tsx", ".js", ".vue", ".svelte"]);
37298
+ var NOT_COMPONENTS = /\.(test|spec|stories|story|d)\.[jt]sx?$/;
37299
+ var ROUTE_FILES = /^(page|layout|template|loading|error|not-found|default|route|_app|_document)\.[jt]sx?$/;
37300
+ var MAX_FILES = 8e3;
37301
+ var MAX_FILE_BYTES = 512e3;
37302
+ var BUDGET_MS = 1500;
37303
+ var cache = /* @__PURE__ */ new Map();
37304
+ function projectComponents(folders) {
37305
+ const roots = [...new Set(folders.map(workspaceRoot))];
37306
+ const out = [];
37307
+ const seen = /* @__PURE__ */ new Set();
37308
+ const deadline = Date.now() + BUDGET_MS;
37309
+ for (const root of roots) {
37310
+ for (const c of scan(root, deadline)) {
37311
+ const key = `${c.name} ${c.file}`;
37312
+ if (!seen.has(key)) {
37313
+ seen.add(key);
37314
+ out.push(c);
37315
+ }
37316
+ }
37317
+ }
37318
+ return out;
37319
+ }
37320
+ function workspaceRoot(folder) {
37321
+ let dir = folder;
37322
+ for (; ; ) {
37323
+ if (isWorkspace(dir)) return dir;
37324
+ const parent = dirname2(dir);
37325
+ if (existsSync2(join2(dir, ".git")) || parent === dir) return folder;
37326
+ dir = parent;
37327
+ }
37328
+ }
37329
+ function isWorkspace(dir) {
37330
+ if (["pnpm-workspace.yaml", "lerna.json", "nx.json", "turbo.json"].some((f) => existsSync2(join2(dir, f)))) return true;
37331
+ try {
37332
+ return "workspaces" in JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
37333
+ } catch {
37334
+ return false;
37335
+ }
37336
+ }
37337
+ function scan(root, deadline) {
37338
+ const known = cache.get(root) ?? /* @__PURE__ */ new Map();
37339
+ const now = /* @__PURE__ */ new Map();
37340
+ const out = [];
37341
+ const walk = (dir) => {
37342
+ let entries;
37343
+ try {
37344
+ entries = readdirSync(dir, { withFileTypes: true });
37345
+ } catch {
37346
+ return;
37347
+ }
37348
+ for (const entry of entries) {
37349
+ if (now.size >= MAX_FILES || Date.now() > deadline) return;
37350
+ const name = entry.name;
37351
+ if (SKIP.has(name) || name.startsWith(".")) continue;
37352
+ const path = join2(dir, name);
37353
+ if (entry.isDirectory()) {
37354
+ walk(path);
37355
+ continue;
37356
+ }
37357
+ if (!entry.isFile() || !EXTENSIONS.has(extname(name)) || NOT_COMPONENTS.test(name) || ROUTE_FILES.test(name)) continue;
37358
+ let stat2;
37359
+ try {
37360
+ stat2 = statSync(path);
37361
+ } catch {
37362
+ continue;
37363
+ }
37364
+ if (stat2.size > MAX_FILE_BYTES) continue;
37365
+ const before = known.get(path);
37366
+ const cached2 = before && before.mtime === stat2.mtimeMs ? before : { mtime: stat2.mtimeMs, components: read(path) };
37367
+ now.set(path, cached2);
37368
+ const file2 = relative(root, path);
37369
+ for (const c of cached2.components) out.push({ name: c.name, file: file2, line: c.line });
37370
+ }
37371
+ };
37372
+ walk(root);
37373
+ cache.set(root, now);
37374
+ return out;
37375
+ }
37376
+ function fileComponentName(path) {
37377
+ return basename2(path, extname(path)).split(/[-_.\s]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join("");
37378
+ }
37379
+ var NAME = "[A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*";
37380
+ var FUNCTION = new RegExp(`^\\s*(export\\s+)?(?:default\\s+)?(?:async\\s+)?function\\s+(${NAME})\\b`);
37381
+ var CONSTANT = new RegExp(`^\\s*(export\\s+)?(?:const|let|var)\\s+(${NAME})\\s*(?::[^=]+)?=\\s*(.*)$`);
37382
+ var COMPONENT_VALUE = /^(?:\(|async\s*\(|function\b|[A-Za-z_$][\w$]*\s*=>|(?:React\.)?(?:forwardRef|memo|lazy)\b|styled[.(]|defineComponent\b|component\$)/;
37383
+ function read(path) {
37384
+ const ext = extname(path);
37385
+ if (ext === ".vue" || ext === ".svelte") return [{ name: fileComponentName(path), line: 1 }];
37386
+ let source;
37387
+ try {
37388
+ source = readFileSync(path, "utf8");
37389
+ } catch {
37390
+ return [];
37391
+ }
37392
+ if (!/<[A-Za-z]|styled[.(]/.test(source)) return [];
37393
+ const found = [];
37394
+ const lines = source.split("\n");
37395
+ for (let i = 0; i < lines.length; i++) {
37396
+ const line = lines[i];
37397
+ const fn = FUNCTION.exec(line);
37398
+ const constant = fn ? null : CONSTANT.exec(line);
37399
+ const m = fn ?? constant;
37400
+ if (!m) continue;
37401
+ const name = m[2];
37402
+ if (constant && !COMPONENT_VALUE.test((constant[3] ?? "").trim())) continue;
37403
+ const exported = !!m[1] || new RegExp(`export\\s+default\\s+${name}\\b|export\\s*\\{[^}]*\\b${name}\\b[^}]*\\}`).test(source);
37404
+ if (exported && !found.some((f) => f.name === name)) found.push({ name, line: i + 1 });
37405
+ }
37406
+ return found;
37407
+ }
37408
+
37159
37409
  // src/hub.ts
37160
37410
  import { randomUUID } from "crypto";
37161
37411
  var AGENT_TTL = 3e4;
@@ -37174,19 +37424,37 @@ var Hub = class {
37174
37424
  register(info, origin) {
37175
37425
  const key = originKey(origin);
37176
37426
  const known = this.agents.get(info.id);
37177
- this.agents.set(info.id, { info, origin: key, seen: this.now() });
37427
+ const { folder, ...shown } = info;
37428
+ this.agents.set(info.id, { info: shown, origin: key, seen: this.now(), folder: folder ?? known?.folder });
37178
37429
  if (!known || known.origin !== key) {
37179
37430
  if (known) this.notifyAgents(known.origin);
37180
37431
  this.notifyAgents(key);
37181
37432
  }
37182
37433
  }
37183
- /** The agent is gone (its process ended or it stopped pinging): its waits end. */
37434
+ /**
37435
+ * The agent is gone (its process ended or it stopped pinging): its waits
37436
+ * end, and the jobs it was working on go back to the queue, for another
37437
+ * chat (or this one, back), instead of staying "working" for nobody.
37438
+ */
37184
37439
  unregister(agentId) {
37185
37440
  const agent = this.agents.get(agentId);
37186
37441
  if (!agent) return;
37187
37442
  this.agents.delete(agentId);
37188
37443
  for (const w of this.waiters.filter((w2) => w2.agentId === agentId)) this.endWait(w, null);
37444
+ for (const job of this.jobs.values()) {
37445
+ if (job.status === "working" && job.agent?.id === agentId) this.update(job, { status: "queued", takenAt: void 0 });
37446
+ }
37189
37447
  this.notifyAgents(agent.origin);
37448
+ this.dispatch(agent.origin);
37449
+ }
37450
+ /** An agent's info as pages see it (no folder). */
37451
+ shown(info) {
37452
+ return this.agents.get(info.id)?.info ?? { id: info.id, label: info.label };
37453
+ }
37454
+ /** The project folders of the agents working on pages of `origin`: where its components are read from. */
37455
+ folders(origin) {
37456
+ const key = originKey(origin);
37457
+ return [...new Set([...this.agents.values()].filter((a) => a.origin === key && a.folder).map((a) => a.folder))];
37190
37458
  }
37191
37459
  /** Drops agents not heard from in AGENT_TTL (`keep`: the ones in this process, always alive). */
37192
37460
  sweep(keep = /* @__PURE__ */ new Set()) {
@@ -37198,7 +37466,7 @@ var Hub = class {
37198
37466
  /** An agent ran /pilot: registers it and tells the open pages of `origin` to launch Pilot. Returns how many pages got it. */
37199
37467
  launch(info, origin) {
37200
37468
  this.register(info, origin);
37201
- return this.sendTo(originKey(origin), { type: "launch", agent: info });
37469
+ return this.sendTo(originKey(origin), { type: "launch", agent: this.shown(info) });
37202
37470
  }
37203
37471
  /**
37204
37472
  * The agent's next job for its origin: the oldest queued one right away, or
@@ -37209,15 +37477,15 @@ var Hub = class {
37209
37477
  this.register(info, origin);
37210
37478
  const key = originKey(origin);
37211
37479
  const queued = this.oldestQueued(key);
37212
- if (queued) return Promise.resolve({ job: this.take(queued, info) });
37213
- return new Promise((resolve) => {
37480
+ if (queued) return Promise.resolve({ job: this.take(queued, this.shown(info)) });
37481
+ return new Promise((resolve2) => {
37214
37482
  const waiter = {
37215
37483
  agentId: info.id,
37216
37484
  origin: key,
37217
37485
  resolve: (job) => {
37218
37486
  clearTimeout(timer);
37219
37487
  signal?.removeEventListener("abort", onAbort);
37220
- resolve({ job });
37488
+ resolve2({ job });
37221
37489
  }
37222
37490
  };
37223
37491
  const timer = setTimeout(() => this.endWait(waiter, null), timeoutMs);
@@ -37233,12 +37501,20 @@ var Hub = class {
37233
37501
  * the answer, see answer). A job asks once: a question on an answered job
37234
37502
  * is dropped. Null for a job the hub doesn't know.
37235
37503
  */
37236
- done(agentId, jobId, notes, question) {
37504
+ done(agentId, jobId, notes, question, props) {
37237
37505
  const job = this.jobs.get(jobId);
37238
37506
  if (!job || job.status === "cancelled") return null;
37239
37507
  const agent = this.agents.get(agentId)?.info ?? job.agent;
37240
37508
  const asks = question && !job.answer ? { question } : {};
37241
- this.update(job, { status: "done", agent, notes: notes?.trim() || void 0, doneAt: new Date(this.now()).toISOString(), ...asks });
37509
+ const listed = props?.length && job.changeSet.request?.kind === "props" ? { props } : {};
37510
+ this.update(job, {
37511
+ status: "done",
37512
+ agent,
37513
+ notes: notes?.trim() || void 0,
37514
+ doneAt: new Date(this.now()).toISOString(),
37515
+ ...asks,
37516
+ ...listed
37517
+ });
37242
37518
  return job;
37243
37519
  }
37244
37520
  /**
@@ -37263,12 +37539,12 @@ var Hub = class {
37263
37539
  const job = this.jobs.get(jobId);
37264
37540
  if (!job) return Promise.resolve(null);
37265
37541
  const requestId = randomUUID();
37266
- return new Promise((resolve) => {
37542
+ return new Promise((resolve2) => {
37267
37543
  const timer = setTimeout(() => finish(null), timeoutMs);
37268
37544
  const finish = (check2) => {
37269
37545
  clearTimeout(timer);
37270
37546
  this.checks.delete(requestId);
37271
- resolve(check2);
37547
+ resolve2(check2);
37272
37548
  };
37273
37549
  this.checks.set(requestId, { origin: job.origin, resolve: finish });
37274
37550
  if (!this.sendTo(job.origin, { type: "check", requestId, jobId })) finish(null);
@@ -37413,14 +37689,14 @@ function startHub(port, hub = new Hub(), options = {}) {
37413
37689
  });
37414
37690
  const sweep = setInterval(() => hub.sweep(localAgents), 5e3);
37415
37691
  sweep.unref();
37416
- return new Promise((resolve, reject) => {
37692
+ return new Promise((resolve2, reject) => {
37417
37693
  server.once("error", (error62) => {
37418
37694
  clearInterval(sweep);
37419
37695
  reject(error62);
37420
37696
  });
37421
37697
  server.listen(port, "127.0.0.1", () => {
37422
37698
  const address = server.address();
37423
- resolve({
37699
+ resolve2({
37424
37700
  hub,
37425
37701
  server,
37426
37702
  port: typeof address === "object" && address ? address.port : port,
@@ -37457,6 +37733,7 @@ async function handle(hub, req, res, attachments) {
37457
37733
  if (path === "/events" && req.method === "GET") return events(hub, origin, req, res);
37458
37734
  if (req.method !== "POST") return json2(res, 405, { error: "POST only" });
37459
37735
  if (!hub.hasAgents(origin)) return json2(res, 403, { error: "no agent works on this page: run /pilot in your agent" });
37736
+ if (path === "/components") return json2(res, 200, { components: projectComponents(hub.folders(origin)) });
37460
37737
  if (path === "/attachments") {
37461
37738
  const type = req.headers["content-type"] ?? "";
37462
37739
  if (!extensionOf(type)) return json2(res, 415, { error: "images (png, jpeg, gif, webp), text files (txt, md, csv, json) and PDFs only" });
@@ -37530,7 +37807,7 @@ async function handleAgent(hub, action, data, req, res) {
37530
37807
  }
37531
37808
  case "done":
37532
37809
  if (!d.jobId) return json2(res, 400, { error: "jobId needed" });
37533
- return json2(res, 200, { job: hub.done(d.agent.id, d.jobId, d.notes, questionOf(d.question)) });
37810
+ return json2(res, 200, { job: hub.done(d.agent.id, d.jobId, d.notes, questionOf(d.question), propsOf(d.props)) });
37534
37811
  case "check": {
37535
37812
  if (!d.jobId) return json2(res, 400, { error: "jobId needed" });
37536
37813
  const check2 = await hub.check(d.jobId, Math.min(d.timeoutMs ?? CHECK_TIMEOUT, 2 * 6e4));
@@ -37553,7 +37830,7 @@ function json2(res, status, data) {
37553
37830
  res.end(JSON.stringify(data));
37554
37831
  }
37555
37832
  function rawBody(req, max) {
37556
- return new Promise((resolve, reject) => {
37833
+ return new Promise((resolve2, reject) => {
37557
37834
  const chunks = [];
37558
37835
  let size = 0;
37559
37836
  let over = false;
@@ -37562,20 +37839,20 @@ function rawBody(req, max) {
37562
37839
  size += chunk.length;
37563
37840
  if (size > max) {
37564
37841
  over = true;
37565
- resolve(null);
37842
+ resolve2(null);
37566
37843
  req.resume();
37567
37844
  return;
37568
37845
  }
37569
37846
  chunks.push(chunk);
37570
37847
  });
37571
37848
  req.on("end", () => {
37572
- if (!over) resolve(Buffer.concat(chunks));
37849
+ if (!over) resolve2(Buffer.concat(chunks));
37573
37850
  });
37574
37851
  req.on("error", reject);
37575
37852
  });
37576
37853
  }
37577
37854
  function body(req) {
37578
- return new Promise((resolve, reject) => {
37855
+ return new Promise((resolve2, reject) => {
37579
37856
  let text = "";
37580
37857
  req.setEncoding("utf8");
37581
37858
  req.on("data", (chunk) => {
@@ -37584,9 +37861,9 @@ function body(req) {
37584
37861
  });
37585
37862
  req.on("end", () => {
37586
37863
  try {
37587
- resolve(text ? JSON.parse(text) : {});
37864
+ resolve2(text ? JSON.parse(text) : {});
37588
37865
  } catch {
37589
- resolve({});
37866
+ resolve2({});
37590
37867
  }
37591
37868
  });
37592
37869
  req.on("error", reject);
@@ -37611,8 +37888,8 @@ var LocalApi = class {
37611
37888
  localAgents.add(agent.id);
37612
37889
  return this.hub.wait(agent, origin, timeoutMs, signal);
37613
37890
  }
37614
- async done(agent, jobId, notes, question) {
37615
- return this.hub.done(agent.id, jobId, notes, question);
37891
+ async done(agent, jobId, notes, question, props) {
37892
+ return this.hub.done(agent.id, jobId, notes, question, props);
37616
37893
  }
37617
37894
  check(_agent, jobId, timeoutMs) {
37618
37895
  return this.hub.check(jobId, timeoutMs);
@@ -37646,8 +37923,8 @@ var RemoteApi = class {
37646
37923
  wait(agent, origin, timeoutMs, signal) {
37647
37924
  return this.post("wait", { agent, origin, timeoutMs }, signal);
37648
37925
  }
37649
- async done(agent, jobId, notes, question) {
37650
- return (await this.post("done", { agent, jobId, notes, question })).job;
37926
+ async done(agent, jobId, notes, question, props) {
37927
+ return (await this.post("done", { agent, jobId, notes, question, props })).job;
37651
37928
  }
37652
37929
  async check(agent, jobId, timeoutMs) {
37653
37930
  return (await this.post("check", { agent, jobId, timeoutMs })).check;
@@ -37695,8 +37972,8 @@ var Bridge = class {
37695
37972
  }
37696
37973
  }
37697
37974
  }
37698
- done(jobId, notes, question) {
37699
- return this.call((api) => api.done(this.agent, jobId, notes, question));
37975
+ done(jobId, notes, question, props) {
37976
+ return this.call((api) => api.done(this.agent, jobId, notes, question, props));
37700
37977
  }
37701
37978
  /** Pilot's width check of a task's element, measured by the page (null: no page answered). */
37702
37979
  check(jobId, timeoutMs = CHECK_TIMEOUT) {
@@ -37788,9 +38065,9 @@ function isConnectionError(error62) {
37788
38065
  }
37789
38066
 
37790
38067
  // src/locate.ts
37791
- import { existsSync as existsSync2, readdirSync, readFileSync, statSync } from "fs";
37792
- import { extname, join as join2, relative } from "path";
37793
- var SKIP = /* @__PURE__ */ new Set([
38068
+ import { existsSync as existsSync3, readdirSync as readdirSync2, readFileSync as readFileSync2, statSync as statSync2 } from "fs";
38069
+ import { basename as basename3, extname as extname2, isAbsolute, join as join3, relative as relative2 } from "path";
38070
+ var SKIP2 = /* @__PURE__ */ new Set([
37794
38071
  "node_modules",
37795
38072
  "dist",
37796
38073
  "build",
@@ -37806,7 +38083,7 @@ var SKIP = /* @__PURE__ */ new Set([
37806
38083
  ".turbo",
37807
38084
  ".cache"
37808
38085
  ]);
37809
- var EXTENSIONS = /* @__PURE__ */ new Set([
38086
+ var EXTENSIONS2 = /* @__PURE__ */ new Set([
37810
38087
  ".html",
37811
38088
  ".htm",
37812
38089
  ".jsx",
@@ -37825,40 +38102,40 @@ var EXTENSIONS = /* @__PURE__ */ new Set([
37825
38102
  ".liquid",
37826
38103
  ".twig"
37827
38104
  ]);
37828
- var MAX_FILES = 4e3;
37829
- var MAX_FILE_BYTES = 512e3;
37830
- var BUDGET_MS = 800;
37831
- var cache = null;
38105
+ var MAX_FILES2 = 4e3;
38106
+ var MAX_FILE_BYTES2 = 512e3;
38107
+ var BUDGET_MS2 = 800;
38108
+ var cache2 = null;
37832
38109
  function sourceFiles(root) {
37833
- if (cache && cache.root === root && Date.now() - cache.at < 3e4) return cache.files;
38110
+ if (cache2 && cache2.root === root && Date.now() - cache2.at < 3e4) return cache2.files;
37834
38111
  const files = [];
37835
38112
  const walk = (dir) => {
37836
38113
  let names;
37837
38114
  try {
37838
- names = readdirSync(dir);
38115
+ names = readdirSync2(dir);
37839
38116
  } catch {
37840
38117
  return;
37841
38118
  }
37842
38119
  for (const name of names) {
37843
- if (files.length >= MAX_FILES) return;
37844
- if (SKIP.has(name) || name.startsWith(".") && name !== ".") continue;
37845
- const path = join2(dir, name);
38120
+ if (files.length >= MAX_FILES2) return;
38121
+ if (SKIP2.has(name) || name.startsWith(".") && name !== ".") continue;
38122
+ const path = join3(dir, name);
37846
38123
  let stat2;
37847
38124
  try {
37848
- stat2 = statSync(path);
38125
+ stat2 = statSync2(path);
37849
38126
  } catch {
37850
38127
  continue;
37851
38128
  }
37852
38129
  if (stat2.isDirectory()) walk(path);
37853
- else if (EXTENSIONS.has(extname(name)) && stat2.size <= MAX_FILE_BYTES) files.push(path);
38130
+ else if (EXTENSIONS2.has(extname2(name)) && stat2.size <= MAX_FILE_BYTES2) files.push(path);
37854
38131
  }
37855
38132
  };
37856
38133
  walk(root);
37857
- cache = { root, at: Date.now(), files };
38134
+ cache2 = { root, at: Date.now(), files };
37858
38135
  return files;
37859
38136
  }
37860
38137
  function searchable(cwd) {
37861
- return existsSync2(join2(cwd, "package.json")) || existsSync2(join2(cwd, ".git"));
38138
+ return existsSync3(join3(cwd, "package.json")) || existsSync3(join3(cwd, ".git"));
37862
38139
  }
37863
38140
  var escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
37864
38141
  function needles(target) {
@@ -37873,15 +38150,26 @@ function needles(target) {
37873
38150
  tag: new RegExp(`<${escape2(target.tag)}[\\s>/]`, "i")
37874
38151
  };
37875
38152
  }
37876
- function locate(target, root, deadline = Date.now() + BUDGET_MS) {
38153
+ function locate(target, root, deadline = Date.now() + BUDGET_MS2) {
37877
38154
  const n = needles(target);
38155
+ const known = target.source?.file && target.source.line ? sourcePath(target.source.file, root) : null;
38156
+ if (known && target.source?.line) {
38157
+ try {
38158
+ const lines = readFileSync2(join3(root, known), "utf8").split("\n");
38159
+ const from = target.source.line - 1;
38160
+ const own2 = bestLine(n, lines, from);
38161
+ const index = own2 && own2.score >= 2 ? own2.index : from;
38162
+ return { file: known, line: index + 1, snippet: snippetAt(lines, index) };
38163
+ } catch {
38164
+ }
38165
+ }
37878
38166
  if (!n.id && !n.text && !n.lead && n.classes.length < 3) return null;
37879
38167
  let best = null;
37880
38168
  for (const file2 of sourceFiles(root)) {
37881
38169
  if (Date.now() > deadline) break;
37882
38170
  let content;
37883
38171
  try {
37884
- content = readFileSync(file2, "utf8");
38172
+ content = readFileSync2(file2, "utf8");
37885
38173
  } catch {
37886
38174
  continue;
37887
38175
  }
@@ -37889,36 +38177,126 @@ function locate(target, root, deadline = Date.now() + BUDGET_MS) {
37889
38177
  if (n.classes.length < 3) continue;
37890
38178
  }
37891
38179
  const lines = content.split("\n");
37892
- const classesOn = (i) => lines[i] === void 0 ? 0 : n.classes.filter((re) => re.test(lines[i])).length;
37893
- for (let i = 0; i < lines.length; i++) {
37894
- const line = lines[i];
37895
- let score = 0;
37896
- if (n.id?.test(line)) score += 8;
37897
- if (n.text && line.includes(n.text)) score += 6;
37898
- else if (n.lead && line.includes(n.lead)) score += 4;
37899
- let classes = 0;
37900
- for (let j = Math.max(0, i - 3); j <= i; j++) classes = Math.max(classes, classesOn(j));
37901
- score += classes;
37902
- if (n.classes.length && classes === n.classes.length) score += 2;
37903
- if (n.tag.test(line)) score += 1;
37904
- if (!best || score > best.score) best = { file: file2, line: i, score, lines };
37905
- }
38180
+ const found = bestLine(n, lines);
38181
+ if (found && (!best || found.score > best.score)) best = { file: file2, line: found.index, score: found.score, lines };
37906
38182
  }
37907
38183
  const enough = best && (best.score >= 6 || n.classes.length >= 3 && best.score >= n.classes.length + 2);
37908
38184
  if (!best || !enough) return null;
37909
- const from = Math.max(0, best.line - 2);
37910
- const snippet = best.lines.slice(from, best.line + 3).map((l) => l.length > 160 ? `${l.slice(0, 159)}\u2026` : l).join("\n");
37911
- return { file: relative(root, best.file), line: best.line + 1, snippet };
38185
+ return { file: relative2(root, best.file), line: best.line + 1, snippet: snippetAt(best.lines, best.line) };
38186
+ }
38187
+ function bestLine(n, lines, from = 0) {
38188
+ const classesOn = (i) => lines[i] === void 0 ? 0 : n.classes.filter((re) => re.test(lines[i])).length;
38189
+ let best = null;
38190
+ for (let i = from; i < lines.length; i++) {
38191
+ const line = lines[i];
38192
+ let score = 0;
38193
+ if (n.id?.test(line)) score += 8;
38194
+ if (n.text && line.includes(n.text)) score += 6;
38195
+ else if (n.lead && line.includes(n.lead)) score += 4;
38196
+ let classes = 0;
38197
+ for (let j = Math.max(from, i - 3); j <= i; j++) classes = Math.max(classes, classesOn(j));
38198
+ score += classes;
38199
+ if (n.classes.length && classes === n.classes.length) score += 2;
38200
+ if (n.tag.test(line)) score += 1;
38201
+ if (!best || score > best.score) best = { index: i, score };
38202
+ }
38203
+ return best;
38204
+ }
38205
+ function snippetAt(lines, index) {
38206
+ return lines.slice(Math.max(0, index - 2), index + 3).map((l) => l.length > 160 ? `${l.slice(0, 159)}\u2026` : l).join("\n");
38207
+ }
38208
+ function sourcePath(file2, root) {
38209
+ const rel = isAbsolute(file2) ? relative2(root, file2) : file2.replace(/^\.\//, "");
38210
+ if (rel.startsWith("..") || isAbsolute(rel)) return null;
38211
+ return existsSync3(join3(root, rel)) ? rel : null;
38212
+ }
38213
+ function componentFile(name, root, deadline = Date.now() + BUDGET_MS2, within) {
38214
+ if (!/^[A-Za-z_$][\w$]*$/.test(name)) return null;
38215
+ const declaration = new RegExp(
38216
+ `^\\s*(export\\s+(?:default\\s+)?)?(?:(?:async\\s+)?function\\s*\\*?\\s+${name}\\b|class\\s+${name}\\b|(?:const|let|var)\\s+${name}\\s*[:=])`
38217
+ );
38218
+ let best = null;
38219
+ const files = within ? [join3(root, within)] : sourceFiles(root);
38220
+ for (const file2 of files) {
38221
+ if (Date.now() > deadline) break;
38222
+ if (!/\.[jt]sx?$|\.mjs$/.test(file2)) continue;
38223
+ let content;
38224
+ try {
38225
+ content = readFileSync2(file2, "utf8");
38226
+ } catch {
38227
+ continue;
38228
+ }
38229
+ if (!content.includes(name)) continue;
38230
+ const lines = content.split("\n");
38231
+ for (let i = 0; i < lines.length; i++) {
38232
+ const m = declaration.exec(lines[i]);
38233
+ if (!m) continue;
38234
+ const score = (basename3(file2).replace(/\.[^.]+$/, "") === name ? 2 : 0) + (m[1] ? 1 : 0);
38235
+ if (!best || score > best.score) best = { file: file2, line: i + 1, score };
38236
+ break;
38237
+ }
38238
+ }
38239
+ return best ? { file: relative2(root, best.file), line: best.line } : null;
38240
+ }
38241
+ function withComponentFiles(job, root) {
38242
+ if (!searchable(root)) return job;
38243
+ const deadline = Date.now() + BUDGET_MS2;
38244
+ const fill = (target) => {
38245
+ const source = target.source;
38246
+ if (!source?.component || source.line) return target;
38247
+ const known = source.file ? sourcePath(source.file, root) : null;
38248
+ if (source.file && !known) return target;
38249
+ const found = componentFile(source.component, root, deadline, known ?? void 0);
38250
+ return found ? { ...target, source: { ...source, file: found.file, line: found.line } } : target;
38251
+ };
38252
+ const workspace = workspaceRoot(root);
38253
+ const declared = (name) => {
38254
+ const found = componentFile(name, workspace, deadline);
38255
+ return found ? { file: relative2(root, join3(workspace, found.file)), line: found.line } : null;
38256
+ };
38257
+ const mention = (r) => {
38258
+ if (r.kind === "element") return { ...r, target: fill(r.target) };
38259
+ if (r.kind === "unlisted") {
38260
+ const source2 = declared(r.name);
38261
+ return source2 ? { kind: "component", name: r.name, source: source2 } : r;
38262
+ }
38263
+ if (r.kind !== "component") return r;
38264
+ if (r.source) {
38265
+ const path = join3(workspace, r.source.file);
38266
+ return existsSync3(path) ? { ...r, source: { ...r.source, file: relative2(root, path) } } : r;
38267
+ }
38268
+ if (r.target?.source?.file) return { ...r, target: fill(r.target) };
38269
+ const source = declared(r.name);
38270
+ return source ? { ...r, source } : r;
38271
+ };
38272
+ const mentions = (refs) => refs?.length ? { references: refs.map(mention) } : {};
38273
+ const { changeSet } = job;
38274
+ const request = changeSet.request;
38275
+ return {
38276
+ ...job,
38277
+ changeSet: {
38278
+ ...changeSet,
38279
+ edits: changeSet.edits.map((e) => ({ ...e, target: fill(e.target) })),
38280
+ ...request ? {
38281
+ request: {
38282
+ ...request,
38283
+ target: fill(request.target),
38284
+ ...request.others ? { others: request.others.map(fill) } : {},
38285
+ ...request.kind === "comment" ? { thread: request.thread.map((m) => ({ ...m, ...mentions(m.references) })) } : mentions(request.references)
38286
+ }
38287
+ } : {}
38288
+ }
38289
+ };
37912
38290
  }
37913
38291
  function whereSection(job, root) {
37914
38292
  if (!searchable(root)) return "";
37915
38293
  const targets = job.changeSet.request ? requestTargets(job.changeSet.request) : job.changeSet.edits.map((e) => e.target);
37916
- const deadline = Date.now() + BUDGET_MS;
38294
+ const deadline = Date.now() + BUDGET_MS2;
37917
38295
  const found = [];
37918
38296
  for (const target of targets) {
37919
38297
  const at = locate(target, root, deadline);
37920
38298
  if (!at) continue;
37921
- const lang = extname(at.file).slice(1) || "text";
38299
+ const lang = extname2(at.file).slice(1) || "text";
37922
38300
  found.push(
37923
38301
  `- \`${target.path}\` \u2192 \`${at.file}:${at.line}\`:`,
37924
38302
  "",
@@ -37931,306 +38309,44 @@ function whereSection(job, root) {
37931
38309
  return [
37932
38310
  "## Where the code probably is",
37933
38311
  "",
37934
- "Pilot searched the project for these elements (by id, text and classes). Start there; if it isn't the right place (the text comes from a prop, a translation, a CMS), search as usual.",
38312
+ "Pilot searched the project for these elements (by component, id, text and classes). Start there; if it isn't the right place (the text comes from a prop, a translation, a CMS), search as usual.",
37935
38313
  "",
37936
38314
  ...found
37937
38315
  ].join("\n");
37938
38316
  }
37939
38317
 
37940
- // src/version.ts
37941
- var VERSION = "0.7.2";
37942
- function olderThan(a, b) {
37943
- const parts = (v) => v.replace(/^[^\d]*/, "").split(/[.-]/).slice(0, 3).map((n) => Number.parseInt(n, 10) || 0);
37944
- const [x, y] = [parts(a), parts(b)];
37945
- for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) < (y[i] ?? 0);
37946
- return false;
37947
- }
37948
-
37949
- // src/mcp.ts
37950
- function waitMsFor(clientName) {
37951
- const configured = Number(process.env.PILOT_WAIT_MS);
37952
- if (configured > 0) return configured;
37953
- return clientName === "claude-code" ? 25 * 6e4 : 5e4;
37954
- }
37955
- var PROGRESS_MS = 2e4;
37956
- var INSTRUCTIONS = `Pilot lets the designer edit the running app in the browser and send the edits back to you as jobs.
37957
-
37958
- The loop, when the user asks to launch or start Pilot, runs /pilot, or asks to hand the design over:
37959
- 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.
37960
- 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.)
37961
- 3. Apply the job's edits to the source: they're design instructions, not code, so write production code the way the project already styles things, whatever it uses (see the job's guidelines). Edits are basic: every value is given, so be fast (no screenshots or browser checks: Pilot checks the page). A "make responsive" job is an advanced task: make one element work at every viewport width. A "break and fix" job is one too: stress-test one element with odd but realistic content, fix what breaks, and put the real content back. Their prompts list the steps; check the result with pilot_check_widths (numbers for every width, instead of screenshots). If you can hand advanced tasks to a more capable model than the one you run on (a subagent, or another model your agent offers), do. A "comment" job is the designer's own words about one element: do what it asks (simple asks right away, open-ended ones as advanced tasks), and your pilot_done notes are your reply in their thread: one short sentence, like a chat message, not a report.
37962
- 4. Call pilot_done with the job id and short notes (values you approximated, anything you did differently). When part of a job needs the designer's decision (they changed only some copies of shared code: each element's "Look-alikes" line counts the others; the jobs' guidelines say when, and what each answer means), do the rest, leave that part, and ask with pilot_done's question and choices ("${SHARED_CHOICES.all.label}", "${SHARED_CHOICES.one.label}", "${SHARED_CHOICES.variant.label}", your suggestion first); go on with other jobs, and their answer comes back as that job. Then call pilot_wait_for_edits again. When several jobs were queued, one wait returns them all: do them all, then call pilot_done once per job, each with its own id and notes.
37963
-
37964
- When the user asks to update Pilot: run \`npx usepilot@latest update\` in the app's folder and tell them, in a few lines, what it prints (the new version, and the steps left).
37965
-
37966
- Keep looping until the user interrupts you. Between jobs keep your messages short: a line on what you changed (and anything you approximated) is enough. If the user talks to you meanwhile, help them, then wait again: queued jobs are kept. 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.`;
37967
- function agentLabel(clientName, cwd) {
37968
- const names = {
37969
- "claude-code": "Claude Code",
37970
- "claude-ai": "Claude",
37971
- cursor: "Cursor",
37972
- "cursor-vscode": "Cursor",
37973
- vscode: "VS Code",
37974
- windsurf: "Windsurf",
37975
- codex: "Codex"
37976
- };
37977
- const app = clientName && (names[clientName.toLowerCase()] ?? clientName) || "Agent";
37978
- return `${app} \xB7 ${basename2(cwd)}`;
37979
- }
37980
- function jobPrompt(job, where = "") {
37981
- 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, { guidelines: false });
37982
- return `${body2}${where ? `
37983
- ${where}
37984
- ` : ""}
37985
- ---
37986
- 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.
37987
- `;
37988
- }
37989
- function answered(job) {
37990
- const meaning = job.answer ? sharedChoiceMeaning(job.answer) : null;
37991
- return [
37992
- "# Pilot: the designer answered your question",
37993
- "",
37994
- `You did this job and asked the designer: ${job.question?.text}`,
37995
- "",
37996
- "Their answer:",
37997
- "",
37998
- job.answer?.trim().split("\n").map((l) => `> ${l}`).join("\n"),
37999
- "",
38000
- ...meaning ? [`What that means for the code: ${meaning}`, ""] : [],
38001
- "Do what's left of the job the way they answered, then call `pilot_done` again. Pilot then checks it like any job. (Don't ask again: say anything still open in your notes.)",
38002
- "",
38003
- "The job, for reference:",
38004
- "",
38005
- formatPrompt(job.changeSet, { guidelines: false })
38006
- ].join("\n");
38007
- }
38008
- function followUp(job) {
38009
- const lines = [
38010
- "# Pilot design edits: follow-up",
38011
- "",
38012
- "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):",
38013
- ""
38014
- ];
38015
- for (const d of job.differences ?? []) {
38016
- const edit = job.changeSet.edits.find((e) => e.target.selector === d.selector);
38017
- const where = edit ? `\`${edit.target.path}\` (selector \`${d.selector}\`${edit.target.text ? `, text "${edit.target.text}"` : ""})` : `\`${d.selector}\``;
38018
- lines.push(`- ${where}: \`${d.property}\` should be \`${d.expected}\`, the page gives \`${d.actual ?? "?"}\`.`);
38019
- }
38020
- lines.push(
38021
- "",
38022
- "Fix them: the usual causes are a rule that overrides yours (more specific, later, or in a media query), an edit in the wrong file or component, or a missed change. If you chose a different value on purpose (a token or the nearest step in the project's scale), keep it and say so in your notes. Pilot takes what the code gives after this."
38023
- );
38024
- return lines.join("\n");
38025
- }
38026
- var MAX_BATCH = 6;
38027
- async function takeQueued(first, take) {
38028
- const advanced = (j) => !!j.changeSet.request && j.changeSet.request.kind !== "comment";
38029
- if (advanced(first)) return [];
38030
- const more = [];
38031
- while (more.length < MAX_BATCH - 1) {
38032
- const { job } = await take();
38033
- if (!job) break;
38034
- more.push(job);
38035
- if (advanced(job)) break;
38036
- }
38037
- return more;
38038
- }
38039
- function batchIntro(jobs) {
38040
- return `# Pilot: ${jobs.length} jobs
38041
-
38042
- The designer sent these while you were busy. Do them all (they're on different elements), then call \`pilot_done\` once per job, each with its own id and notes (you can make the calls together): ${jobs.map((j) => `\`${j.id}\``).join(", ")}. Then call \`pilot_wait_for_edits\` again.`;
38043
- }
38044
- function notesFor(job) {
38045
- switch (job.changeSet.request?.kind) {
38046
- case "comment":
38047
- 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";
38048
- case "responsive":
38049
- return "what changed at which widths, anything left for the designer";
38050
- case "break-and-fix":
38051
- return "what broke and how you fixed it, anything for the designer to decide";
38052
- default:
38053
- return "values you approximated, anything you did differently";
38054
- }
38055
- }
38056
- function taskFollowUp(job) {
38057
- const request = job.changeSet.request;
38058
- const target = `\`${request?.target.path ?? "the element"}\``;
38059
- const breakFix = request?.kind === "break-and-fix";
38060
- const lines = [
38061
- breakFix ? "# Pilot: break and fix, follow-up" : "# Pilot: make responsive, follow-up",
38062
- "",
38063
- 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:`,
38064
- "",
38065
- ...(job.issues ?? []).map((i) => `- ${i}`),
38066
- "",
38067
- "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.",
38068
- "",
38069
- "The task, for reference:",
38070
- "",
38071
- formatPrompt(job.changeSet)
38072
- ];
38073
- return lines.join("\n");
38074
- }
38075
- function createPilotServer(options = {}) {
38076
- const port = options.port ?? (Number(process.env.PILOT_PORT) || DEFAULT_BRIDGE_PORT);
38077
- const cwd = options.cwd ?? process.cwd();
38078
- let waitMs = options.waitMs ?? waitMsFor(void 0);
38079
- const server = new McpServer({ name: "pilot", version: VERSION }, { instructions: INSTRUCTIONS });
38080
- const agent = { id: randomUUID2(), label: agentLabel(void 0, cwd) };
38081
- const bridge = new Bridge(agent, port);
38082
- let origin = null;
38083
- server.server.oninitialized = () => {
38084
- const client = server.server.getClientVersion()?.name;
38085
- agent.label = agentLabel(client, cwd);
38086
- waitMs = options.waitMs ?? waitMsFor(client);
38087
- };
38088
- const text = (t, isError = false) => ({ content: [{ type: "text", text: t }], isError });
38089
- server.registerTool(
38090
- "pilot_launch",
38091
- {
38092
- title: "Launch Pilot",
38093
- 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.",
38094
- inputSchema: {
38095
- 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).")
38096
- }
38097
- },
38098
- async ({ url: url2 }) => {
38099
- const o = originOf(url2);
38100
- if (!o) return text(`"${url2}" isn't a page URL. Pass the dev server's URL, e.g. http://localhost:5173.`, true);
38101
- origin = o;
38102
- try {
38103
- const pages = await bridge.launch(o);
38104
- const where = pages > 0 ? `Pilot is open in ${pages === 1 ? "the page" : `${pages} pages`} at ${o}.` : `No page at ${o} is connected yet. Ask the designer to open ${url2} (with the dev server running): Pilot opens there.`;
38105
- return text(`${where} Now call pilot_wait_for_edits and wait for the designer to press Send.`);
38106
- } catch (error62) {
38107
- return text(`Pilot couldn't start its bridge: ${error62.message}`, true);
38108
- }
38109
- }
38110
- );
38111
- server.registerTool(
38112
- "pilot_wait_for_edits",
38113
- {
38114
- title: "Wait for design edits",
38115
- // The edit guidelines live here, read once with the tool, not repeated in every job (they're the most frequent).
38116
- description: `Waits for the designer to press Send in Pilot, and returns the job to apply (or several, when they were queued: do them all, and report each done). Returns "no edits yet" after a few minutes: call it again to keep waiting. Call pilot_launch first.
38117
-
38118
- Guidelines for every design-edits job (the job doesn't repeat them):
38119
- ${EDIT_GUIDELINES.join("\n")}`,
38120
- inputSchema: {}
38121
- },
38122
- async (_args, extra) => {
38123
- if (!origin) return text("Call pilot_launch with the page's URL first.", true);
38124
- const token = extra._meta?.progressToken;
38125
- let progress = 0;
38126
- const ticker = token !== void 0 ? setInterval(() => {
38127
- extra.sendNotification({
38128
- method: "notifications/progress",
38129
- params: { progressToken: token, progress: ++progress, message: "Waiting for the designer to send edits" }
38130
- }).catch(() => {
38131
- });
38132
- }, PROGRESS_MS) : null;
38133
- try {
38134
- const { job } = await bridge.wait(origin, waitMs, extra.signal);
38135
- if (!job) return text("No edits yet. Call pilot_wait_for_edits again to keep waiting (the designer can keep editing meanwhile).");
38136
- const jobs = [job, ...await takeQueued(job, () => bridge.wait(origin, 0, extra.signal))];
38137
- const parts = await Promise.all(
38138
- jobs.map(async (j) => ({
38139
- // Where its elements' code probably is: found here, in the project, so the agent can go straight to the edit.
38140
- text: jobPrompt(j, j.attempt === 2 ? "" : whereSection(j, cwd)),
38141
- // A comment's images and text files come with it, so the agent sees them without opening files.
38142
- blocks: await attachmentBlocks(j)
38143
- }))
38144
- );
38145
- if (parts.length === 1) return { content: [{ type: "text", text: parts[0]?.text ?? "" }, ...parts[0]?.blocks ?? []], isError: false };
38146
- return {
38147
- content: [
38148
- { type: "text", text: batchIntro(jobs) },
38149
- ...parts.flatMap((p, i) => [{ type: "text", text: `## Job ${i + 1} of ${jobs.length}
38150
-
38151
- ${p.text}` }, ...p.blocks])
38152
- ],
38153
- isError: false
38154
- };
38155
- } catch (error62) {
38156
- return text(`Pilot's bridge failed while waiting: ${error62.message}. Call pilot_wait_for_edits again.`, true);
38157
- } finally {
38158
- if (ticker) clearInterval(ticker);
38159
- }
38160
- }
38161
- );
38162
- server.registerTool(
38163
- "pilot_done",
38164
- {
38165
- title: "Report a job done",
38166
- description: "Tells Pilot you applied a job. Pilot then checks each change against the page's real CSS; a change that didn't land comes back to you once as a follow-up. Then call pilot_wait_for_edits again. When part of the job needs the designer's decision (they changed only some copies of shared code), apply the rest, leave that part, and ask with `question`: Pilot shows it in a comment on the element, with one-click `choices`, holds the job until they answer, and their answer comes back to you as this job again. You go on with other jobs meanwhile. A job asks once.",
38167
- inputSchema: {
38168
- jobId: external_exports.string().describe("The job's id, from pilot_wait_for_edits."),
38169
- notes: external_exports.string().optional().describe("Short notes for the designer: values you approximated (e.g. 22px \u2192 pt-6, 24px), anything done differently."),
38170
- question: external_exports.object({
38171
- text: external_exports.string().describe(`One short sentence, the component's name in **bold** (it's shown as markdown), e.g. "This title comes from the shared **Card**: change every card, or only this one?"`),
38172
- choices: external_exports.array(external_exports.string()).max(MAX_CHOICES).optional().describe(
38173
- `One-click answers, a few words each (they sit on one line), your suggestion first (it's the main button). For shared code: "${SHARED_CHOICES.all.label}", "${SHARED_CHOICES.one.label}", "${SHARED_CHOICES.variant.label}". The designer can also write their own.`
38174
- )
38175
- }).optional().describe("Only when part of the job needs the designer's decision: see the description.")
38176
- }
38177
- },
38178
- async ({ jobId, notes, question }) => {
38179
- try {
38180
- const asked = questionOf(question);
38181
- const job = await bridge.done(jobId, notes, asked);
38182
- if (!job) return text(`Pilot doesn't know job ${jobId} (or the designer cancelled it). Call pilot_wait_for_edits for the next one.`);
38183
- if (asked && job.question)
38184
- return text("Done. Pilot shows your question to the designer; their answer comes back as this job. Call pilot_wait_for_edits for the next job meanwhile.");
38185
- if (asked) return text("Done. This job was answered already, so the question wasn't asked: Pilot is checking the changes. Say it in your notes next time. Call pilot_wait_for_edits for the next job.");
38186
- return text("Done. Pilot is checking the changes in the page. Call pilot_wait_for_edits for the next job.");
38187
- } catch (error62) {
38188
- return text(`Pilot couldn't report the job done: ${error62.message}`, true);
38189
- }
38190
- }
38191
- );
38192
- server.registerTool(
38193
- "pilot_check_widths",
38194
- {
38195
- title: "Check an element at every width",
38196
- description: "For a Make responsive or Break and fix 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.",
38197
- inputSchema: {
38198
- jobId: external_exports.string().describe("The Make responsive or Break and fix job's id, from pilot_wait_for_edits.")
38199
- }
38200
- },
38201
- async ({ jobId }) => {
38202
- try {
38203
- const check2 = await bridge.check(jobId);
38204
- if (!check2) {
38205
- return text(
38206
- `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 or Break and fix one. If you can, check the widths in a browser instead.`,
38207
- true
38208
- );
38209
- }
38210
- return text(formatWidthCheck(check2));
38211
- } catch (error62) {
38212
- return text(`Pilot couldn't run the width check: ${error62.message}`, true);
38213
- }
38214
- }
38215
- );
38216
- return { server, bridge, agent };
38318
+ // src/clients.ts
38319
+ var RESTART = {
38320
+ "claude-code": "In Claude Code, open a new chat (or run `/mcp` and reconnect `pilot`).",
38321
+ cursor: "In Cursor, restart Pilot's server: Cursor Settings, MCP section, switch `pilot` off and on. A new chat isn't enough: Cursor keeps one server for all its chats.",
38322
+ vscode: "In VS Code, restart Pilot's server: run **MCP: List Servers** from the Command Palette, pick `pilot`, then **Restart Server**.",
38323
+ codex: "In Codex, start a new session.",
38324
+ other: "Restart Pilot's server in your agent (its MCP settings), or restart the agent."
38325
+ };
38326
+ function clientOf(name) {
38327
+ const n = name?.toLowerCase() ?? "";
38328
+ if (n.startsWith("claude-code") || n === "claude-ai") return "claude-code";
38329
+ if (n.startsWith("cursor")) return "cursor";
38330
+ if (n === "vscode" || n.includes("visual studio code")) return "vscode";
38331
+ if (n.startsWith("codex")) return "codex";
38332
+ return null;
38217
38333
  }
38218
38334
 
38219
38335
  // src/init.ts
38220
38336
  import { spawnSync } from "child_process";
38221
- import { existsSync as existsSync4, readdirSync as readdirSync2, readFileSync as readFileSync2 } from "fs";
38337
+ import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync3 } from "fs";
38222
38338
  import { mkdir as mkdir3, readFile as readFile3, writeFile as writeFile3 } from "fs/promises";
38223
38339
  import { homedir as homedir2 } from "os";
38224
- import { dirname as dirname2, join as join4, relative as relative3 } from "path";
38340
+ import { dirname as dirname3, join as join5, relative as relative4 } from "path";
38225
38341
 
38226
38342
  // src/setup.ts
38227
- import { existsSync as existsSync3 } from "fs";
38343
+ import { existsSync as existsSync4 } from "fs";
38228
38344
  import { lstat, mkdir as mkdir2, readFile as readFile2, unlink, writeFile as writeFile2 } from "fs/promises";
38229
38345
  import { homedir } from "os";
38230
- import { join as join3, relative as relative2 } from "path";
38346
+ import { join as join4, relative as relative3 } from "path";
38231
38347
 
38232
38348
  // ../../skills/pilot/SKILL.md
38233
- var SKILL_default = "---\nname: pilot\ndescription: Hand the UI to the designer with Pilot, then apply the design edits they send, job after job. Use when the user runs /pilot, says they want to take control of the design or edit the UI in the browser, or pastes a \"Pilot design edits\" brief, or asks to update Pilot.\n---\n\n# Pilot\n\nPilot lets the designer edit the running app in the browser. They select elements, change CSS properties with Pilot's editors, and press **Send**. Each Send reaches you as a **job**: plain CSS `property: from \u2192 to` (and new text, when they rewrote one) on identifiable elements, for you to write into the source in this project's conventions. The designer keeps designing while you work; Pilot previews each job's changes until you report it done, then checks them against the page's real CSS.\n\n## When the user asks to update Pilot\n\nRun `npx usepilot@latest update` in the app's folder (the one with `usepilot` in its `package.json`), and tell the user in a few lines what it prints: the new version and the steps left (restart the app's dev server, open a new chat).\n\n## When the user runs /pilot (or asks to launch Pilot)\n\n0. **Check that Pilot's tools are here** (`pilot_launch`, `pilot_wait_for_edits`, `pilot_done`). If they aren't, don't look for them in files, packages or settings: they come from Pilot's MCP server, which an agent loads when a chat starts, so a chat opened before Pilot was set up doesn't have them. Say so in one or two lines and stop: open a new chat (approve Pilot's server if asked, or turn it on in the agent's MCP settings: Cursor keeps a project's new servers off until they're switched on in Cursor Settings, MCP section), then run `/pilot` there. If the project has no Pilot at all (no `usepilot` in its `package.json`), offer to set it up instead: `npx usepilot@latest init --agent <you>`.\n1. **Find the page.** Work out the URL of the app's dev server: the dev script and its config (`vite.config.*` \u2192 `server.port`, Next.js \u2192 3000, a `--port` flag\u2026), or a server already running in a terminal. If the dev server isn't running, start it in the background. If you can't tell the URL, ask.\n2. **Launch:** call `pilot_launch` with that URL. Pilot opens in the page (if the page isn't open yet, tell the designer to open it).\n3. **Tell the designer** in one line that Pilot is ready: select an element, edit, press Send.\n4. **Wait:** call `pilot_wait_for_edits`. It returns a job when the designer presses Send, or \"no edits yet\" after a while: call it again, without saying anything to the user. In Claude Code, a wait longer than two minutes moves to the background: end your turn with a short \"Waiting for your edits\", and the job arrives as the task's result.\n5. **Apply the job** (below), then call `pilot_done` with the job id and short notes, and go back to step 4. When several jobs were queued, one wait returns them all: do them all, then call `pilot_done` once per job, each with its own id and notes.\n\nKeep looping until the user asks you to stop. Keep your messages between jobs short: a line on what you changed (and anything you approximated) is enough. If the user talks to you meanwhile, help them, and keep (or start again) a wait in the background so their next Send reaches you (queued jobs are kept).\n\n## Applying a job\n\nJobs come in three kinds:\n\n- **Edits** (basic): the designer set every value; you only translate them. **Speed is what matters**: go straight to the code, apply, call `pilot_done`. No screenshots, browser checks, builds or tests: Pilot checks the page itself and sends back what didn't land.\n- **Comments**: the designer's own words about one element (\"make it the brand green\", \"can this be calmer?\"), with the thread so far. Do what the latest one asks: a specific, small ask right away (like an edit), an open-ended one as an advanced task (below). A question gets an answer and no change. Your `pilot_done` notes are your reply in their thread, a small chat box for quick design back-and-forth: one short sentence, like a chat message (about 120 characters), with no lists or code blocks. Not a report: they see the result on the page.\n- **Tasks** (advanced), like **Make responsive** and **Break and fix**: the designer selected an element and asked for an outcome (work at every viewport width; hold up with odd but realistic content, like very long text, with the real content put back after testing). They need judgment more than speed. The prompt has the steps. Check the result with `pilot_check_widths` (numbers for every width, no screenshots needed). If you can hand it to a more capable model than the one you run on (a subagent, or another model your agent offers), do, then call `pilot_done` with its notes. Pilot checks the widths again when you're done; problems come back once as a follow-up.\n\n### Edits\n\nThe values are **design instructions, not code**: the designer's intent. Use your judgment and write production code the way this project already styles things, whatever it uses. First look at how the element's component is styled, and follow that. For example:\n\n- **Utility classes (Tailwind):** the closest utility or theme value (`border-radius: 12px` \u2192 `rounded-xl`, `padding-top: 24px` \u2192 `pt-6`). Arbitrary values only when nothing fits.\n- **CSS / CSS modules / Sass:** edit the rule that styles the element. Don't add a new override.\n- **Design tokens / CSS variables:** prefer an existing token that matches. Don't hard-code its value.\n- **CSS-in-JS and compiled styles (StyleX, vanilla-extract, Panda, styled-components, Emotion):** edit the style definition where the component is styled, with the project's tokens.\n- **A component library's props (MUI, Chakra\u2026):** use its props and theme values before any custom CSS.\n\nRules:\n\n- Never leave inline styles or `!important` behind. Pilot's preview is only a preview.\n- Find each element by its selector, DOM path and text snippet, then the component that renders it.\n- **Shared code, only some copies:** an element's \"Look-alikes\" line counts the elements like it the job leaves out. If they come from the same code (a shared component, a loop over data) and the designer didn't say which they meant, don't guess: do the rest of the job, leave that part, and ask with `pilot_done`'s `question` (one short sentence, the component's name in **bold**) and `choices` \"All of them\", \"Only this\", \"New variant\" (your suggestion first). Go on with other jobs; the answer comes back as that job. **All of them**: change the component itself. **Only this**: change it where it's used, with what the component accepts (classes through its `className`, merged the project's way; a prop), else the smallest pass-through, not a variant. **New variant**: add a named option the way the component defines variants (`cva`, a `variant` prop), use it here, and name it in your notes. Don't ask when the designer already said, when every copy is in the job, or when nothing else uses that code.\n- **Widths:** a change for some viewport widths goes in a media query; use the project's breakpoints when one matches (or is within a few pixels). \"Every width\" means no media query should override it.\n- **Removed:** the element shouldn't declare the property at all (not `0` or `none`).\n- **Text:** the designer rewrote the element's copy. Change it where it comes from (the markup, a prop, a translation file), for this element only; Pilot checks that the page shows the new text.\n- If you approximated a value to fit a token or scale, say which and by how much in `pilot_done`'s notes (`22px \u2192 pt-6, 24px`). Pilot checks the page after each job: a change that doesn't give the designer's value comes back to you once as a follow-up. Fix it, or keep a deliberate choice and say why; after that, Pilot takes what the code gives.\n- Don't run builds or tests for a job unless it's needed: hot reload shows the result, and the designer is waiting to see it.\n";
38349
+ var SKILL_default = "---\nname: pilot\ndescription: Hand the UI to the designer with Pilot, then apply the design edits they send, job after job. Use when the user runs /pilot, says they want to take control of the design or edit the UI in the browser, or pastes a \"Pilot design edits\" brief, or asks to update Pilot.\n---\n\n# Pilot\n\nPilot lets the designer edit the running app in the browser. They select elements, change CSS properties with Pilot's editors, and press **Send**. Each Send reaches you as a **job**: plain CSS `property: from \u2192 to` (and new text, when they rewrote one) on identifiable elements, for you to write into the source in this project's conventions. The designer keeps designing while you work; Pilot previews each job's changes until you report it done, then checks them against the page's real CSS.\n\n## When the user asks to update Pilot\n\nRun `npx usepilot@latest update` in the app's folder (the one with `usepilot` in its `package.json`), and tell the user in a few lines what it prints: the new version and the steps left (restart the app's dev server, open a new chat).\n\n## When the user runs /pilot (or asks to launch Pilot)\n\n0. **Check that Pilot's tools are here** (`pilot_launch`, `pilot_wait_for_edits`, `pilot_done`). If they aren't, don't look for them in files, packages or settings: they come from Pilot's MCP server, which an agent loads when a chat starts, so a chat opened before Pilot was set up doesn't have them. Say so in one or two lines and stop: open a new chat (approve Pilot's server if asked, or turn it on in the agent's MCP settings: Cursor keeps a project's new servers off until they're switched on in Cursor Settings, MCP section), then run `/pilot` there. If the project has no Pilot at all (no `usepilot` in its `package.json`), offer to set it up instead: `npx usepilot@latest init --agent <you>`.\n1. **Find the page.** Work out the URL of the app's dev server: the dev script and its config (`vite.config.*` \u2192 `server.port`, Next.js \u2192 3000, a `--port` flag\u2026), or a server already running in a terminal. If the dev server isn't running, start it in the background. If you can't tell the URL, ask.\n2. **Launch:** call `pilot_launch` with that URL and `folder`, the project's folder as an absolute path (your working directory): Pilot searches the code there for each job, and some agents start its server elsewhere. Pilot opens in the page (if the page isn't open yet, tell the designer to open it).\n3. **Tell the designer** in one line that Pilot is ready: select an element, edit, press Send.\n4. **Wait:** call `pilot_wait_for_edits`. It returns a job when the designer presses Send, or \"no edits yet\" after a while: call it again, without saying anything to the user. In Claude Code, a wait longer than two minutes moves to the background: end your turn with a short \"Waiting for your edits\", and the job arrives as the task's result.\n5. **Apply the job** (below), then call `pilot_done` with the job id and short notes, and go back to step 4. When several jobs were queued, one wait returns them all: do them all, then call `pilot_done` once per job, each with its own id and notes.\n\nKeep looping until the user asks you to stop. Keep your messages between jobs short: a line on what you changed (and anything you approximated) is enough. If the user talks to you meanwhile, help them, and keep (or start again) a wait in the background so their next Send reaches you (queued jobs are kept).\n\n## Applying a job\n\nJobs come in three kinds:\n\n- **Edits** (basic): the designer set every value; you only translate them. **Speed is what matters**: go straight to the code, apply, call `pilot_done`. No screenshots, browser checks, builds or tests: Pilot checks the page itself and sends back what didn't land.\n- **Comments**: the designer's own words about one element (\"make it the brand green\", \"can this be calmer?\"), with the thread so far. Do what the latest one asks: a specific, small ask right away (like an edit), an open-ended one as an advanced task (below). A question gets an answer and no change. Your `pilot_done` notes are your reply in their thread, a small chat box for quick design back-and-forth: one short sentence, like a chat message (about 120 characters), with no lists or code blocks. Not a report: they see the result on the page.\n- **Tasks** (advanced), like **Make responsive** and **Break and fix**: the designer selected an element and asked for an outcome (work at every viewport width; hold up with odd but realistic content, like very long text, with the real content put back after testing). They need judgment more than speed. The prompt has the steps. Check the result with `pilot_check_widths` (numbers for every width, no screenshots needed). If you can hand it to a more capable model than the one you run on (a subagent, or another model your agent offers), do, then call `pilot_done` with its notes. Pilot checks the widths again when you're done; problems come back once as a follow-up.\n\n### Edits\n\nThe values are **design instructions, not code**: the designer's intent. Use your judgment and write production code the way this project already styles things, whatever it uses. First look at how the element's component is styled, and follow that. For example:\n\n- **Utility classes (Tailwind):** the closest utility or theme value (`border-radius: 12px` \u2192 `rounded-xl`, `padding-top: 24px` \u2192 `pt-6`). Arbitrary values only when nothing fits.\n- **CSS / CSS modules / Sass:** edit the rule that styles the element. Don't add a new override.\n- **Design tokens / CSS variables:** prefer an existing token that matches. Don't hard-code its value.\n- **CSS-in-JS and compiled styles (StyleX, vanilla-extract, Panda, styled-components, Emotion):** edit the style definition where the component is styled, with the project's tokens.\n- **A component library's props (MUI, Chakra\u2026):** use its props and theme values before any custom CSS.\n\nRules:\n\n- Never leave inline styles or `!important` behind. Pilot's preview is only a preview.\n- Find each element by its selector, DOM path and text snippet, then the component that renders it.\n- **Shared code, only some copies:** an element's \"Look-alikes\" line counts the elements like it the job leaves out. If they come from the same code (a shared component, a loop over data) and the designer didn't say which they meant, don't guess: do the rest of the job, leave that part, and ask with `pilot_done`'s `question` (one short sentence, the component's name in **bold**) and `choices` \"All of them\", \"Only this\", \"New variant\" (your suggestion first). Go on with other jobs; the answer comes back as that job. **All of them**: change the component itself. **Only this**: change it where it's used, with what the component accepts (classes through its `className`, merged the project's way; a prop), else the smallest pass-through, not a variant. **New variant**: add a named option the way the component defines variants (`cva`, a `variant` prop), use it here, and name it in your notes. Don't ask when the designer already said, when every copy is in the job, or when nothing else uses that code.\n- **Widths:** a change for some viewport widths goes in a media query; use the project's breakpoints when one matches (or is within a few pixels). \"Every width\" means no media query should override it.\n- **Removed:** the element shouldn't declare the property at all (not `0` or `none`).\n- **Text:** the designer rewrote the element's copy. Change it where it comes from (the markup, a prop, a translation file), for this element only; Pilot checks that the page shows the new text.\n- If you approximated a value to fit a token or scale, say which and by how much in `pilot_done`'s notes (`22px \u2192 pt-6, 24px`). Pilot checks the page after each job: a change that doesn't give the designer's value comes back to you once as a follow-up. Fix it, or keep a deliberate choice and say why; after that, Pilot takes what the code gives.\n- Don't run builds or tests for a job unless it's needed: hot reload shows the result, and the designer is waiting to see it.\n";
38234
38350
 
38235
38351
  // src/setup.ts
38236
38352
  var MCP_SERVER = { command: "npx", args: ["-y", "usepilot", "mcp"] };
@@ -38238,7 +38354,7 @@ async function setup(options = {}) {
38238
38354
  return options.project ? setupProject(options.cwd ?? process.cwd()) : setupMachine(options.home ?? homedir());
38239
38355
  }
38240
38356
  async function setupMachine(home) {
38241
- const file2 = await writeSkill(join3(home, ".claude", "skills", "pilot"));
38357
+ const file2 = await writeSkill(join4(home, ".claude", "skills", "pilot"));
38242
38358
  return `Installed the /pilot skill: ${file2}
38243
38359
 
38244
38360
  Now register Pilot's MCP server with Claude Code, once, for every project:
@@ -38250,11 +38366,11 @@ Then, in any Claude Code chat: /pilot
38250
38366
  `;
38251
38367
  }
38252
38368
  async function setupProject(cwd) {
38253
- const skillFile = await writeSkill(join3(cwd, ".claude", "skills", "pilot"));
38254
- const mcpFile = join3(cwd, ".mcp.json");
38369
+ const skillFile = await writeSkill(join4(cwd, ".claude", "skills", "pilot"));
38370
+ const mcpFile = join4(cwd, ".mcp.json");
38255
38371
  const { added } = await addMcpServer(mcpFile);
38256
- const rel = (f) => relative2(cwd, f);
38257
- const app = existsSync3(join3(cwd, "package.json")) ? "" : "\nNo package.json here: run this in the project's root folder, where the app is.\n";
38372
+ const rel = (f) => relative3(cwd, f);
38373
+ const app = existsSync4(join4(cwd, "package.json")) ? "" : "\nNo package.json here: run this in the project's root folder, where the app is.\n";
38258
38374
  const width = rel(skillFile).length + 2;
38259
38375
  return `Set up /pilot for this repo:
38260
38376
  ${rel(skillFile).padEnd(width)}the /pilot skill
@@ -38273,7 +38389,7 @@ Then, in a Claude Code chat in this folder: /pilot
38273
38389
  async function writeSkill(dir) {
38274
38390
  if (await isLink(dir)) await unlink(dir);
38275
38391
  await mkdir2(dir, { recursive: true });
38276
- const file2 = join3(dir, "SKILL.md");
38392
+ const file2 = join4(dir, "SKILL.md");
38277
38393
  await writeFile2(file2, SKILL_default);
38278
38394
  return file2;
38279
38395
  }
@@ -38286,7 +38402,7 @@ async function isLink(path) {
38286
38402
  }
38287
38403
  async function addMcpServer(file2) {
38288
38404
  let config2 = {};
38289
- if (existsSync3(file2)) {
38405
+ if (existsSync4(file2)) {
38290
38406
  const text = await readFile2(file2, "utf8");
38291
38407
  try {
38292
38408
  config2 = text.trim() ? JSON.parse(text) : {};
@@ -38302,6 +38418,15 @@ async function addMcpServer(file2) {
38302
38418
  return { added };
38303
38419
  }
38304
38420
 
38421
+ // src/version.ts
38422
+ var VERSION = "0.9.0";
38423
+ function olderThan(a, b) {
38424
+ const parts = (v) => v.replace(/^[^\d]*/, "").split(/[.-]/).slice(0, 3).map((n) => Number.parseInt(n, 10) || 0);
38425
+ const [x, y] = [parts(a), parts(b)];
38426
+ for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) < (y[i] ?? 0);
38427
+ return false;
38428
+ }
38429
+
38305
38430
  // src/init.ts
38306
38431
  var AGENT_IDS = ["claude-code", "cursor", "codex", "vscode", "other"];
38307
38432
  var COMMAND = `${MCP_SERVER.command} ${MCP_SERVER.args.join(" ")}`;
@@ -38310,15 +38435,15 @@ var AGENTS = [
38310
38435
  id: "claude-code",
38311
38436
  name: "Claude Code",
38312
38437
  mcp: { file: ".mcp.json", key: "mcpServers", entry: MCP_SERVER },
38313
- skills: join4(".claude", "skills"),
38438
+ skills: join5(".claude", "skills"),
38314
38439
  invoke: "`/pilot`",
38315
38440
  signals: [".mcp.json", ".claude"]
38316
38441
  },
38317
38442
  {
38318
38443
  id: "cursor",
38319
38444
  name: "Cursor",
38320
- mcp: { file: join4(".cursor", "mcp.json"), key: "mcpServers", entry: MCP_SERVER },
38321
- skills: join4(".cursor", "skills"),
38445
+ mcp: { file: join5(".cursor", "mcp.json"), key: "mcpServers", entry: MCP_SERVER },
38446
+ skills: join5(".cursor", "skills"),
38322
38447
  invoke: "`/pilot`",
38323
38448
  signals: [".cursor"],
38324
38449
  // Cursor sees a project's new MCP server but leaves it off: it never starts until the user turns it on.
@@ -38327,16 +38452,16 @@ var AGENTS = [
38327
38452
  {
38328
38453
  id: "vscode",
38329
38454
  name: "VS Code",
38330
- mcp: { file: join4(".vscode", "mcp.json"), key: "servers", entry: { type: "stdio", ...MCP_SERVER } },
38331
- skills: join4(".github", "skills"),
38455
+ mcp: { file: join5(".vscode", "mcp.json"), key: "servers", entry: { type: "stdio", ...MCP_SERVER } },
38456
+ skills: join5(".github", "skills"),
38332
38457
  invoke: "`/pilot`",
38333
- signals: [join4(".vscode", "mcp.json"), join4(".github", "skills"), join4(".github", "copilot-instructions.md")]
38458
+ signals: [join5(".vscode", "mcp.json"), join5(".github", "skills"), join5(".github", "copilot-instructions.md")]
38334
38459
  },
38335
38460
  {
38336
38461
  id: "codex",
38337
38462
  name: "Codex",
38338
38463
  register: `\`codex mcp add pilot -- ${COMMAND}\``,
38339
- skills: join4(".agents", "skills"),
38464
+ skills: join5(".agents", "skills"),
38340
38465
  invoke: "`$pilot`",
38341
38466
  signals: [".codex"]
38342
38467
  },
@@ -38345,7 +38470,7 @@ var AGENTS = [
38345
38470
  name: "your agent",
38346
38471
  register: `in your MCP settings: a server named \`pilot\`, running \`${COMMAND}\``,
38347
38472
  // The open skills folder, read by many agents.
38348
- skills: join4(".agents", "skills"),
38473
+ skills: join5(".agents", "skills"),
38349
38474
  invoke: "the `pilot` skill",
38350
38475
  signals: []
38351
38476
  }
@@ -38356,51 +38481,62 @@ var MACHINE = {
38356
38481
  command: {
38357
38482
  cmd: "claude",
38358
38483
  args: ["mcp", "add", "--scope", "user", "pilot", "--", ...MCP_SERVER_ARGV],
38359
- has: (home) => !!readJson(join4(home, ".claude.json"))?.mcpServers?.pilot
38484
+ has: (home) => !!readJson(join5(home, ".claude.json"))?.mcpServers?.pilot
38360
38485
  },
38361
- skills: (home) => join4(home, ".claude", "skills")
38486
+ skills: (home) => join5(home, ".claude", "skills")
38362
38487
  },
38363
38488
  cursor: {
38364
- mcp: { file: (home) => join4(home, ".cursor", "mcp.json"), key: "mcpServers", entry: MCP_SERVER },
38365
- skills: (home) => join4(home, ".cursor", "skills")
38489
+ mcp: { file: (home) => join5(home, ".cursor", "mcp.json"), key: "mcpServers", entry: MCP_SERVER },
38490
+ skills: (home) => join5(home, ".cursor", "skills")
38366
38491
  },
38367
38492
  vscode: {
38368
38493
  mcp: {
38369
- file: (home, platform) => join4(vscodeUserDir(home, platform), "mcp.json"),
38494
+ file: (home, platform) => join5(vscodeUserDir(home, platform), "mcp.json"),
38370
38495
  key: "servers",
38371
38496
  entry: { type: "stdio", ...MCP_SERVER }
38372
38497
  },
38373
- skills: (home) => join4(home, ".copilot", "skills")
38498
+ skills: (home) => join5(home, ".copilot", "skills")
38374
38499
  },
38375
38500
  codex: {
38376
38501
  command: {
38377
38502
  cmd: "codex",
38378
38503
  args: ["mcp", "add", "pilot", "--", ...MCP_SERVER_ARGV],
38379
- has: (home) => /\[mcp_servers\.pilot\]/.test(readText(join4(home, ".codex", "config.toml")))
38504
+ has: (home) => /\[mcp_servers\.pilot\]/.test(readText(join5(home, ".codex", "config.toml")))
38380
38505
  },
38381
- skills: (home) => join4(home, ".agents", "skills")
38506
+ skills: (home) => join5(home, ".agents", "skills")
38382
38507
  },
38383
- other: { skills: (home) => join4(home, ".agents", "skills") }
38508
+ other: { skills: (home) => join5(home, ".agents", "skills") }
38384
38509
  };
38385
38510
  function skillFolders(root, home) {
38386
- const machine = AGENT_IDS.map((id) => join4(MACHINE[id].skills(home), "pilot"));
38387
- const project = AGENTS.map((a) => join4(root, a.skills, "pilot"));
38511
+ const machine = AGENT_IDS.map((id) => join5(MACHINE[id].skills(home), "pilot"));
38512
+ const project = AGENTS.map((a) => join5(root, a.skills, "pilot"));
38388
38513
  return [.../* @__PURE__ */ new Set([...machine, ...project])];
38389
38514
  }
38515
+ function agentsWithPilot(root, home, platform = process.platform) {
38516
+ const hasServer = (file2, key) => !!(readJson(file2)?.[key] ?? {}).pilot;
38517
+ return AGENTS.filter((a) => {
38518
+ if (a.id === "other") return false;
38519
+ const machine = MACHINE[a.id];
38520
+ if (machine.mcp && hasServer(machine.mcp.file(home, platform), machine.mcp.key)) return true;
38521
+ if (machine.command?.has(home)) return true;
38522
+ if (a.mcp && hasServer(join5(root, a.mcp.file), a.mcp.key)) return true;
38523
+ return a.id !== "codex" && existsSync5(join5(machine.skills(home), "pilot"));
38524
+ }).map((a) => a.id);
38525
+ }
38390
38526
  function installArgs(pm, spec = "usepilot") {
38391
38527
  return pm === "npm" ? ["install", "-D", spec] : pm === "bun" ? ["add", "-d", spec] : ["add", "-D", spec];
38392
38528
  }
38393
38529
  function installedVersion(cwd, root) {
38394
- for (let dir = cwd; ; dir = dirname2(dir)) {
38395
- const version2 = readJson(join4(dir, "node_modules", "usepilot", "package.json"))?.version;
38530
+ for (let dir = cwd; ; dir = dirname3(dir)) {
38531
+ const version2 = readJson(join5(dir, "node_modules", "usepilot", "package.json"))?.version;
38396
38532
  if (version2) return version2;
38397
- if (dir === root || dirname2(dir) === dir) return null;
38533
+ if (dir === root || dirname3(dir) === dir) return null;
38398
38534
  }
38399
38535
  }
38400
38536
  function vscodeUserDir(home, platform) {
38401
- if (platform === "darwin") return join4(home, "Library", "Application Support", "Code", "User");
38402
- if (platform === "win32") return join4(process.env.APPDATA ?? join4(home, "AppData", "Roaming"), "Code", "User");
38403
- return join4(home, ".config", "Code", "User");
38537
+ if (platform === "darwin") return join5(home, "Library", "Application Support", "Code", "User");
38538
+ if (platform === "win32") return join5(process.env.APPDATA ?? join5(home, "AppData", "Roaming"), "Code", "User");
38539
+ return join5(home, ".config", "Code", "User");
38404
38540
  }
38405
38541
  function tilde(path, home) {
38406
38542
  return path.startsWith(home) ? `~${path.slice(home.length)}` : path;
@@ -38414,8 +38550,8 @@ function detectAgent(env) {
38414
38550
  async function init(options = {}) {
38415
38551
  const cwd = options.cwd ?? process.cwd();
38416
38552
  const run = options.run ?? runCommand;
38417
- const pkgFile = join4(cwd, "package.json");
38418
- if (!existsSync4(pkgFile)) {
38553
+ const pkgFile = join5(cwd, "package.json");
38554
+ if (!existsSync5(pkgFile)) {
38419
38555
  return `# Pilot: not set up
38420
38556
 
38421
38557
  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.
@@ -38471,16 +38607,16 @@ ${apps.map((a) => `- ${a}`).join("\n")}` : "."}
38471
38607
  } else if (agent.register) {
38472
38608
  todo.push(`**Register Pilot's MCP server with yourself**, for every project: ${agent.register}.`);
38473
38609
  }
38474
- const skill = join4(machine.skills(home), "pilot");
38610
+ const skill = join5(machine.skills(home), "pilot");
38475
38611
  await writeSkill(skill);
38476
38612
  parts.push(`the \`pilot\` skill (\`${tilde(skill, home)}/\`)`);
38477
38613
  done.push(`Connected ${agent.name} to Pilot, once for every project on this machine: ${list(parts)}. Nothing was added to the repo.`);
38478
38614
  } else if (named) {
38479
- const present = AGENTS.filter((a) => a.id !== named && a.signals.some((p) => existsSync4(join4(root, p))));
38615
+ const present = AGENTS.filter((a) => a.id !== named && a.signals.some((p) => existsSync5(join5(root, p))));
38480
38616
  for (const agent of [...AGENTS.filter((a) => a.id === named), ...present]) {
38481
38617
  const parts = [];
38482
38618
  if (agent.mcp) {
38483
- const file2 = join4(root, agent.mcp.file);
38619
+ const file2 = join5(root, agent.mcp.file);
38484
38620
  if (await addServer(file2, agent.mcp.key, agent.mcp.entry) === "invalid") {
38485
38621
  todo.push(
38486
38622
  `\`${agent.mcp.file}\` isn't valid JSON, so Pilot wasn't added to it: fix it, and add the \`pilot\` server (\`${COMMAND}\`).`
@@ -38490,8 +38626,8 @@ ${apps.map((a) => `- ${a}`).join("\n")}` : "."}
38490
38626
  written.push(`\`${agent.mcp.file}\``);
38491
38627
  }
38492
38628
  }
38493
- const skill = join4(agent.skills, "pilot");
38494
- await writeSkill(join4(root, skill));
38629
+ const skill = join5(agent.skills, "pilot");
38630
+ await writeSkill(join5(root, skill));
38495
38631
  parts.push(`the \`pilot\` skill (\`${skill}/\`)`);
38496
38632
  if (!written.includes(`\`${skill}/\``)) written.push(`\`${skill}/\``);
38497
38633
  done.push(`Set Pilot up for ${agent.name} in this project: ${list(parts)}.`);
@@ -38502,7 +38638,7 @@ ${apps.map((a) => `- ${a}`).join("\n")}` : "."}
38502
38638
  `**Connect yourself:** run \`npx usepilot@latest init --agent <you>\` in ${cwd}, with \`<you>\` the agent you are: ${AGENT_IDS.map((a) => `\`${a}\``).join(", ")}.`
38503
38639
  );
38504
38640
  }
38505
- if (framework.loads) done.push(`The app already loads Pilot (\`${relative3(cwd, framework.loads)}\`).`);
38641
+ if (framework.loads) done.push(`The app already loads Pilot (\`${relative4(cwd, framework.loads)}\`).`);
38506
38642
  else todo.push(loadStep(framework, cwd));
38507
38643
  const me = AGENTS.find((a) => a.id === named);
38508
38644
  const enable = project && me?.enable ? `Before that, ${me.enable}. ` : "";
@@ -38519,23 +38655,23 @@ ${todo.map((t, i) => `${i + 1}. ${t}`).join("\n")}
38519
38655
  `;
38520
38656
  }
38521
38657
  function projectRoot(cwd) {
38522
- for (let dir = cwd; ; dir = dirname2(dir)) {
38523
- if (existsSync4(join4(dir, ".git"))) return dir;
38524
- if (dirname2(dir) === dir) return cwd;
38658
+ for (let dir = cwd; ; dir = dirname3(dir)) {
38659
+ if (existsSync5(join5(dir, ".git"))) return dir;
38660
+ if (dirname3(dir) === dir) return cwd;
38525
38661
  }
38526
38662
  }
38527
38663
  function packageManager(cwd, root) {
38528
- for (let dir = cwd; ; dir = dirname2(dir)) {
38529
- if (existsSync4(join4(dir, "pnpm-lock.yaml"))) return "pnpm";
38530
- if (existsSync4(join4(dir, "yarn.lock"))) return "yarn";
38531
- if (existsSync4(join4(dir, "bun.lock")) || existsSync4(join4(dir, "bun.lockb"))) return "bun";
38532
- if (existsSync4(join4(dir, "package-lock.json"))) return "npm";
38533
- if (dir === root || dirname2(dir) === dir) return "npm";
38664
+ for (let dir = cwd; ; dir = dirname3(dir)) {
38665
+ if (existsSync5(join5(dir, "pnpm-lock.yaml"))) return "pnpm";
38666
+ if (existsSync5(join5(dir, "yarn.lock"))) return "yarn";
38667
+ if (existsSync5(join5(dir, "bun.lock")) || existsSync5(join5(dir, "bun.lockb"))) return "bun";
38668
+ if (existsSync5(join5(dir, "package-lock.json"))) return "npm";
38669
+ if (dir === root || dirname3(dir) === dir) return "npm";
38534
38670
  }
38535
38671
  }
38536
38672
  function detectFramework(cwd, deps) {
38537
38673
  const has = (name) => name in deps;
38538
- const first = (...files) => files.map((f) => join4(cwd, f)).find((f) => existsSync4(f));
38674
+ const first = (...files) => files.map((f) => join5(cwd, f)).find((f) => existsSync5(f));
38539
38675
  const loads = findLoader(cwd);
38540
38676
  const result = (kind, file2) => ({ kind, file: file2, loads });
38541
38677
  if (has("next")) {
@@ -38557,8 +38693,8 @@ function detectFramework(cwd, deps) {
38557
38693
  if (has("vite") || Object.keys(deps).some((d) => d.startsWith("@vitejs/"))) {
38558
38694
  const entry = viteEntry(cwd);
38559
38695
  if (entry) return result("vite", entry);
38560
- if (existsSync4(join4(cwd, "index.html"))) {
38561
- const config2 = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"].map((f) => join4(cwd, f)).find((f) => existsSync4(f));
38696
+ if (existsSync5(join5(cwd, "index.html"))) {
38697
+ const config2 = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"].map((f) => join5(cwd, f)).find((f) => existsSync5(f));
38562
38698
  return result("vite-html", config2);
38563
38699
  }
38564
38700
  return result("vite");
@@ -38572,16 +38708,16 @@ function detectFramework(cwd, deps) {
38572
38708
  return { kind: "unknown", loads };
38573
38709
  }
38574
38710
  function viteEntry(cwd) {
38575
- const html = join4(cwd, "index.html");
38576
- if (existsSync4(html)) {
38577
- for (const tag of readFileSync2(html, "utf8").match(/<script\b[^>]*>/gi) ?? []) {
38711
+ const html = join5(cwd, "index.html");
38712
+ if (existsSync5(html)) {
38713
+ for (const tag of readFileSync3(html, "utf8").match(/<script\b[^>]*>/gi) ?? []) {
38578
38714
  if (!/type=["']module["']/i.test(tag)) continue;
38579
38715
  const src = /src=["']\/?([^"'?#]+)/i.exec(tag)?.[1];
38580
- if (src && existsSync4(join4(cwd, src))) return join4(cwd, src);
38716
+ if (src && existsSync5(join5(cwd, src))) return join5(cwd, src);
38581
38717
  }
38582
38718
  return void 0;
38583
38719
  }
38584
- return ["src/main.tsx", "src/main.ts", "src/main.jsx", "src/main.js", "src/index.tsx", "src/index.ts"].map((f) => join4(cwd, f)).find((f) => existsSync4(f));
38720
+ return ["src/main.tsx", "src/main.ts", "src/main.jsx", "src/main.js", "src/index.tsx", "src/index.ts"].map((f) => join5(cwd, f)).find((f) => existsSync5(f));
38585
38721
  }
38586
38722
  var SOURCE_DIRS = ["src", "app", "pages", "plugins", "components", "lib"];
38587
38723
  var SOURCE_FILE = /\.(m?[jt]sx?|vue|svelte|astro|html)$/;
@@ -38590,13 +38726,13 @@ function findLoader(cwd) {
38590
38726
  const walk = (dir, depth) => {
38591
38727
  let names;
38592
38728
  try {
38593
- names = readdirSync2(dir);
38729
+ names = readdirSync3(dir);
38594
38730
  } catch {
38595
38731
  return void 0;
38596
38732
  }
38597
38733
  for (const name of names) {
38598
38734
  if (budget-- <= 0 || name === "node_modules" || name.startsWith(".")) continue;
38599
- const path = join4(dir, name);
38735
+ const path = join5(dir, name);
38600
38736
  if (SOURCE_FILE.test(name)) {
38601
38737
  if (/["']usepilot(\/auto)?["']/.test(readText(path))) return path;
38602
38738
  } else if (depth > 0 && !name.includes(".")) {
@@ -38607,40 +38743,40 @@ function findLoader(cwd) {
38607
38743
  return void 0;
38608
38744
  };
38609
38745
  for (const name of ["index.html", "vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"]) {
38610
- const file2 = join4(cwd, name);
38611
- if (existsSync4(file2) && /usepilot/.test(readText(file2))) return file2;
38746
+ const file2 = join5(cwd, name);
38747
+ if (existsSync5(file2) && /usepilot/.test(readText(file2))) return file2;
38612
38748
  }
38613
38749
  for (const dir of SOURCE_DIRS) {
38614
- const found = walk(join4(cwd, dir), 6);
38750
+ const found = walk(join5(cwd, dir), 6);
38615
38751
  if (found) return found;
38616
38752
  }
38617
38753
  return void 0;
38618
38754
  }
38619
38755
  function readText(file2) {
38620
38756
  try {
38621
- return readFileSync2(file2, "utf8");
38757
+ return readFileSync3(file2, "utf8");
38622
38758
  } catch {
38623
38759
  return "";
38624
38760
  }
38625
38761
  }
38626
38762
  function isWorkspaceRoot(cwd, pkg) {
38627
- return !!pkg.workspaces || existsSync4(join4(cwd, "pnpm-workspace.yaml"));
38763
+ return !!pkg.workspaces || existsSync5(join5(cwd, "pnpm-workspace.yaml"));
38628
38764
  }
38629
38765
  function workspaceApps(cwd) {
38630
38766
  const found = [];
38631
38767
  for (const group of ["apps", "packages", "examples", "sites"]) {
38632
- const dir = join4(cwd, group);
38633
- if (!existsSync4(dir)) continue;
38634
- for (const name of readdirSync2(dir)) {
38635
- const pkg = readJson(join4(dir, name, "package.json"));
38636
- if (pkg && detectFramework(join4(dir, name), { ...pkg.dependencies, ...pkg.devDependencies }).kind !== "unknown")
38637
- found.push(join4(group, name));
38768
+ const dir = join5(cwd, group);
38769
+ if (!existsSync5(dir)) continue;
38770
+ for (const name of readdirSync3(dir)) {
38771
+ const pkg = readJson(join5(dir, name, "package.json"));
38772
+ if (pkg && detectFramework(join5(dir, name), { ...pkg.dependencies, ...pkg.devDependencies }).kind !== "unknown")
38773
+ found.push(join5(group, name));
38638
38774
  }
38639
38775
  }
38640
38776
  return found;
38641
38777
  }
38642
38778
  function loadStep(framework, cwd) {
38643
- const at = (file2, otherwise) => file2 ? `\`${relative3(cwd, file2)}\`` : otherwise;
38779
+ const at = (file2, otherwise) => file2 ? `\`${relative4(cwd, file2)}\`` : otherwise;
38644
38780
  const code = (lang, text) => `
38645
38781
 
38646
38782
  \`\`\`${lang}
@@ -38710,7 +38846,7 @@ export function Pilot() {
38710
38846
  }
38711
38847
  async function addServer(file2, key, entry) {
38712
38848
  let config2 = {};
38713
- if (existsSync4(file2)) {
38849
+ if (existsSync5(file2)) {
38714
38850
  const text = await readFile3(file2, "utf8");
38715
38851
  try {
38716
38852
  config2 = text.trim() ? JSON.parse(text) : {};
@@ -38722,14 +38858,14 @@ async function addServer(file2, key, entry) {
38722
38858
  const servers = config2[key] ?? {};
38723
38859
  const result = "pilot" in servers ? "updated" : "added";
38724
38860
  config2[key] = { ...servers, pilot: entry };
38725
- await mkdir3(dirname2(file2), { recursive: true });
38861
+ await mkdir3(dirname3(file2), { recursive: true });
38726
38862
  await writeFile3(file2, `${JSON.stringify(config2, null, 2)}
38727
38863
  `);
38728
38864
  return result;
38729
38865
  }
38730
38866
  function readJson(file2) {
38731
38867
  try {
38732
- return JSON.parse(readFileSync2(file2, "utf8"));
38868
+ return JSON.parse(readFileSync3(file2, "utf8"));
38733
38869
  } catch {
38734
38870
  return null;
38735
38871
  }
@@ -38742,16 +38878,349 @@ function runCommand(command2, args, cwd) {
38742
38878
  return result.status === 0;
38743
38879
  }
38744
38880
 
38881
+ // src/mcp.ts
38882
+ function waitMsFor(clientName) {
38883
+ const configured = Number(process.env.PILOT_WAIT_MS);
38884
+ if (configured > 0) return configured;
38885
+ return clientName === "claude-code" ? 25 * 6e4 : 5e4;
38886
+ }
38887
+ var PROGRESS_MS = 2e4;
38888
+ var INSTRUCTIONS = `Pilot lets the designer edit the running app in the browser and send the edits back to you as jobs.
38889
+
38890
+ The loop, when the user asks to launch or start Pilot, runs /pilot, or asks to hand the design over:
38891
+ 1. Find the page: the URL of the app's dev server, from the dev script and its config (vite.config \u2192 server.port, Next.js \u2192 3000, a --port flag\u2026) or a server already running. If it isn't running, start it in the background; if you can't tell the URL, ask. Call pilot_launch with that URL and \`folder\`, the project's folder as an absolute path (your working directory: Pilot searches the code there for each job, and some clients start its server in another folder): Pilot opens in that page (if the page isn't open, tell the user to open it), then tell the user in one line that Pilot is ready: select an element, edit, press Send.
38892
+ 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.)
38893
+ 3. Apply the job's edits to the source: they're design instructions, not code, so write production code the way the project already styles things, whatever it uses (see the job's guidelines). Edits are basic: every value is given, so be fast (no screenshots or browser checks: Pilot checks the page). A "make responsive" job is an advanced task: make one element work at every viewport width. A "break and fix" job is one too: stress-test one element with odd but realistic content, fix what breaks, and put the real content back. Their prompts list the steps; check the result with pilot_check_widths (numbers for every width, instead of screenshots). If you can hand advanced tasks to a more capable model than the one you run on (a subagent, or another model your agent offers), do. A "comment" job is the designer's own words about one element: do what it asks (simple asks right away, open-ended ones as advanced tasks), and your pilot_done notes are your reply in their thread: one short sentence, like a chat message, not a report.
38894
+ 4. Call pilot_done with the job id and short notes (values you approximated, anything you did differently). When part of a job needs the designer's decision (they changed only some copies of shared code: each element's "Look-alikes" line counts the others; the jobs' guidelines say when, and what each answer means), do the rest, leave that part, and ask with pilot_done's question and choices ("${SHARED_CHOICES.all.label}", "${SHARED_CHOICES.one.label}", "${SHARED_CHOICES.variant.label}", your suggestion first); go on with other jobs, and their answer comes back as that job. Then call pilot_wait_for_edits again. When several jobs were queued, one wait returns them all: do them all, then call pilot_done once per job, each with its own id and notes.
38895
+
38896
+ When the user asks to update Pilot: run \`npx usepilot@latest update\` in the app's folder and tell them, in a few lines, what it prints (the new version, and the steps left).
38897
+
38898
+ Keep looping until the user interrupts you. Between jobs keep your messages short: a line on what you changed (and anything you approximated) is enough. If the user talks to you meanwhile, help them, then wait again: queued jobs are kept. 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.`;
38899
+ function agentLabel(clientName, cwd) {
38900
+ const names = {
38901
+ "claude-code": "Claude Code",
38902
+ "claude-ai": "Claude",
38903
+ cursor: "Cursor",
38904
+ "cursor-vscode": "Cursor",
38905
+ vscode: "VS Code",
38906
+ windsurf: "Windsurf",
38907
+ codex: "Codex"
38908
+ };
38909
+ const app = clientName && (names[clientName.toLowerCase()] ?? clientName) || "Agent";
38910
+ return `${app} \xB7 ${basename4(cwd)}`;
38911
+ }
38912
+ function jobPrompt(job, where = "") {
38913
+ 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, { guidelines: false });
38914
+ return `${body2}${where ? `
38915
+ ${where}
38916
+ ` : ""}
38917
+ ---
38918
+ 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.
38919
+ `;
38920
+ }
38921
+ function answered(job) {
38922
+ const meaning = job.answer ? sharedChoiceMeaning(job.answer) : null;
38923
+ return [
38924
+ "# Pilot: the designer answered your question",
38925
+ "",
38926
+ `You did this job and asked the designer: ${job.question?.text}`,
38927
+ "",
38928
+ "Their answer:",
38929
+ "",
38930
+ job.answer?.trim().split("\n").map((l) => `> ${l}`).join("\n"),
38931
+ "",
38932
+ ...meaning ? [`What that means for the code: ${meaning}`, ""] : [],
38933
+ "Do what's left of the job the way they answered, then call `pilot_done` again. Pilot then checks it like any job. (Don't ask again: say anything still open in your notes.)",
38934
+ "",
38935
+ "The job, for reference:",
38936
+ "",
38937
+ formatPrompt(job.changeSet, { guidelines: false })
38938
+ ].join("\n");
38939
+ }
38940
+ function followUp(job) {
38941
+ const lines = [
38942
+ "# Pilot design edits: follow-up",
38943
+ "",
38944
+ "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):",
38945
+ ""
38946
+ ];
38947
+ for (const d of job.differences ?? []) {
38948
+ const edit = job.changeSet.edits.find((e) => e.target.selector === d.selector);
38949
+ const where = edit ? `\`${edit.target.path}\` (selector \`${d.selector}\`${edit.target.text ? `, text "${edit.target.text}"` : ""})` : `\`${d.selector}\``;
38950
+ lines.push(`- ${where}: \`${d.property}\` should be \`${d.expected}\`, the page gives \`${d.actual ?? "?"}\`.`);
38951
+ }
38952
+ lines.push(
38953
+ "",
38954
+ "Fix them: the usual causes are a rule that overrides yours (more specific, later, or in a media query), an edit in the wrong file or component, or a missed change. If you chose a different value on purpose (a token or the nearest step in the project's scale), keep it and say so in your notes. Pilot takes what the code gives after this."
38955
+ );
38956
+ return lines.join("\n");
38957
+ }
38958
+ var MAX_BATCH = 6;
38959
+ async function takeQueued(first, take) {
38960
+ const advanced = (j) => !!j.changeSet.request && j.changeSet.request.kind !== "comment" && j.changeSet.request.kind !== "props";
38961
+ if (advanced(first)) return [];
38962
+ const more = [];
38963
+ while (more.length < MAX_BATCH - 1) {
38964
+ const { job } = await take();
38965
+ if (!job) break;
38966
+ more.push(job);
38967
+ if (advanced(job)) break;
38968
+ }
38969
+ return more;
38970
+ }
38971
+ function batchIntro(jobs) {
38972
+ return `# Pilot: ${jobs.length} jobs
38973
+
38974
+ The designer sent these while you were busy. Do them all (they're on different elements), then call \`pilot_done\` once per job, each with its own id and notes (you can make the calls together): ${jobs.map((j) => `\`${j.id}\``).join(", ")}. Then call \`pilot_wait_for_edits\` again.`;
38975
+ }
38976
+ function notesFor(job) {
38977
+ switch (job.changeSet.request?.kind) {
38978
+ case "comment":
38979
+ 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";
38980
+ case "responsive":
38981
+ return "what changed at which widths, anything left for the designer";
38982
+ case "break-and-fix":
38983
+ return "what broke and how you fixed it, anything for the designer to decide";
38984
+ case "props":
38985
+ return "one short sentence for the designer, like a chat message; the props go in `props`";
38986
+ default:
38987
+ return "values you approximated, anything you did differently";
38988
+ }
38989
+ }
38990
+ function taskFollowUp(job) {
38991
+ const request = job.changeSet.request;
38992
+ const target = `\`${request?.target.path ?? "the element"}\``;
38993
+ if (request?.kind === "comment")
38994
+ return [
38995
+ "# Pilot: props, follow-up",
38996
+ "",
38997
+ `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:`,
38998
+ "",
38999
+ ...(job.issues ?? []).map((i) => `- ${i}`),
39000
+ "",
39001
+ "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.",
39002
+ "",
39003
+ "The comment, for reference:",
39004
+ "",
39005
+ formatPrompt(job.changeSet, { guidelines: false })
39006
+ ].join("\n");
39007
+ const breakFix = request?.kind === "break-and-fix";
39008
+ const lines = [
39009
+ breakFix ? "# Pilot: break and fix, follow-up" : "# Pilot: make responsive, follow-up",
39010
+ "",
39011
+ 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:`,
39012
+ "",
39013
+ ...(job.issues ?? []).map((i) => `- ${i}`),
39014
+ "",
39015
+ "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.",
39016
+ "",
39017
+ "The task, for reference:",
39018
+ "",
39019
+ formatPrompt(job.changeSet)
39020
+ ];
39021
+ return lines.join("\n");
39022
+ }
39023
+ function projectFolder(candidate) {
39024
+ if (!candidate) return null;
39025
+ let path = candidate;
39026
+ if (path.startsWith("file://")) {
39027
+ try {
39028
+ path = fileURLToPath(path);
39029
+ } catch {
39030
+ return null;
39031
+ }
39032
+ }
39033
+ if (!isAbsolute2(path)) return null;
39034
+ path = resolve(path);
39035
+ return existsSync6(path) && searchable(path) ? path : null;
39036
+ }
39037
+ function createPilotServer(options = {}) {
39038
+ const port = options.port ?? (Number(process.env.PILOT_PORT) || DEFAULT_BRIDGE_PORT);
39039
+ const cwd = options.cwd ?? process.cwd();
39040
+ let project = cwd;
39041
+ let client;
39042
+ let waitMs = options.waitMs ?? waitMsFor(void 0);
39043
+ const server = new McpServer({ name: "pilot", version: VERSION }, { instructions: INSTRUCTIONS });
39044
+ const agent = { id: randomUUID2(), label: agentLabel(void 0, cwd), ...searchable(cwd) ? { folder: cwd } : {} };
39045
+ const bridge = new Bridge(agent, port);
39046
+ let origin = null;
39047
+ const useProject = (folder) => {
39048
+ project = folder;
39049
+ agent.label = agentLabel(client, folder);
39050
+ agent.folder = folder;
39051
+ };
39052
+ server.server.oninitialized = () => {
39053
+ client = server.server.getClientVersion()?.name;
39054
+ agent.label = agentLabel(client, project);
39055
+ waitMs = options.waitMs ?? waitMsFor(client);
39056
+ if (searchable(project) || !server.server.getClientCapabilities()?.roots) return;
39057
+ void server.server.listRoots().then(({ roots }) => {
39058
+ const folder = roots.map((r) => projectFolder(r.uri)).find((f) => !!f);
39059
+ if (folder && !searchable(project)) useProject(folder);
39060
+ }).catch(() => {
39061
+ });
39062
+ };
39063
+ const text = (t, isError = false) => ({ content: [{ type: "text", text: t }], isError });
39064
+ server.registerTool(
39065
+ "pilot_launch",
39066
+ {
39067
+ title: "Launch Pilot",
39068
+ 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.",
39069
+ inputSchema: {
39070
+ 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)."),
39071
+ folder: external_exports.string().optional().describe(
39072
+ "The project's folder, as an absolute path: your working directory (the app's folder, with its package.json). Pilot searches its code there for each job. Always pass it: some clients start Pilot's server in another folder."
39073
+ )
39074
+ }
39075
+ },
39076
+ async ({ url: url2, folder }) => {
39077
+ const o = originOf(url2);
39078
+ if (!o) return text(`"${url2}" isn't a page URL. Pass the dev server's URL, e.g. http://localhost:5173.`, true);
39079
+ origin = o;
39080
+ const given = projectFolder(folder);
39081
+ if (given) useProject(given);
39082
+ const lost = !searchable(project) && !given ? ` Pilot can't search the project's code from ${project}${folder ? ` (nor from ${folder}: it needs a package.json or a .git)` : ""}: call pilot_launch again with \`folder\` set to the project's folder (absolute).` : "";
39083
+ try {
39084
+ const pages = await bridge.launch(o);
39085
+ const where = pages > 0 ? `Pilot is open in ${pages === 1 ? "the page" : `${pages} pages`} at ${o}.` : `No page at ${o} is connected yet. Ask the designer to open ${url2} (with the dev server running): Pilot opens there.`;
39086
+ const installed = searchable(project) ? installedVersion(project, project) : null;
39087
+ const stale = installed && olderThan(VERSION, installed) ? ` This chat's Pilot server is ${VERSION}, older than the project's ${installed}: tell the user to restart it, so it loads ${installed}. ${RESTART[clientOf(client) ?? "other"]}` : "";
39088
+ return text(`${where} Now call pilot_wait_for_edits and wait for the designer to press Send.${lost}${stale}`);
39089
+ } catch (error62) {
39090
+ return text(`Pilot couldn't start its bridge: ${error62.message}`, true);
39091
+ }
39092
+ }
39093
+ );
39094
+ server.registerTool(
39095
+ "pilot_wait_for_edits",
39096
+ {
39097
+ title: "Wait for design edits",
39098
+ // The edit guidelines live here, read once with the tool, not repeated in every job (they're the most frequent).
39099
+ description: `Waits for the designer to press Send in Pilot, and returns the job to apply (or several, when they were queued: do them all, and report each done). Returns "no edits yet" after a few minutes: call it again to keep waiting. Call pilot_launch first.
39100
+
39101
+ Guidelines for every design-edits job (the job doesn't repeat them):
39102
+ ${EDIT_GUIDELINES.join("\n")}`,
39103
+ inputSchema: {}
39104
+ },
39105
+ async (_args, extra) => {
39106
+ if (!origin) return text("Call pilot_launch with the page's URL first.", true);
39107
+ const token = extra._meta?.progressToken;
39108
+ let progress = 0;
39109
+ const ticker = token !== void 0 ? setInterval(() => {
39110
+ extra.sendNotification({
39111
+ method: "notifications/progress",
39112
+ params: { progressToken: token, progress: ++progress, message: "Waiting for the designer to send edits" }
39113
+ }).catch(() => {
39114
+ });
39115
+ }, PROGRESS_MS) : null;
39116
+ try {
39117
+ const { job } = await bridge.wait(origin, waitMs, extra.signal);
39118
+ if (!job) return text("No edits yet. Call pilot_wait_for_edits again to keep waiting (the designer can keep editing meanwhile).");
39119
+ const jobs = [job, ...await takeQueued(job, () => bridge.wait(origin, 0, extra.signal))];
39120
+ const parts = await Promise.all(
39121
+ jobs.map(async (taken) => {
39122
+ const j = withComponentFiles(taken, project);
39123
+ return {
39124
+ // Where its elements' code probably is: found here, in the project, so the agent can go straight to the edit.
39125
+ text: jobPrompt(j, j.attempt === 2 ? "" : whereSection(j, project)),
39126
+ // A comment's images and text files come with it, so the agent sees them without opening files.
39127
+ blocks: await attachmentBlocks(j)
39128
+ };
39129
+ })
39130
+ );
39131
+ if (parts.length === 1) return { content: [{ type: "text", text: parts[0]?.text ?? "" }, ...parts[0]?.blocks ?? []], isError: false };
39132
+ return {
39133
+ content: [
39134
+ { type: "text", text: batchIntro(jobs) },
39135
+ ...parts.flatMap((p, i) => [{ type: "text", text: `## Job ${i + 1} of ${jobs.length}
39136
+
39137
+ ${p.text}` }, ...p.blocks])
39138
+ ],
39139
+ isError: false
39140
+ };
39141
+ } catch (error62) {
39142
+ return text(`Pilot's bridge failed while waiting: ${error62.message}. Call pilot_wait_for_edits again.`, true);
39143
+ } finally {
39144
+ if (ticker) clearInterval(ticker);
39145
+ }
39146
+ }
39147
+ );
39148
+ server.registerTool(
39149
+ "pilot_done",
39150
+ {
39151
+ title: "Report a job done",
39152
+ description: "Tells Pilot you applied a job. Pilot then checks each change against the page's real CSS; a change that didn't land comes back to you once as a follow-up. Then call pilot_wait_for_edits again. When part of the job needs the designer's decision (they changed only some copies of shared code), apply the rest, leave that part, and ask with `question`: Pilot shows it in a comment on the element, with one-click `choices`, holds the job until they answer, and their answer comes back to you as this job again. You go on with other jobs meanwhile. A job asks once. For a props job (`/props`), pass the component's props in `props`: Pilot shows them to the designer to pick values from.",
39153
+ inputSchema: {
39154
+ jobId: external_exports.string().describe("The job's id, from pilot_wait_for_edits."),
39155
+ notes: external_exports.string().optional().describe("Short notes for the designer: values you approximated (e.g. 22px \u2192 pt-6, 24px), anything done differently."),
39156
+ question: external_exports.object({
39157
+ text: external_exports.string().describe(`One short sentence, the component's name in **bold** (it's shown as markdown), e.g. "This title comes from the shared **Card**: change every card, or only this one?"`),
39158
+ choices: external_exports.array(external_exports.string()).max(MAX_CHOICES).optional().describe(
39159
+ `One-click answers, a few words each (they sit on one line), your suggestion first (it's the main button). For shared code: "${SHARED_CHOICES.all.label}", "${SHARED_CHOICES.one.label}", "${SHARED_CHOICES.variant.label}". The designer can also write their own.`
39160
+ )
39161
+ }).optional().describe("Only when part of the job needs the designer's decision: see the description."),
39162
+ props: external_exports.array(
39163
+ external_exports.object({
39164
+ name: external_exports.string().describe("The prop's name, as the code has it (`variant`)."),
39165
+ type: external_exports.enum(["options", "boolean", "text", "number"]).describe("`options`: one of a set of values; `boolean`: on or off; `text` or `number`: typed."),
39166
+ options: external_exports.array(external_exports.string()).optional().describe("For `options`: every value it accepts, in the code's order."),
39167
+ default: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]).optional().describe("Its default value, when it has one."),
39168
+ description: external_exports.string().optional().describe("What it does, in a few words, when the name doesn't say.")
39169
+ })
39170
+ ).max(MAX_PROPS).optional().describe("Only for a props job (`/props`): the component's props the designer can set, the most useful first.")
39171
+ }
39172
+ },
39173
+ async ({ jobId, notes, question, props }) => {
39174
+ try {
39175
+ const asked = questionOf(question);
39176
+ const job = await bridge.done(jobId, notes, asked, propsOf(props));
39177
+ if (!job) return text(`Pilot doesn't know job ${jobId} (or the designer cancelled it). Call pilot_wait_for_edits for the next one.`);
39178
+ if (asked && job.question)
39179
+ return text("Done. Pilot shows your question to the designer; their answer comes back as this job. Call pilot_wait_for_edits for the next job meanwhile.");
39180
+ if (asked) return text("Done. This job was answered already, so the question wasn't asked: Pilot is checking the changes. Say it in your notes next time. Call pilot_wait_for_edits for the next job.");
39181
+ return text("Done. Pilot is checking the changes in the page. Call pilot_wait_for_edits for the next job.");
39182
+ } catch (error62) {
39183
+ return text(`Pilot couldn't report the job done: ${error62.message}`, true);
39184
+ }
39185
+ }
39186
+ );
39187
+ server.registerTool(
39188
+ "pilot_check_widths",
39189
+ {
39190
+ title: "Check an element at every width",
39191
+ description: "For a Make responsive or Break and fix 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.",
39192
+ inputSchema: {
39193
+ jobId: external_exports.string().describe("The Make responsive or Break and fix job's id, from pilot_wait_for_edits.")
39194
+ }
39195
+ },
39196
+ async ({ jobId }) => {
39197
+ try {
39198
+ const check2 = await bridge.check(jobId);
39199
+ if (!check2) {
39200
+ return text(
39201
+ `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 or Break and fix one. If you can, check the widths in a browser instead.`,
39202
+ true
39203
+ );
39204
+ }
39205
+ return text(formatWidthCheck(check2));
39206
+ } catch (error62) {
39207
+ return text(`Pilot couldn't run the width check: ${error62.message}`, true);
39208
+ }
39209
+ }
39210
+ );
39211
+ return { server, bridge, agent };
39212
+ }
39213
+
38745
39214
  // src/update.ts
38746
39215
  import { spawnSync as spawnSync2 } from "child_process";
38747
- import { existsSync as existsSync5, lstatSync, readFileSync as readFileSync3 } from "fs";
39216
+ import { existsSync as existsSync7, lstatSync, readFileSync as readFileSync4 } from "fs";
38748
39217
  import { homedir as homedir3 } from "os";
38749
- import { dirname as dirname3, join as join5 } from "path";
39218
+ import { dirname as dirname4, join as join6 } from "path";
38750
39219
  async function update(options = {}) {
38751
39220
  const cwd = options.cwd ?? process.cwd();
38752
39221
  const run = options.run ?? runCommand2;
38753
39222
  const home = options.home ?? homedir3();
38754
- const pkg = readJson2(join5(cwd, "package.json"));
39223
+ const pkg = readJson2(join6(cwd, "package.json"));
38755
39224
  const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
38756
39225
  if (!pkg || !deps.usepilot) {
38757
39226
  return `# Pilot isn't installed here
@@ -38768,7 +39237,7 @@ Run this in your app's folder, the one where Pilot was set up. To set Pilot up i
38768
39237
  const after = installed ? installedVersion(cwd, root) ?? VERSION : before;
38769
39238
  const skills = [];
38770
39239
  for (const folder of skillFolders(root, home)) {
38771
- if (!existsSync5(folder) || isLink2(folder)) continue;
39240
+ if (!existsSync7(folder) || isLink2(folder)) continue;
38772
39241
  await writeSkill(folder);
38773
39242
  skills.push(folder.startsWith(home) ? `~${folder.slice(home.length)}` : folder);
38774
39243
  }
@@ -38783,9 +39252,11 @@ ${pm} ${args.join(" ")}
38783
39252
  `;
38784
39253
  }
38785
39254
  const changed = !!before && !!after && olderThan(before, after);
39255
+ const agents = agentsWithPilot(root, home, options.platform);
38786
39256
  const steps = [
38787
39257
  "Restart your app's dev server, so the page loads the new Pilot.",
38788
- "Open a new chat in your agent, and ask it to launch Pilot (or run `/pilot`). A chat that was open keeps the old Pilot."
39258
+ ...agents.length ? agents.map((a) => RESTART[a]) : [RESTART.other],
39259
+ "Then, in a new chat, ask your agent to launch Pilot (or run `/pilot`)."
38789
39260
  ];
38790
39261
  if (oldBridge !== null && oldBridge !== BRIDGE_VERSION) {
38791
39262
  steps.push(
@@ -38803,13 +39274,13 @@ ${steps.map((s, i) => `${i + 1}. ${s}`).join("\n")}
38803
39274
  ` : "Nothing else to do.\n"}`;
38804
39275
  }
38805
39276
  function bridgeOf(cwd, root) {
38806
- for (let dir = cwd; ; dir = dirname3(dir)) {
38807
- const file2 = join5(dir, "node_modules", "usepilot", "cli", "index.js");
38808
- if (existsSync5(file2)) {
38809
- const match = /BRIDGE_VERSION = (\d+)/.exec(readFileSync3(file2, "utf8"));
39277
+ for (let dir = cwd; ; dir = dirname4(dir)) {
39278
+ const file2 = join6(dir, "node_modules", "usepilot", "cli", "index.js");
39279
+ if (existsSync7(file2)) {
39280
+ const match = /BRIDGE_VERSION = (\d+)/.exec(readFileSync4(file2, "utf8"));
38810
39281
  return match ? Number(match[1]) : null;
38811
39282
  }
38812
- if (dir === root || dirname3(dir) === dir) return null;
39283
+ if (dir === root || dirname4(dir) === dir) return null;
38813
39284
  }
38814
39285
  }
38815
39286
  function isLink2(path) {
@@ -38821,7 +39292,7 @@ function isLink2(path) {
38821
39292
  }
38822
39293
  function readJson2(file2) {
38823
39294
  try {
38824
- return JSON.parse(readFileSync3(file2, "utf8"));
39295
+ return JSON.parse(readFileSync4(file2, "utf8"));
38825
39296
  } catch {
38826
39297
  return null;
38827
39298
  }
@@ -38832,7 +39303,7 @@ function runCommand2(command2, args, cwd) {
38832
39303
  }
38833
39304
 
38834
39305
  // src/index.ts
38835
- var HELP = `usepilot: take the controls from your coding agent
39306
+ var HELP = `usepilot: design in your running app, your agents write the code
38836
39307
 
38837
39308
  Usage: npx usepilot <command>
38838
39309