@greatstore/cli 0.2.0 → 0.2.1

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/CHANGELOG.md CHANGED
@@ -3,6 +3,11 @@
3
3
  All notable changes to `@greatstore/cli` are recorded here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/).
5
5
 
6
+ ## 0.2.1 — 2026-09-30
7
+
8
+ ### Changed
9
+ - Updated skill and agent documentation.
10
+
6
11
  ## 0.2.0 — 2026-09-22
7
12
 
8
13
  ### Removed
package/dist/cli.js CHANGED
@@ -20,7 +20,7 @@ p{color:#2c3a38}`,Rn=`<!doctype html>
20
20
  h1{font-size:1.4rem;color:#a40000}code{background:#f4f4f4;padding:.1em .3em;border-radius:.2em}</style></head>
21
21
  <body><h1>Sign-in failed.</h1>
22
22
  <p>Return to your terminal for details.</p></body></html>`,K=class extends Error{constructor(t){super(t),this.name="LoopbackError"}};async function me(e){let t=(e.generateState??Tn)(),n=e.timeoutMs??300*1e3,r=e.openBrowser??(s=>On(s,e.browserCmdEnv)),o=Ve.createServer();try{await new Promise(c=>o.listen(0,"127.0.0.1",c));let s=o.address(),i=new URL(`${e.dashboardBaseUrl}/cli/authorize`);i.searchParams.set("port",String(s.port)),i.searchParams.set("state",t),e.requestedStore&&i.searchParams.set("store",e.requestedStore);let a=i.toString(),l=_n(o,t,n);return r(a),await l}finally{o.close()}}function _n(e,t,n){return new Promise((r,o)=>{let s=!1,i=l=>{s||(s=!0,l())},a=setTimeout(()=>{i(()=>o(new K("Sign-in timed out. Re-run `gs login`.")))},n);typeof a.unref=="function"&&a.unref(),e.on("request",(l,c)=>{let p=new URL(l.url??"/","http://127.0.0.1");if(p.pathname!==En){c.writeHead(404,{"content-type":"text/plain"}),c.end("Not found");return}let u=p.searchParams,f=u.get("error"),j=u.get("error_description"),P=u.get("code");if(u.get("state")!==t){c.writeHead(400,{"content-type":"text/html"}),c.end(Ge),clearTimeout(a),i(()=>o(new K("Sign-in didn't complete. Please try again.")));return}if(f||!P){c.writeHead(400,{"content-type":"text/html"}),c.end(Ge),clearTimeout(a),i(()=>o(new K(j??"Sign-in failed. Please try again.")));return}c.writeHead(200,{"content-type":"text/html"}),c.end(Rn),clearTimeout(a);let R=u.get("store")?.trim();i(()=>r(R?{token:P,store:R}:{token:P}))})})}function Tn(){return qe.randomBytes(16).toString("hex")}function On(e,t){let r=t?.trim()??Ln();if(r)try{let o;if(r==="start"){let s=`start "" "${e}"`;o=Ue("cmd.exe",["/d","/s","/c",s],{stdio:"ignore",detached:!0,windowsVerbatimArguments:!0})}else o=Ue(r,[e],{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}function Ln(){switch(process.platform){case"darwin":return"open";case"win32":return"start";case"linux":return"xdg-open";default:return null}}import*as C from"fs";import*as Q from"os";import*as _e from"path";var In=".greatstore",Fn="credentials.json";function Je(e=Q.homedir()){return _e.join(e,In)}function Te(e=Q.homedir()){return _e.join(Je(e),Fn)}function _(e=Q.homedir()){let t=Te(e),n;try{let r=C.statSync(t);if(process.platform!=="win32"){let o=r.mode&511;if(o&63)throw new Error(`Refusing to read ${t}: permissions are ${o.toString(8)} (should be 600). Run \`chmod 600 ${t}\`.`)}n=C.readFileSync(t,"utf8")}catch(r){if(Nn(r))return null;throw r}try{let r=JSON.parse(n);return typeof r.access_token!="string"?null:r}catch{return null}}function ge(e,t=Q.homedir()){let n=Je(t);if(C.mkdirSync(n,{recursive:!0,mode:448}),process.platform!=="win32")try{C.chmodSync(n,448)}catch{}let r=Te(t);C.writeFileSync(r,`${JSON.stringify(e,null,2)}
23
- `,{mode:384}),process.platform!=="win32"&&C.chmodSync(r,384)}function Ke(e=Q.homedir()){C.rmSync(Te(e),{force:!0})}function We(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT: expected three dot-separated segments");let n=t[1];if(!n)throw new Error("Invalid JWT: empty payload segment");let o=(n+"=".repeat((4-n.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=Buffer.from(o,"base64").toString("utf8");return JSON.parse(s)}function he(e,t=Math.floor(Date.now()/1e3)){return e.expires_at<=t}function Nn(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}var N="0.2.0";var D=class extends Error{constructor(n,r,o){super(r);this.status=n;this.code=o;this.name="HttpError"}},L=class extends Error{constructor(t="Sign in first. Run `gs login`."){super(t),this.name="AuthRequiredError"}};function Dn(e){let t;try{t=new URL(e)}catch{return}let n=t.pathname.split("/").filter(Boolean);if(n[1]==="admin"&&n[0])return n[0];let r=t.hostname.split(".")[0],o=new Set(["my","www","app","api","admin","localhost"]);if(t.hostname.includes(".")&&r&&!o.has(r))return r}function Bn(e){let t=Dn(e)??_()?.store;return t?`gs login --store ${t}`:"gs login"}async function d(e,t={}){let n=()=>`Run \`${Bn(e)}\`.`,r=_();if(!r)throw new L(`Sign in first. ${n()}`);if(he(r))throw new L(`Session expired. ${n()}`);try{return await Hn(e,t,r.access_token)}catch(o){throw o instanceof D&&o.status===401?new L(`Session expired. ${n()}`):o}}async function Hn(e,t,n){let r={accept:"application/json",authorization:`Bearer ${n}`,"x-gs-cli-version":N,...t.headers??{}},o;if(t.multipart&&t.body!==void 0)throw new Error("request(): pass either `body` or `multipart`, not both");t.multipart?(o=t.multipart,delete r["content-type"]):t.body!==void 0&&(o=JSON.stringify(t.body),r["content-type"]="application/json");let s={method:t.method??"GET",headers:r};o!==void 0&&(s.body=o);let i=await fetch(e,s);if(i.status>=200&&i.status<300)return i.status===204?void 0:(i.headers.get("content-type")??"").includes("application/json")?await i.json():await i.text();let a=await i.text(),l={};try{l=JSON.parse(a)}catch{}let c=l.code??l.error,p=t.validationDetail&&i.status===400&&l.error?l.error:Mn(i.status,c,l.detail);throw new D(i.status,p,l.code??l.error)}var Ye=`This version of the GreatStore CLI is no longer supported.
23
+ `,{mode:384}),process.platform!=="win32"&&C.chmodSync(r,384)}function Ke(e=Q.homedir()){C.rmSync(Te(e),{force:!0})}function We(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT: expected three dot-separated segments");let n=t[1];if(!n)throw new Error("Invalid JWT: empty payload segment");let o=(n+"=".repeat((4-n.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=Buffer.from(o,"base64").toString("utf8");return JSON.parse(s)}function he(e,t=Math.floor(Date.now()/1e3)){return e.expires_at<=t}function Nn(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}var N="0.2.1";var D=class extends Error{constructor(n,r,o){super(r);this.status=n;this.code=o;this.name="HttpError"}},L=class extends Error{constructor(t="Sign in first. Run `gs login`."){super(t),this.name="AuthRequiredError"}};function Dn(e){let t;try{t=new URL(e)}catch{return}let n=t.pathname.split("/").filter(Boolean);if(n[1]==="admin"&&n[0])return n[0];let r=t.hostname.split(".")[0],o=new Set(["my","www","app","api","admin","localhost"]);if(t.hostname.includes(".")&&r&&!o.has(r))return r}function Bn(e){let t=Dn(e)??_()?.store;return t?`gs login --store ${t}`:"gs login"}async function d(e,t={}){let n=()=>`Run \`${Bn(e)}\`.`,r=_();if(!r)throw new L(`Sign in first. ${n()}`);if(he(r))throw new L(`Session expired. ${n()}`);try{return await Hn(e,t,r.access_token)}catch(o){throw o instanceof D&&o.status===401?new L(`Session expired. ${n()}`):o}}async function Hn(e,t,n){let r={accept:"application/json",authorization:`Bearer ${n}`,"x-gs-cli-version":N,...t.headers??{}},o;if(t.multipart&&t.body!==void 0)throw new Error("request(): pass either `body` or `multipart`, not both");t.multipart?(o=t.multipart,delete r["content-type"]):t.body!==void 0&&(o=JSON.stringify(t.body),r["content-type"]="application/json");let s={method:t.method??"GET",headers:r};o!==void 0&&(s.body=o);let i=await fetch(e,s);if(i.status>=200&&i.status<300)return i.status===204?void 0:(i.headers.get("content-type")??"").includes("application/json")?await i.json():await i.text();let a=await i.text(),l={};try{l=JSON.parse(a)}catch{}let c=l.code??l.error,p=t.validationDetail&&i.status===400&&l.error?l.error:Mn(i.status,c,l.detail);throw new D(i.status,p,l.code??l.error)}var Ye=`This version of the GreatStore CLI is no longer supported.
24
24
 
25
25
  npm install -g @greatstore/cli@latest
26
26
  `,ze={cli_upgrade_required:{message:Ye},INVALID_NAME:{message:"Invalid component name. Use lowercase letters, digits, and underscores, starting with a letter."},not_found:{message:"Component not found on the server."},concurrent_write:{message:"Another change landed before this one. Run `gs apps pull` and try again."},stale_base:{message:"The store has moved past the version this copy was taken from. Run `gs apps pull` first, or push again with --force to overwrite it.",includeDetail:!0},name_taken:{message:"Another component in this store already has that name."},name_mismatch:{message:"Manifest `name` does not match the component folder name.",includeDetail:!0},manifest_invalid:{message:"manifest.json is invalid.",includeDetail:!0},bundle_too_large:{message:"bundle.js is too large."},bundle_not_module:{message:"bundle.js is not a valid ES module."},source_too_large:{message:"component.tsx is too large."}};function Mn(e,t,n){if(t&&t in ze){let r=ze[t];return r?r.includeDetail&&n?`${r.message} (${n})`:r.message:Xe(e)}return Xe(e)}function Xe(e){return e===401?"Sign-in needed. Run `gs login`.":e===426?Ye:e===403?"Not authorized for this component or store.":e===404?"Not found.":e===409?"Conflict \u2014 refresh and try again.":e===413?"Upload too large.":e===429?"Too many requests \u2014 wait a moment and retry.":e>=500?"Server error \u2014 try again shortly.":e>=400?"Request rejected.":"Unexpected response."}function we(e,t){let n=We(e),r=Qe(n,"sub");if(!r)throw new Error("Token is missing a `sub` claim.");let o=Un(n,"exp");return{access_token:e,expires_at:o??Math.floor(Date.now()/1e3)+3600,sub:r,...ye(n,"email","email"),...ye(n,"accountId","accountId"),...ye(n,"name","name"),...ye(n,"surname","surname"),...Gn(n,"superUser","superUser"),...t?{store:t}:{}}}function Qe(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Un(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ye(e,t,n){let r=Qe(e,t);return r?{[n]:r}:{}}function Gn(e,t,n){let r=e[t];return r===!0?{[n]:!0}:typeof r=="string"&&r.toLowerCase()==="true"?{[n]:!0}:{}}import*as Se from"fs";import*as H from"path";var qn="https://my.greatstore.ai",B=class extends Error{constructor(t){super(t),this.name="StoreResolutionError"}};function $(e={}){let t=Oe(e.cwd??process.cwd());if(t)return ee(t);throw new B("No .gsrc found in this directory or any ancestor. Run `gs apps init --store <slug>` first to scaffold a GreatStore project.")}function Ze(e=process.cwd()){let t=Oe(e);if(t)return ee(t);let n=ce();if(n)return n;throw new B("No store selected. Run `gs login`, or run from a project with a .gsrc.")}function ce(){try{return _()?.store??null}catch{return null}}function ee(e){let t=ce();if(t&&t!==e)throw new B(`This targets store "${e}" but you're signed in to "${t}". Run \`gs switch ${e}\` to change stores.`);return e}function Oe(e){let t=H.resolve(e),n=H.parse(t).root;for(;;){let r=H.join(t,".gsrc");if(Se.existsSync(r))try{let s=Se.readFileSync(r,"utf8"),i=JSON.parse(s);if(typeof i.store=="string"&&i.store.trim())return i.store.trim()}catch{}if(t===n)return null;let o=H.dirname(t);if(o===t)return null;t=o}}function y(e){let t=h(e.flags,"store")?.trim();if(t)return ee(t);let n=Oe(process.cwd());if(n)return ee(n);let r=ce();if(r)return r;throw new B("No store selected. Pass --store <slug>, or run from a project with a .gsrc.")}function x(e,t=process.env){let n=t.GS_API_BASE?.trim();return n?et(n):`https://${e}.greatstore.ai`}function le(e=process.env){let t=e.GS_DASHBOARD_BASE?.trim();return t?et(t):qn}function S(e,t=process.env){return`${le(t)}/${e}/admin`}function et(e){return e.endsWith("/")?e.slice(0,-1):e}async function tt(e){let t=h(e.flags,"store")?.trim();process.stdout.write(`Opening browser for sign-in\u2026
@@ -78,7 +78,7 @@ Examples:
78
78
  gs configure set --theme.fontFamily Manrope --theme.radius sharp
79
79
  gs configure set --theme.brandColor "#1e1d66"
80
80
  gs configure set --theme '{"mode":"dark"}' --replace
81
- `}function pt(e){if(e===void 0||e==="show")return Qn;if(e==="set")return tr()}import*as g from"fs";import*as k from"path";import{readdirSync as Po,readFileSync as $o}from"fs";import{fileURLToPath as Eo}from"url";var ve=null;function dt(){return ve||(ve=JSON.parse('{"component/component.tsx":"import React from \\"react\\";\\n\\n// Add your tool args (matching manifest.json#inputSchema.properties)\\n// alongside the GreatStore-injected lifecycle props. See AGENTS.md for\\n// what each lifecycle prop does.\\ninterface Props {\\n onSendMessage: (text: string) => void;\\n onUpdateModelContext: (context: string) => void;\\n onShowLightbox: (options: { src: string; originRect?: DOMRect }) => void;\\n onClose: () => void;\\n // Ask the store\'s assistant for content matching a JSON Schema (or Zod\\n // schema) \u2014 the app\'s own catalog-grounded generation, for recommended\\n // picks or a personalized summary. Resolves to the generated object.\\n // `fallback` is a required, schema-shaped stand-in rendered in the app\\n // preview (and validated against the schema). See AGENTS.md.\\n onGenerateStructuredContent: <T = unknown>(\\n schema: object,\\n prompt: string,\\n fallback: T,\\n ) => Promise<T>;\\n // Drop-in for <img>: `<Image src=\u2026 alt=\u2026 />`. See AGENTS.md.\\n Image: React.ElementType<React.ComponentProps<\\"img\\">>;\\n}\\n\\n// See AGENTS.md for how an app runs (the assistant picks it by the\\n// manifest\'s name and description, then calls it with these props), the\\n// design rules (em-based sizing, brand CSS variables), and how to write an\\n// async, backend-backed app.\\nexport default function Component(_props: Props): React.ReactElement {\\n return (\\n <div\\n style={{\\n padding: \\"1em\\",\\n border: \\"1px solid var(--color-border-default)\\",\\n borderRadius: \\"var(--radius-lg)\\",\\n background: \\"var(--color-surface)\\",\\n color: \\"var(--color-foreground)\\",\\n fontFamily: \\"var(--font-primary)\\",\\n }}\\n >\\n <strong>__GS_NAME__</strong> \u2014 hello from your app!\\n </div>\\n );\\n}\\n","component/manifest.json":"{\\n \\"name\\": \\"__GS_NAME__\\",\\n \\"displayName\\": \\"__GS_DISPLAY_NAME__\\",\\n \\"description\\": \\"Use when <the shopper situation that should make the assistant open this app \u2014 say when to reach for it and what it reports back, never what it looks like; see AGENTS.md>.\\",\\n \\"displayMode\\": \\"inline\\",\\n \\"async\\": false,\\n \\"inputSchema\\": {\\n \\"type\\": \\"object\\",\\n \\"properties\\": {}\\n }\\n}\\n","root/.gitignore":"node_modules/\\ncomponents/*/bundle.js\\ncomponents/*/.gssync.json\\n*.tsbuildinfo\\n.DS_Store\\n","root/.gsrc":"{\\n \\"store\\": \\"__GS_STORE__\\"\\n}\\n","root/AGENTS.md":"# AGENTS.md\\n\\n> **Do not edit \u2014 auto-generated by the GreatStore CLI v__GS_VERSION__.**\\n> This file is rewritten by `gs apps init`, so any changes you make here\\n> will be overwritten. If this version trails your installed CLI, re-run\\n> `gs apps init` to refresh it. Put project-specific notes in another file.\\n\\nGuidance for AI coding agents working on the apps in this project.\\n`CLAUDE.md` and `GEMINI.md` are symlinks to this file.\\n\\nAn app is interactive UI the store\'s assistant renders inside the\\nconversation \u2014 a configurator, a quiz, a size guide, a booking form. You\\nwrite it in React; each app is one folder under `components/`, holding\\n`manifest.json` and `component.tsx`.\\n\\nApps render inside arbitrary publisher websites (the embed widget mounts\\non a host page) as well as the GreatStore storefront. You control neither\\nthe host page\'s base font size nor its color scheme, and the store owner\\ncontrols the look from GreatStore theme settings. The rules below keep\\napps portable across both.\\n\\n## How an app runs\\n\\nAn app is not a page the shopper navigates to. It is a tool the assistant\\ncalls mid-conversation, and once it is on screen it can talk back \u2014 which\\nis the part that makes apps worth building.\\n\\n```\\nShopper Assistant Your app\\n \u2502 \u2502 \u2502\\n \u2502 \\"what size am I?\\" \u2502 \u2502\\n \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\u2502 \u2502\\n \u2502 \u2502 picks the app by its \u2502\\n \u2502 \u2502 name + description \u2502\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 calls it with props \u2502\\n \u2502 \u2502 your inputSchema asked \u2502\\n \u2502 \u2502 for (productName, \u2026) \u2502\\n \u2502 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\u2502\\n \u2502 \u2502 \u251C\u2500\u2500\u2510 onGenerateStructured-\\n \u2502 \u2502 \u2502 \u2502 Content(): its own\\n \u2502 \u2502 \u2502 \u2502 catalog-grounded\\n \u2502 \u2502 \u2502<\u2500\u2518 generation, if wanted\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 \u2502 renders the moment your\\n \u2502 \u2502 \u2502 happy path has what it\\n \u2502 \u2502 \u2502 needs (async: after your\\n \u2502<\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 promise resolves)\\n \u2502 sees the app \u2502 \u2502\\n \u2502 \u2502 \u2502\\n \u2502 picks size M \u2502 \u2502\\n \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\u2502\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 onUpdateModelContext() \u2502 silent: the assistant\\n \u2502 \u2502<\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 now knows the pick\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 onSendMessage() \u2502 visible: a shopper turn\\n \u2502 \u2502<\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 happens right now\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 calls the app again \u2502 same app, new props \u2014\\n \u2502 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\u2502 re-rendered in place\\n \u2502 \u2502 \u2502\\n```\\n\\nFour consequences worth designing around:\\n\\n1. **The assistant chooses the app, so `manifest.json` is the interface it\\n sees** \u2014 see the next section.\\n2. **Control is bidirectional once the app is up.** The app reports what\\n the shopper is doing (`onUpdateModelContext`), can speak for the\\n shopper (`onSendMessage`), and the assistant can call the app again\\n with revised props. Keep the render a function of the props it was\\n given, so a re-call is a re-render rather than a reset.\\n3. **The app can run its own generation, not just receive props.**\\n `onGenerateStructuredContent` returns a catalog-grounded,\\n shopper-personalized object matching your schema \u2014 recommended picks, a\\n personalized summary, a reason per option \u2014 which you render in your\\n own markup.\\n4. **Render on the happy path, not on a shell.** Whatever the app needs to\\n be correct \u2014 props, or awaited data in an async app \u2014 should be there\\n before anything paints; GreatStore owns the loading state.\\n\\n## `manifest.json` \u2014 the name and description decide whether your app runs\\n\\nThe assistant never sees your app. It sees a name and a sentence, next to\\nevery other tool it has, and picks one. Write the description for that\\n*caller*, answering one question: when should I reach for this, and what\\ndo I get back?\\n\\n**Describing the UI is the most common mistake.** Layout, sliders, tabs,\\ncarousels and colors are the shopper\'s concern. To the assistant they are\\nnoise \u2014 they say nothing about when to call the tool.\\n\\n| Don\'t | Do |\\n| --- | --- |\\n| \\"Renders a two-column table of measurements with a unit toggle.\\" | \\"Use when a shopper is unsure which size to buy or asks how an item fits.\\" |\\n| \\"A carousel of product cards with images and prices.\\" | \\"Use to show 2\u20138 specific products you have already chosen, when the shopper wants to see them side by side before deciding.\\" |\\n| \\"Modal with a multi-step form and a progress bar.\\" | \\"Use when the shopper wants a gift but can\'t say what \u2014 collects budget, recipient and occasion, then reports them back so you can recommend.\\" |\\n\\nWhat belongs in a description, in this order:\\n\\n1. **The trigger** \u2014 the shopper situation or intent, in the words a\\n shopper would actually use. Start with `Use when \u2026`.\\n2. **The boundary** \u2014 when *not* to, if another tool overlaps. One clause\\n is enough: \\"Use for in-store appointments; not for delivery scheduling.\\"\\n3. **What the assistant gets back** \u2014 if the app reports state or sends\\n messages, say so: \\"reports the size the shopper settles on back to you.\\"\\n\\nOne or two sentences. If a required `inputSchema` field is subtle, say\\nwhat it means here rather than trusting the schema alone.\\n\\nThe same rule governs the **name** (snake_case, matching the folder under\\n`components/`): name it after the job, not the widget. `size_guide`,\\n`gift_finder`, `book_appointment` read as intents; `size_modal`,\\n`quiz_ui`, `product_grid_v2` read as implementation details and get\\nskipped. `displayName` is the one field written for the shopper.\\n\\nKeep `inputSchema` tight: required fields the assistant can\'t infer from\\nthe conversation cause bad calls.\\n\\n## Design requirements\\n\\n### Never use `rem` for fonts and sizing \u2014 always use `em`\\n\\n`rem` resolves against the host page\'s root font size, which is\\narbitrary and outside our control. A host that sets `html { font-size:\\n8px }` (or 200%) will shrink or blow up every `rem`-based dimension.\\n`em` resolves against the app\'s own font size, so it stays\\nself-consistent wherever the app is mounted.\\n\\nUse `em` for font sizes, padding, margins, gaps, widths, heights,\\nand any other length. Borders may stay in `px` (hairlines should not\\nscale with text).\\n\\n```tsx\\n// Bad \u2014 breaks on hosts with a non-default root font size\\n<div style={{ padding: \\"1rem\\", fontSize: \\"0.875rem\\" }} />\\n\\n// Good\\n<div style={{ padding: \\"1em\\", fontSize: \\"0.875em\\" }} />\\n```\\n\\n### Don\'t hardcode colors, fonts, or corner radius \u2014 use GreatStore brand variables\\n\\nThe store owner themes the assistant from GreatStore settings. Hardcoded\\nvalues ignore that and make the app clash with the rest of the store.\\nRead from the CSS variables GreatStore injects on the surface instead, so\\nthe app restyles itself when the theme changes.\\n\\nAvailable variables:\\n\\n| Purpose | Variable |\\n| --- | --- |\\n| Surface background | `--color-surface` |\\n| Secondary surface | `--color-surface-secondary` |\\n| Accent surface | `--color-surface-accent` |\\n| Hover surface | `--color-surface-hover` |\\n| Foreground text | `--color-foreground` |\\n| Secondary text | `--color-foreground-secondary` |\\n| Muted text | `--color-foreground-muted` |\\n| Accent text | `--color-foreground-accent` |\\n| Border | `--color-border-default` |\\n| Focus border | `--color-border-focus` |\\n| Primary / brand | `--color-primary` |\\n| Text on primary | `--color-primary-foreground` |\\n| Primary hover | `--color-primary-hover` |\\n| Primary muted | `--color-primary-muted` |\\n| Text on primary muted | `--color-primary-muted-foreground` |\\n| Primary tint | `--color-primary-tint` |\\n| Link | `--color-link` |\\n| Font family | `--font-primary` |\\n| Secondary font family | `--font-secondary` |\\n| Corner radius (scale) | `--radius-xs` \u2026 `--radius-4xl`, `--radius-pill` |\\n\\nThe store owner can set a secondary font family in their GreatStore\\ntheme settings, exposed as `--font-secondary` (it falls back to\\n`--font-primary` when unset). Reach for it to add a tasteful second\\nlayer of typography \u2014 pair `--font-primary` for body copy with\\n`--font-secondary` for headings, prices, or other accents \u2014 so the app\\nreflects the store\'s full type system instead of a single face.\\n\\n```tsx\\n// Bad \u2014 hardcoded, ignores the store\'s theme\\n<button style={{ background: \\"#4f46e5\\", borderRadius: 8, fontFamily: \\"Inter\\" }} />\\n\\n// Good\\n<button\\n style={{\\n background: \\"var(--color-primary)\\",\\n color: \\"var(--color-primary-foreground)\\",\\n borderRadius: \\"var(--radius-lg)\\",\\n fontFamily: \\"var(--font-primary)\\",\\n }}\\n/>\\n```\\n\\nProvide a sensible fallback only when a value might be absent, e.g.\\n`var(--color-primary, currentColor)`.\\n\\n## App props\\n\\nEach app receives its tool args (the fields you declare in\\n`manifest.json#inputSchema.properties`) plus these GreatStore-injected\\nlifecycle props, which are always present:\\n\\n| Prop | What it does |\\n| --- | --- |\\n| `onSendMessage(text)` | Send text into the chat as if the shopper typed it. |\\n| `onUpdateModelContext(context)` | Inject invisible background context for the model (selected variant, configured options, current step). Replaces the prior value \u2014 never appends; pass `\\"\\"` to clear. Read on the next chat turn. Use it when the assistant should *know* in-app state without a visible message; use `onSendMessage` when you want a turn to happen now. |\\n| `onShowLightbox({ src, originRect? })` | Expand an image in the chat\'s shared full-screen lightbox \u2014 an on-brand zoom overlay your app can\'t render itself (it\'s boxed inside its own bounds and shadow root). Pass the image `src`; for a smooth zoom, also pass the clicked element\'s `getBoundingClientRect()` as `originRect` (omit it and the image grows from the viewport centre). |\\n| `onGenerateStructuredContent(schema, prompt, fallback)` | Ask the store\'s assistant for content matching a JSON Schema (or a Zod schema); resolves to the generated object. Personalized to the shopper. Works the same in the conversation on the storefront and every embed. Best inside an async app that builds its render from the generated payload \u2014 `await` it, then return the JSX. `fallback` is **required**: a schema-shaped object you supply that the app preview renders (so a generation-driven app previews without a live store). It\'s validated against the schema and throws if the two don\'t line up. |\\n| `onClose()` | Dismiss the host slot. Over-input clears the overlay, fullscreen reverts the pane, inline is a no-op. |\\n| `Image` | A drop-in for `<img>`: render `<Image src=\u2026 alt=\u2026 />` instead of `<img>` and your images are automatically served at the right size for the store. Takes the same props as `<img>` (`src`, `alt`, `style`, `loading`, `onClick`, \u2026). Previewing the app outside the store? Pass `Image={\\"img\\"}` (or your own component) to render a plain image. |\\n\\n## Async apps (backend-backed, render-blocking data)\\n\\nIf an app must load data from a backend/API before it can render\\ncorrectly, make it async \u2014 don\'t render an empty shell and fetch in a\\n`useEffect`. Set `\\"async\\": true` in `manifest.json` and export an async\\ndefault. GreatStore waits for your promise (showing a normal loading\\nstate, so you don\'t render your own placeholder), then renders what it\\nresolves to. Apps that render purely from their props stay synchronous.\\n\\nA thrown error is a **retry signal**: the in-store AI sees it and\\nusually re-calls the tool. So only throw when a *different* call could\\nhelp:\\n\\n1. `await` the backend call, then return the finished JSX.\\n2. Validate the AI-passed props first and throw on bad input \u2014 the AI\\n can fix the args and retry. (Don\'t validate the API\'s *output* and\\n throw: the AI can\'t fix the backend, it\'ll just loop.)\\n3. Broadcast a backend failure ONLY when retrying differently could\\n succeed, and say what to change (e.g. empty search \u2192 \\"try a broader\\n keyword\\"). For idempotent failures (500, timeout, missing record)\\n re-running the same call changes nothing \u2014 render a graceful fallback\\n instead of throwing.\\n\\n```tsx\\nexport default async function Example(props: Props) {\\n if (!props.query?.trim()) throw new Error(\\"missing required prop: query\\");\\n const res = await fetch(`/api/search?q=${encodeURIComponent(props.query)}`);\\n if (res.ok) {\\n const { results } = await res.json();\\n if (results.length === 0)\\n throw new Error(`no results for \\"${props.query}\\" \u2014 try a broader keyword`);\\n return <ul>{/* render results */}</ul>;\\n }\\n return <p>Couldn\'t load results right now.</p>; // idempotent: don\'t throw\\n}\\n```\\n","root/README.md":"# GreatStore apps\\n\\nCustom in-chat apps published to your GreatStore tenant. Each app is a\\nReact component living in its own folder under `components/`.\\n\\n```\\nnpm install\\ngs apps init <app_name> # add a new app\\ngs apps build # builds every components/<name>/bundle.js\\ngs apps push # uploads every changed app as a draft\\ngs apps publish <app_name> # promote a specific app to live\\n```\\n\\n- `gs apps push` (no args) hashes each app and only uploads the ones that\\n have changed since the last sync.\\n- `gs apps pull` (no args) refreshes every live app into\\n `components/<name>/`. Apps with unsaved local edits are skipped with a\\n warning; pass `--force` to overwrite.\\n\\nSee `AGENTS.md` for how an app runs, how to write a manifest name and\\ndescription the assistant will actually pick, and the design rules every\\napp must follow (em-based sizing, brand CSS variables) \u2014 it doubles as\\nguidance for AI coding agents (`CLAUDE.md` / `GEMINI.md` symlink to it).\\n","root/package.json":"{\\n \\"name\\": \\"greatstore-components\\",\\n \\"version\\": \\"0.0.1\\",\\n \\"private\\": true,\\n \\"type\\": \\"module\\",\\n \\"scripts\\": {\\n \\"build\\": \\"gs apps build\\",\\n \\"push\\": \\"gs apps build && gs apps push\\"\\n },\\n \\"dependencies\\": {\\n \\"react\\": \\"^19.0.0\\",\\n \\"react-dom\\": \\"^19.0.0\\"\\n },\\n \\"devDependencies\\": {\\n \\"@types/react\\": \\"^19.0.0\\",\\n \\"@types/react-dom\\": \\"^19.0.0\\",\\n \\"@vitejs/plugin-react\\": \\"^4.3.0\\",\\n \\"typescript\\": \\"^5.6.0\\",\\n \\"vite\\": \\"^5.4.0\\"\\n }\\n}\\n","root/tsconfig.json":"{\\n \\"compilerOptions\\": {\\n \\"target\\": \\"ES2022\\",\\n \\"module\\": \\"ESNext\\",\\n \\"moduleResolution\\": \\"Bundler\\",\\n \\"jsx\\": \\"react-jsx\\",\\n \\"lib\\": [\\"ES2022\\", \\"DOM\\"],\\n \\"strict\\": true,\\n \\"esModuleInterop\\": true,\\n \\"skipLibCheck\\": true,\\n \\"isolatedModules\\": true,\\n \\"noEmit\\": true\\n },\\n \\"include\\": [\\"components/**/component.tsx\\", \\"vite.config.ts\\"]\\n}\\n","root/vite.config.ts":"import { defineConfig } from \\"vite\\";\\nimport react from \\"@vitejs/plugin-react\\";\\n\\n// Real builds happen in `gs build` (one Vite invocation per\\n// component, externals + runtime shim paths owned by the CLI). This\\n// file exists only so editors / language servers can resolve the\\n// React plugin when inspecting components/*/component.tsx.\\nexport default defineConfig({\\n plugins: [react()],\\n});\\n"}'),ve)}var ft={name:"__GS_NAME__",displayName:"__GS_DISPLAY_NAME__",store:"__GS_STORE__",version:"__GS_VERSION__"};function mt(e,t){let n=e;for(let o of Object.keys(ft)){let s=t[o];s!==void 0&&(n=n.split(ft[o]).join(s))}let r=n.match(/__GS_[A-Z_]+__/);if(r)throw new Error(`internal: template placeholder ${r[0]} was not provided`);return n}var gt=/^[a-z][a-z0-9_]*$/;function yt(e){let t=e.positional[0];if(t!==void 0&&!gt.test(t))throw new Error(`Invalid component name: "${t}" (must match ${gt}).`);let n=m(e.flags,"force"),r=h(e.flags,"store"),o=h(e.flags,"out")??".",s=k.resolve(o),i=nr(s),a;if(i){if(r!==void 0)throw new Error(`Project at ${s} is already pinned to a store via .gsrc. Drop --store; a project folder ships to exactly one store.`);$({cwd:s})}else if(a=r!==void 0?ee(r):ce()??void 0,a===void 0){let u=t?`gs apps init ${t} --store <slug>`:"gs apps init --store <slug>";throw new Error(`--store <slug> is required when scaffolding a new project root. Run \`${u}\`.`)}let l=rr(s,i,n,{store:a});if(!t){let u=[];i?(u.push(`Updated GreatStore project root in ${s}.`),l.length>0?u.push("",`Added: ${l.join(", ")}`):u.push("","Already up to date \u2014 nothing to add.")):u.push(`Scaffolded GreatStore project root in ${s}.`),u.push("","Next steps:",` cd ${k.relative(process.cwd(),s)||"."}`," npm install"," gs apps init <component_name> # add your first component",""),process.stdout.write(u.join(`
81
+ `}function pt(e){if(e===void 0||e==="show")return Qn;if(e==="set")return tr()}import*as g from"fs";import*as k from"path";import{readdirSync as Po,readFileSync as $o}from"fs";import{fileURLToPath as Eo}from"url";var ve=null;function dt(){return ve||(ve=JSON.parse('{"component/component.tsx":"import React from \\"react\\";\\n\\n// Add your tool args (matching manifest.json#inputSchema.properties)\\n// alongside the GreatStore-injected lifecycle props. See AGENTS.md for\\n// what each lifecycle prop does.\\ninterface Props {\\n onSendMessage: (text: string) => void;\\n onUpdateModelContext: (context: string) => void;\\n onShowLightbox: (options: { src: string; originRect?: DOMRect }) => void;\\n onClose: () => void;\\n // Ask the store\'s assistant for content matching a JSON Schema (or Zod\\n // schema) \u2014 the app\'s own catalog-grounded generation, for recommended\\n // picks or a personalized summary. Resolves to the generated object.\\n // `fallback` is a required, schema-shaped stand-in rendered in the app\\n // preview (and validated against the schema). See AGENTS.md.\\n onGenerateStructuredContent: <T = unknown>(\\n schema: object,\\n prompt: string,\\n fallback: T,\\n ) => Promise<T>;\\n // Drop-in for <img>: `<Image src=\u2026 alt=\u2026 />`. See AGENTS.md.\\n Image: React.ElementType<React.ComponentProps<\\"img\\">>;\\n}\\n\\n// See AGENTS.md for how an app runs (the assistant picks it by the\\n// manifest\'s name and description, then calls it with these props), the\\n// design rules (em-based sizing, brand CSS variables), and how to write an\\n// async, backend-backed app.\\nexport default function Component(_props: Props): React.ReactElement {\\n return (\\n <div\\n style={{\\n padding: \\"1em\\",\\n border: \\"1px solid var(--color-border-default)\\",\\n borderRadius: \\"var(--radius-lg)\\",\\n background: \\"var(--color-surface)\\",\\n color: \\"var(--color-foreground)\\",\\n fontFamily: \\"var(--font-primary)\\",\\n }}\\n >\\n <strong>__GS_NAME__</strong> \u2014 hello from your app!\\n </div>\\n );\\n}\\n","component/manifest.json":"{\\n \\"name\\": \\"__GS_NAME__\\",\\n \\"displayName\\": \\"__GS_DISPLAY_NAME__\\",\\n \\"description\\": \\"Use when <the shopper situation that should make the assistant open this app \u2014 say when to reach for it and what it reports back, never what it looks like; see AGENTS.md>.\\",\\n \\"displayMode\\": \\"inline\\",\\n \\"async\\": false,\\n \\"inputSchema\\": {\\n \\"type\\": \\"object\\",\\n \\"properties\\": {}\\n }\\n}\\n","root/.gitignore":"node_modules/\\ncomponents/*/bundle.js\\ncomponents/*/.gssync.json\\n*.tsbuildinfo\\n.DS_Store\\n","root/.gsrc":"{\\n \\"store\\": \\"__GS_STORE__\\"\\n}\\n","root/AGENTS.md":"# AGENTS.md\\n\\n> **Do not edit \u2014 auto-generated by the GreatStore CLI v__GS_VERSION__.**\\n> This file is rewritten by `gs apps init`, so any changes you make here\\n> will be overwritten. If this version trails your installed CLI, re-run\\n> `gs apps init` to refresh it. Put project-specific notes in another file.\\n\\nGuidance for AI coding agents working on the apps in this project.\\n`CLAUDE.md` and `GEMINI.md` are symlinks to this file.\\n\\nAn app is interactive UI the store\'s assistant renders inside the\\nconversation \u2014 a configurator, a quiz, a size guide, a booking form. You\\nwrite it in React; each app is one folder under `components/`, holding\\n`manifest.json` and `component.tsx`.\\n\\nApps render inside arbitrary publisher websites (the embed widget mounts\\non a host page) as well as the GreatStore storefront. You control neither\\nthe host page\'s base font size nor its color scheme, and the store owner\\ncontrols the look from GreatStore theme settings. The rules below keep\\napps portable across both.\\n\\n## How an app runs\\n\\nAn app is not a page the shopper navigates to. It is a tool the assistant\\ncalls mid-conversation, and once it is on screen it can talk back \u2014 which\\nis the part that makes apps worth building.\\n\\n```\\nShopper Assistant Your app\\n \u2502 \u2502 \u2502\\n \u2502 \\"what size am I?\\" \u2502 \u2502\\n \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\u2502 \u2502\\n \u2502 \u2502 picks the app by its \u2502\\n \u2502 \u2502 name + description \u2502\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 calls it with props \u2502\\n \u2502 \u2502 your inputSchema asked \u2502\\n \u2502 \u2502 for (productName, \u2026) \u2502\\n \u2502 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\u2502\\n \u2502 \u2502 \u251C\u2500\u2500\u2510 onGenerateStructured-\\n \u2502 \u2502 \u2502 \u2502 Content(): its own\\n \u2502 \u2502 \u2502 \u2502 catalog-grounded\\n \u2502 \u2502 \u2502<\u2500\u2518 generation, if wanted\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 \u2502 renders the moment your\\n \u2502 \u2502 \u2502 happy path has what it\\n \u2502 \u2502 \u2502 needs (async: after your\\n \u2502<\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 promise resolves)\\n \u2502 sees the app \u2502 \u2502\\n \u2502 \u2502 \u2502\\n \u2502 picks size M \u2502 \u2502\\n \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\u2502\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 onUpdateModelContext() \u2502 silent: the assistant\\n \u2502 \u2502<\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 now knows the pick\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 onSendMessage() \u2502 visible: a shopper turn\\n \u2502 \u2502<\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 happens right now\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 calls the app again \u2502 same app, new props \u2014\\n \u2502 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\u2502 re-rendered in place\\n \u2502 \u2502 \u2502\\n```\\n\\nFour consequences worth designing around:\\n\\n1. **The assistant chooses the app, so `manifest.json` is the interface it\\n sees** \u2014 see the next section.\\n2. **Control is bidirectional once the app is up.** The app reports what\\n the shopper is doing (`onUpdateModelContext`), can speak for the\\n shopper (`onSendMessage`), and the assistant can call the app again\\n with revised props. Keep the render a function of the props it was\\n given, so a re-call is a re-render rather than a reset.\\n3. **The app can run its own generation, not just receive props.**\\n `onGenerateStructuredContent` returns a catalog-grounded,\\n shopper-personalized object matching your schema \u2014 recommended picks, a\\n personalized summary, a reason per option \u2014 which you render in your\\n own markup.\\n4. **Render on the happy path, not on a shell.** Whatever the app needs to\\n be correct \u2014 props, or awaited data in an async app \u2014 should be there\\n before anything paints; GreatStore owns the loading state.\\n\\n## `manifest.json` \u2014 the name and description decide whether your app runs\\n\\nThe assistant never sees your app. It sees a name and a sentence, next to\\nevery other tool it has, and picks one. Write the description for that\\n*caller*, answering one question: when should I reach for this, and what\\ndo I get back?\\n\\n**Describing the UI is the most common mistake.** Layout, sliders, tabs,\\ncarousels and colors are the shopper\'s concern. To the assistant they are\\nnoise \u2014 they say nothing about when to call the tool.\\n\\n| Don\'t | Do |\\n| --- | --- |\\n| \\"Renders a two-column table of measurements with a unit toggle.\\" | \\"Use when a shopper is unsure which size to buy or asks how an item fits.\\" |\\n| \\"A carousel of product cards with images and prices.\\" | \\"Use to show 2\u20138 specific products you have already chosen, when the shopper wants to see them side by side before deciding.\\" |\\n| \\"Modal with a multi-step form and a progress bar.\\" | \\"Use when the shopper wants a gift but can\'t say what \u2014 collects budget, recipient and occasion, then reports them back so you can recommend.\\" |\\n\\nWhat belongs in a description, in this order:\\n\\n1. **The trigger** \u2014 the shopper situation or intent, in the words a\\n shopper would actually use. Start with `Use when \u2026`.\\n2. **The boundary** \u2014 when *not* to, if another tool overlaps. One clause\\n is enough: \\"Use for in-store appointments; not for delivery scheduling.\\"\\n3. **What the assistant gets back** \u2014 if the app reports state or sends\\n messages, say so: \\"reports the size the shopper settles on back to you.\\"\\n\\nOne or two sentences. If a required `inputSchema` field is subtle, say\\nwhat it means here rather than trusting the schema alone.\\n\\nThe same rule governs the **name** (snake_case, matching the folder under\\n`components/`): name it after the job, not the widget. `size_guide`,\\n`gift_finder`, `book_appointment` read as intents; `size_modal`,\\n`quiz_ui`, `product_grid_v2` read as implementation details and get\\nskipped. `displayName` is the one field written for the shopper.\\n\\nKeep `inputSchema` tight: required fields the assistant can\'t infer from\\nthe conversation cause bad calls.\\n\\n## Design requirements\\n\\n### Never use `rem` for fonts and sizing \u2014 always use `em`\\n\\n`rem` resolves against the host page\'s root font size, which is\\narbitrary and outside our control. A host that sets `html { font-size:\\n8px }` (or 200%) will shrink or blow up every `rem`-based dimension.\\n`em` resolves against the app\'s own font size, so it stays\\nself-consistent wherever the app is mounted.\\n\\nUse `em` for font sizes, padding, margins, gaps, widths, heights,\\nand any other length. Borders may stay in `px` (hairlines should not\\nscale with text).\\n\\n```tsx\\n// Bad \u2014 breaks on hosts with a non-default root font size\\n<div style={{ padding: \\"1rem\\", fontSize: \\"0.875rem\\" }} />\\n\\n// Good\\n<div style={{ padding: \\"1em\\", fontSize: \\"0.875em\\" }} />\\n```\\n\\n### Fullscreen apps must leave a safe-zone at the bottom\\n\\nOn the storefront the chat widget floats over the bottom of the screen, so\\nanything a `fullscreen` app renders there can be covered by it. Reserve a\\nsafe-zone of `6.25em` (100px at the default font size) at the bottom of the\\napp\'s scrolling content \u2014 e.g. `padding-bottom: 6.25em` on the scroll\\ncontainer \u2014 so the last row, button, or link can always be scrolled clear of\\nthe widget. Inline and over-input apps don\'t need it.\\n\\n### Don\'t hardcode colors, fonts, or corner radius \u2014 use GreatStore brand variables\\n\\nThe store owner themes the assistant from GreatStore settings. Hardcoded\\nvalues ignore that and make the app clash with the rest of the store.\\nRead from the CSS variables GreatStore injects on the surface instead, so\\nthe app restyles itself when the theme changes.\\n\\nAvailable variables:\\n\\n| Purpose | Variable |\\n| --- | --- |\\n| Surface background | `--color-surface` |\\n| Secondary surface | `--color-surface-secondary` |\\n| Accent surface | `--color-surface-accent` |\\n| Hover surface | `--color-surface-hover` |\\n| Foreground text | `--color-foreground` |\\n| Secondary text | `--color-foreground-secondary` |\\n| Muted text | `--color-foreground-muted` |\\n| Accent text | `--color-foreground-accent` |\\n| Border | `--color-border-default` |\\n| Focus border | `--color-border-focus` |\\n| Primary / brand | `--color-primary` |\\n| Text on primary | `--color-primary-foreground` |\\n| Primary hover | `--color-primary-hover` |\\n| Primary muted | `--color-primary-muted` |\\n| Text on primary muted | `--color-primary-muted-foreground` |\\n| Primary tint | `--color-primary-tint` |\\n| Link | `--color-link` |\\n| Font family | `--font-primary` |\\n| Secondary font family | `--font-secondary` |\\n| Corner radius (scale) | `--radius-xs` \u2026 `--radius-4xl`, `--radius-pill` |\\n\\nThe store owner can set a secondary font family in their GreatStore\\ntheme settings, exposed as `--font-secondary` (it falls back to\\n`--font-primary` when unset). Reach for it to add a tasteful second\\nlayer of typography \u2014 pair `--font-primary` for body copy with\\n`--font-secondary` for headings, prices, or other accents \u2014 so the app\\nreflects the store\'s full type system instead of a single face.\\n\\n```tsx\\n// Bad \u2014 hardcoded, ignores the store\'s theme\\n<button style={{ background: \\"#4f46e5\\", borderRadius: 8, fontFamily: \\"Inter\\" }} />\\n\\n// Good\\n<button\\n style={{\\n background: \\"var(--color-primary)\\",\\n color: \\"var(--color-primary-foreground)\\",\\n borderRadius: \\"var(--radius-lg)\\",\\n fontFamily: \\"var(--font-primary)\\",\\n }}\\n/>\\n```\\n\\nProvide a sensible fallback only when a value might be absent, e.g.\\n`var(--color-primary, currentColor)`.\\n\\n## App props\\n\\nEach app receives its tool args (the fields you declare in\\n`manifest.json#inputSchema.properties`) plus these GreatStore-injected\\nlifecycle props, which are always present:\\n\\n| Prop | What it does |\\n| --- | --- |\\n| `onSendMessage(text)` | Send text into the chat as if the shopper typed it. |\\n| `onUpdateModelContext(context)` | Inject invisible background context for the model (selected variant, configured options, current step). Replaces the prior value \u2014 never appends; pass `\\"\\"` to clear. Read on the next chat turn. Use it when the assistant should *know* in-app state without a visible message; use `onSendMessage` when you want a turn to happen now. |\\n| `onShowLightbox({ src, originRect? })` | Expand an image in the chat\'s shared full-screen lightbox \u2014 an on-brand zoom overlay your app can\'t render itself (it\'s boxed inside its own bounds and shadow root). Pass the image `src`; for a smooth zoom, also pass the clicked element\'s `getBoundingClientRect()` as `originRect` (omit it and the image grows from the viewport centre). |\\n| `onGenerateStructuredContent(schema, prompt, fallback)` | Ask the store\'s assistant for content matching a JSON Schema (or a Zod schema); resolves to the generated object. Personalized to the shopper. Works the same in the conversation on the storefront and every embed. Best inside an async app that builds its render from the generated payload \u2014 `await` it, then return the JSX. `fallback` is **required**: a schema-shaped object you supply that the app preview renders (so a generation-driven app previews without a live store). It\'s validated against the schema and throws if the two don\'t line up. |\\n| `onClose()` | Dismiss the host slot. Over-input clears the overlay, fullscreen reverts the pane, inline is a no-op. |\\n| `Image` | A drop-in for `<img>`: render `<Image src=\u2026 alt=\u2026 />` instead of `<img>` and your images are automatically served at the right size for the store. Takes the same props as `<img>` (`src`, `alt`, `style`, `loading`, `onClick`, \u2026). Previewing the app outside the store? Pass `Image={\\"img\\"}` (or your own component) to render a plain image. |\\n\\n## Async apps (backend-backed, render-blocking data)\\n\\nIf an app must load data from a backend/API before it can render\\ncorrectly, make it async \u2014 don\'t render an empty shell and fetch in a\\n`useEffect`. Set `\\"async\\": true` in `manifest.json` and export an async\\ndefault. GreatStore waits for your promise (showing a normal loading\\nstate, so you don\'t render your own placeholder), then renders what it\\nresolves to. Apps that render purely from their props stay synchronous.\\n\\nA thrown error is a **retry signal**: the in-store AI sees it and\\nusually re-calls the tool. So only throw when a *different* call could\\nhelp:\\n\\n1. `await` the backend call, then return the finished JSX.\\n2. Validate the AI-passed props first and throw on bad input \u2014 the AI\\n can fix the args and retry. (Don\'t validate the API\'s *output* and\\n throw: the AI can\'t fix the backend, it\'ll just loop.)\\n3. Broadcast a backend failure ONLY when retrying differently could\\n succeed, and say what to change (e.g. empty search \u2192 \\"try a broader\\n keyword\\"). For idempotent failures (500, timeout, missing record)\\n re-running the same call changes nothing \u2014 render a graceful fallback\\n instead of throwing.\\n\\n```tsx\\nexport default async function Example(props: Props) {\\n if (!props.query?.trim()) throw new Error(\\"missing required prop: query\\");\\n const res = await fetch(`/api/search?q=${encodeURIComponent(props.query)}`);\\n if (res.ok) {\\n const { results } = await res.json();\\n if (results.length === 0)\\n throw new Error(`no results for \\"${props.query}\\" \u2014 try a broader keyword`);\\n return <ul>{/* render results */}</ul>;\\n }\\n return <p>Couldn\'t load results right now.</p>; // idempotent: don\'t throw\\n}\\n```\\n","root/README.md":"# GreatStore apps\\n\\nCustom in-chat apps published to your GreatStore tenant. Each app is a\\nReact component living in its own folder under `components/`.\\n\\n```\\nnpm install\\ngs apps init <app_name> # add a new app\\ngs apps build # builds every components/<name>/bundle.js\\ngs apps push # uploads every changed app as a draft\\ngs apps publish <app_name> # promote a specific app to live\\n```\\n\\n- `gs apps push` (no args) hashes each app and only uploads the ones that\\n have changed since the last sync.\\n- `gs apps pull` (no args) refreshes every live app into\\n `components/<name>/`. Apps with unsaved local edits are skipped with a\\n warning; pass `--force` to overwrite.\\n\\nSee `AGENTS.md` for how an app runs, how to write a manifest name and\\ndescription the assistant will actually pick, and the design rules every\\napp must follow (em-based sizing, brand CSS variables) \u2014 it doubles as\\nguidance for AI coding agents (`CLAUDE.md` / `GEMINI.md` symlink to it).\\n","root/package.json":"{\\n \\"name\\": \\"greatstore-components\\",\\n \\"version\\": \\"0.0.1\\",\\n \\"private\\": true,\\n \\"type\\": \\"module\\",\\n \\"scripts\\": {\\n \\"build\\": \\"gs apps build\\",\\n \\"push\\": \\"gs apps build && gs apps push\\"\\n },\\n \\"dependencies\\": {\\n \\"react\\": \\"^19.0.0\\",\\n \\"react-dom\\": \\"^19.0.0\\"\\n },\\n \\"devDependencies\\": {\\n \\"@types/react\\": \\"^19.0.0\\",\\n \\"@types/react-dom\\": \\"^19.0.0\\",\\n \\"@vitejs/plugin-react\\": \\"^4.3.0\\",\\n \\"typescript\\": \\"^5.6.0\\",\\n \\"vite\\": \\"^5.4.0\\"\\n }\\n}\\n","root/tsconfig.json":"{\\n \\"compilerOptions\\": {\\n \\"target\\": \\"ES2022\\",\\n \\"module\\": \\"ESNext\\",\\n \\"moduleResolution\\": \\"Bundler\\",\\n \\"jsx\\": \\"react-jsx\\",\\n \\"lib\\": [\\"ES2022\\", \\"DOM\\"],\\n \\"strict\\": true,\\n \\"esModuleInterop\\": true,\\n \\"skipLibCheck\\": true,\\n \\"isolatedModules\\": true,\\n \\"noEmit\\": true\\n },\\n \\"include\\": [\\"components/**/component.tsx\\", \\"vite.config.ts\\"]\\n}\\n","root/vite.config.ts":"import { defineConfig } from \\"vite\\";\\nimport react from \\"@vitejs/plugin-react\\";\\n\\n// Real builds happen in `gs build` (one Vite invocation per\\n// component, externals + runtime shim paths owned by the CLI). This\\n// file exists only so editors / language servers can resolve the\\n// React plugin when inspecting components/*/component.tsx.\\nexport default defineConfig({\\n plugins: [react()],\\n});\\n"}'),ve)}var ft={name:"__GS_NAME__",displayName:"__GS_DISPLAY_NAME__",store:"__GS_STORE__",version:"__GS_VERSION__"};function mt(e,t){let n=e;for(let o of Object.keys(ft)){let s=t[o];s!==void 0&&(n=n.split(ft[o]).join(s))}let r=n.match(/__GS_[A-Z_]+__/);if(r)throw new Error(`internal: template placeholder ${r[0]} was not provided`);return n}var gt=/^[a-z][a-z0-9_]*$/;function yt(e){let t=e.positional[0];if(t!==void 0&&!gt.test(t))throw new Error(`Invalid component name: "${t}" (must match ${gt}).`);let n=m(e.flags,"force"),r=h(e.flags,"store"),o=h(e.flags,"out")??".",s=k.resolve(o),i=nr(s),a;if(i){if(r!==void 0)throw new Error(`Project at ${s} is already pinned to a store via .gsrc. Drop --store; a project folder ships to exactly one store.`);$({cwd:s})}else if(a=r!==void 0?ee(r):ce()??void 0,a===void 0){let u=t?`gs apps init ${t} --store <slug>`:"gs apps init --store <slug>";throw new Error(`--store <slug> is required when scaffolding a new project root. Run \`${u}\`.`)}let l=rr(s,i,n,{store:a});if(!t){let u=[];i?(u.push(`Updated GreatStore project root in ${s}.`),l.length>0?u.push("",`Added: ${l.join(", ")}`):u.push("","Already up to date \u2014 nothing to add.")):u.push(`Scaffolded GreatStore project root in ${s}.`),u.push("","Next steps:",` cd ${k.relative(process.cwd(),s)||"."}`," npm install"," gs apps init <component_name> # add your first component",""),process.stdout.write(u.join(`
82
82
  `));return}let c=k.join(s,"components",t);ir(c,t,n);let p=k.relative(process.cwd(),s)||".";process.stdout.write([`Added component "${t}" at components/${t}/.`,...i&&l.length>0?["",`Also added to the project root: ${l.join(", ")}`]:[],"","Next steps:",...i?[]:[` cd ${p}`," npm install"],` # edit components/${t}/component.tsx and manifest.json`," gs apps build"," gs apps push",""].join(`
83
83
  `))}function nr(e){return g.existsSync(k.join(e,"package.json"))&&g.existsSync(k.join(e,".gsrc"))}function rr(e,t,n,r){if(g.mkdirSync(e,{recursive:!0}),!t&&!n&&g.readdirSync(e).filter(a=>a!==".gsrc").length>0)throw new Error(`Refusing to scaffold project root into non-empty directory ${e}. Pass --force to override.`);let o=t?cr():ar({store:r.store}),s=sr(e,o,n);return g.mkdirSync(k.join(e,"components"),{recursive:!0}),s}var or=new Set(["AGENTS.md"]);function sr(e,t,n){let r=[];for(let[o,s]of t){let i=k.join(e,o);g.mkdirSync(k.dirname(i),{recursive:!0});let a=g.existsSync(i);if(!n&&a&&!or.has(o))continue;let l=!a||g.readFileSync(i,"utf8")!==s;g.writeFileSync(i,s),l&&r.push(o)}for(let o of["CLAUDE.md","GEMINI.md"]){let s=k.join(e,o);n&&ht(s)&&g.rmSync(s),ht(s)||(g.symlinkSync("AGENTS.md",s),r.push(o))}return r}function ht(e){try{return g.lstatSync(e),!0}catch{return!1}}function ir(e,t,n){if(g.existsSync(e)&&!n&&g.readdirSync(e).length>0)throw new Error(`Refusing to overwrite existing components/${t}/. Pass --force to override.`);g.mkdirSync(e,{recursive:!0});for(let[r,o]of lr(t))g.writeFileSync(k.join(e,r),o)}function Le(e,t,n=new Set){let r=dt();return Object.entries(r).filter(([o])=>o.startsWith(e)).map(([o,s])=>[o.slice(e.length),s]).filter(([o])=>!n.has(o)).map(([o,s])=>[o,mt(s,t)])}function ar(e){if(!e.store)throw new Error("internal: rootFiles called without a store slug");return Le("root/",{store:e.store,version:N})}function cr(){return Le("root/",{version:N},new Set([".gsrc"]))}function lr(e){return Le("component/",{name:e,displayName:ur(e)})}function ur(e){let t=e.split("_").filter(Boolean);if(t.length===0)return e;let n=t[0];return n.charAt(0).toUpperCase()+n.slice(1)+(t.length>1?" "+t.slice(1).join(" "):"")}import*as b from"fs";import*as w from"path";import{createRequire as xr}from"module";import*as jt from"fs";import*as U from"path";import{createRequire as pr}from"module";import*as xe from"path";function St(e,t,n){let r=vt(e);if(!r)return{ok:!1,reason:"couldn't check props against the manifest \u2014 `typescript` isn't installed in this project (run `npm install`)"};try{let o=r.createSourceFile(t,n,r.ScriptTarget.Latest,!0,r.ScriptKind.TSX),s=dr(r,o);return s?hr(r,o,s):{ok:!1,reason:"couldn't find a default-exported component function to check props against \u2014 export the component as `export default function \u2026`"}}catch(o){return{ok:!1,reason:`couldn't check props against the manifest \u2014 ${xe.basename(t)} could not be parsed (${o.message})`}}}function bt(e,t,n){let r=vt(e);if(!r)return!1;try{let o=r.createSourceFile(t,n,r.ScriptTarget.Latest,!0,r.ScriptKind.TSX),s=!1,i=a=>{if(!s){if(fr(r,a)){s=!0;return}r.forEachChild(a,i)}};return i(o),s}catch{return!1}}function fr(e,t){if(e.isPropertyAccessExpression(t))return wt(e,t.expression)&&t.name.text==="GreatStore";if(e.isElementAccessExpression(t)){let n=t.argumentExpression;return wt(e,t.expression)&&e.isStringLiteralLike(n)&&n.text==="GreatStore"}return!1}function wt(e,t){return e.isIdentifier(t)&&(t.text==="window"||t.text==="globalThis")}function vt(e){let t=pr(xe.join(e,"package.json"));try{return t("typescript")}catch{return null}}function dr(e,t){let n=null;for(let o of t.statements){if(e.isFunctionDeclaration(o)&&mr(e,o))return o;e.isExportAssignment(o)&&!o.isExportEquals&&(n=o.expression)}if(!n)return null;let r=xt(e,n);return e.isArrowFunction(r)||e.isFunctionExpression(r)?r:e.isIdentifier(r)?gr(e,t,r.text):null}function mr(e,t){return t.modifiers?.some(n=>n.kind===e.SyntaxKind.DefaultKeyword)??!1}function xt(e,t){let n=t;for(;e.isParenthesizedExpression(n)||e.isAsExpression(n)||e.isSatisfiesExpression(n);)n=n.expression;return n}function gr(e,t,n){for(let r of t.statements){if(e.isFunctionDeclaration(r)&&r.name?.text===n)return r;if(e.isVariableStatement(r))for(let o of r.declarationList.declarations){if(!e.isIdentifier(o.name)||o.name.text!==n||!o.initializer)continue;let s=xt(e,o.initializer);if(e.isArrowFunction(s)||e.isFunctionExpression(s))return s}}return null}function hr(e,t,n){let r=n.parameters[0];if(!r)return{ok:!0,props:{names:[],open:!1}};if(r.type){let o=Ie(e,t,r.type,new Set);if(o)return{ok:!0,props:o}}return e.isObjectBindingPattern(r.name)?{ok:!0,props:yr(e,r.name)}:{ok:!1,reason:"couldn't check props against the manifest \u2014 declare the component's props as a local `interface`/`type` or destructure them in the signature"}}function Ie(e,t,n,r){if(e.isTypeLiteralNode(n))return Pt(e,n.members);if(e.isTypeReferenceNode(n)&&e.isIdentifier(n.typeName))return kt(e,t,n.typeName.text,r);if(e.isIntersectionTypeNode(n)){let o=n.types.map(s=>Ie(e,t,s,r));return o.every(s=>s===null)?null:Ct(o.map(s=>s??{names:[],open:!0}))}return null}function kt(e,t,n,r){if(r.has(n))return{names:[],open:!1};r.add(n);for(let o of t.statements){if(e.isInterfaceDeclaration(o)&&o.name.text===n){let s=Pt(e,o.members),i=(o.heritageClauses??[]).flatMap(a=>a.types.map(l=>e.isIdentifier(l.expression)?kt(e,t,l.expression.text,r)??{names:[],open:!0}:{names:[],open:!0}));return Ct([s,...i])}if(e.isTypeAliasDeclaration(o)&&o.name.text===n)return Ie(e,t,o.type,r)}return null}function Pt(e,t){let n=[],r=!1;for(let o of t){if(e.isIndexSignatureDeclaration(o)){r=!0;continue}if(!e.isPropertySignature(o)&&!e.isMethodSignature(o))continue;let s=$t(e,o.name);if(s===null){r=!0;continue}n.push(s)}return{names:n,open:r}}function yr(e,t){let n=[],r=!1;for(let o of t.elements){if(o.dotDotDotToken){r=!0;continue}let s=o.propertyName??o.name,i=$t(e,s);i===null?r=!0:n.push(i)}return{names:n,open:r}}function $t(e,t){return e.isIdentifier(t)||e.isStringLiteral(t)?t.text:null}function Ct(e){let t=[],n=!1;for(let r of e){for(let o of r.names)t.includes(o)||t.push(o);n||=r.open}return{names:t,open:n}}function Rt(e){let{root:t,name:n}=e,r=U.join(t,"components",n),o=e.manifestPath??U.join(r,"manifest.json"),s=e.sourcePath??U.join(r,"component.tsx"),i=At(t,o),a=At(t,s),l=[],c=null,p=Et(o);if(p===null)l.push({severity:"error",rule:"manifest/missing",file:i,message:"manifest not found."});else try{let P=JSON.parse(p);!P||typeof P!="object"||Array.isArray(P)?l.push({severity:"error",rule:"manifest/invalid",file:i,message:"manifest must be a JSON object."}):c=P}catch(P){l.push({severity:"error",rule:"manifest/invalid",file:i,message:`manifest is not valid JSON: ${P.message}`})}let u=Et(s),f=u===null?{ok:!1,reason:`couldn't check props against the manifest \u2014 ${a} not found`}:St(t,s,u),j=u===null?!1:bt(t,s,u);return{ctx:{name:n,manifestFile:i,sourceFile:a,manifest:c,props:f,usesWindowGreatStore:j},diagnostics:l}}function Et(e){try{return jt.readFileSync(e,"utf8")}catch{return null}}function At(e,t){let n=U.relative(e,t);return n.startsWith("..")?t:n.split(U.sep).join("/")}var _t=new Set(["onSendMessage","onClose","onUpdateModelContext","onShowLightbox","onGenerateStructuredContent","storeData","Image"]);var Tt=new Map([["onError",'prop `onError` is deprecated and no longer provided \u2014 prefer an async component to report failures. Drop the prop; see the "Async components" section in AGENTS.md for how to signal errors.']]);function Lt(e){if(!e.manifest)return[];let t=Sr(e.manifest.inputSchema);if(t===null)return[];if(!e.props.ok)return[{severity:"warning",rule:"props/not-analyzable",file:e.sourceFile,message:`${e.props.reason}.`}];if(e.props.props.open)return[];let n=new Set(e.props.props.names),r=new Set(t),o=[];for(let i of e.props.props.names){if(_t.has(i))continue;let a=Tt.get(i);if(a){o.push({severity:"warning",rule:"props/retired-lifecycle",file:e.sourceFile,message:a});continue}r.has(i)||o.push({severity:"warning",rule:"props/undeclared",file:e.sourceFile,message:`prop \`${i}\` is not declared in ${e.manifestFile}#inputSchema.properties, so nothing will ever pass it. Declare it in the schema, or drop it from the component.`})}let s=t.filter(i=>!n.has(i));return s.length>0&&o.push({severity:"error",rule:"props/missing",file:e.sourceFile,message:wr(e.manifestFile,s)}),o}var Ot=8;function wr(e,t){if(t.length===1){let[s]=t;return`${e} declares inputSchema field \`${s}\`, but the component does not accept a \`${s}\` prop. Add it to the component's props, or remove it from the schema.`}let n=t.slice(0,Ot).map(s=>`\`${s}\``).join(", "),r=t.length-Ot,o=r>0?`${n} (+${r} more)`:n;return`${e} declares ${t.length} inputSchema fields the component does not accept: ${o}. Add them to the component's props, or remove them from the schema.`}function Sr(e){if(!e||typeof e!="object")return null;let t=e.properties;return!t||typeof t!="object"||Array.isArray(t)?null:Object.keys(t)}var br=["anyOf","oneOf","allOf","$ref","not"];function ke(e,t,n){if(Array.isArray(e)){e.forEach((s,i)=>ke(s,`${t}[${i}]`,n));return}if(!e||typeof e!="object")return;let r=e;for(let s of br)s in r&&n.unionPaths.push(`${t}.${s}`);let o=r.properties;if(o&&typeof o=="object"&&!Array.isArray(o))for(let[s,i]of Object.entries(o))n.fields+=1,ke(i,`${t}.${s}`,n);"items"in r&&ke(r.items,`${t}[]`,n)}function It(e){let t=e.manifest?.inputSchema;if(!t||typeof t!="object")return[];let n={bytes:Buffer.byteLength(JSON.stringify(t),"utf8"),fields:0,unionPaths:[]};ke(t,"inputSchema",n);let r=[];if(n.unionPaths.length>0){let o=n.unionPaths.slice(0,3).join(", "),s=n.unionPaths.length>3?` (+${n.unionPaths.length-3} more)`:"";r.push(`uses ${o}${s} \u2014 declare exactly one type per field; accept alternate shapes in component code instead`)}return n.bytes>8192&&r.push(`is ${(n.bytes/1024).toFixed(1)} KB serialized (limit ${8192/1024} KB)`),n.fields>50&&r.push(`declares ${n.fields} fields (limit 50)`),r.length===0?[]:[{severity:"error",rule:"manifest/input-schema-too-complex",file:e.manifestFile,message:`inputSchema ${r.join("; ")}.
84
84
  A schema this complex is usually a sign the component is overengineered, and the assistant will fill it unreliably or stop calling the tool altogether. Keep it to a small set of flat, single-type fields (one canonical name per concept \u2014 no aliases), and let component code handle formatting, fallbacks, and edge cases.`}]}function Ft(e){let t=e.manifest?.name;return typeof t!="string"||t===e.name?[]:[{severity:"error",rule:"manifest/name-mismatch",file:e.manifestFile,message:`manifest name "${t}" does not match folder name "${e.name}".`}]}function Nt(e){return e.usesWindowGreatStore?[{severity:"warning",rule:"globals/window-greatstore",file:e.sourceFile,message:"this component reads `window.GreatStore`, the host-page embed API. Components should interact with GreatStore through their injected lifecycle props (`onSendMessage`, `onGenerateStructuredContent`, \u2026) instead \u2014 those are wired to the surface the component is mounted in."}]:[]}function pe(e){return e.filter(t=>t.severity==="error")}function Fe(e){return e.filter(t=>t.severity==="warning")}function fe(e){return`${e.severity==="error"?"error":"warning"} ${e.file}: ${e.message}`}var vr=[Ft,It,Lt,Nt];function Pe(e){let{ctx:t,diagnostics:n}=Rt(e);for(let r of vr)n.push(...r(t));return{diagnostics:n,ok:pe(n).length===0}}var W="components";async function Bt(e){let t=process.cwd();if(!b.existsSync(w.join(t,"package.json"))||!b.existsSync(w.join(t,W)))throw new Error(`\`gs apps build\` must run from a project root (contains \`package.json\` and \`${W}/\`). Current dir: ${t}`);let n=kr(t);if(n.length===0){process.stdout.write(`(no components in ./${W} \u2014 run \`gs apps init <name>\` to add one)
@@ -166,6 +166,11 @@ Did you mean: ${i.join(", ")}?`:""))}if(typeof r!="string"){if(s.kind==="boolean
166
166
  All notable changes to \`@greatstore/cli\` are recorded here. The format
167
167
  follows [Keep a Changelog](https://keepachangelog.com/).
168
168
 
169
+ ## 0.2.1 \u2014 2026-09-30
170
+
171
+ ### Changed
172
+ - Updated skill and agent documentation.
173
+
169
174
  ## 0.2.0 \u2014 2026-09-22
170
175
 
171
176
  ### Removed
@@ -7,10 +7,7 @@
7
7
  > as-is.
8
8
 
9
9
  The flagship pattern: an AI-generated quiz card in your design, whose answers
10
- drop the shopper into a chat that can act on the page. Uses the
11
- `onGreatStoreReady` helper from the
12
- [embed API reference](../references/embed-api.md#availability) — define
13
- that once and it works for every use on the page.
10
+ drop the shopper into a chat that can act on the page.
14
11
 
15
12
  ```html
16
13
  <section id="gift-finder" hidden>
@@ -19,15 +16,9 @@ that once and it works for every use on the page.
19
16
  </section>
20
17
 
21
18
  <script>
22
- // Depending on where this script tag sits relative to the embed script
23
- // tag, this inline script could run either before embed.js has executed
24
- // at all, or after it's already mounted — checking `window.GreatStore`
25
- // synchronously and bailing if it's not there yet would silently skip
26
- // the whole funnel in the first case, and a bare
27
- // `addEventListener("greatstore:ready", ...)` would silently miss the
28
- // (one-shot, already-fired) event in the second.
29
- // onGreatStoreReady (see the embed API reference) handles both.
30
- onGreatStoreReady(async (gs) => {
19
+ // Works whether this runs before or after the embed script: a listener
20
+ // attached once GreatStore is already ready still receives the event.
21
+ window.addEventListener("greatstore:ready", async ({ detail: gs }) => {
31
22
  // Tools the resulting conversation can use — discovered on its next
32
23
  // turn automatically.
33
24
  document.modelContext.registerTool({
@@ -88,7 +79,7 @@ that once and it works for every use on the page.
88
79
  }
89
80
  document.getElementById("gift-finder").hidden = false;
90
81
  } catch {}
91
- });
82
+ }, { once: true });
92
83
  </script>
93
84
  ```
94
85
 
@@ -7,15 +7,12 @@
7
7
  > as-is.
8
8
 
9
9
  Give every conversation on the site real capabilities. Register once in a
10
- shared snippet, after the SDK is ready (which guarantees
11
- `document.modelContext` exists) — using the `onGreatStoreReady` helper from
12
- the [embed API reference](../references/embed-api.md#availability), which
13
- handles both load orderings (embed script not run yet vs. already mounted)
14
- that a plain `window.GreatStore?.ready.then()` or a bare
15
- `addEventListener("greatstore:ready", ...)` each only cover one side of:
10
+ shared snippet, once GreatStore is ready (which guarantees
11
+ `document.modelContext` exists). The listener works whether the snippet runs
12
+ before or after the embed script:
16
13
 
17
14
  ```js
18
- onGreatStoreReady(() => {
15
+ window.addEventListener("greatstore:ready", () => {
19
16
  const text = (value) => ({
20
17
  content: [{ type: "text", text: JSON.stringify(value) }],
21
18
  });
@@ -72,7 +69,7 @@ onGreatStoreReady(() => {
72
69
  });
73
70
  },
74
71
  });
75
- });
72
+ }, { once: true });
76
73
  ```
77
74
 
78
75
  Principles at work: throw on failure (the assistant explains and recovers),
@@ -182,6 +182,11 @@ name yours for the distinct thing it does (`show_catalog_inline` alongside
182
182
  - `fullscreen` — takes over the full preview surface; persists until the
183
183
  next widget-emitting tool call or an explicit close.
184
184
 
185
+ **Safe-zone for `fullscreen` apps.** The floating chat widget sits over the
186
+ bottom of a fullscreen app, covering whatever is rendered there. Leave
187
+ `6.25em` (100px at the default font size) of bottom padding on the app's
188
+ scrolling content so everything can be scrolled clear of it.
189
+
185
190
  ## The app contract
186
191
 
187
192
  `component.tsx` default-exports a React component. Its props are the
@@ -81,12 +81,24 @@ characters) are silently ignored and fall back to the configured default.
81
81
  | `slug` | `string` | The store identifier the script was loaded for. |
82
82
  | `host` | `string` | `"greatstore.ai"`. |
83
83
  | `embedHost` | `string` | Origin the embed assets load from, e.g. `https://<slug>.greatstore.ai`. |
84
- | `ready` | `Promise<void>` | Resolves when the chat UI has mounted and `open()` would render instantly. Resolved promises replay, so `.then()` works no matter when it's attached. The readiness signal to gate on. |
85
84
 
86
- A `greatstore:ready` `CustomEvent` (with the SDK object as `detail`) is also
87
- dispatched on `window` at the moment `ready` resolves, for declarative
88
- tooling. Unlike the promise, the listener must be attached before mount
89
- completes — attach it before (or immediately after) the embed script tag.
85
+ ## Readiness: the `greatstore:ready` event
86
+
87
+ A `greatstore:ready` `CustomEvent` (with the SDK object as `detail`) is
88
+ dispatched on `window` once the chat UI has mounted and `open()` would render
89
+ instantly. It is the signal to gate on, and it works no matter when the
90
+ listener is attached: a listener added after GreatStore is ready receives the
91
+ event once, straight away.
92
+
93
+ ```js
94
+ window.addEventListener(
95
+ "greatstore:ready",
96
+ () => {
97
+ button.hidden = false;
98
+ },
99
+ { once: true },
100
+ );
101
+ ```
90
102
 
91
103
  ## Methods
92
104
 
@@ -204,21 +216,21 @@ navigating away from the only route that should show it.
204
216
  No-ops (with a console warning) if nothing is mounted. The cached identity
205
217
  and downloaded chat bundle are kept, so a later `load()` (or any call that
206
218
  triggers a mount, like `open()`) mounts a fresh panel without a network
207
- round-trip for either. `ready` becomes a new pending promise at the moment
208
- `destroy()` is called, resolving again once the next mount completes:
219
+ round-trip for either. `greatstore:ready` fires again once the next mount
220
+ completes:
209
221
 
210
222
  ```js
211
223
  window.GreatStore.destroy();
212
224
  // ...later, on the page/route where the embed should come back:
225
+ window.addEventListener("greatstore:ready", onRemounted, { once: true });
213
226
  window.GreatStore.load();
214
- await window.GreatStore.ready; // resolves once the fresh mount is done
215
227
  ```
216
228
 
217
229
  ## Page tools — WebMCP (`document.modelContext`)
218
230
 
219
231
  The recommended way to expose page capabilities to the assistant is the
220
232
  WebMCP standard. The GreatStore assistant uses every tool registered on
221
- `document.modelContext` **once GreatStore is ready** (see `onGreatStoreReady`
233
+ `document.modelContext` **once GreatStore is ready** (see [Availability](#availability)
222
234
  below), re-reading the list on each conversational turn — so tools
223
235
  registered mid-session appear on the next message without a reload. Tools
224
236
  registered before GreatStore is ready are ignored.
@@ -234,45 +246,20 @@ position, which matters if the page also has another script (a nav widget,
234
246
  an analytics tag) registering its own WebMCP tools: whichever executes
235
247
  first wins that registration, and only a synchronous, unconditionally-first
236
248
  script gives GreatStore's fallback shim a real chance of installing before
237
- one of those calls happens. That said, your own code can still end up on
238
- either side of two different races relative to `embed.js`, depending on
239
- where your script tag sits and whether it uses `async`/`defer` itself:
240
-
241
- - **Your script runs before `embed.js` has executed at all** — `window.GreatStore`
242
- doesn't exist yet. `window.GreatStore?.ready` silently evaluates to
243
- `undefined` here (optional chaining swallows it), so accessing `.then()`
244
- on it throws or (written more defensively) just does nothing.
245
- - **Your script runs after `embed.js` has already mounted** — the
246
- `greatstore:ready` event already fired once, in the past.
247
- `window.addEventListener("greatstore:ready", ...)` attached now will
248
- never see it: the event isn't replayed for late listeners, unlike a
249
- resolved Promise (`.then()` on an already-resolved Promise still fires).
250
-
251
- Neither `.ready.then(...)` alone nor `addEventListener("greatstore:ready", ...)`
252
- alone is safe against both orderings. Use both, picking whichever is valid
253
- at the moment your code runs:
249
+ one of those calls happens. Your own code
250
+ can still run on either side of `embed.js` — before it has executed at all
251
+ (`window.GreatStore` doesn't exist yet), or long after it has mounted (a lazily rendered component, a
252
+ tag manager). Listening for `greatstore:ready` covers both: a listener
253
+ attached after GreatStore is already ready still receives the event, once.
254
254
 
255
255
  ```js
256
- function onGreatStoreReady(callback) {
257
- if (window.GreatStore?.ready) {
258
- // embed.js has already run — .then() on its ready Promise fires
259
- // immediately if it already resolved, or once it does.
260
- window.GreatStore.ready.then(() => callback(window.GreatStore));
261
- } else {
262
- // embed.js hasn't run yet — wait for the one-shot event it'll dispatch
263
- // once it has. Safe to attach now: nothing can fire it between this
264
- // check and the listener attaching, since JS execution isn't preemptible.
265
- window.addEventListener(
266
- "greatstore:ready",
267
- (event) => callback(event.detail),
268
- { once: true },
269
- );
270
- }
271
- }
272
-
273
- onGreatStoreReady(() => {
274
- document.modelContext.registerTool(/* … */);
275
- });
256
+ window.addEventListener(
257
+ "greatstore:ready",
258
+ () => {
259
+ document.modelContext.registerTool(/* … */);
260
+ },
261
+ { once: true },
262
+ );
276
263
  ```
277
264
 
278
265
  (`navigator.modelContext` is a deprecated alias for the same object; use
@@ -308,11 +295,10 @@ document.modelContext.registerTool(
308
295
  - **Treat `args` as untrusted input**: values are AI-generated. Validate
309
296
  before passing to your own APIs, and never `eval` anything from them.
310
297
 
311
- A complete tool, registered once GreatStore is ready (using the
312
- `onGreatStoreReady` helper defined above):
298
+ A complete tool, registered once GreatStore is ready:
313
299
 
314
300
  ```js
315
- onGreatStoreReady(() => {
301
+ window.addEventListener("greatstore:ready", () => {
316
302
  document.modelContext.registerTool({
317
303
  name: "add_to_cart",
318
304
  description:
@@ -337,7 +323,7 @@ onGreatStoreReady(() => {
337
323
  return { content: [{ type: "text", text: JSON.stringify(cart) }] };
338
324
  },
339
325
  });
340
- });
326
+ }, { once: true });
341
327
  ```
342
328
 
343
329
  Returning the fresh cart state after the mutation lets the assistant confirm
@@ -380,4 +366,4 @@ in campaign links, emails, and post-login redirects.
380
366
  | Console: `[GreatStore] Embed script must be loaded from <slug>.greatstore.ai/embed.js` | The script was copied/self-hosted instead of loaded from the store's embed URL. Always load it from `https://<slug>.greatstore.ai/embed.js`. |
381
367
  | `generateStructuredContent` rejects with a rate-limit message | More than ~20 requests/minute from one visitor. Consolidate calls into fewer, richer schemas. |
382
368
  | Chat won't auto-open after returning to the page | Intentional: the drawer never auto-opens on resume — it would cover the content the shopper is reading. The transcript is preserved; they'll see it when they tap the launcher. |
383
- | Tools registered but the assistant doesn't use them | Check the `description` — it's the only signal for *when* to call. Also confirm the registration ran (`document.modelContext` exists after `ready`) on the same page the conversation is on. |
369
+ | Tools registered but the assistant doesn't use them | Check the `description` — it's the only signal for *when* to call. Also confirm the registration ran (it runs inside a `greatstore:ready` listener) on the same page the conversation is on. |
@@ -101,9 +101,14 @@ Supported keywords (anything else is tolerated but ignored):
101
101
  Validation of the output is real: `required` is enforced, `enum`/`const`
102
102
  must match, numeric and length bounds are checked, and
103
103
  `additionalProperties: false` rejects extra keys. Constraints are therefore a
104
- *tool* — `maxItems: 4` reliably caps a list, `enum` reliably restricts a
105
- field — but every constraint is also a way for generation to fail, so apply
106
- them only where you'd rather have no content than non-conforming content.
104
+ *tool* — `enum` reliably restricts a field — but every constraint is also a
105
+ way for generation to fail, so apply them only where you'd rather have no
106
+ content than non-conforming content.
107
+
108
+ Item counts are the exception. `minItems` is honored as the content is
109
+ written, so a list comes back with at least that many entries, and a list
110
+ longer than `maxItems` is cut to its first `maxItems` entries rather than
111
+ failing. The same applies to an app's `inputSchema`.
107
112
 
108
113
  Zod schemas (or anything with a `.toJSONSchema()` method) are accepted and
109
114
  converted automatically.
@@ -221,7 +226,6 @@ A decline is only ever one of these `error.reason` values — anything else
221
226
  | `harmful` | asks for unsafe, hateful, sexual, or illegal content, or advice that could hurt someone |
222
227
  | `deceptive` | asks for fake reviews, invented discounts or scarcity, claims the catalog contradicts, or impersonating/disparaging a named brand or person |
223
228
  | `system_probe` | asks about or tries to override the assistant's own instructions or tools |
224
- | `no_data` | depends on specific store facts and research found nothing to fill the required fields — check `gs connectors`, or make those fields optional |
225
229
 
226
230
  The uniform shopper-facing strategy: render into a hidden-by-default
227
231
  container, reveal on success, leave hidden (or show your static fallback) on
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@greatstore/cli",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "CLI for administering GreatStore stores and authoring custom components.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",