@greatstore/cli 0.2.15 → 0.2.16

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,12 @@
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.16 — 2026-10-30
7
+
8
+ ### Added
9
+ - `connectors tools webmcp` lists the WebMCP tools your pages register: each tool's name, description, whether the assistant may call it, and that a page can run it with `GreatStore.callTool`.
10
+ - The agent guide covers running a page's own WebMCP tools with `GreatStore.callTool` and an app's `$.callTool`, including that a page tool takes precedence over an app or connector tool of the same name.
11
+
6
12
  ## 0.2.15 — 2026-10-29
7
13
 
8
14
  ### Added
package/dist/cli.js CHANGED
@@ -20,7 +20,7 @@ p{color:#2c3a38}`,jr=`<!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>`,ne=class extends Error{constructor(t){super(t),this.name="LoopbackError"}};async function Ce(e){let t=(e.generateState??Tr)(),n=e.timeoutMs??300*1e3,r=e.openBrowser??(s=>Rr(s,e.browserCmdEnv)),o=_t.createServer();try{await new Promise(l=>o.listen(0,"127.0.0.1",l));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(),c=_r(o,t,n);return r(a),await c}finally{o.close()}}function _r(e,t,n){return new Promise((r,o)=>{let s=!1,i=c=>{s||(s=!0,c())},a=setTimeout(()=>{i(()=>o(new ne("Sign-in timed out. Re-run `npx greatstore login`.")))},n);typeof a.unref=="function"&&a.unref(),e.on("request",(c,l)=>{let p=new URL(c.url??"/","http://127.0.0.1");if(p.pathname!==Er){l.writeHead(404,{"content-type":"text/plain"}),l.end("Not found");return}let u=p.searchParams,d=u.get("error"),x=u.get("error_description"),m=u.get("code");if(u.get("state")!==t){l.writeHead(400,{"content-type":"text/html"}),l.end(At),clearTimeout(a),i(()=>o(new ne("Sign-in didn't complete. Please try again.")));return}if(d||!m){l.writeHead(400,{"content-type":"text/html"}),l.end(At),clearTimeout(a),i(()=>o(new ne(x??"Sign-in failed. Please try again.")));return}l.writeHead(200,{"content-type":"text/html"}),l.end(jr),clearTimeout(a);let Ee=u.get("store")?.trim();i(()=>r(Ee?{token:m,store:Ee}:{token:m}))})})}function Tr(){return jt.randomBytes(16).toString("hex")}function Rr(e,t){let r=t?.trim()??Lr();if(r)try{let o;if(r==="start"){let s=`start "" "${e}"`;o=Ct("cmd.exe",["/d","/s","/c",s],{stdio:"ignore",detached:!0,windowsVerbatimArguments:!0})}else o=Ct(r,[e],{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}function Lr(){switch(process.platform){case"darwin":return"open";case"win32":return"start";case"linux":return"xdg-open";default:return null}}import*as L from"fs";import*as le from"os";import*as et from"path";var Or=".greatstore",Ir="credentials.json";function Ae(e=le.homedir()){return et.join(e,Or)}function tt(e=le.homedir()){return et.join(Ae(e),Ir)}function I(e=le.homedir()){let t=tt(e),n;try{let r=L.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=L.readFileSync(t,"utf8")}catch(r){if(Fr(r))return null;throw r}try{let r=JSON.parse(n);return typeof r.access_token!="string"?null:r}catch{return null}}function je(e,t=le.homedir()){let n=Ae(t);if(L.mkdirSync(n,{recursive:!0,mode:448}),process.platform!=="win32")try{L.chmodSync(n,448)}catch{}let r=tt(t);L.writeFileSync(r,`${JSON.stringify(e,null,2)}
23
- `,{mode:384}),process.platform!=="win32"&&L.chmodSync(r,384)}function Tt(e=le.homedir()){L.rmSync(tt(e),{force:!0})}function Rt(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 _e(e,t=Math.floor(Date.now()/1e3)){return e.expires_at<=t}function Fr(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}var F="0.2.15";var D=class extends Error{constructor(n,r,o){super(r);this.status=n;this.code=o;this.name="HttpError"}},M=class extends Error{constructor(t="Sign in first. Run `npx greatstore login`."){super(t),this.name="AuthRequiredError"}};function Nr(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 Br(e){let t=Nr(e)??I()?.store;return t?`npx greatstore login --store ${t}`:"npx greatstore login"}var nt=null;function Ft(e){nt=e}async function f(e,t={}){if(nt!==null)return Lt(e,t,nt);let n=()=>`Run \`${Br(e)}\`.`,r=I();if(!r)throw new M(`Sign in first. ${n()}`);if(_e(r))throw new M(`Session expired. ${n()}`);try{return await Lt(e,t,r.access_token)}catch(o){throw o instanceof D&&o.status===401?new M(`Session expired. ${n()}`):o}}async function Lt(e,t,n){let r={accept:"application/json",authorization:`Bearer ${n}`,"x-gs-cli-version":F,...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(),c={};try{c=JSON.parse(a)}catch{}let l=c.code??c.error,p=t.validationDetail&&i.status===400&&c.error?c.error:Dr(i.status,l,c.detail);throw new D(i.status,p,c.code??c.error)}var Nt=`This version of the GreatStore CLI is no longer supported. Run the latest one:
23
+ `,{mode:384}),process.platform!=="win32"&&L.chmodSync(r,384)}function Tt(e=le.homedir()){L.rmSync(tt(e),{force:!0})}function Rt(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 _e(e,t=Math.floor(Date.now()/1e3)){return e.expires_at<=t}function Fr(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}var F="0.2.16";var D=class extends Error{constructor(n,r,o){super(r);this.status=n;this.code=o;this.name="HttpError"}},M=class extends Error{constructor(t="Sign in first. Run `npx greatstore login`."){super(t),this.name="AuthRequiredError"}};function Nr(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 Br(e){let t=Nr(e)??I()?.store;return t?`npx greatstore login --store ${t}`:"npx greatstore login"}var nt=null;function Ft(e){nt=e}async function f(e,t={}){if(nt!==null)return Lt(e,t,nt);let n=()=>`Run \`${Br(e)}\`.`,r=I();if(!r)throw new M(`Sign in first. ${n()}`);if(_e(r))throw new M(`Session expired. ${n()}`);try{return await Lt(e,t,r.access_token)}catch(o){throw o instanceof D&&o.status===401?new M(`Session expired. ${n()}`):o}}async function Lt(e,t,n){let r={accept:"application/json",authorization:`Bearer ${n}`,"x-gs-cli-version":F,...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(),c={};try{c=JSON.parse(a)}catch{}let l=c.code??c.error,p=t.validationDetail&&i.status===400&&c.error?c.error:Dr(i.status,l,c.detail);throw new D(i.status,p,c.code??c.error)}var Nt=`This version of the GreatStore CLI is no longer supported. Run the latest one:
24
24
 
25
25
  npx greatstore@latest <command>
26
26
 
@@ -81,7 +81,7 @@ Examples:
81
81
  npx greatstore configure set --theme.fontFamily Manrope --theme.radius sharp
82
82
  npx greatstore configure set --theme.brandColor "#1e1d66"
83
83
  npx greatstore configure set --theme '{"mode":"dark"}' --replace
84
- `}function Xt(e){if(e===void 0||e==="show")return zr;if(e==="set")return Zr()}import*as S from"fs";import*as A from"path";import{readdirSync as Ds,readFileSync as Hs}from"fs";import{fileURLToPath as Us}from"url";var Fe=null;function Zt(){return Fe||(Fe=JSON.parse('{"component/component.tsx":"import React from \\"react\\";\\nimport \\"./style.css\\";\\n\\n// Add your tool args (matching manifest.json#inputSchema.properties)\\n// alongside `$`, the GreatStore prop every app receives. See AGENTS.md for\\n// what each `$` member does.\\ninterface Props {\\n $: {\\n sendMessage: (text: string) => void;\\n updateModelContext: (context: string) => void;\\n // Run one of the store\'s read-only connector tools and get its result,\\n // or open one of its full-screen apps by name. See AGENTS.md.\\n callTool: (\\n name: string,\\n args?: Record<string, unknown>,\\n ) => Promise<Record<string, unknown> | undefined>;\\n showLightbox: (options: { src: string; originRect?: DOMRect }) => void;\\n close: () => 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 generateStructuredContent: <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 // A hook for a voice call with the store\'s assistant: call it at the top\\n // of the component. See AGENTS.md.\\n useVoiceCall: () => {\\n status:\\n | \\"started\\"\\n | \\"connecting\\"\\n | \\"connected\\"\\n | \\"speaking\\"\\n | \\"listening\\"\\n | \\"working\\"\\n | \\"disconnected\\"\\n | \\"ended\\"\\n | null;\\n available: boolean;\\n start: () => Promise<void>;\\n end: () => void;\\n };\\n store: { slug: string };\\n };\\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 (style.css, em-based sizing, brand CSS variables), and how to\\n// write an async, backend-backed app.\\n//\\n// Take what you need from `$` at the top: `const { callTool, Image } = props.$;`\\nexport default function Component(_props: Props): React.ReactElement {\\n return (\\n <div className=\\"app\\">\\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","component/style.css":"/*\\n * Your app\'s styles. Plain CSS, applied inside the app alone: nothing here\\n * reaches the store\'s page, and nothing on the page reaches in.\\n *\\n * Style with the store\'s theme variables rather than fixed values \u2014 write\\n * `color: var(--color-foreground)`, never `color: #111827`. Each store sets\\n * its colours, fonts and corner style (and dark mode) in its GreatStore\\n * dashboard; an app built on these variables follows those settings, and\\n * changes with them.\\n *\\n * Fonts: --font-primary, --font-secondary\\n * Surfaces: --color-surface, --color-surface-secondary, --color-surface-accent,\\n * --color-surface-hover\\n * Text: --color-foreground, --color-foreground-secondary,\\n * --color-foreground-muted, --color-foreground-accent\\n * Borders: --color-border-default, --color-border-focus\\n * Brand: --color-primary, --color-primary-foreground, --color-primary-hover,\\n * --color-primary-muted, --color-primary-muted-foreground,\\n * --color-primary-tint, --color-link\\n * Status: --color-error, --color-error-surface, --color-error-border,\\n * --color-success\\n * Corners: --radius-xs, --radius-sm, --radius-md, --radius-lg, --radius-xl,\\n * --radius-2xl, --radius-3xl, --radius-4xl, --radius-pill\\n */\\n\\n/* Size in em, never rem: an app sits inside other people\'s pages. */\\n.app {\\n padding: 1em;\\n border: 1px solid var(--color-border-default);\\n border-radius: var(--radius-lg);\\n background: var(--color-surface);\\n color: var(--color-foreground);\\n font-family: var(--font-primary);\\n}\\n","root/.gitignore":"node_modules/\\ncomponents/*/bundle.js\\ncomponents/*/bundle.css\\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 `npx greatstore apps init`, so any changes you make here\\n> will be overwritten. If this version trails your installed CLI, re-run\\n> `npx greatstore 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 $.generateStructured-\\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 $.updateModelContext() \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 $.sendMessage() \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 (`$.updateModelContext`), can speak for the\\n shopper (`$.sendMessage`), 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 `$.generateStructuredContent` 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### Style in `style.css`\\n\\nEach app\'s styles live in `components/<name>/style.css`, imported once at\\nthe top of `component.tsx`:\\n\\n```tsx\\nimport \\"./style.css\\";\\n```\\n\\nWrite ordinary CSS there and use `className` in the component. The sheet\\napplies to your app alone \u2014 it can\'t affect the store\'s page, and the page\\ncan\'t affect your app \u2014 so short class names like `.card` are safe.\\nInline `style={{\u2026}}` still works for values computed at render time.\\n\\nThe rules for `style.css`:\\n\\n- Import only `./style.css`, and only from `component.tsx`. Every other CSS\\n import fails the build.\\n- Keep it self-contained: no `@import`, and `url()` only with `https:` or\\n `data:` URLs \u2014 nothing beside the sheet is uploaded with it.\\n- At most 256 KB.\\n\\n`npx greatstore apps build` minifies the sheet into `bundle.css` beside\\n`bundle.js`; shoppers get that, so comments in `style.css` are for you and\\nnever reach them. Like `bundle.js`, `bundle.css` is generated \u2014 edit\\n`style.css` and build again.\\n\\nThe comment at the top of the scaffolded `style.css` lists the theme\\nvariables below. Style with them rather than fixed values: each store sets\\nits colours, fonts and corner style in its GreatStore dashboard, and an app\\nbuilt on the variables follows those settings.\\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```css\\n/* Bad \u2014 breaks on hosts with a non-default root font size */\\n.card { padding: 1rem; font-size: 0.875rem; }\\n\\n/* Good */\\n.card { padding: 1em; font-size: 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```css\\n/* Bad \u2014 hardcoded, ignores the store\'s theme */\\n.buy { background: #4f46e5; border-radius: 8px; font-family: Inter; }\\n\\n/* Good */\\n.buy {\\n background: var(--color-primary);\\n color: var(--color-primary-foreground);\\n border-radius: var(--radius-lg);\\n font-family: var(--font-primary);\\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 one GreatStore prop, `$`,\\nwhich is always present. Destructure what you need from it at the top of\\nthe component:\\n\\n```tsx\\nexport default function SizeFinder({ category, $ }: Props) {\\n const { callTool, sendMessage, Image } = $;\\n // ...\\n}\\n```\\n\\nNever declare a `$` field in `inputSchema` \u2014 the build refuses it.\\n\\n| `$` member | What it does |\\n| --- | --- |\\n| `$.sendMessage(text)` | Send text into the chat as if the shopper typed it. |\\n| `$.updateModelContext(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 `$.sendMessage` when you want a turn to happen now. |\\n| `$.callTool(name, args?)` | The same call as the page\'s `window.GreatStore.callTool`: run one of the store\'s read-only connector tools and get its result back, or open one of the store\'s full-screen apps by name. It never touches the conversation \u2014 the assistant doesn\'t learn the call happened (tell it with `$.updateModelContext` if it should). Look up tool names and inputs with `npx greatstore connectors tools`. In the app preview, tools run for real and naming a full-screen app only logs what would open. Inside other AI assistants (ChatGPT, \u2026) it always rejects, so handle the rejection. |\\n| `$.showLightbox({ 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| `$.generateStructuredContent(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| `$.close()` | Dismiss the host slot. Over-input clears the overlay, fullscreen reverts the pane, inline is a no-op. |\\n| `$.useVoiceCall()` | A hook \u2014 call it at the top of your component like any other \u2014 returning `{ status, available, start, end }` for a voice call with the store\'s assistant. `start()` starts the call without opening the chat \u2014 it runs in the collapsed chat bar (which stays hidden if the store hides the chat until opened), and the chat opens only when the assistant shows an inline app (call it from a click; it rejects when the store has no voice), `end()` hangs up. `available` says whether the store has voice. `status` is `null` until a call starts, then `started`, `connecting`, `connected`, `listening` / `speaking` / `working` as the conversation goes, `disconnected` while the network drops (the call recovers on its own), and `ended`. Your app re-renders on every change. |\\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 your own `$` with `Image: \\"img\\"` (or your own component) to render a plain image. |\\n| `$.store` | `{ slug }` \u2014 the store the app is running in. |\\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\\nnpx greatstore apps init <app_name> # add a new app\\nnpx greatstore apps build # builds every components/<name>/bundle.js\\nnpx greatstore apps push # uploads every changed app as a draft\\nnpx greatstore apps publish <app_name> # promote a specific app to live\\n```\\n\\n- `npx greatstore apps push` (no args) hashes each app and only uploads the ones that\\n have changed since the last sync.\\n- `npx greatstore 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\\": \\"npx greatstore apps build\\",\\n \\"push\\": \\"npx greatstore apps build && npx greatstore 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 `npx greatstore 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"}'),Fe)}var Qt={name:"__GS_NAME__",displayName:"__GS_DISPLAY_NAME__",store:"__GS_STORE__",version:"__GS_VERSION__"};function en(e,t){let n=e;for(let o of Object.keys(Qt)){let s=t[o];s!==void 0&&(n=n.split(Qt[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 tn=/^[a-z][a-z0-9_]*$/;function rn(e){let t=e.positional[0];if(t!==void 0&&!tn.test(t))throw new Error(`Invalid component name: "${t}" (must match ${tn}).`);let n=g(e.flags,"force"),r=y(e.flags,"store"),o=y(e.flags,"out")??".",s=A.resolve(o),i=eo(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.`);E({cwd:s})}else if(a=r!==void 0?ue(r):xe()??void 0,a===void 0){let u=t?`npx greatstore apps init ${t} --store <slug>`:"npx greatstore apps init --store <slug>";throw new Error(`--store <slug> is required when scaffolding a new project root. Run \`${u}\`.`)}let c=to(s,i,n,{store:a});if(!t){let u=[];i?(u.push(`Updated GreatStore project root in ${s}.`),c.length>0?u.push("",`Added: ${c.join(", ")}`):u.push("","Already up to date \u2014 nothing to add.")):u.push(`Scaffolded GreatStore project root in ${s}.`),u.push("","Next steps:",` cd ${A.relative(process.cwd(),s)||"."}`," npm install"," npx greatstore apps init <component_name> # add your first component",""),process.stdout.write(u.join(`
84
+ `}function Xt(e){if(e===void 0||e==="show")return zr;if(e==="set")return Zr()}import*as S from"fs";import*as A from"path";import{readdirSync as Ds,readFileSync as Hs}from"fs";import{fileURLToPath as Us}from"url";var Fe=null;function Zt(){return Fe||(Fe=JSON.parse('{"component/component.tsx":"import React from \\"react\\";\\nimport \\"./style.css\\";\\n\\n// Add your tool args (matching manifest.json#inputSchema.properties)\\n// alongside `$`, the GreatStore prop every app receives. See AGENTS.md for\\n// what each `$` member does.\\ninterface Props {\\n $: {\\n sendMessage: (text: string) => void;\\n updateModelContext: (context: string) => void;\\n // Run one of the store\'s read-only connector tools and get its result,\\n // or open one of its full-screen apps by name. See AGENTS.md.\\n callTool: (\\n name: string,\\n args?: Record<string, unknown>,\\n ) => Promise<Record<string, unknown> | undefined>;\\n showLightbox: (options: { src: string; originRect?: DOMRect }) => void;\\n close: () => 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 generateStructuredContent: <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 // A hook for a voice call with the store\'s assistant: call it at the top\\n // of the component. See AGENTS.md.\\n useVoiceCall: () => {\\n status:\\n | \\"started\\"\\n | \\"connecting\\"\\n | \\"connected\\"\\n | \\"speaking\\"\\n | \\"listening\\"\\n | \\"working\\"\\n | \\"disconnected\\"\\n | \\"ended\\"\\n | \\"rejected\\"\\n | null;\\n available: boolean;\\n start: () => Promise<void>;\\n end: () => void;\\n };\\n store: { slug: string };\\n };\\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 (style.css, em-based sizing, brand CSS variables), and how to\\n// write an async, backend-backed app.\\n//\\n// Take what you need from `$` at the top: `const { callTool, Image } = props.$;`\\nexport default function Component(_props: Props): React.ReactElement {\\n return (\\n <div className=\\"app\\">\\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","component/style.css":"/*\\n * Your app\'s styles. Plain CSS, applied inside the app alone: nothing here\\n * reaches the store\'s page, and nothing on the page reaches in.\\n *\\n * Style with the store\'s theme variables rather than fixed values \u2014 write\\n * `color: var(--color-foreground)`, never `color: #111827`. Each store sets\\n * its colours, fonts and corner style (and dark mode) in its GreatStore\\n * dashboard; an app built on these variables follows those settings, and\\n * changes with them.\\n *\\n * Fonts: --font-primary, --font-secondary\\n * Surfaces: --color-surface, --color-surface-secondary, --color-surface-accent,\\n * --color-surface-hover\\n * Text: --color-foreground, --color-foreground-secondary,\\n * --color-foreground-muted, --color-foreground-accent\\n * Borders: --color-border-default, --color-border-focus\\n * Brand: --color-primary, --color-primary-foreground, --color-primary-hover,\\n * --color-primary-muted, --color-primary-muted-foreground,\\n * --color-primary-tint, --color-link\\n * Status: --color-error, --color-error-surface, --color-error-border,\\n * --color-success\\n * Corners: --radius-xs, --radius-sm, --radius-md, --radius-lg, --radius-xl,\\n * --radius-2xl, --radius-3xl, --radius-4xl, --radius-pill\\n */\\n\\n/* Size in em, never rem: an app sits inside other people\'s pages. */\\n.app {\\n padding: 1em;\\n border: 1px solid var(--color-border-default);\\n border-radius: var(--radius-lg);\\n background: var(--color-surface);\\n color: var(--color-foreground);\\n font-family: var(--font-primary);\\n}\\n","root/.gitignore":"node_modules/\\ncomponents/*/bundle.js\\ncomponents/*/bundle.css\\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 `npx greatstore apps init`, so any changes you make here\\n> will be overwritten. If this version trails your installed CLI, re-run\\n> `npx greatstore 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 $.generateStructured-\\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 $.updateModelContext() \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 $.sendMessage() \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 (`$.updateModelContext`), can speak for the\\n shopper (`$.sendMessage`), 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 `$.generateStructuredContent` 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### Style in `style.css`\\n\\nEach app\'s styles live in `components/<name>/style.css`, imported once at\\nthe top of `component.tsx`:\\n\\n```tsx\\nimport \\"./style.css\\";\\n```\\n\\nWrite ordinary CSS there and use `className` in the component. The sheet\\napplies to your app alone \u2014 it can\'t affect the store\'s page, and the page\\ncan\'t affect your app \u2014 so short class names like `.card` are safe.\\nInline `style={{\u2026}}` still works for values computed at render time.\\n\\nThe rules for `style.css`:\\n\\n- Import only `./style.css`, and only from `component.tsx`. Every other CSS\\n import fails the build.\\n- Keep it self-contained: no `@import`, and `url()` only with `https:` or\\n `data:` URLs \u2014 nothing beside the sheet is uploaded with it.\\n- At most 256 KB.\\n\\n`npx greatstore apps build` minifies the sheet into `bundle.css` beside\\n`bundle.js`; shoppers get that, so comments in `style.css` are for you and\\nnever reach them. Like `bundle.js`, `bundle.css` is generated \u2014 edit\\n`style.css` and build again.\\n\\nThe comment at the top of the scaffolded `style.css` lists the theme\\nvariables below. Style with them rather than fixed values: each store sets\\nits colours, fonts and corner style in its GreatStore dashboard, and an app\\nbuilt on the variables follows those settings.\\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```css\\n/* Bad \u2014 breaks on hosts with a non-default root font size */\\n.card { padding: 1rem; font-size: 0.875rem; }\\n\\n/* Good */\\n.card { padding: 1em; font-size: 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```css\\n/* Bad \u2014 hardcoded, ignores the store\'s theme */\\n.buy { background: #4f46e5; border-radius: 8px; font-family: Inter; }\\n\\n/* Good */\\n.buy {\\n background: var(--color-primary);\\n color: var(--color-primary-foreground);\\n border-radius: var(--radius-lg);\\n font-family: var(--font-primary);\\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 one GreatStore prop, `$`,\\nwhich is always present. Destructure what you need from it at the top of\\nthe component:\\n\\n```tsx\\nexport default function SizeFinder({ category, $ }: Props) {\\n const { callTool, sendMessage, Image } = $;\\n // ...\\n}\\n```\\n\\nNever declare a `$` field in `inputSchema` \u2014 the build refuses it.\\n\\n| `$` member | What it does |\\n| --- | --- |\\n| `$.sendMessage(text)` | Send text into the chat as if the shopper typed it. |\\n| `$.updateModelContext(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 `$.sendMessage` when you want a turn to happen now. |\\n| `$.callTool(name, args?)` | The same call as the page\'s `window.GreatStore.callTool`: run one of the page\'s own WebMCP tools or one of the store\'s read-only connector tools and get its result back, or open one of the store\'s full-screen apps by name. It never touches the conversation \u2014 the assistant doesn\'t learn the call happened (tell it with `$.updateModelContext` if it should). Look up tool names and inputs with `npx greatstore connectors tools` (`webmcp` for page tools). In the app preview, tools run for real and naming a full-screen app only logs what would open. Inside other AI assistants (ChatGPT, \u2026) it always rejects, so handle the rejection. |\\n| `$.showLightbox({ 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| `$.generateStructuredContent(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| `$.close()` | Dismiss the host slot. Over-input clears the overlay, fullscreen reverts the pane, inline is a no-op. |\\n| `$.useVoiceCall()` | A hook \u2014 call it at the top of your component like any other \u2014 returning `{ status, available, start, end }` for a voice call with the store\'s assistant. `start()` starts the call without opening the chat \u2014 it runs in the collapsed chat bar (which stays hidden if the store hides the chat until opened), and the chat opens only when the assistant shows an inline app (call it from a click; it rejects when the store has no voice), `end()` hangs up. `available` says whether the store has voice. `status` is `null` until a call starts, then `started`, `connecting`, `connected`, `listening` / `speaking` / `working` as the conversation goes, `disconnected` while the network drops (the call recovers on its own), and `ended` \u2014 or `rejected` instead of `ended` when the shopper refuses the microphone (calling `start()` again asks again, though a browser where they blocked it refuses without asking). Your app re-renders on every change. |\\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 your own `$` with `Image: \\"img\\"` (or your own component) to render a plain image. |\\n| `$.store` | `{ slug }` \u2014 the store the app is running in. |\\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\\nnpx greatstore apps init <app_name> # add a new app\\nnpx greatstore apps build # builds every components/<name>/bundle.js\\nnpx greatstore apps push # uploads every changed app as a draft\\nnpx greatstore apps publish <app_name> # promote a specific app to live\\n```\\n\\n- `npx greatstore apps push` (no args) hashes each app and only uploads the ones that\\n have changed since the last sync.\\n- `npx greatstore 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\\": \\"npx greatstore apps build\\",\\n \\"push\\": \\"npx greatstore apps build && npx greatstore 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 `npx greatstore 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"}'),Fe)}var Qt={name:"__GS_NAME__",displayName:"__GS_DISPLAY_NAME__",store:"__GS_STORE__",version:"__GS_VERSION__"};function en(e,t){let n=e;for(let o of Object.keys(Qt)){let s=t[o];s!==void 0&&(n=n.split(Qt[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 tn=/^[a-z][a-z0-9_]*$/;function rn(e){let t=e.positional[0];if(t!==void 0&&!tn.test(t))throw new Error(`Invalid component name: "${t}" (must match ${tn}).`);let n=g(e.flags,"force"),r=y(e.flags,"store"),o=y(e.flags,"out")??".",s=A.resolve(o),i=eo(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.`);E({cwd:s})}else if(a=r!==void 0?ue(r):xe()??void 0,a===void 0){let u=t?`npx greatstore apps init ${t} --store <slug>`:"npx greatstore apps init --store <slug>";throw new Error(`--store <slug> is required when scaffolding a new project root. Run \`${u}\`.`)}let c=to(s,i,n,{store:a});if(!t){let u=[];i?(u.push(`Updated GreatStore project root in ${s}.`),c.length>0?u.push("",`Added: ${c.join(", ")}`):u.push("","Already up to date \u2014 nothing to add.")):u.push(`Scaffolded GreatStore project root in ${s}.`),u.push("","Next steps:",` cd ${A.relative(process.cwd(),s)||"."}`," npm install"," npx greatstore apps init <component_name> # add your first component",""),process.stdout.write(u.join(`
85
85
  `));return}let l=A.join(s,"components",t);oo(l,t,n);let p=A.relative(process.cwd(),s)||".";process.stdout.write([`Added component "${t}" at components/${t}/.`,...i&&c.length>0?["",`Also added to the project root: ${c.join(", ")}`]:[],"","Next steps:",...i?[]:[` cd ${p}`," npm install"],` # edit components/${t}/component.tsx and manifest.json`," npx greatstore apps build"," npx greatstore apps push",""].join(`
86
86
  `))}function eo(e){return S.existsSync(A.join(e,"package.json"))&&S.existsSync(A.join(e,".gsrc"))}function to(e,t,n,r){if(S.mkdirSync(e,{recursive:!0}),!t&&!n&&S.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?io():so({store:r.store}),s=ro(e,o,n);return S.mkdirSync(A.join(e,"components"),{recursive:!0}),s}var no=new Set(["AGENTS.md"]);function ro(e,t,n){let r=[];for(let[o,s]of t){let i=A.join(e,o);S.mkdirSync(A.dirname(i),{recursive:!0});let a=S.existsSync(i);if(!n&&a&&!no.has(o))continue;let c=!a||S.readFileSync(i,"utf8")!==s;S.writeFileSync(i,s),c&&r.push(o)}for(let o of["CLAUDE.md","GEMINI.md"]){let s=A.join(e,o);n&&nn(s)&&S.rmSync(s),nn(s)||(S.symlinkSync("AGENTS.md",s),r.push(o))}return r}function nn(e){try{return S.lstatSync(e),!0}catch{return!1}}function oo(e,t,n){if(S.existsSync(e)&&!n&&S.readdirSync(e).length>0)throw new Error(`Refusing to overwrite existing components/${t}/. Pass --force to override.`);S.mkdirSync(e,{recursive:!0});for(let[r,o]of ao(t))S.writeFileSync(A.join(e,r),o)}function at(e,t,n=new Set){let r=Zt();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,en(s,t)])}function so(e){if(!e.store)throw new Error("internal: rootFiles called without a store slug");return at("root/",{store:e.store,version:F})}function io(){return at("root/",{version:F},new Set([".gsrc"]))}function ao(e){return at("component/",{name:e,displayName:lo(e)})}function lo(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 k from"fs";import*as h from"path";import*as fe from"fs";import*as lt from"path";var $="style.css",_="bundle.css",Ne=`./${$}`,on=256*1024;function co(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,""),n=[],r=/(?:^|[;{}])\s*import\s+(?:[^'";]*?\s+from\s+)?["']([^"']+\.css)(?:\?[^"']*)?["']/gm,o=/\bimport\s*\(\s*["']([^"']+\.css)(?:\?[^"']*)?["']\s*\)/g;for(let s of t.matchAll(r))n.push(s[1]);for(let s of t.matchAll(o))n.push(s[1]);return n}function N(e){let t=lt.join(e,"component.tsx");if(!fe.existsSync(t))return{imported:!1,problems:[]};let n=co(fe.readFileSync(t,"utf8")),r=n.filter(i=>i!==Ne).map(i=>({file:"component.tsx",message:`imports "${i}". A component's styles go in its own ${$}, imported as "${Ne}"; move these rules there.`})),o=n.includes(Ne);if(!o)return{imported:o,problems:r};let s=lt.join(e,$);if(!fe.existsSync(s))return r.push({file:"component.tsx",message:`imports "${Ne}", but there's no ${$} beside it.`}),{imported:o,problems:r};for(let i of uo(fe.readFileSync(s,"utf8")))r.push({file:$,message:i});return{imported:o,problems:r}}function uo(e){let t=[],n=Buffer.byteLength(e,"utf8");n>on&&t.push(`is ${(n/1024).toFixed(1)} KB; the limit is ${on/1024} KB.`);let r=e.replace(/\/\*[\s\S]*?\*\//g,s=>s.replace(/[^\n]/g," ")),o=s=>r.slice(0,s).split(`
87
87
  `).length;for(let s of r.matchAll(/@import\b/gi))t.push(`line ${o(s.index)} uses @import. A stylesheet ships on its own, so copy the rules in instead.`);for(let s of r.matchAll(/url\(\s*(["']?)([^"')]*)\1\s*\)/gi)){let i=s[2].trim();/^(https:|data:|#)/i.test(i)||t.push(`line ${o(s.index)} refers to "${i}". Only https: and data: URLs work here \u2014 nothing beside the stylesheet is uploaded with it.`)}return t}import{createRequire as vo}from"module";import{pathToFileURL as Cn}from"url";import*as hn from"fs";import*as U from"path";import{createRequire as po}from"module";import*as Be from"path";function an(e,t,n){let r=cn(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=mo(r,o);return s?yo(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 ${Be.basename(t)} could not be parsed (${o.message})`}}}function ln(e,t,n){let r=cn(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(fo(r,a)){s=!0;return}r.forEachChild(a,i)}};return i(o),s}catch{return!1}}function fo(e,t){if(e.isPropertyAccessExpression(t))return sn(e,t.expression)&&t.name.text==="GreatStore";if(e.isElementAccessExpression(t)){let n=t.argumentExpression;return sn(e,t.expression)&&e.isStringLiteralLike(n)&&n.text==="GreatStore"}return!1}function sn(e,t){return e.isIdentifier(t)&&(t.text==="window"||t.text==="globalThis")}function cn(e){let t=po(Be.join(e,"package.json"));try{return t("typescript")}catch{return null}}function mo(e,t){let n=null;for(let o of t.statements){if(e.isFunctionDeclaration(o)&&go(e,o))return o;e.isExportAssignment(o)&&!o.isExportEquals&&(n=o.expression)}if(!n)return null;let r=un(e,n);return e.isArrowFunction(r)||e.isFunctionExpression(r)?r:e.isIdentifier(r)?ho(e,t,r.text):null}function go(e,t){return t.modifiers?.some(n=>n.kind===e.SyntaxKind.DefaultKeyword)??!1}function un(e,t){let n=t;for(;e.isParenthesizedExpression(n)||e.isAsExpression(n)||e.isSatisfiesExpression(n);)n=n.expression;return n}function ho(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=un(e,o.initializer);if(e.isArrowFunction(s)||e.isFunctionExpression(s))return s}}return null}function yo(e,t,n){let r=n.parameters[0];if(!r)return{ok:!0,props:{names:[],open:!1}};if(r.type){let o=ct(e,t,r.type,new Set);if(o)return{ok:!0,props:o}}return e.isObjectBindingPattern(r.name)?{ok:!0,props:wo(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 ct(e,t,n,r){if(e.isTypeLiteralNode(n))return fn(e,n.members);if(e.isTypeReferenceNode(n)&&e.isIdentifier(n.typeName))return pn(e,t,n.typeName.text,r);if(e.isIntersectionTypeNode(n)){let o=n.types.map(s=>ct(e,t,s,r));return o.every(s=>s===null)?null:mn(o.map(s=>s??{names:[],open:!0}))}return null}function pn(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=fn(e,o.members),i=(o.heritageClauses??[]).flatMap(a=>a.types.map(c=>e.isIdentifier(c.expression)?pn(e,t,c.expression.text,r)??{names:[],open:!0}:{names:[],open:!0}));return mn([s,...i])}if(e.isTypeAliasDeclaration(o)&&o.name.text===n)return ct(e,t,o.type,r)}return null}function fn(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=dn(e,o.name);if(s===null){r=!0;continue}n.push(s)}return{names:n,open:r}}function wo(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=dn(e,s);i===null?r=!0:n.push(i)}return{names:n,open:r}}function dn(e,t){return e.isIdentifier(t)||e.isStringLiteral(t)?t.text:null}function mn(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 yn(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=ut(t,o),a=ut(t,s),c=[],l=null,p=gn(o);if(p===null)c.push({severity:"error",rule:"manifest/missing",file:i,message:"manifest not found."});else try{let m=JSON.parse(p);!m||typeof m!="object"||Array.isArray(m)?c.push({severity:"error",rule:"manifest/invalid",file:i,message:"manifest must be a JSON object."}):l=m}catch(m){c.push({severity:"error",rule:"manifest/invalid",file:i,message:`manifest is not valid JSON: ${m.message}`})}let u=gn(s),d=u===null?{ok:!1,reason:`couldn't check props against the manifest \u2014 ${a} not found`}:an(t,s,u),x=u===null?!1:ln(t,s,u);return{ctx:{name:n,manifestFile:i,sourceFile:a,manifest:l,props:d,usesWindowGreatStore:x,styleFile:ut(t,U.join(r,"style.css")),stylesheet:N(r)},diagnostics:c}}function gn(e){try{return hn.readFileSync(e,"utf8")}catch{return null}}function ut(e,t){let n=U.relative(e,t);return n.startsWith("..")?t:n.split(U.sep).join("/")}var wn=new Set(["$"]);var pt=new Map([["onSendMessage","sendMessage"],["onClose","close"],["onUpdateModelContext","updateModelContext"],["onShowLightbox","showLightbox"],["onGenerateStructuredContent","generateStructuredContent"],["storeData","store"],["Image","Image"],["useVoiceCall","useVoiceCall"]]);function Sn(e){let t=e.map(o=>`\`${o}\``).join(", "),n=e.map(o=>pt.get(o)).join(", "),r=e.length===1;return`${t} ${r?"is":"are"} retired \u2014 new apps must use \`const { ${n} } = $\`. Support for the old ${r?"prop":"props"} can end without notice; migrate before your next release.`}var bn=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 $n(e){if(!e.manifest)return[];let t=bo(e.manifest.inputSchema);if(t===null)return[];let n=[];if(t.includes("$")&&n.push({severity:"error",rule:"props/reserved",file:e.manifestFile,message:`${e.manifestFile} declares inputSchema field \`$\`, but GreatStore always passes its own \`$\` prop, so that field can never reach the component. Rename the field.`}),!e.props.ok)return[...n,{severity:"warning",rule:"props/not-analyzable",file:e.sourceFile,message:`${e.props.reason}.`}];if(e.props.props.open)return n;let r=new Set(e.props.props.names),o=new Set(t),s=[];for(let a of e.props.props.names){if(wn.has(a))continue;if(pt.has(a)){s.push(a);continue}let c=bn.get(a);if(c){n.push({severity:"warning",rule:"props/retired-lifecycle",file:e.sourceFile,message:c});continue}o.has(a)||n.push({severity:"warning",rule:"props/undeclared",file:e.sourceFile,message:`prop \`${a}\` 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.`})}s.length>0&&n.push({severity:"warning",rule:"props/retired-app-api",file:e.sourceFile,message:Sn(s)});let i=t.filter(a=>a!=="$"&&!r.has(a));return i.length>0&&n.push({severity:"error",rule:"props/missing",file:e.sourceFile,message:So(e.manifestFile,i)}),n}var xn=8;function So(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,xn).map(s=>`\`${s}\``).join(", "),r=t.length-xn,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 bo(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 xo=["anyOf","oneOf","allOf","$ref","not"];function De(e,t,n){if(Array.isArray(e)){e.forEach((s,i)=>De(s,`${t}[${i}]`,n));return}if(!e||typeof e!="object")return;let r=e;for(let s of xo)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,De(i,`${t}.${s}`,n);"items"in r&&De(r.items,`${t}[]`,n)}function vn(e){let t=e.manifest?.inputSchema;if(!t||typeof t!="object")return[];let n={bytes:Buffer.byteLength(JSON.stringify(t),"utf8"),fields:0,unionPaths:[]};De(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("; ")}.
@@ -176,11 +176,13 @@ Did you mean: ${i.join(", ")}?`:""))}if(typeof r!="string"){if(s.kind==="boolean
176
176
  `);return}let s=`${v(t)}/connectors/health`,i=await f(s,{method:"POST",body:r?{id:r}:{}});if(g(e.flags,"json")){process.stdout.write(JSON.stringify(i.health,null,2)+`
177
177
  `);return}let a=new Map(n.connectors.map(c=>[c.id,c.name]));for(let c of i.health){let l=a.get(c.id)??c.id;c.ok?process.stdout.write(` ok ${l} (${c.toolCount??0} tools)
178
178
  `):(process.stdout.write(` failed ${l}: ${c.error??"discovery failed"}
179
- `),process.exitCode=1)}}var Qo={readOnly:"read-only",write:"write",other:"other"};async function yr(e){let t=w(e),n=e.positional[0];if(!n)throw new Error("Usage: npx greatstore connectors tools <name|id|maker> [<tool>] [--json]");let r=n==="maker"?"maker":te(await R(t),n).id,o=await f(`${v(t)}/connectors/tools`,{method:"POST",body:{id:r}});if(!o.ok||!o.tools)throw new Error(`Couldn't list the tools of ${n}: ${o.error??"discovery failed"}`);let s=e.positional[1],i=s?o.tools.filter(a=>a.name===s):o.tools;if(s&&i.length===0)throw new Error(`${n} has no tool named "${s}". Run \`npx greatstore connectors tools ${n}\` to see them.`);if(g(e.flags,"json")){process.stdout.write(JSON.stringify(s?i[0]:i,null,2)+`
179
+ `),process.exitCode=1)}}var Qo={readOnly:"read-only",write:"write",other:"other"};async function yr(e){let t=w(e),n=e.positional[0];if(!n)throw new Error("Usage: npx greatstore connectors tools <name|id|maker|webmcp> [<tool>] [--json]");let r=n==="maker"||n==="webmcp"?n:te(await R(t),n).id,o=await f(`${v(t)}/connectors/tools`,{method:"POST",body:{id:r}});if(!o.ok||!o.tools)throw new Error(`Couldn't list the tools of ${n}: ${o.error??"discovery failed"}`);let s=e.positional[1],i=s?o.tools.filter(a=>a.name===s):o.tools;if(s&&i.length===0)throw new Error(`${n} has no tool named "${s}". Run \`npx greatstore connectors tools ${n}\` to see them.`);if(g(e.flags,"json")){process.stdout.write(JSON.stringify(s?i[0]:i,null,2)+`
180
+ `);return}if(r==="webmcp"&&i.length===0){process.stdout.write(`No page tools yet. A tool shows up here after a chat on a page that registers it once GreatStore is ready.
180
181
  `);return}process.stdout.write(i.map(es).join(`
181
182
 
182
183
  `)+`
183
- `)}function Zo(e){if(e.callable)return"callable from the page with GreatStore.callTool";switch(e.reason){case"not_read_only":return"not callable from the page: it changes state";case"shadowed":return`not callable from the page: the name reaches ${e.shadowedBy==="app"?"a store app":e.shadowedBy} instead`;case"unavailable":return"not callable from the page: its connector is off, the tool is disallowed, or it was added in the last few minutes"}}function es(e){let t=[`## ${e.name}`,`${Qo[e.group]}, ${e.allowed?"allowed":"disallowed"} \u2014 ${Zo(e.page)}`];e.description&&t.push("",e.description.trim()),t.push("","Input:");let n=yt(e.inputSchema??{},1);return t.push(...n.length>0?n:[" (none)"]),t.join(`
184
+ `)}function Zo(e){if(e.callable)return"callable from the page with GreatStore.callTool";switch(e.reason){case"not_read_only":return"not callable from the page: it changes state";case"shadowed":return`not callable from the page: the name reaches ${e.shadowedBy==="app"?"a store app":e.shadowedBy} instead`;case"unavailable":return"not callable from the page: its connector is off, the tool is disallowed, or it was added in the last few minutes"}}function es(e){let t=[`## ${e.name}`,`${Qo[e.group]}, ${e.allowed?"allowed":"disallowed"} \u2014 ${Zo(e.page)}`];if(e.notSeenRecently&&t.push("not registered by your pages in the last 30 days"),e.description&&t.push("",e.description.trim()),!e.inputSchema)return t.push("","Input: as declared in the page's own registerTool call"),t.join(`
185
+ `);t.push("","Input:");let n=yt(e.inputSchema,1);return t.push(...n.length>0?n:[" (none)"]),t.join(`
184
186
  `)}function yt(e,t){let n=Pe(e.properties);if(!n)return[];let r=new Set(Array.isArray(e.required)?e.required:[]),o=[];for(let[s,i]of Object.entries(n)){let a=Pe(i)??{};o.push(...wt(s,a,r.has(s),t))}return e.additionalProperties===!1&&o.push(`${St(t)}(no other fields accepted)`),o}function wt(e,t,n,r){let o=[ts(t),n?"required":"optional",...hr(t)],s=typeof t.description=="string"?` \u2014 ${t.description.trim()}`:"",i=[`${St(r)}${e} (${o.join(", ")})${s}`];i.push(...yt(t,r+1));let a=Pe(t.items);if(a){let c=yt(a,r+2);c.length>0?i.push(`${St(r+1)}each item:`,...c):(hr(a).length>0||a.description)&&i.push(...wt("each item",a,!0,r+1))}for(let c of["anyOf","oneOf","allOf"])(Array.isArray(t[c])?t[c]:[]).forEach((p,u)=>{let d=Pe(p);d&&i.push(...wt(`${c}[${u}]`,d,!0,r+1))});return i}function ts(e){let t=e.type,n=Array.isArray(t)?t.join(" | "):typeof t=="string"?t:"any",r=Pe(e.items);return n==="array"&&r&&typeof r.type=="string"?`array of ${r.type}`:n}var ns=[["minimum","min"],["maximum","max"],["exclusiveMinimum","greater than"],["exclusiveMaximum","less than"],["minLength","min length"],["maxLength","max length"],["minItems","min items"],["maxItems","max items"],["pattern","pattern"],["format","format"]];function hr(e){let t=[];Array.isArray(e.enum)&&t.push(`one of ${e.enum.map(n=>JSON.stringify(n)).join(", ")}`),"const"in e&&t.push(`always ${JSON.stringify(e.const)}`);for(let[n,r]of ns)e[n]!==void 0&&t.push(`${r} ${String(e[n])}`);return e.uniqueItems===!0&&t.push("unique items"),"default"in e&&t.push(`default ${JSON.stringify(e.default)}`),t}function Pe(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function St(e){return" ".repeat(e)}var rs=7,wr=120,os=864e5,ss={mcp:"connector",local:"custom app",browser:"browser"};async function Sr(e){let t=w(e),n=is(y(e.flags,"days")),r=y(e.flags,"tool"),o=new Date,s=new Date(o.getTime()-n*os),i=await f(`${v(t)}/usage/report`,{method:"POST",body:{from:s.toISOString(),to:o.toISOString(),bucket:"day"}}),a=i.data.tools.toolFailures??[],c=r?a.filter(u=>u.tool_name===r):a,l=i.data.tools.toolFailuresTruncated===!0;if(g(e.flags,"json")){process.stdout.write(JSON.stringify({days:n,errors:c,truncated:l},null,2)+`
185
187
  `);return}let p=r?`${r} in ${t}`:t;if(c.length===0){process.stdout.write(`(no tool errors in ${p} in the last ${n} days)
186
188
  `);return}process.stdout.write(`Tool errors in ${p}, last ${n} days (most frequent first):
@@ -196,6 +198,12 @@ The rarest errors are left out of this list.
196
198
  All notable changes to \`@greatstore/cli\` are recorded here. The format
197
199
  follows [Keep a Changelog](https://keepachangelog.com/).
198
200
 
201
+ ## 0.2.16 \u2014 2026-10-30
202
+
203
+ ### Added
204
+ - \`connectors tools webmcp\` lists the WebMCP tools your pages register: each tool's name, description, whether the assistant may call it, and that a page can run it with \`GreatStore.callTool\`.
205
+ - The agent guide covers running a page's own WebMCP tools with \`GreatStore.callTool\` and an app's \`$.callTool\`, including that a page tool takes precedence over an app or connector tool of the same name.
206
+
199
207
  ## 0.2.15 \u2014 2026-10-29
200
208
 
201
209
  ### Added
@@ -865,7 +873,8 @@ Store administration:
865
873
  connectors maker on|off Toggle the Maker MCP.
866
874
  connectors health [<name>] Live-probe saved connectors.
867
875
  connectors tools <name> [<t>] A connector's tools in full; 'maker'
868
- for the Maker MCP.
876
+ for the Maker MCP, 'webmcp' for the
877
+ tools your pages register.
869
878
  connectors errors The store's most frequent tool errors (last 7 days;
870
879
  --days N for up to 120, --tool <name> for one tool).
871
880
  apps <subcommand> Author and ship custom in-chat apps (init, build,
@@ -23,10 +23,10 @@ constraints) that the references spell out.
23
23
  | Goal | Use | Read |
24
24
  |---|---|---|
25
25
  | Install the widget; control the panel; readiness, events, troubleshooting | `window.GreatStore` SDK | [references/embed-api.md](references/embed-api.md) |
26
- | AI-generated, catalog-grounded content rendered in **your own HTML/CSS** (highlights, comparisons, FAQs, gift guides) | `generateStructuredContent(schema, prompt)` | [references/structured-content.md](references/structured-content.md) |
26
+ | AI-generated, catalog-grounded content rendered in **your own HTML/CSS** (highlights, comparisons, FAQs, gift guides) | `generateStructuredContent(schema, prompt)` | [references/embed-api/generate-structured-content.md](references/embed-api/generate-structured-content.md) |
27
27
  | Contextual **conversation entry points** anywhere on the page | `sendMessage(text)`, `open()`, `?gs_chat=open` | [references/embed-api/send-message.md](references/embed-api/send-message.md) |
28
28
  | Feed the assistant **invisible page/app state** (current product, cart, selected variant) | `updateModelContext(text)`; an app's `$.updateModelContext` | [references/embed-api/update-model-context.md](references/embed-api/update-model-context.md), [references/apps.md](references/apps.md) |
29
- | **Fetch store data into your own UI** from a connector's read-only tool, or open a full-screen app from a button | `callTool(name, args)`; an app's `$.callTool` | [references/embed-api/call-tool.md](references/embed-api/call-tool.md) |
29
+ | **Fetch store data into your own UI** from a connector's read-only tool, open a full-screen app from a button, or run a page tool || `callTool(name, args)`; an app's `$.callTool` | [references/embed-api/call-tool.md](references/embed-api/call-tool.md) |
30
30
  | Let the assistant **act on the page** (cart, navigation, filters) | WebMCP: `document.modelContext.registerTool(...)` | [references/embed-api/webmcp.md](references/embed-api/webmcp.md) |
31
31
  | Custom **interactive UI inside the chat** (configurators, quizzes, size guides, booking forms) | apps shipped with the `gs` CLI | [references/apps.md](references/apps.md) |
32
32
  | Run one of those apps **on your own page**, outside the conversation | `surfaces: ["embed"]` + the container snippet | [references/apps.md](references/apps.md) |
@@ -256,11 +256,11 @@ component. Never declare a `$` field in `inputSchema` — the build refuses it.
256
256
  |---|---|
257
257
  | `$.sendMessage(text)` | Send text into the chat as if the shopper typed it — lets the app drive the conversation ("Selected size M, what's the return policy?"). |
258
258
  | `$.updateModelContext(context)` | Inject **invisible** background context for the model — the variant the shopper selected, the options they configured, the step they're on. Replaces the prior value (never appends); pass `""` to clear. Read on the next chat turn. Use this instead of `$.sendMessage` when the assistant should *know* state without a message appearing in the transcript. |
259
- | `$.callTool(name, args?)` | The page's `window.GreatStore.callTool`, for the app: run a read-only connector tool and get its result, or open a full-screen app by name — see [embed-api/call-tool.md](embed-api/call-tool.md) for what it reaches, what comes back, and how to look up tools. Never touches the conversation. In the app preview, tools run for real and naming a full-screen app only logs what would open. Inside other AI assistants (ChatGPT, …) it always rejects — handle the rejection. |
259
+ | `$.callTool(name, args?)` | The page's `window.GreatStore.callTool`, for the app: run one of the page's own WebMCP tools or a read-only connector tool and get its result, or open a full-screen app by name — see [embed-api/call-tool.md](embed-api/call-tool.md) for what it reaches, what comes back, and how to look up tools. Never touches the conversation. In the app preview, tools run for real and naming a full-screen app only logs what would open. Inside other AI assistants (ChatGPT, …) it always rejects — handle the rejection. |
260
260
  | `$.showLightbox({ src, originRect? })` | Expand an image in the chat's shared full-screen lightbox — an on-brand zoom overlay you can't render yourself (your app is 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). |
261
261
  | `$.generateStructuredContent(schema, prompt, fallback)` | Ask the store's assistant for content matching a JSON Schema (or Zod schema) and get back the generated object. Personalized to the shopper. Works the same in the conversation on the storefront and every embed. Best for async apps that build their render from a generated payload. `fallback` is **required**: a schema-shaped object you provide that the app preview renders (no live store there), validated against the schema — a mismatch throws. |
262
262
  | `$.close()` | Dismiss the host slot. `over-input` clears the overlay, `fullscreen` reverts the pane, `inline` is a no-op. |
263
- | `$.useVoiceCall()` | A hook — call it at the top of your component like any other — returning `{ status, available, start, end }` for a voice call with the store's assistant. `start()` starts the call without opening the chat — it runs in the collapsed chat bar (which stays hidden if the store hides the chat until opened), and the chat opens only when the assistant shows an inline app (call it from a click; it rejects when the store has no voice), `end()` hangs up. `available` says whether the store has voice. `status` is `null` until a call starts, then `started`, `connecting`, `connected`, `listening` / `speaking` / `working` as the conversation goes, `disconnected` while the network drops (the call recovers on its own), and `ended`. Your app re-renders on every change. |
263
+ | `$.useVoiceCall()` | A hook — call it at the top of your component like any other — returning `{ status, available, start, end }` for a voice call with the store's assistant. `start()` starts the call without opening the chat — it runs in the collapsed chat bar (which stays hidden if the store hides the chat until opened), and the chat opens only when the assistant shows an inline app (call it from a click; it rejects when the store has no voice), `end()` hangs up. `available` says whether the store has voice. `status` is `null` until a call starts, then `started`, `connecting`, `connected`, `listening` / `speaking` / `working` as the conversation goes, `disconnected` while the network drops (the call recovers on its own), and `ended` — or `rejected` instead of `ended` when the shopper refuses the microphone (calling `start()` again asks again, though a browser where they blocked it refuses without asking). Your app re-renders on every change. |
264
264
  | `$.Image` | A drop-in for `<img>` — render `<Image src=… alt=… />` and the image is served at the right size for the store. Takes the same props as `<img>`. |
265
265
  | `$.store` | `{ slug }` — the store the app is running in. |
266
266
 
@@ -384,7 +384,7 @@ export default async function Results(props: Props) {
384
384
  ## When to build an app vs. the other facets
385
385
 
386
386
  - Content for the **merchant's page** → `window.GreatStore.generateStructuredContent`
387
- ([structured-content.md](structured-content.md)). Inside an app, use
387
+ ([embed-api/generate-structured-content.md](embed-api/generate-structured-content.md)). Inside an app, use
388
388
  `$.generateStructuredContent` instead — same idea, but personalized to the
389
389
  shopper and available on every surface without the global.
390
390
  - Letting the assistant **act on the page** → WebMCP page tools
@@ -1,6 +1,6 @@
1
1
  # `callTool(name: string, args?: object): Promise<object | undefined>`
2
2
 
3
- The page's own way to reach two things by name, without the shopper asking
3
+ The page's own way to reach three things by name, without the shopper asking
4
4
  and without touching the conversation (nothing is added to the chat and the
5
5
  assistant never learns the call happened).
6
6
 
@@ -16,6 +16,20 @@ page's, not the conversation's — a reload drops it. `inline` and
16
16
  window.GreatStore.callTool("show_size_guide", { category: "boots" });
17
17
  ```
18
18
 
19
+ **A page tool.** Name a WebMCP tool the page registered once GreatStore was
20
+ ready (anything listed in `window.GreatStore.tools`) and it runs right there
21
+ on the page, resolving with the tool's result: `content`, plus
22
+ `structuredContent` when `execute` returned an object. Unlike a connector tool it may change state —
23
+ it is the page's own code. A page tool wins over an app or connector tool of
24
+ the same name, which is how a page overrides one for GreatStore alone.
25
+
26
+ ```js
27
+ await window.GreatStore.callTool("add_to_cart", { variant_id: 123, quantity: 1 });
28
+ ```
29
+
30
+ `npx greatstore connectors tools webmcp --store my-store` lists the page
31
+ tools the store's pages have registered in recent chats.
32
+
19
33
  **A read-only connector tool.** Name any read-only tool from the store's
20
34
  connectors (Maker MCP or the merchant's own MCP servers) and it resolves
21
35
  with the tool's MCP `tools/call` result exactly as the server returned it:
@@ -43,15 +57,14 @@ not when it doesn't. Trust that line over your own reading of the tool. It
43
57
  also spells out every input: type, whether it's required, allowed values,
44
58
  limits and description, nested fields included. Add `--json` for the raw input
45
59
  schema. In short, only read-only tools the assistant itself can call are
46
- reachable. A tool that changes state (cart, checkout) is refused, and so are
47
- WebMCP page tools (the page already has those). When an app and a tool share
48
- a name, the app wins. Before writing code against the
60
+ reachable. A connector tool that changes state (cart, checkout) is refused.
61
+ When an app and a connector tool share a name, the app wins. Before writing code against the
49
62
  result, call the tool once from the browser console and read what comes back:
50
63
  the result's shape is the connector's too, and the listing doesn't describe
51
64
  it.
52
65
 
53
- It rejects with an `Error` when the name is neither, when an app isn't
54
- full-screen or the args don't match its schema, when the tool is not
66
+ It rejects with an `Error` when the name is none of these, when an app isn't
67
+ full-screen or the args don't match its schema, when a connector tool is not
55
68
  read-only, when the tool answers with an error (the message is the tool's
56
69
  own text), or when the server can't be reached. Loads the chat first if it
57
70
  isn't up yet.
@@ -1,15 +1,285 @@
1
1
  # `generateStructuredContent(schema: object, prompt: string): Promise<unknown>`
2
2
 
3
3
  Generates JSON matching `schema` from `prompt`, grounded in the store's live
4
- catalog. Resolves to the generated data object itself. Rejects with `Error`
5
- on any failure (invalid input, decline, validation failure, rate limit,
6
- network); a decline sets `error.reason`. See
7
- [structured-content.md](../structured-content.md) for the full
8
- contract, schema support, caching, and error semantics.
9
-
10
- Accepts either a plain JSON Schema object or any object exposing a
11
- `.toJSONSchema()` method (e.g. Zod schemas) — the conversion is called for
12
- you.
13
-
14
- Throws synchronously (rejects) if `prompt` is not a non-empty string or
15
- `schema` is not an object.
4
+ catalog, for UI the page renders itself — the chat panel is not involved.
5
+ Resolves to **the generated data object itself**. Rejects with an `Error` on
6
+ any failure (invalid input, decline, validation failure, rate limit,
7
+ network); see [Errors](#errors).
8
+
9
+ ```js
10
+ const data = await window.GreatStore.generateStructuredContent(schema, prompt);
11
+ ```
12
+
13
+ - `schema` — a JSON Schema object describing the output, or any object
14
+ exposing `.toJSONSchema()` (e.g. a Zod schema); the conversion is called
15
+ for you, and `.describe("…")` becomes the field's `description`.
16
+ - `prompt` — what to generate.
17
+
18
+ Rejects immediately if `prompt` is not a non-empty string or `schema` is not
19
+ an object.
20
+
21
+ ## The rules that make it work well
22
+
23
+ Each is unpacked in the sections below; this is the checklist.
24
+
25
+ 1. **Top level must be an object.** Want a list? Wrap it:
26
+ `{ type: "object", properties: { items: { type: "array", … } }, required: ["items"] }`.
27
+ 2. **Steer the whole output with the prompt, single fields with
28
+ `description`.** Use self-explanatory property names (`benefitHeadline`,
29
+ not `text1`) and describe only where the name isn't enough.
30
+ 3. **Only `require` what's guaranteed.** `required` is strictly enforced; if
31
+ the catalog can't ground a required field the whole call can fail. Require
32
+ structural fields, keep per-product details (image URLs, prices) optional,
33
+ and make rendering tolerate missing values.
34
+ 4. **Point, don't paste.** GreatStore researches the store's live catalog on
35
+ its own — name the entity (`` `…the product "${productName}" (SKU ${sku})` ``)
36
+ and let it look the facts up. The one thing it *can't* see is your page,
37
+ so page-only context (which page the shopper is on, what the section is
38
+ for) does belong in the prompt.
39
+ 5. **Research is bounded by the store's connectors — validate before you
40
+ build.** Ask for something no connector provides — currency conversion,
41
+ live shipping rates, review data the store never wired up — and it has
42
+ nothing to ground on, so it will decline, omit… or hallucinate. Run
43
+ `npx greatstore connectors` (and `npx greatstore connectors health`,
44
+ [store-admin.md](../store-admin.md)) first; if there's no connector for
45
+ it, don't ask for it.
46
+ 6. **Responses are cached** for up to ~24h per page + prompt + schema. Keep
47
+ prompts deterministic per page — no timestamps, random values, or
48
+ per-visitor data.
49
+ 7. **Progressive enhancement, always.** Generate after the page renders into
50
+ a hidden container, reveal on success, leave the fallback on error. Render
51
+ generated strings via `textContent`, never `innerHTML`.
52
+ 8. **One rich call beats many small ones** — there's a per-IP rate limit
53
+ (~20 requests/minute); fetch multiple surfaces with one combined schema.
54
+
55
+ ## What happens on a call
56
+
57
+ 1. The SDK posts your schema + prompt to the store, along with the current
58
+ **page context**, sent automatically — you don't pass it, and you can't
59
+ override it:
60
+ - the page URL, **without its query string or fragment**;
61
+ - the page title;
62
+ - a small, length-capped subset of the page's schema.org JSON-LD
63
+ (`Product`, `ProductGroup`, `Offer`, `Article`, `WebPage`, `FAQPage`,
64
+ `AggregateRating`). For products that's identifiers only — name,
65
+ brand, SKU, GTIN, URL — so emitting product JSON-LD is the most
66
+ reliable way to tell GreatStore exactly which product the page is
67
+ about.
68
+ 2. GreatStore **researches** the store's live catalog (products, prices,
69
+ availability, store info) using read-only lookups. The page context only
70
+ hints at which product or category to look up — it is *not* a source of
71
+ product data, and nothing else on the page (visible text, reviews, your
72
+ markup) is read. Its reach is exactly the store's MCP connectors.
73
+ 3. The AI fills your schema from the researched data under a strict
74
+ grounding contract: it must not invent product names, prices, images, IDs,
75
+ or descriptions. Fields it can't ground are omitted or `null`. For an
76
+ identified shopper it also sees their shopper profile — the same identity
77
+ the chat assistant has — so the output can be subtly personalized without
78
+ you passing anything about the visitor.
79
+ 4. The output is validated against your schema (with internal retries)
80
+ before being returned and cached.
81
+
82
+ Because GreatStore already knows who's reading, never put shopper data in
83
+ the prompt — it's redundant, and it poisons the cache key.
84
+
85
+ ## Schema support
86
+
87
+ Top level **must describe an object**: `type: "object"` (or a bare
88
+ `properties` / `anyOf`).
89
+
90
+ Supported keywords (anything else is tolerated but ignored):
91
+
92
+ - Types: `object`, `array`, `string`, `number`, `integer`, `boolean`, `null`
93
+ - Structure: `properties`, `required`, `items`, `additionalProperties`
94
+ - Choice: `enum`, `const`, `anyOf`, `nullable`
95
+ - Constraints: `minimum`, `maximum`, `minLength`, `maxLength`, `minItems`,
96
+ `maxItems`, `pattern`, `format`, `default`
97
+ - Guidance: `description`, `example`, `title` (on any property)
98
+
99
+ Validation of the output is real: `required` is enforced, `enum`/`const`
100
+ must match, numeric and length bounds are checked, and
101
+ `additionalProperties: false` rejects extra keys. Constraints are therefore a
102
+ *tool* — `enum` reliably restricts a field — but every constraint is also a
103
+ way for generation to fail, so apply them only where you'd rather have no
104
+ content than non-conforming content.
105
+
106
+ Item counts are the exception. `minItems` is honored as the content is
107
+ written, so a list comes back with at least that many entries, and a list
108
+ longer than `maxItems` is cut to its first `maxItems` entries rather than
109
+ failing. The same applies to an app's `inputSchema`.
110
+
111
+ ### Field descriptions
112
+
113
+ A property's `description` is shown to the AI as guidance for that one
114
+ field, and an `example` shows the exact shape you want (`"4.5 out of 5"`,
115
+ `"SKU-1234"`). Both are optional: a field without them is filled from its
116
+ name, the prompt, and its constraints.
117
+
118
+ ```js
119
+ {
120
+ type: "object",
121
+ properties: {
122
+ headline: { type: "string", maxLength: 60 },
123
+ priceJustification: {
124
+ type: "string",
125
+ description: "One sentence on why the price is fair, citing a real material or feature",
126
+ },
127
+ rating: { type: "string", example: "4.5 out of 5" },
128
+ },
129
+ required: ["headline"],
130
+ }
131
+ ```
132
+
133
+ Split the work between the two channels:
134
+
135
+ - **Prompt** — the situation, the task as a whole, grounding, and voice.
136
+ - **`description` / `example`** — what one specific field holds: its unit,
137
+ length in words, perspective ("first-person, as the shopper"), or how it
138
+ relates to a sibling.
139
+ - Property *names* still carry most of the intent — make them
140
+ self-documenting (`ctaLabel`, `warmthRating`, `priceJustification`) and
141
+ reach for a description when the name can't say it.
142
+
143
+ ## Prompting
144
+
145
+ A good prompt states, in order:
146
+
147
+ 1. **Context** — what page/situation the shopper is in, naming the entity so
148
+ research targets the right thing (the AI can't see your DOM):
149
+ `The shopper is viewing the product "Aurora Down Parka" (SKU AUR-021) on its product page.`
150
+ 2. **Task** — what to generate, mapped loosely onto your schema's fields:
151
+ `Write a heading and 3 reasons to love it; each reason has a short title and one supporting sentence.`
152
+ 3. **Grounding expectations** — what store data to draw on:
153
+ `Base every claim on the product's real materials, features, and price.`
154
+ 4. **Voice** — tone and constraints:
155
+ `Warm and concrete. No exclamation marks, no generic marketing filler.`
156
+
157
+ Note what's *not* in that prompt: no pasted specs, prices, or descriptions.
158
+ Pointing at the SKU is enough, and the data research finds is live rather
159
+ than whatever was true when you wrote the prompt.
160
+
161
+ Anti-patterns:
162
+
163
+ - **Pasting researched material into the prompt** (specs, prices,
164
+ descriptions fetched from your platform's API). Pasted facts go stale,
165
+ bloat the cache key, and compete with the fresher data research returns.
166
+ - **Per-visitor or per-moment data in the prompt** (names, cart contents,
167
+ timestamps, `Math.random()`): destroys caching, so every visitor pays full
168
+ generation latency and the store pays for every call — and it's redundant,
169
+ because identified shoppers are personalized for server-side. For
170
+ per-shopper *interaction*, use [`sendMessage`](send-message.md) and the
171
+ chat panel.
172
+ - **Asking for data no connector provides** ("convert the price to EUR",
173
+ "estimate delivery to the shopper's city"): the AI may hallucinate
174
+ plausible-looking values rather than leave the field empty.
175
+ - **Asking it to read the page** ("summarize the reviews shown below") — it
176
+ can't. Page-only data (review snippets, UGC, things that exist nowhere but
177
+ the DOM) is the one kind worth inlining — keep it stable per page so
178
+ caching still works.
179
+ - **Asking for minute-fresh operational data** (exact live stock counts,
180
+ delivery countdowns). Even when a connector could answer, responses cache
181
+ for up to ~24h — display operational data from your own platform APIs and
182
+ use GreatStore for *editorial intelligence over the catalog*.
183
+ - **Putting whole-output instructions in a field's `description`** (voice,
184
+ grounding, what the page is) — they belong in the prompt, where they apply
185
+ to every field.
186
+
187
+ ## Caching
188
+
189
+ Responses are cached server-side for up to **24 hours**, keyed by page
190
+ context (URL path, title, JSON-LD identifiers) + prompt + schema. Anonymous
191
+ visitors share one entry per key; identified shoppers each get their own
192
+ (their output may be personalized, so it's only ever served back to them).
193
+
194
+ **The query string and fragment never reach GreatStore.** `/product?id=123`
195
+ and `/product?id=456` are the same page to it — same hints, same cache entry.
196
+ If your page picks its product from a query param, name that product in the
197
+ prompt (`` `…the product "${name}" (SKU ${sku})` ``), or emit JSON-LD for it;
198
+ either one differentiates the content and the cache.
199
+
200
+ The one exception is `intent_id`, the ad reference some ad landing URLs
201
+ carry: when it's present, content is steered toward what that ad showed and
202
+ cached for that ad alone. You don't need to do anything for this, and the
203
+ call behaves the same either way.
204
+
205
+ Practical consequences:
206
+
207
+ - **The first render pays, repeats fly.** Expect a few seconds on a cache
208
+ miss and near-instant responses after. The catalog research underneath is
209
+ also cached briefly and shared, so even misses — and several distinct
210
+ surfaces on one page — are cheaper than cold. Design loading states for
211
+ the miss case.
212
+ - **Same call on different pages = different content**, automatically — the
213
+ page path is in the key and in the AI's hints. A single site-wide snippet
214
+ with a constant prompt yields per-page content for free.
215
+ - **Content refreshes roughly daily.** Don't build experiences that assume
216
+ minute-level freshness.
217
+ - **To force different content, change the prompt or schema** (e.g. a
218
+ campaign variant string that changes weekly — deliberate, low-cardinality
219
+ variation is fine; per-visitor cardinality is not).
220
+
221
+ ## Errors
222
+
223
+ The promise rejects with `new Error(message)`. The message is
224
+ developer-facing — never render it to shoppers. Server-side failures also
225
+ carry `error.code`, and a decline carries `error.reason`.
226
+
227
+ | Case | Message you'll see | Retry? |
228
+ |---|---|---|
229
+ | Bad input (empty prompt, non-object schema) | rejected immediately by the SDK | Fix the call |
230
+ | Invalid schema shape, or constraints no output could satisfy | `Invalid schema: …` | Fix the schema |
231
+ | AI declined the request | `The assistant declined to generate content for this request.` with `error.reason` (below) | No — rework the prompt. `insufficient_data` alone can change as the catalog does. |
232
+ | Output couldn't satisfy the schema | `Failed to produce valid structured content` | No — usually `required`/constraints demand data the catalog lacks. Loosen the schema. |
233
+ | Rate limit (~20/min per IP address) | rate-limit message | Later — and consolidate calls |
234
+ | Network / server | varies | Next page load |
235
+
236
+ A decline is only ever one of these `error.reason` values — anything else
237
+ (vague wording, missing data for optional fields, marketing copy) is served:
238
+
239
+ | `reason` | Declined because the request… |
240
+ |---|---|
241
+ | `off_topic` | has nothing to do with the store or shopping there (homework, code, news, another business's products) |
242
+ | `harmful` | asks for unsafe, hateful, sexual, or illegal content, or advice that could hurt someone |
243
+ | `deceptive` | asks for fake reviews, invented discounts or scarcity, claims the catalog contradicts, or impersonating/disparaging a named brand or person |
244
+ | `system_probe` | asks about or tries to override the assistant's own instructions or tools |
245
+ | `insufficient_data` | needs store data that isn't there — the catalog doesn't carry what it's about, or nothing it needs could be found |
246
+
247
+ The uniform shopper-facing strategy: render into a hidden-by-default
248
+ container, reveal on success, leave hidden (or show your static fallback) on
249
+ any rejection. One `try/catch`, no case analysis needed unless you're
250
+ logging.
251
+
252
+ ## Performance pattern
253
+
254
+ Fire generation as early as possible without blocking render — top of your
255
+ deferred script, before other work:
256
+
257
+ ```js
258
+ const highlightsPromise = window.GreatStore?.generateStructuredContent
259
+ ? window.GreatStore.generateStructuredContent(schema, prompt).catch(() => null)
260
+ : Promise.resolve(null);
261
+
262
+ // …rest of page setup…
263
+
264
+ const data = await highlightsPromise;
265
+ if (data) renderHighlights(data);
266
+ ```
267
+
268
+ The `.catch(() => null)` attached immediately avoids unhandled-rejection
269
+ noise while keeping a single render path.
270
+
271
+ For multiple surfaces on one page, prefer **one call with a combined
272
+ schema** over parallel calls — it's one research pass, one cache entry, and
273
+ no rate-limit pressure:
274
+
275
+ ```js
276
+ const schema = {
277
+ type: "object",
278
+ properties: {
279
+ highlights: { /* … */ },
280
+ faq: { /* … */ },
281
+ crossSell: { /* … */ },
282
+ },
283
+ required: ["highlights"],
284
+ };
285
+ ```
@@ -24,16 +24,33 @@ receives the status) and as a `greatstore:voicestatus` event on `window`
24
24
  | `speaking` | The assistant is talking. |
25
25
  | `working` | The assistant is thinking or looking something up. |
26
26
  | `disconnected` | The shopper's network dropped mid-call. The call recovers on its own, back to `listening`. |
27
- | `ended` | The call is over — hung up, ended by the assistant, failed, or the microphone was refused. Always the last status. |
27
+ | `ended` | The call is over — hung up, ended by the assistant, or failed. |
28
+ | `rejected` | The shopper refused the microphone, so the call never connected. Comes in place of `ended`. |
29
+
30
+ Every call finishes on exactly one of `ended` or `rejected`.
31
+
32
+ Use `rejected` to tell the shopper why nothing happened. Calling
33
+ `startVoiceCall()` again asks for the microphone again, but whether the shopper
34
+ sees the prompt is up to the browser: once they've blocked the microphone for
35
+ the site, the browser refuses without asking (and `rejected` fires again) until
36
+ they allow it in the browser's site settings. A prompt the shopper only closed
37
+ usually comes back.
28
38
 
29
39
  ```js
30
40
  const callButton = document.querySelector("#talk");
41
+ const micNote = document.querySelector("#mic-note");
31
42
  callButton.addEventListener("click", () => {
32
43
  if (callButton.dataset.live) window.GreatStore.endVoiceCall();
33
44
  else window.GreatStore.startVoiceCall().catch(() => (callButton.hidden = true));
34
45
  });
35
46
  window.addEventListener("greatstore:voicestatus", (event) => {
36
- const live = event.detail.status !== "ended";
47
+ const { status } = event.detail;
48
+ if (status === "rejected") {
49
+ micNote.textContent = "Allow microphone access in your browser to talk to us.";
50
+ } else if (status === "started") {
51
+ micNote.textContent = "";
52
+ }
53
+ const live = status !== "ended" && status !== "rejected";
37
54
  callButton.dataset.live = live ? "1" : "";
38
55
  callButton.textContent = live ? "Hang up" : "Talk to us";
39
56
  });
@@ -112,7 +112,7 @@ and replay in order.
112
112
  | `load()`, `open()`, `close()`, `toggle()`, `destroy()` | Pre-warm, show, hide, or tear down the chat panel. | [embed-api/panel.md](embed-api/panel.md) |
113
113
  | `sendMessage(text)` | Send a visible message as the shopper and open the panel — a conversation entry point from any element. | [embed-api/send-message.md](embed-api/send-message.md) |
114
114
  | `updateModelContext(text)` | Give the assistant invisible background context about the page (product, cart, account). | [embed-api/update-model-context.md](embed-api/update-model-context.md) |
115
- | `callTool(name, args)` | Open a full-screen app from the page, or fetch data from a connector's read-only tool. | [embed-api/call-tool.md](embed-api/call-tool.md) |
115
+ | `callTool(name, args)` | Run one of the page's own WebMCP tools, open a full-screen app from the page, or fetch data from a connector's read-only tool. | [embed-api/call-tool.md](embed-api/call-tool.md) |
116
116
  | `on(event, handler)` | Subscribe to panel and voice events. | [embed-api/events.md](embed-api/events.md) |
117
117
  | `startVoiceCall()`, `endVoiceCall()` | Start or hang up a voice call without opening the chat. | [embed-api/voice-call.md](embed-api/voice-call.md) |
118
118
  | `generateStructuredContent(schema, prompt)` | Generate catalog-grounded JSON for the page's own UI. | [embed-api/generate-structured-content.md](embed-api/generate-structured-content.md) |
@@ -32,6 +32,7 @@ npx greatstore configure --store my-store --json # brand config
32
32
  npx greatstore connectors --store my-store --json # MCP connectors feeding the assistant
33
33
  npx greatstore connectors health --store my-store # live-probe them (reports tool counts)
34
34
  npx greatstore connectors tools maker --store my-store # a connector's tools, inputs in full
35
+ npx greatstore connectors tools webmcp --store my-store # the page tools the store's pages register
35
36
  npx greatstore connectors errors --store my-store --json # tools' most frequent errors, last 7 days
36
37
  npx greatstore apps list --store my-store --json # deployed custom in-chat apps
37
38
  ```
@@ -45,17 +46,22 @@ What each read is good for:
45
46
  - **`npx greatstore connectors`** — which MCP connectors the assistant has, and whether
46
47
  the Maker MCP is on. This tells you what the assistant can actually *do*:
47
48
  check it before building features that lean on catalog data (e.g.
48
- [structured content](structured-content.md) grounding), and before
49
+ [structured content](embed-api/generate-structured-content.md) grounding), and before
49
50
  registering WebMCP page tools that would duplicate a capability a
50
51
  server-side connector already provides.
51
52
  - **`npx greatstore connectors health`** — a connector being listed doesn't mean it's
52
53
  reachable; this probes each one live. Run it when assistant behaviour
53
54
  suggests a tool isn't responding.
54
- - **`npx greatstore connectors tools <name|maker> [<tool>]`** — what a
55
+ - **`npx greatstore connectors tools <name|maker|webmcp> [<tool>]`** — what a
55
56
  connector offers, live: each tool's group, whether the assistant may call it,
56
57
  whether a page can call it with `GreatStore.callTool`, its description and
57
58
  every input with its type, constraints and description. Read it before
58
59
  writing a `callTool` call (see [embed-api/call-tool.md](embed-api/call-tool.md)).
60
+ `webmcp` lists the WebMCP page tools the store's pages have registered in
61
+ recent chats, with their names and descriptions; their inputs are whatever
62
+ the page's own `registerTool` call declares. Check it before registering a
63
+ page tool, so you extend or override what the site already has instead of
64
+ duplicating it. A tool only appears after a chat on a page that registers it.
59
65
  - **`npx greatstore connectors errors`** — what actually went wrong when the assistant
60
66
  called a tool on shoppers' behalf: each connector, custom-app or page tool's
61
67
  distinct errors, how often each happened and when last. Health only says a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@greatstore/cli",
3
- "version": "0.2.15",
3
+ "version": "0.2.16",
4
4
  "description": "CLI for administering GreatStore stores and authoring custom components.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -1,317 +0,0 @@
1
- # `generateStructuredContent` deep dive
2
-
3
- AI-generated, catalog-grounded JSON for UI you render yourself — the chat
4
- panel is not involved.
5
-
6
- ```js
7
- const data = await window.GreatStore.generateStructuredContent(schema, prompt);
8
- ```
9
-
10
- - `schema` — a JSON Schema describing the output (or a Zod schema exposing
11
- `.toJSONSchema()`).
12
- - `prompt` — what to generate.
13
- - Resolves to **the generated JSON object itself**, matching the schema.
14
- Rejects with an `Error` on any failure.
15
-
16
- Code samples here are framework-free reference implementations — re-express
17
- them in the host repo's framework (React, Vue, Shopify Liquid, …) rather
18
- than retrofitting them as-is.
19
-
20
- ## The rules that make it work well
21
-
22
- Each is unpacked in the sections below; this is the checklist.
23
-
24
- 1. **Top level must be an object.** Want a list? Wrap it:
25
- `{ type: "object", properties: { items: { type: "array", … } }, required: ["items"] }`.
26
- 2. **Steer the whole output with the prompt, single fields with
27
- `description`.** A property's `description` reaches the AI as guidance for
28
- that field; it's optional, so use self-explanatory property names
29
- (`benefitHeadline`, not `text1`) and describe only where the name isn't
30
- enough.
31
- 3. **Only `require` what's guaranteed.** `required` is strictly enforced; if
32
- the catalog can't ground a required field the whole call can fail. Require
33
- structural fields, keep per-product details (image URLs, prices) optional,
34
- and make rendering tolerate missing values.
35
- 4. **Point, don't paste.** GreatStore researches the store's live catalog on
36
- its own — name the entity (`` `…the product "${productName}" (SKU ${sku})` ``)
37
- and let it look the facts up. Don't fetch specs/prices/descriptions
38
- yourself and paste them into the prompt. The one thing it *can't* see is
39
- your page, so page-only context (which page the shopper is on, what the
40
- section is for) does belong in the prompt.
41
- 5. **Research is bounded by the store's connectors — validate before you
42
- build.** The AI can only look up what the store's MCP connectors actually
43
- provide. Ask for something outside them — currency conversion, live
44
- shipping rates, review data the store never wired up — and it has nothing
45
- to ground on, so it will decline, omit… or hallucinate. Before writing a
46
- prompt or schema that depends on a data capability, run `npx greatstore connectors`
47
- (and `npx greatstore connectors health`, [store-admin.md](store-admin.md)) and confirm
48
- a connector for it exists; if it doesn't, don't ask for it.
49
- 6. **Responses are cached** for up to ~24h per page + prompt + schema —
50
- shared across anonymous visitors, per-shopper for identified ones. "Page"
51
- means the URL path: query strings are dropped, so a page that varies by
52
- `?param` must name its product in the prompt. Keep
53
- prompts deterministic per page — no timestamps, random values, or
54
- per-visitor data (GreatStore already knows who the shopper is; see below).
55
- 7. **Progressive enhancement, always.** Generate after the page renders into
56
- a hidden container, reveal on success, leave the fallback on error. Render
57
- generated strings via `textContent`, never `innerHTML`.
58
- 8. **One rich call beats many small ones** — there's a per-IP rate limit
59
- (~20 requests/minute); fetch multiple surfaces with one combined schema.
60
-
61
- ## What actually happens
62
-
63
- 1. The SDK posts your schema + prompt to the store's GreatStore endpoint,
64
- along with the current **page context**, sent automatically — you don't
65
- pass it, and you can't override it:
66
- - the page URL, **without its query string or fragment**;
67
- - the page title;
68
- - a small, length-capped subset of the page's schema.org JSON-LD
69
- (`Product`, `ProductGroup`, `Offer`, `Article`, `WebPage`, `FAQPage`,
70
- `AggregateRating`). For products that's identifiers only — name,
71
- brand, SKU, GTIN, URL — so emitting product JSON-LD is the most
72
- reliable way to tell GreatStore exactly which product the page is
73
- about.
74
- 2. GreatStore first **researches**: it looks up real data from the store's
75
- live catalog (products, prices, availability, store info) using read-only
76
- lookups. The page context serves as hints about which product or category
77
- to look up — it is *not* treated as a source of product data, and nothing
78
- else on the page (visible text, reviews, your markup) is read. Research
79
- happens on GreatStore's side — your
80
- prompt only needs to *point* it at the right SKU, product, or collection,
81
- not carry the material. Its reach is exactly the store's MCP connectors:
82
- validate with `npx greatstore connectors` ([store-admin.md](store-admin.md)) that a
83
- connector for the data you want actually exists before you build on it —
84
- research can't exceed the wired-up connectors, and prompts that assume
85
- otherwise invite hallucinated filler.
86
- 3. The AI then fills your schema from the researched data, under a strict
87
- grounding contract: it must not invent product names, prices, images, IDs,
88
- or descriptions. Fields it can't ground are omitted or `null`. For an
89
- identified shopper this step also sees their shopper profile — the same
90
- identity the chat assistant has — so the output can be subtly personalized
91
- without you passing anything about the visitor.
92
- 4. The output is validated against your schema (with internal retries) before
93
- being returned and cached.
94
-
95
- GreatStore already knows who's reading: identity rides the request the same
96
- way it does for chat, and responses for identified shoppers are cached just
97
- for them (anonymous visitors share one entry). The practical consequence:
98
- never put shopper data in the prompt — it's redundant, and it poisons the
99
- cache key.
100
-
101
- ## Schema support
102
-
103
- Top level **must describe an object**: `type: "object"` (or a bare
104
- `properties` / `anyOf`). To get a list, wrap it in an object property.
105
-
106
- Supported keywords (anything else is tolerated but ignored):
107
-
108
- - Types: `object`, `array`, `string`, `number`, `integer`, `boolean`, `null`
109
- - Structure: `properties`, `required`, `items`, `additionalProperties`
110
- - Choice: `enum`, `const`, `anyOf`, `nullable`
111
- - Constraints: `minimum`, `maximum`, `minLength`, `maxLength`, `minItems`,
112
- `maxItems`, `pattern`, `format`, `default`
113
- - Guidance: `description`, `example`, `title` (on any property)
114
-
115
- Validation of the output is real: `required` is enforced, `enum`/`const`
116
- must match, numeric and length bounds are checked, and
117
- `additionalProperties: false` rejects extra keys. Constraints are therefore a
118
- *tool* — `enum` reliably restricts a field — but every constraint is also a
119
- way for generation to fail, so apply them only where you'd rather have no
120
- content than non-conforming content.
121
-
122
- Item counts are the exception. `minItems` is honored as the content is
123
- written, so a list comes back with at least that many entries, and a list
124
- longer than `maxItems` is cut to its first `maxItems` entries rather than
125
- failing. The same applies to an app's `inputSchema`.
126
-
127
- Zod schemas (or anything with a `.toJSONSchema()` method) are accepted and
128
- converted automatically — `.describe("…")` becomes the field's `description`.
129
-
130
- ### Field descriptions
131
-
132
- A property's `description` is shown to the AI as guidance for that one
133
- field, and an `example` shows the exact shape you want (`"4.5 out of 5"`,
134
- `"SKU-1234"`). Both are optional: a field without them is filled from its
135
- name, the prompt, and its constraints.
136
-
137
- ```js
138
- {
139
- type: "object",
140
- properties: {
141
- headline: { type: "string", maxLength: 60 },
142
- priceJustification: {
143
- type: "string",
144
- description: "One sentence on why the price is fair, citing a real material or feature",
145
- },
146
- rating: { type: "string", example: "4.5 out of 5" },
147
- },
148
- required: ["headline"],
149
- }
150
- ```
151
-
152
- Split the work between the two channels:
153
-
154
- - **Prompt** — the situation, the task as a whole, grounding, and voice.
155
- - **`description` / `example`** — what one specific field holds: its unit, length in
156
- words, perspective ("first-person, as the shopper"), or how it relates to
157
- a sibling. Instructions that apply to the whole output don't belong here.
158
- - Property *names* still carry most of the intent — make them
159
- self-documenting (`ctaLabel`, `warmthRating`, `priceJustification`) and
160
- reach for a description when the name can't say it.
161
-
162
- ## Prompting guide
163
-
164
- The prompt carries the instructions for the output as a whole (per-field
165
- guidance can sit in each field's `description` or `example`). A good prompt states, in
166
- order:
167
-
168
- 1. **Context** — what page/situation the shopper is in, naming the entity so
169
- research targets the right thing (the AI can't see your DOM, so identify
170
- it explicitly):
171
- `The shopper is viewing the product "Aurora Down Parka" (SKU AUR-021) on its product page.`
172
- 2. **Task** — what to generate, mapped loosely onto your schema's fields:
173
- `Write a heading and 3 reasons to love it; each reason has a short title and one supporting sentence.`
174
- 3. **Grounding expectations** — what store data to draw on:
175
- `Base every claim on the product's real materials, features, and price.`
176
- 4. **Voice** — tone and constraints:
177
- `Warm and concrete. No exclamation marks, no generic marketing filler.`
178
-
179
- Note what's *not* in that prompt: no pasted specs, prices, or descriptions.
180
- Pointing at the SKU is enough — GreatStore researches the rest itself, from
181
- data that's live rather than whatever was true when you wrote the prompt.
182
-
183
- Anti-patterns:
184
-
185
- - **Pasting researched material into the prompt** (specs, prices,
186
- descriptions you fetched from your platform's API). GreatStore researches
187
- the live catalog itself — point it at the SKU/product/collection and let
188
- it look things up. Pasted facts go stale, bloat the cache key, and compete
189
- with the fresher data research returns.
190
- - **Per-visitor or per-moment data in the prompt** (names, cart contents,
191
- timestamps, `Math.random()`): destroys caching, so every visitor pays full
192
- generation latency and the store pays for every call — and it's redundant,
193
- because GreatStore already knows the shopper and personalizes for
194
- identified ones server-side. If you need per-shopper *interaction*, that's
195
- what `sendMessage` and the chat panel are for.
196
- - **Asking for data no connector provides** ("convert the price to EUR",
197
- "estimate delivery to the shopper's city"): research can't exceed the
198
- store's MCP connectors, and the AI may hallucinate plausible-looking
199
- values rather than leave the field empty. Validate first — `npx greatstore connectors`
200
- shows what's wired up ([store-admin.md](store-admin.md)); if there's no
201
- connector for it, don't ask for it.
202
- - **Asking it to read the page** ("summarize the reviews shown below") — it
203
- can't. Page-only data (review snippets, UGC, things that exist nowhere but
204
- the DOM) is the one kind worth inlining — keep it stable per page so
205
- caching still works.
206
- - **Asking for minute-fresh operational data** (exact live stock counts,
207
- delivery countdowns). Even when a connector could answer, responses cache
208
- for up to ~24h — display operational data from your own platform APIs and
209
- use GreatStore for *editorial intelligence over the catalog*.
210
- - **Putting whole-output instructions in a field's `description`** (voice,
211
- grounding, what the page is) — they belong in the prompt, where they apply
212
- to every field.
213
-
214
- ## Caching: design for it
215
-
216
- Responses are cached server-side for up to **24 hours**, keyed by the
217
- combination of page context (URL path, title, JSON-LD identifiers) + prompt +
218
- schema. Anonymous visitors share one entry per key; identified shoppers each
219
- get their own (their output may be personalized, so it's only ever served
220
- back to them).
221
-
222
- **The query string and fragment never reach GreatStore.** `/product?id=123`
223
- and `/product?id=456` are the same page to it — same hints, same cache entry.
224
- If your page picks its product from a query param, name that product in the
225
- prompt (`` `…the product "${name}" (SKU ${sku})` ``), or emit JSON-LD for it;
226
- either one differentiates the content and the cache.
227
-
228
- The one exception is `intent_id`, the ad reference some ad landing URLs
229
- carry: when it's present, content is steered toward what that ad showed and
230
- cached for that ad alone. You don't need to do anything for this, and the
231
- call behaves the same either way.
232
-
233
- Practical consequences:
234
-
235
- - **The first render pays, repeats fly.** Expect a few seconds on a cache
236
- miss and near-instant responses after — shared across all anonymous
237
- traffic, per-shopper for identified traffic (the research underneath is
238
- cached briefly and shared, so even those misses are cheaper than cold).
239
- Design loading states for the miss case.
240
- - **Same call on different pages = different content**, automatically — the
241
- page path is in the key and in the AI's hints. A single site-wide snippet
242
- with a constant prompt yields per-page content for free.
243
- - **Content refreshes roughly daily.** Don't build experiences that assume
244
- minute-level freshness.
245
- - **To force different content, change the prompt or schema** (e.g. a
246
- campaign variant string that changes weekly — deliberate, low-cardinality
247
- variation is fine; per-visitor cardinality is not).
248
-
249
- The catalog research underneath is also cached briefly, so several distinct
250
- surfaces on the same page (different prompts/schemas) stay cheap even on
251
- cold cache.
252
-
253
- ## Errors and how to handle them
254
-
255
- The promise rejects with `new Error(message)`. The message is
256
- developer-facing — never render it to shoppers. Server-side failures also
257
- carry `error.code`, and a decline carries `error.reason`. Cases:
258
-
259
- | Case | Message you'll see | Retry? |
260
- |---|---|---|
261
- | Bad input (empty prompt, non-object schema) | thrown immediately by the SDK | Fix the call |
262
- | Invalid schema shape, or constraints no output could satisfy | `Invalid schema: …` | Fix the schema |
263
- | AI declined the request | `The assistant declined to generate content for this request.` with `error.reason` (below) | No — rework the prompt. `insufficient_data` alone can change as the catalog does. |
264
- | Output couldn't satisfy the schema | `Failed to produce valid structured content` | No — usually `required`/constraints demand data the catalog lacks. Loosen the schema. |
265
- | Rate limit (~20/min per IP address) | rate-limit message | Later — and consolidate calls |
266
- | Network / server | varies | Next page load |
267
-
268
- A decline is only ever one of these `error.reason` values — anything else
269
- (vague wording, missing data for optional fields, marketing copy) is served:
270
-
271
- | `reason` | Declined because the request… |
272
- |---|---|
273
- | `off_topic` | has nothing to do with the store or shopping there (homework, code, news, another business's products) |
274
- | `harmful` | asks for unsafe, hateful, sexual, or illegal content, or advice that could hurt someone |
275
- | `deceptive` | asks for fake reviews, invented discounts or scarcity, claims the catalog contradicts, or impersonating/disparaging a named brand or person |
276
- | `system_probe` | asks about or tries to override the assistant's own instructions or tools |
277
- | `insufficient_data` | needs store data that isn't there — the catalog doesn't carry what it's about, or nothing it needs could be found |
278
-
279
- The uniform shopper-facing strategy: render into a hidden-by-default
280
- container, reveal on success, leave hidden (or show your static fallback) on
281
- any rejection. One `try/catch`, no case analysis needed unless you're
282
- logging.
283
-
284
- ## Performance pattern
285
-
286
- Fire generation as early as possible without blocking render — top of your
287
- deferred script, before other work:
288
-
289
- ```js
290
- const highlightsPromise = window.GreatStore?.generateStructuredContent
291
- ? window.GreatStore.generateStructuredContent(schema, prompt).catch(() => null)
292
- : Promise.resolve(null);
293
-
294
- // …rest of page setup…
295
-
296
- const data = await highlightsPromise;
297
- if (data) renderHighlights(data);
298
- ```
299
-
300
- The `.catch(() => null)` attached immediately avoids unhandled-rejection
301
- noise while keeping a single render path.
302
-
303
- For multiple surfaces on one page, prefer **one call with a combined
304
- schema** over parallel calls — it's one research pass, one cache entry, and
305
- no rate-limit pressure:
306
-
307
- ```js
308
- const schema = {
309
- type: "object",
310
- properties: {
311
- highlights: { /* … */ },
312
- faq: { /* … */ },
313
- crossSell: { /* … */ },
314
- },
315
- required: ["highlights"],
316
- };
317
- ```