@greatstore/cli 0.1.12 → 0.1.15

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,32 @@
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.1.15 — 2026-09-17
7
+
8
+ ### Changed
9
+ - The bundled agent skill (`gs skill`) calls custom in-chat UI **apps**
10
+ throughout, matching `gs apps` and the dashboard, and documents the
11
+ lifecycle a coding agent needs: the assistant picks an app and calls it
12
+ with the props the manifest declares, the app renders, and from there it
13
+ can report what the shopper is doing, send a message on their behalf, run
14
+ a catalog-grounded generation of its own for recommendations or a
15
+ personalized summary, or be called again with revised props. Guidance on
16
+ writing a `name` and `description` now spells out that they should say
17
+ *when* the assistant should reach for the app, not what the app looks like.
18
+
19
+ ## 0.1.13 — 2026-09-16
20
+
21
+ ### Removed
22
+ - Components are no longer passed an `onCallTool` prop. Drop it from your
23
+ component's `Props` — one still declaring it gets an undeclared-prop
24
+ warning from `gs apps validate`. To hand off to another component, call
25
+ `onSendMessage(...)` with the follow-up you want and let the assistant
26
+ take it from there.
27
+
28
+ ### Changed
29
+ - This release is the minimum version the server accepts — earlier ones stop
30
+ working. Run `npm install -g @greatstore/cli@latest` to upgrade.
31
+
6
32
  ## 0.1.12 — 2026-09-14
7
33
 
8
34
  ### Changed
@@ -125,7 +151,7 @@ follows [Keep a Changelog](https://keepachangelog.com/).
125
151
  ### Changed
126
152
  - Component validation now warns when a component reaches for the page-level
127
153
  `window.GreatStore` API. Components should interact with GreatStore through
128
- the lifecycle props passed into them (`onSendMessage`, `onCallTool`,
154
+ the lifecycle props passed into them (`onSendMessage`,
129
155
  `onGenerateStructuredContent`, …), which are wired to the surface the
130
156
  component is mounted in; the warning points you there. It's a nudge, not a
131
157
  build failure.
@@ -184,7 +210,7 @@ follows [Keep a Changelog](https://keepachangelog.com/).
184
210
  - New check: a component's props and its `inputSchema.properties` must
185
211
  agree. A schema field the component doesn't accept is an error; a prop
186
212
  the schema doesn't declare is a warning, since nothing will ever pass
187
- it. The props GreatStore injects (`onSendMessage`, `onCallTool`,
213
+ it. The props GreatStore injects (`onSendMessage`,
188
214
  `onUpdateModelContext`, `onShowLightbox`, `onClose`, `storeData`,
189
215
  `Image`) are exempt.
190
216
 
@@ -421,8 +447,8 @@ follows [Keep a Changelog](https://keepachangelog.com/).
421
447
  ## 0.0.15 — 2026-05-24
422
448
 
423
449
  ### Added
424
- - Scaffolded `component.tsx` now declares the four injected lifecycle
425
- props (`onSendMessage`, `onCallTool`, `onClose`, `onError`) on
450
+ - Scaffolded `component.tsx` now declares the injected lifecycle
451
+ props (`onSendMessage`, `onClose`, `onError`) on
426
452
  `Props`. Use `onError(message)` to report expected failures (failed
427
453
  fetch, host action rejected, invalid host state) so the AI can
428
454
  recover on its next turn. Render-time crashes are reported for you.
package/README.md CHANGED
@@ -83,8 +83,8 @@ The checks cover the manifest (valid JSON, a `name` matching the folder,
83
83
  an `inputSchema` simple enough for the assistant to fill reliably) and
84
84
  the component's props: every prop it declares should be a field in
85
85
  `inputSchema.properties`, apart from the props GreatStore injects
86
- (`onSendMessage`, `onCallTool`, `onUpdateModelContext`,
87
- `onShowLightbox`, `onClose`, `storeData`, `Image`). A prop nothing
86
+ (`onSendMessage`, `onUpdateModelContext`, `onShowLightbox`,
87
+ `onClose`, `storeData`, `Image`). A prop nothing
88
88
  declares is a warning — nothing will ever pass it. A schema field the
89
89
  component doesn't accept is an error. A component still declaring
90
90
  `onError` gets a warning pointing at async components, which replaced it.
package/dist/cli.js CHANGED
@@ -20,7 +20,7 @@ p{color:#2c3a38}`,Rn=`<!doctype html>
20
20
  h1{font-size:1.4rem;color:#a40000}code{background:#f4f4f4;padding:.1em .3em;border-radius:.2em}</style></head>
21
21
  <body><h1>Sign-in failed.</h1>
22
22
  <p>Return to your terminal for details.</p></body></html>`,K=class extends Error{constructor(t){super(t),this.name="LoopbackError"}};async function me(e){let t=(e.generateState??Tn)(),n=e.timeoutMs??300*1e3,r=e.openBrowser??(s=>Ln(s,e.browserCmdEnv)),o=Ve.createServer();try{await new Promise(c=>o.listen(0,"127.0.0.1",c));let s=o.address(),i=new URL(`${e.dashboardBaseUrl}/cli/authorize`);i.searchParams.set("port",String(s.port)),i.searchParams.set("state",t),e.requestedStore&&i.searchParams.set("store",e.requestedStore);let a=i.toString(),l=_n(o,t,n);return r(a),await l}finally{o.close()}}function _n(e,t,n){return new Promise((r,o)=>{let s=!1,i=l=>{s||(s=!0,l())},a=setTimeout(()=>{i(()=>o(new K("Sign-in timed out. Re-run `gs login`.")))},n);typeof a.unref=="function"&&a.unref(),e.on("request",(l,c)=>{let p=new URL(l.url??"/","http://127.0.0.1");if(p.pathname!==En){c.writeHead(404,{"content-type":"text/plain"}),c.end("Not found");return}let u=p.searchParams,f=u.get("error"),j=u.get("error_description"),P=u.get("code");if(u.get("state")!==t){c.writeHead(400,{"content-type":"text/html"}),c.end(Ge),clearTimeout(a),i(()=>o(new K("Sign-in didn't complete. Please try again.")));return}if(f||!P){c.writeHead(400,{"content-type":"text/html"}),c.end(Ge),clearTimeout(a),i(()=>o(new K(j??"Sign-in failed. Please try again.")));return}c.writeHead(200,{"content-type":"text/html"}),c.end(Rn),clearTimeout(a);let R=u.get("store")?.trim();i(()=>r(R?{token:P,store:R}:{token:P}))})})}function Tn(){return qe.randomBytes(16).toString("hex")}function Ln(e,t){let r=t?.trim()??On();if(r)try{let o;if(r==="start"){let s=`start "" "${e}"`;o=Ue("cmd.exe",["/d","/s","/c",s],{stdio:"ignore",detached:!0,windowsVerbatimArguments:!0})}else o=Ue(r,[e],{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}function On(){switch(process.platform){case"darwin":return"open";case"win32":return"start";case"linux":return"xdg-open";default:return null}}import*as C from"fs";import*as Q from"os";import*as _e from"path";var In=".greatstore",Fn="credentials.json";function Je(e=Q.homedir()){return _e.join(e,In)}function Te(e=Q.homedir()){return _e.join(Je(e),Fn)}function _(e=Q.homedir()){let t=Te(e),n;try{let r=C.statSync(t);if(process.platform!=="win32"){let o=r.mode&511;if(o&63)throw new Error(`Refusing to read ${t}: permissions are ${o.toString(8)} (should be 600). Run \`chmod 600 ${t}\`.`)}n=C.readFileSync(t,"utf8")}catch(r){if(Nn(r))return null;throw r}try{let r=JSON.parse(n);return typeof r.access_token!="string"?null:r}catch{return null}}function ge(e,t=Q.homedir()){let n=Je(t);if(C.mkdirSync(n,{recursive:!0,mode:448}),process.platform!=="win32")try{C.chmodSync(n,448)}catch{}let r=Te(t);C.writeFileSync(r,`${JSON.stringify(e,null,2)}
23
- `,{mode:384}),process.platform!=="win32"&&C.chmodSync(r,384)}function Ke(e=Q.homedir()){C.rmSync(Te(e),{force:!0})}function We(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT: expected three dot-separated segments");let n=t[1];if(!n)throw new Error("Invalid JWT: empty payload segment");let o=(n+"=".repeat((4-n.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=Buffer.from(o,"base64").toString("utf8");return JSON.parse(s)}function he(e,t=Math.floor(Date.now()/1e3)){return e.expires_at<=t}function Nn(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}var N="0.1.12";var D=class extends Error{constructor(n,r,o){super(r);this.status=n;this.code=o;this.name="HttpError"}},O=class extends Error{constructor(t="Sign in first. Run `gs login`."){super(t),this.name="AuthRequiredError"}};function Dn(e){let t;try{t=new URL(e)}catch{return}let n=t.pathname.split("/").filter(Boolean);if(n[1]==="admin"&&n[0])return n[0];let r=t.hostname.split(".")[0],o=new Set(["my","www","app","api","admin","localhost"]);if(t.hostname.includes(".")&&r&&!o.has(r))return r}function Bn(e){let t=Dn(e)??_()?.store;return t?`gs login --store ${t}`:"gs login"}async function d(e,t={}){let n=()=>`Run \`${Bn(e)}\`.`,r=_();if(!r)throw new O(`Sign in first. ${n()}`);if(he(r))throw new O(`Session expired. ${n()}`);try{return await Hn(e,t,r.access_token)}catch(o){throw o instanceof D&&o.status===401?new O(`Session expired. ${n()}`):o}}async function Hn(e,t,n){let r={accept:"application/json",authorization:`Bearer ${n}`,"x-gs-cli-version":N,...t.headers??{}},o;if(t.multipart&&t.body!==void 0)throw new Error("request(): pass either `body` or `multipart`, not both");t.multipart?(o=t.multipart,delete r["content-type"]):t.body!==void 0&&(o=JSON.stringify(t.body),r["content-type"]="application/json");let s={method:t.method??"GET",headers:r};o!==void 0&&(s.body=o);let i=await fetch(e,s);if(i.status>=200&&i.status<300)return i.status===204?void 0:(i.headers.get("content-type")??"").includes("application/json")?await i.json():await i.text();let a=await i.text(),l={};try{l=JSON.parse(a)}catch{}let c=l.code??l.error,p=t.validationDetail&&i.status===400&&l.error?l.error:Mn(i.status,c,l.detail);throw new D(i.status,p,l.code??l.error)}var Ye=`This version of the GreatStore CLI is no longer supported.
23
+ `,{mode:384}),process.platform!=="win32"&&C.chmodSync(r,384)}function Ke(e=Q.homedir()){C.rmSync(Te(e),{force:!0})}function We(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT: expected three dot-separated segments");let n=t[1];if(!n)throw new Error("Invalid JWT: empty payload segment");let o=(n+"=".repeat((4-n.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=Buffer.from(o,"base64").toString("utf8");return JSON.parse(s)}function he(e,t=Math.floor(Date.now()/1e3)){return e.expires_at<=t}function Nn(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}var N="0.1.15";var D=class extends Error{constructor(n,r,o){super(r);this.status=n;this.code=o;this.name="HttpError"}},O=class extends Error{constructor(t="Sign in first. Run `gs login`."){super(t),this.name="AuthRequiredError"}};function Dn(e){let t;try{t=new URL(e)}catch{return}let n=t.pathname.split("/").filter(Boolean);if(n[1]==="admin"&&n[0])return n[0];let r=t.hostname.split(".")[0],o=new Set(["my","www","app","api","admin","localhost"]);if(t.hostname.includes(".")&&r&&!o.has(r))return r}function Bn(e){let t=Dn(e)??_()?.store;return t?`gs login --store ${t}`:"gs login"}async function d(e,t={}){let n=()=>`Run \`${Bn(e)}\`.`,r=_();if(!r)throw new O(`Sign in first. ${n()}`);if(he(r))throw new O(`Session expired. ${n()}`);try{return await Hn(e,t,r.access_token)}catch(o){throw o instanceof D&&o.status===401?new O(`Session expired. ${n()}`):o}}async function Hn(e,t,n){let r={accept:"application/json",authorization:`Bearer ${n}`,"x-gs-cli-version":N,...t.headers??{}},o;if(t.multipart&&t.body!==void 0)throw new Error("request(): pass either `body` or `multipart`, not both");t.multipart?(o=t.multipart,delete r["content-type"]):t.body!==void 0&&(o=JSON.stringify(t.body),r["content-type"]="application/json");let s={method:t.method??"GET",headers:r};o!==void 0&&(s.body=o);let i=await fetch(e,s);if(i.status>=200&&i.status<300)return i.status===204?void 0:(i.headers.get("content-type")??"").includes("application/json")?await i.json():await i.text();let a=await i.text(),l={};try{l=JSON.parse(a)}catch{}let c=l.code??l.error,p=t.validationDetail&&i.status===400&&l.error?l.error:Mn(i.status,c,l.detail);throw new D(i.status,p,l.code??l.error)}var Ye=`This version of the GreatStore CLI is no longer supported.
24
24
 
25
25
  npm install -g @greatstore/cli@latest
26
26
  `,ze={cli_upgrade_required:{message:Ye},INVALID_NAME:{message:"Invalid component name. Use lowercase letters, digits, and underscores, starting with a letter."},not_found:{message:"Component not found on the server."},concurrent_write:{message:"Another change landed before this one. Run `gs apps pull` and try again."},stale_base:{message:"The store has moved past the version this copy was taken from. Run `gs apps pull` first, or push again with --force to overwrite it.",includeDetail:!0},name_taken:{message:"Another component in this store already has that name."},name_mismatch:{message:"Manifest `name` does not match the component folder name.",includeDetail:!0},manifest_invalid:{message:"manifest.json is invalid.",includeDetail:!0},bundle_too_large:{message:"bundle.js is too large."},bundle_not_module:{message:"bundle.js is not a valid ES module."},source_too_large:{message:"component.tsx is too large."}};function Mn(e,t,n){if(t&&t in ze){let r=ze[t];return r?r.includeDetail&&n?`${r.message} (${n})`:r.message:Xe(e)}return Xe(e)}function Xe(e){return e===401?"Sign-in needed. Run `gs login`.":e===426?Ye:e===403?"Not authorized for this component or store.":e===404?"Not found.":e===409?"Conflict \u2014 refresh and try again.":e===413?"Upload too large.":e===429?"Too many requests \u2014 wait a moment and retry.":e>=500?"Server error \u2014 try again shortly.":e>=400?"Request rejected.":"Unexpected response."}function we(e,t){let n=We(e),r=Qe(n,"sub");if(!r)throw new Error("Token is missing a `sub` claim.");let o=Un(n,"exp");return{access_token:e,expires_at:o??Math.floor(Date.now()/1e3)+3600,sub:r,...ye(n,"email","email"),...ye(n,"accountId","accountId"),...ye(n,"name","name"),...ye(n,"surname","surname"),...Gn(n,"superUser","superUser"),...t?{store:t}:{}}}function Qe(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Un(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ye(e,t,n){let r=Qe(e,t);return r?{[n]:r}:{}}function Gn(e,t,n){let r=e[t];return r===!0?{[n]:!0}:typeof r=="string"&&r.toLowerCase()==="true"?{[n]:!0}:{}}import*as Se from"fs";import*as H from"path";var qn="https://my.greatstore.ai",B=class extends Error{constructor(t){super(t),this.name="StoreResolutionError"}};function $(e={}){let t=Le(e.cwd??process.cwd());if(t)return ee(t);throw new B("No .gsrc found in this directory or any ancestor. Run `gs apps init --store <slug>` first to scaffold a GreatStore project.")}function Ze(e=process.cwd()){let t=Le(e);if(t)return ee(t);let n=ce();if(n)return n;throw new B("No store selected. Run `gs login`, or run from a project with a .gsrc.")}function ce(){try{return _()?.store??null}catch{return null}}function ee(e){let t=ce();if(t&&t!==e)throw new B(`This targets store "${e}" but you're signed in to "${t}". Run \`gs switch ${e}\` to change stores.`);return e}function Le(e){let t=H.resolve(e),n=H.parse(t).root;for(;;){let r=H.join(t,".gsrc");if(Se.existsSync(r))try{let s=Se.readFileSync(r,"utf8"),i=JSON.parse(s);if(typeof i.store=="string"&&i.store.trim())return i.store.trim()}catch{}if(t===n)return null;let o=H.dirname(t);if(o===t)return null;t=o}}function y(e){let t=h(e.flags,"store")?.trim();if(t)return ee(t);let n=Le(process.cwd());if(n)return ee(n);let r=ce();if(r)return r;throw new B("No store selected. Pass --store <slug>, or run from a project with a .gsrc.")}function x(e,t=process.env){let n=t.GS_API_BASE?.trim();return n?et(n):`https://${e}.greatstore.ai`}function le(e=process.env){let t=e.GS_DASHBOARD_BASE?.trim();return t?et(t):qn}function S(e,t=process.env){return`${le(t)}/${e}/admin`}function et(e){return e.endsWith("/")?e.slice(0,-1):e}async function tt(e){let t=h(e.flags,"store")?.trim();process.stdout.write(`Opening browser for sign-in\u2026
@@ -78,10 +78,10 @@ Examples:
78
78
  gs configure set --theme.fontFamily Manrope --theme.radius sharp
79
79
  gs configure set --theme.brandColor "#1e1d66"
80
80
  gs configure set --theme '{"mode":"dark"}' --replace
81
- `}function pt(e){if(e===void 0||e==="show")return Qn;if(e==="set")return tr()}import*as g from"fs";import*as k from"path";import{readdirSync as Po,readFileSync as $o}from"fs";import{fileURLToPath as Eo}from"url";var ve=null;function dt(){return ve||(ve=JSON.parse('{"component/component.tsx":"import React from \\"react\\";\\n\\n// Add your tool args (matching manifest.json#inputSchema.properties)\\n// alongside the GreatStore-injected lifecycle props. See AGENTS.md for\\n// what each lifecycle prop does.\\ninterface Props {\\n onSendMessage: (text: string) => void;\\n onCallTool: (name: string, args: Record<string, unknown>) => void;\\n onUpdateModelContext: (context: string) => void;\\n onShowLightbox: (options: { src: string; originRect?: DOMRect }) => void;\\n onClose: () => void;\\n // Ask the store\'s assistant for content matching a JSON Schema (or Zod\\n // schema). Resolves to the generated object. `fallback` is a required,\\n // schema-shaped stand-in rendered in the component preview (and validated\\n // against the schema). See AGENTS.md.\\n onGenerateStructuredContent: <T = unknown>(\\n schema: object,\\n prompt: string,\\n fallback: T,\\n ) => Promise<T>;\\n // Drop-in for <img>: `<Image src=\u2026 alt=\u2026 />`. See AGENTS.md.\\n Image: React.ElementType<React.ComponentProps<\\"img\\">>;\\n}\\n\\n// See AGENTS.md for the design rules (em-based sizing, brand CSS\\n// variables), the lifecycle props, and how to write an async,\\n// backend-backed component.\\nexport default function Component(_props: Props): React.ReactElement {\\n return (\\n <div\\n style={{\\n padding: \\"1em\\",\\n border: \\"1px solid var(--color-border-default)\\",\\n borderRadius: \\"var(--radius-lg)\\",\\n background: \\"var(--color-surface)\\",\\n color: \\"var(--color-foreground)\\",\\n fontFamily: \\"var(--font-primary)\\",\\n }}\\n >\\n <strong>__GS_NAME__</strong> \u2014 hello from your component!\\n </div>\\n );\\n}\\n","component/manifest.json":"{\\n \\"name\\": \\"__GS_NAME__\\",\\n \\"displayName\\": \\"__GS_DISPLAY_NAME__\\",\\n \\"description\\": \\"Renders the __GS_NAME__ widget.\\",\\n \\"displayMode\\": \\"inline\\",\\n \\"async\\": false,\\n \\"inputSchema\\": {\\n \\"type\\": \\"object\\",\\n \\"properties\\": {}\\n }\\n}\\n","root/.gitignore":"node_modules/\\ncomponents/*/bundle.js\\ncomponents/*/.gssync.json\\n*.tsbuildinfo\\n.DS_Store\\n","root/.gsrc":"{\\n \\"store\\": \\"__GS_STORE__\\"\\n}\\n","root/AGENTS.md":"# AGENTS.md\\n\\n> **Do not edit \u2014 auto-generated by the GreatStore CLI v__GS_VERSION__.**\\n> This file is rewritten by `gs apps init`, so any changes you make here\\n> will be overwritten. If this version trails your installed CLI, re-run\\n> `gs apps init` to refresh it. Put project-specific notes in another file.\\n\\nGuidance for AI coding agents working on the components in this project.\\n`CLAUDE.md` and `GEMINI.md` are symlinks to this file.\\n\\nThese components render inside arbitrary publisher websites (the embed\\nwidget mounts on a host page) as well as the GreatStore storefront. You\\ncontrol neither the host page\'s base font size nor its color scheme, and\\nthe store owner controls the look from GreatStore theme settings. The\\nrules below keep components portable across both.\\n\\n## Design requirements\\n\\n### Never use `rem` for fonts and sizing \u2014 always use `em`\\n\\n`rem` resolves against the host page\'s root font size, which is\\narbitrary and outside our control. A host that sets `html { font-size:\\n8px }` (or 200%) will shrink or blow up every `rem`-based dimension.\\n`em` resolves against the component\'s own font size, so it stays\\nself-consistent wherever the component is mounted.\\n\\nUse `em` for font sizes, padding, margins, gaps, widths, heights,\\nand any other length. Borders may stay in `px` (hairlines should not\\nscale with text).\\n\\n```tsx\\n// Bad \u2014 breaks on hosts with a non-default root font size\\n<div style={{ padding: \\"1rem\\", fontSize: \\"0.875rem\\" }} />\\n\\n// Good\\n<div style={{ padding: \\"1em\\", fontSize: \\"0.875em\\" }} />\\n```\\n\\n### Don\'t hardcode colors, fonts, or corner radius \u2014 use GreatStore brand variables\\n\\nThe store owner themes the assistant from GreatStore settings. Hardcoded\\nvalues ignore that and make the component clash with the rest of the\\nstore. Read from the CSS variables GreatStore injects on the surface\\ninstead, so the component 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\\ncomponent reflects the store\'s full type system instead of a single\\nface.\\n\\n```tsx\\n// Bad \u2014 hardcoded, ignores the store\'s theme\\n<button style={{ background: \\"#4f46e5\\", borderRadius: 8, fontFamily: \\"Inter\\" }} />\\n\\n// Good\\n<button\\n style={{\\n background: \\"var(--color-primary)\\",\\n color: \\"var(--color-primary-foreground)\\",\\n borderRadius: \\"var(--radius-lg)\\",\\n fontFamily: \\"var(--font-primary)\\",\\n }}\\n/>\\n```\\n\\nProvide a sensible fallback only when a value might be absent, e.g.\\n`var(--color-primary, currentColor)`.\\n\\n## Component props\\n\\nEach component receives its tool args (the fields you declare in\\n`manifest.json#inputSchema.properties`) plus these GreatStore-injected\\nlifecycle props, which are always present:\\n\\n| Prop | What it does |\\n| --- | --- |\\n| `onSendMessage(text)` | Send text into the chat as if the shopper typed it. |\\n| `onCallTool(name, args)` | Chain into another remote-component tool by name. |\\n| `onUpdateModelContext(context)` | Inject invisible background context for the model (selected variant, configured options, current step). Replaces the prior value \u2014 never appends; pass `\\"\\"` to clear. Read on the next chat turn. Use it when the assistant should *know* in-component state without a visible message; use `onSendMessage` when you want a turn to happen now. |\\n| `onShowLightbox({ src, originRect? })` | Expand an image in the chat\'s shared full-screen lightbox \u2014 an on-brand zoom overlay your component can\'t render itself (it\'s boxed inside its own bounds and shadow root). Pass the image `src`; for a smooth zoom, also pass the clicked element\'s `getBoundingClientRect()` as `originRect` (omit it and the image grows from the viewport centre). |\\n| `onGenerateStructuredContent(schema, prompt, fallback)` | Ask the store\'s assistant for content matching a JSON Schema (or a Zod schema); resolves to the generated object. Personalized to the shopper. Works the same in the conversation on the storefront and every embed. Best inside an async component 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 component preview renders (so a generation-driven component previews without a live store). It\'s validated against the schema and throws if the two don\'t line up. |\\n| `onClose()` | Dismiss the host slot. Over-input clears the overlay, fullscreen reverts the pane, inline is a no-op. |\\n| `Image` | A drop-in for `<img>`: render `<Image src=\u2026 alt=\u2026 />` instead of `<img>` and your images are automatically served at the right size for the store. Takes the same props as `<img>` (`src`, `alt`, `style`, `loading`, `onClick`, \u2026). Previewing the component outside the store? Pass `Image={\\"img\\"}` (or your own component) to render a plain image. |\\n\\n## Async components (backend-backed, render-blocking data)\\n\\nIf a component 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. Components that render purely from their props stay\\nsynchronous.\\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 components\\n\\nCustom React components published to your GreatStore tenant. Each\\ncomponent lives in its own folder under `components/`.\\n\\n```\\nnpm install\\ngs apps init <component_name> # add a new component\\ngs apps build # builds every components/<name>/bundle.js\\ngs apps push # uploads every changed component as a draft\\ngs apps publish <component_name> # promote a specific component to live\\n```\\n\\n- `gs apps push` (no args) hashes each component and only uploads the ones\\n that have changed since the last sync.\\n- `gs apps pull` (no args) refreshes every remote component into\\n `components/<name>/`. Components with unsaved local edits are skipped\\n with a warning; pass `--force` to overwrite.\\n\\nSee `AGENTS.md` for the design rules every component must follow\\n(em-based sizing, brand CSS variables) \u2014 it doubles as guidance for AI\\ncoding agents (`CLAUDE.md` / `GEMINI.md` symlink to it).\\n","root/package.json":"{\\n \\"name\\": \\"greatstore-components\\",\\n \\"version\\": \\"0.0.1\\",\\n \\"private\\": true,\\n \\"type\\": \\"module\\",\\n \\"scripts\\": {\\n \\"build\\": \\"gs apps build\\",\\n \\"push\\": \\"gs apps build && gs apps push\\"\\n },\\n \\"dependencies\\": {\\n \\"react\\": \\"^19.0.0\\",\\n \\"react-dom\\": \\"^19.0.0\\"\\n },\\n \\"devDependencies\\": {\\n \\"@types/react\\": \\"^19.0.0\\",\\n \\"@types/react-dom\\": \\"^19.0.0\\",\\n \\"@vitejs/plugin-react\\": \\"^4.3.0\\",\\n \\"typescript\\": \\"^5.6.0\\",\\n \\"vite\\": \\"^5.4.0\\"\\n }\\n}\\n","root/tsconfig.json":"{\\n \\"compilerOptions\\": {\\n \\"target\\": \\"ES2022\\",\\n \\"module\\": \\"ESNext\\",\\n \\"moduleResolution\\": \\"Bundler\\",\\n \\"jsx\\": \\"react-jsx\\",\\n \\"lib\\": [\\"ES2022\\", \\"DOM\\"],\\n \\"strict\\": true,\\n \\"esModuleInterop\\": true,\\n \\"skipLibCheck\\": true,\\n \\"isolatedModules\\": true,\\n \\"noEmit\\": true\\n },\\n \\"include\\": [\\"components/**/component.tsx\\", \\"vite.config.ts\\"]\\n}\\n","root/vite.config.ts":"import { defineConfig } from \\"vite\\";\\nimport react from \\"@vitejs/plugin-react\\";\\n\\n// Real builds happen in `gs build` (one Vite invocation per\\n// component, externals + runtime shim paths owned by the CLI). This\\n// file exists only so editors / language servers can resolve the\\n// React plugin when inspecting components/*/component.tsx.\\nexport default defineConfig({\\n plugins: [react()],\\n});\\n"}'),ve)}var ft={name:"__GS_NAME__",displayName:"__GS_DISPLAY_NAME__",store:"__GS_STORE__",version:"__GS_VERSION__"};function mt(e,t){let n=e;for(let o of Object.keys(ft)){let s=t[o];s!==void 0&&(n=n.split(ft[o]).join(s))}let r=n.match(/__GS_[A-Z_]+__/);if(r)throw new Error(`internal: template placeholder ${r[0]} was not provided`);return n}var gt=/^[a-z][a-z0-9_]*$/;function yt(e){let t=e.positional[0];if(t!==void 0&&!gt.test(t))throw new Error(`Invalid component name: "${t}" (must match ${gt}).`);let n=m(e.flags,"force"),r=h(e.flags,"store"),o=h(e.flags,"out")??".",s=k.resolve(o),i=nr(s),a;if(i){if(r!==void 0)throw new Error(`Project at ${s} is already pinned to a store via .gsrc. Drop --store; a project folder ships to exactly one store.`);$({cwd:s})}else if(a=r!==void 0?ee(r):ce()??void 0,a===void 0){let u=t?`gs apps init ${t} --store <slug>`:"gs apps init --store <slug>";throw new Error(`--store <slug> is required when scaffolding a new project root. Run \`${u}\`.`)}let l=rr(s,i,n,{store:a});if(!t){let u=[];i?(u.push(`Updated GreatStore project root in ${s}.`),l.length>0?u.push("",`Added: ${l.join(", ")}`):u.push("","Already up to date \u2014 nothing to add.")):u.push(`Scaffolded GreatStore project root in ${s}.`),u.push("","Next steps:",` cd ${k.relative(process.cwd(),s)||"."}`," npm install"," gs apps init <component_name> # add your first component",""),process.stdout.write(u.join(`
81
+ `}function pt(e){if(e===void 0||e==="show")return Qn;if(e==="set")return tr()}import*as g from"fs";import*as k from"path";import{readdirSync as Po,readFileSync as $o}from"fs";import{fileURLToPath as Eo}from"url";var ve=null;function dt(){return ve||(ve=JSON.parse('{"component/component.tsx":"import React from \\"react\\";\\n\\n// Add your tool args (matching manifest.json#inputSchema.properties)\\n// alongside the GreatStore-injected lifecycle props. See AGENTS.md for\\n// what each lifecycle prop does.\\ninterface Props {\\n onSendMessage: (text: string) => void;\\n onUpdateModelContext: (context: string) => void;\\n onShowLightbox: (options: { src: string; originRect?: DOMRect }) => void;\\n onClose: () => void;\\n // Ask the store\'s assistant for content matching a JSON Schema (or Zod\\n // schema). Resolves to the generated object. `fallback` is a required,\\n // schema-shaped stand-in rendered in the component preview (and validated\\n // against the schema). See AGENTS.md.\\n onGenerateStructuredContent: <T = unknown>(\\n schema: object,\\n prompt: string,\\n fallback: T,\\n ) => Promise<T>;\\n // Drop-in for <img>: `<Image src=\u2026 alt=\u2026 />`. See AGENTS.md.\\n Image: React.ElementType<React.ComponentProps<\\"img\\">>;\\n}\\n\\n// See AGENTS.md for the design rules (em-based sizing, brand CSS\\n// variables), the lifecycle props, and how to write an async,\\n// backend-backed component.\\nexport default function Component(_props: Props): React.ReactElement {\\n return (\\n <div\\n style={{\\n padding: \\"1em\\",\\n border: \\"1px solid var(--color-border-default)\\",\\n borderRadius: \\"var(--radius-lg)\\",\\n background: \\"var(--color-surface)\\",\\n color: \\"var(--color-foreground)\\",\\n fontFamily: \\"var(--font-primary)\\",\\n }}\\n >\\n <strong>__GS_NAME__</strong> \u2014 hello from your component!\\n </div>\\n );\\n}\\n","component/manifest.json":"{\\n \\"name\\": \\"__GS_NAME__\\",\\n \\"displayName\\": \\"__GS_DISPLAY_NAME__\\",\\n \\"description\\": \\"Renders the __GS_NAME__ widget.\\",\\n \\"displayMode\\": \\"inline\\",\\n \\"async\\": false,\\n \\"inputSchema\\": {\\n \\"type\\": \\"object\\",\\n \\"properties\\": {}\\n }\\n}\\n","root/.gitignore":"node_modules/\\ncomponents/*/bundle.js\\ncomponents/*/.gssync.json\\n*.tsbuildinfo\\n.DS_Store\\n","root/.gsrc":"{\\n \\"store\\": \\"__GS_STORE__\\"\\n}\\n","root/AGENTS.md":"# AGENTS.md\\n\\n> **Do not edit \u2014 auto-generated by the GreatStore CLI v__GS_VERSION__.**\\n> This file is rewritten by `gs apps init`, so any changes you make here\\n> will be overwritten. If this version trails your installed CLI, re-run\\n> `gs apps init` to refresh it. Put project-specific notes in another file.\\n\\nGuidance for AI coding agents working on the components in this project.\\n`CLAUDE.md` and `GEMINI.md` are symlinks to this file.\\n\\nThese components render inside arbitrary publisher websites (the embed\\nwidget mounts on a host page) as well as the GreatStore storefront. You\\ncontrol neither the host page\'s base font size nor its color scheme, and\\nthe store owner controls the look from GreatStore theme settings. The\\nrules below keep components portable across both.\\n\\n## Design requirements\\n\\n### Never use `rem` for fonts and sizing \u2014 always use `em`\\n\\n`rem` resolves against the host page\'s root font size, which is\\narbitrary and outside our control. A host that sets `html { font-size:\\n8px }` (or 200%) will shrink or blow up every `rem`-based dimension.\\n`em` resolves against the component\'s own font size, so it stays\\nself-consistent wherever the component is mounted.\\n\\nUse `em` for font sizes, padding, margins, gaps, widths, heights,\\nand any other length. Borders may stay in `px` (hairlines should not\\nscale with text).\\n\\n```tsx\\n// Bad \u2014 breaks on hosts with a non-default root font size\\n<div style={{ padding: \\"1rem\\", fontSize: \\"0.875rem\\" }} />\\n\\n// Good\\n<div style={{ padding: \\"1em\\", fontSize: \\"0.875em\\" }} />\\n```\\n\\n### Don\'t hardcode colors, fonts, or corner radius \u2014 use GreatStore brand variables\\n\\nThe store owner themes the assistant from GreatStore settings. Hardcoded\\nvalues ignore that and make the component clash with the rest of the\\nstore. Read from the CSS variables GreatStore injects on the surface\\ninstead, so the component 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\\ncomponent reflects the store\'s full type system instead of a single\\nface.\\n\\n```tsx\\n// Bad \u2014 hardcoded, ignores the store\'s theme\\n<button style={{ background: \\"#4f46e5\\", borderRadius: 8, fontFamily: \\"Inter\\" }} />\\n\\n// Good\\n<button\\n style={{\\n background: \\"var(--color-primary)\\",\\n color: \\"var(--color-primary-foreground)\\",\\n borderRadius: \\"var(--radius-lg)\\",\\n fontFamily: \\"var(--font-primary)\\",\\n }}\\n/>\\n```\\n\\nProvide a sensible fallback only when a value might be absent, e.g.\\n`var(--color-primary, currentColor)`.\\n\\n## Component props\\n\\nEach component receives its tool args (the fields you declare in\\n`manifest.json#inputSchema.properties`) plus these GreatStore-injected\\nlifecycle props, which are always present:\\n\\n| Prop | What it does |\\n| --- | --- |\\n| `onSendMessage(text)` | Send text into the chat as if the shopper typed it. |\\n| `onUpdateModelContext(context)` | Inject invisible background context for the model (selected variant, configured options, current step). Replaces the prior value \u2014 never appends; pass `\\"\\"` to clear. Read on the next chat turn. Use it when the assistant should *know* in-component state without a visible message; use `onSendMessage` when you want a turn to happen now. |\\n| `onShowLightbox({ src, originRect? })` | Expand an image in the chat\'s shared full-screen lightbox \u2014 an on-brand zoom overlay your component can\'t render itself (it\'s boxed inside its own bounds and shadow root). Pass the image `src`; for a smooth zoom, also pass the clicked element\'s `getBoundingClientRect()` as `originRect` (omit it and the image grows from the viewport centre). |\\n| `onGenerateStructuredContent(schema, prompt, fallback)` | Ask the store\'s assistant for content matching a JSON Schema (or a Zod schema); resolves to the generated object. Personalized to the shopper. Works the same in the conversation on the storefront and every embed. Best inside an async component 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 component preview renders (so a generation-driven component previews without a live store). It\'s validated against the schema and throws if the two don\'t line up. |\\n| `onClose()` | Dismiss the host slot. Over-input clears the overlay, fullscreen reverts the pane, inline is a no-op. |\\n| `Image` | A drop-in for `<img>`: render `<Image src=\u2026 alt=\u2026 />` instead of `<img>` and your images are automatically served at the right size for the store. Takes the same props as `<img>` (`src`, `alt`, `style`, `loading`, `onClick`, \u2026). Previewing the component outside the store? Pass `Image={\\"img\\"}` (or your own component) to render a plain image. |\\n\\n## Async components (backend-backed, render-blocking data)\\n\\nIf a component 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. Components that render purely from their props stay\\nsynchronous.\\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 components\\n\\nCustom React components published to your GreatStore tenant. Each\\ncomponent lives in its own folder under `components/`.\\n\\n```\\nnpm install\\ngs apps init <component_name> # add a new component\\ngs apps build # builds every components/<name>/bundle.js\\ngs apps push # uploads every changed component as a draft\\ngs apps publish <component_name> # promote a specific component to live\\n```\\n\\n- `gs apps push` (no args) hashes each component and only uploads the ones\\n that have changed since the last sync.\\n- `gs apps pull` (no args) refreshes every remote component into\\n `components/<name>/`. Components with unsaved local edits are skipped\\n with a warning; pass `--force` to overwrite.\\n\\nSee `AGENTS.md` for the design rules every component must follow\\n(em-based sizing, brand CSS variables) \u2014 it doubles as guidance for AI\\ncoding agents (`CLAUDE.md` / `GEMINI.md` symlink to it).\\n","root/package.json":"{\\n \\"name\\": \\"greatstore-components\\",\\n \\"version\\": \\"0.0.1\\",\\n \\"private\\": true,\\n \\"type\\": \\"module\\",\\n \\"scripts\\": {\\n \\"build\\": \\"gs apps build\\",\\n \\"push\\": \\"gs apps build && gs apps push\\"\\n },\\n \\"dependencies\\": {\\n \\"react\\": \\"^19.0.0\\",\\n \\"react-dom\\": \\"^19.0.0\\"\\n },\\n \\"devDependencies\\": {\\n \\"@types/react\\": \\"^19.0.0\\",\\n \\"@types/react-dom\\": \\"^19.0.0\\",\\n \\"@vitejs/plugin-react\\": \\"^4.3.0\\",\\n \\"typescript\\": \\"^5.6.0\\",\\n \\"vite\\": \\"^5.4.0\\"\\n }\\n}\\n","root/tsconfig.json":"{\\n \\"compilerOptions\\": {\\n \\"target\\": \\"ES2022\\",\\n \\"module\\": \\"ESNext\\",\\n \\"moduleResolution\\": \\"Bundler\\",\\n \\"jsx\\": \\"react-jsx\\",\\n \\"lib\\": [\\"ES2022\\", \\"DOM\\"],\\n \\"strict\\": true,\\n \\"esModuleInterop\\": true,\\n \\"skipLibCheck\\": true,\\n \\"isolatedModules\\": true,\\n \\"noEmit\\": true\\n },\\n \\"include\\": [\\"components/**/component.tsx\\", \\"vite.config.ts\\"]\\n}\\n","root/vite.config.ts":"import { defineConfig } from \\"vite\\";\\nimport react from \\"@vitejs/plugin-react\\";\\n\\n// Real builds happen in `gs build` (one Vite invocation per\\n// component, externals + runtime shim paths owned by the CLI). This\\n// file exists only so editors / language servers can resolve the\\n// React plugin when inspecting components/*/component.tsx.\\nexport default defineConfig({\\n plugins: [react()],\\n});\\n"}'),ve)}var ft={name:"__GS_NAME__",displayName:"__GS_DISPLAY_NAME__",store:"__GS_STORE__",version:"__GS_VERSION__"};function mt(e,t){let n=e;for(let o of Object.keys(ft)){let s=t[o];s!==void 0&&(n=n.split(ft[o]).join(s))}let r=n.match(/__GS_[A-Z_]+__/);if(r)throw new Error(`internal: template placeholder ${r[0]} was not provided`);return n}var gt=/^[a-z][a-z0-9_]*$/;function yt(e){let t=e.positional[0];if(t!==void 0&&!gt.test(t))throw new Error(`Invalid component name: "${t}" (must match ${gt}).`);let n=m(e.flags,"force"),r=h(e.flags,"store"),o=h(e.flags,"out")??".",s=k.resolve(o),i=nr(s),a;if(i){if(r!==void 0)throw new Error(`Project at ${s} is already pinned to a store via .gsrc. Drop --store; a project folder ships to exactly one store.`);$({cwd:s})}else if(a=r!==void 0?ee(r):ce()??void 0,a===void 0){let u=t?`gs apps init ${t} --store <slug>`:"gs apps init --store <slug>";throw new Error(`--store <slug> is required when scaffolding a new project root. Run \`${u}\`.`)}let l=rr(s,i,n,{store:a});if(!t){let u=[];i?(u.push(`Updated GreatStore project root in ${s}.`),l.length>0?u.push("",`Added: ${l.join(", ")}`):u.push("","Already up to date \u2014 nothing to add.")):u.push(`Scaffolded GreatStore project root in ${s}.`),u.push("","Next steps:",` cd ${k.relative(process.cwd(),s)||"."}`," npm install"," gs apps init <component_name> # add your first component",""),process.stdout.write(u.join(`
82
82
  `));return}let c=k.join(s,"components",t);ir(c,t,n);let p=k.relative(process.cwd(),s)||".";process.stdout.write([`Added component "${t}" at components/${t}/.`,...i&&l.length>0?["",`Also added to the project root: ${l.join(", ")}`]:[],"","Next steps:",...i?[]:[` cd ${p}`," npm install"],` # edit components/${t}/component.tsx and manifest.json`," gs apps build"," gs apps push",""].join(`
83
- `))}function nr(e){return g.existsSync(k.join(e,"package.json"))&&g.existsSync(k.join(e,".gsrc"))}function rr(e,t,n,r){if(g.mkdirSync(e,{recursive:!0}),!t&&!n&&g.readdirSync(e).filter(a=>a!==".gsrc").length>0)throw new Error(`Refusing to scaffold project root into non-empty directory ${e}. Pass --force to override.`);let o=t?cr():ar({store:r.store}),s=sr(e,o,n);return g.mkdirSync(k.join(e,"components"),{recursive:!0}),s}var or=new Set(["AGENTS.md"]);function sr(e,t,n){let r=[];for(let[o,s]of t){let i=k.join(e,o);g.mkdirSync(k.dirname(i),{recursive:!0});let a=g.existsSync(i);if(!n&&a&&!or.has(o))continue;let l=!a||g.readFileSync(i,"utf8")!==s;g.writeFileSync(i,s),l&&r.push(o)}for(let o of["CLAUDE.md","GEMINI.md"]){let s=k.join(e,o);n&&ht(s)&&g.rmSync(s),ht(s)||(g.symlinkSync("AGENTS.md",s),r.push(o))}return r}function ht(e){try{return g.lstatSync(e),!0}catch{return!1}}function ir(e,t,n){if(g.existsSync(e)&&!n&&g.readdirSync(e).length>0)throw new Error(`Refusing to overwrite existing components/${t}/. Pass --force to override.`);g.mkdirSync(e,{recursive:!0});for(let[r,o]of lr(t))g.writeFileSync(k.join(e,r),o)}function Oe(e,t,n=new Set){let r=dt();return Object.entries(r).filter(([o])=>o.startsWith(e)).map(([o,s])=>[o.slice(e.length),s]).filter(([o])=>!n.has(o)).map(([o,s])=>[o,mt(s,t)])}function ar(e){if(!e.store)throw new Error("internal: rootFiles called without a store slug");return Oe("root/",{store:e.store,version:N})}function cr(){return Oe("root/",{version:N},new Set([".gsrc"]))}function lr(e){return Oe("component/",{name:e,displayName:ur(e)})}function ur(e){let t=e.split("_").filter(Boolean);if(t.length===0)return e;let n=t[0];return n.charAt(0).toUpperCase()+n.slice(1)+(t.length>1?" "+t.slice(1).join(" "):"")}import*as b from"fs";import*as w from"path";import{createRequire as xr}from"module";import*as jt from"fs";import*as U from"path";import{createRequire as pr}from"module";import*as xe from"path";function St(e,t,n){let r=vt(e);if(!r)return{ok:!1,reason:"couldn't check props against the manifest \u2014 `typescript` isn't installed in this project (run `npm install`)"};try{let o=r.createSourceFile(t,n,r.ScriptTarget.Latest,!0,r.ScriptKind.TSX),s=dr(r,o);return s?hr(r,o,s):{ok:!1,reason:"couldn't find a default-exported component function to check props against \u2014 export the component as `export default function \u2026`"}}catch(o){return{ok:!1,reason:`couldn't check props against the manifest \u2014 ${xe.basename(t)} could not be parsed (${o.message})`}}}function bt(e,t,n){let r=vt(e);if(!r)return!1;try{let o=r.createSourceFile(t,n,r.ScriptTarget.Latest,!0,r.ScriptKind.TSX),s=!1,i=a=>{if(!s){if(fr(r,a)){s=!0;return}r.forEachChild(a,i)}};return i(o),s}catch{return!1}}function fr(e,t){if(e.isPropertyAccessExpression(t))return wt(e,t.expression)&&t.name.text==="GreatStore";if(e.isElementAccessExpression(t)){let n=t.argumentExpression;return wt(e,t.expression)&&e.isStringLiteralLike(n)&&n.text==="GreatStore"}return!1}function wt(e,t){return e.isIdentifier(t)&&(t.text==="window"||t.text==="globalThis")}function vt(e){let t=pr(xe.join(e,"package.json"));try{return t("typescript")}catch{return null}}function dr(e,t){let n=null;for(let o of t.statements){if(e.isFunctionDeclaration(o)&&mr(e,o))return o;e.isExportAssignment(o)&&!o.isExportEquals&&(n=o.expression)}if(!n)return null;let r=xt(e,n);return e.isArrowFunction(r)||e.isFunctionExpression(r)?r:e.isIdentifier(r)?gr(e,t,r.text):null}function mr(e,t){return t.modifiers?.some(n=>n.kind===e.SyntaxKind.DefaultKeyword)??!1}function xt(e,t){let n=t;for(;e.isParenthesizedExpression(n)||e.isAsExpression(n)||e.isSatisfiesExpression(n);)n=n.expression;return n}function gr(e,t,n){for(let r of t.statements){if(e.isFunctionDeclaration(r)&&r.name?.text===n)return r;if(e.isVariableStatement(r))for(let o of r.declarationList.declarations){if(!e.isIdentifier(o.name)||o.name.text!==n||!o.initializer)continue;let s=xt(e,o.initializer);if(e.isArrowFunction(s)||e.isFunctionExpression(s))return s}}return null}function hr(e,t,n){let r=n.parameters[0];if(!r)return{ok:!0,props:{names:[],open:!1}};if(r.type){let o=Ie(e,t,r.type,new Set);if(o)return{ok:!0,props:o}}return e.isObjectBindingPattern(r.name)?{ok:!0,props:yr(e,r.name)}:{ok:!1,reason:"couldn't check props against the manifest \u2014 declare the component's props as a local `interface`/`type` or destructure them in the signature"}}function Ie(e,t,n,r){if(e.isTypeLiteralNode(n))return Pt(e,n.members);if(e.isTypeReferenceNode(n)&&e.isIdentifier(n.typeName))return kt(e,t,n.typeName.text,r);if(e.isIntersectionTypeNode(n)){let o=n.types.map(s=>Ie(e,t,s,r));return o.every(s=>s===null)?null:Ct(o.map(s=>s??{names:[],open:!0}))}return null}function kt(e,t,n,r){if(r.has(n))return{names:[],open:!1};r.add(n);for(let o of t.statements){if(e.isInterfaceDeclaration(o)&&o.name.text===n){let s=Pt(e,o.members),i=(o.heritageClauses??[]).flatMap(a=>a.types.map(l=>e.isIdentifier(l.expression)?kt(e,t,l.expression.text,r)??{names:[],open:!0}:{names:[],open:!0}));return Ct([s,...i])}if(e.isTypeAliasDeclaration(o)&&o.name.text===n)return Ie(e,t,o.type,r)}return null}function Pt(e,t){let n=[],r=!1;for(let o of t){if(e.isIndexSignatureDeclaration(o)){r=!0;continue}if(!e.isPropertySignature(o)&&!e.isMethodSignature(o))continue;let s=$t(e,o.name);if(s===null){r=!0;continue}n.push(s)}return{names:n,open:r}}function yr(e,t){let n=[],r=!1;for(let o of t.elements){if(o.dotDotDotToken){r=!0;continue}let s=o.propertyName??o.name,i=$t(e,s);i===null?r=!0:n.push(i)}return{names:n,open:r}}function $t(e,t){return e.isIdentifier(t)||e.isStringLiteral(t)?t.text:null}function Ct(e){let t=[],n=!1;for(let r of e){for(let o of r.names)t.includes(o)||t.push(o);n||=r.open}return{names:t,open:n}}function Rt(e){let{root:t,name:n}=e,r=U.join(t,"components",n),o=e.manifestPath??U.join(r,"manifest.json"),s=e.sourcePath??U.join(r,"component.tsx"),i=At(t,o),a=At(t,s),l=[],c=null,p=Et(o);if(p===null)l.push({severity:"error",rule:"manifest/missing",file:i,message:"manifest not found."});else try{let P=JSON.parse(p);!P||typeof P!="object"||Array.isArray(P)?l.push({severity:"error",rule:"manifest/invalid",file:i,message:"manifest must be a JSON object."}):c=P}catch(P){l.push({severity:"error",rule:"manifest/invalid",file:i,message:`manifest is not valid JSON: ${P.message}`})}let u=Et(s),f=u===null?{ok:!1,reason:`couldn't check props against the manifest \u2014 ${a} not found`}:St(t,s,u),j=u===null?!1:bt(t,s,u);return{ctx:{name:n,manifestFile:i,sourceFile:a,manifest:c,props:f,usesWindowGreatStore:j},diagnostics:l}}function Et(e){try{return jt.readFileSync(e,"utf8")}catch{return null}}function At(e,t){let n=U.relative(e,t);return n.startsWith("..")?t:n.split(U.sep).join("/")}var _t=new Set(["onSendMessage","onCallTool","onClose","onUpdateModelContext","onShowLightbox","onGenerateStructuredContent","storeData","Image"]);var Tt=new Map([["onError",'prop `onError` is deprecated and no longer provided \u2014 prefer an async component to report failures. Drop the prop; see the "Async components" section in AGENTS.md for how to signal errors.']]);function Ot(e){if(!e.manifest)return[];let t=Sr(e.manifest.inputSchema);if(t===null)return[];if(!e.props.ok)return[{severity:"warning",rule:"props/not-analyzable",file:e.sourceFile,message:`${e.props.reason}.`}];if(e.props.props.open)return[];let n=new Set(e.props.props.names),r=new Set(t),o=[];for(let i of e.props.props.names){if(_t.has(i))continue;let a=Tt.get(i);if(a){o.push({severity:"warning",rule:"props/retired-lifecycle",file:e.sourceFile,message:a});continue}r.has(i)||o.push({severity:"warning",rule:"props/undeclared",file:e.sourceFile,message:`prop \`${i}\` is not declared in ${e.manifestFile}#inputSchema.properties, so nothing will ever pass it. Declare it in the schema, or drop it from the component.`})}let s=t.filter(i=>!n.has(i));return s.length>0&&o.push({severity:"error",rule:"props/missing",file:e.sourceFile,message:wr(e.manifestFile,s)}),o}var Lt=8;function wr(e,t){if(t.length===1){let[s]=t;return`${e} declares inputSchema field \`${s}\`, but the component does not accept a \`${s}\` prop. Add it to the component's props, or remove it from the schema.`}let n=t.slice(0,Lt).map(s=>`\`${s}\``).join(", "),r=t.length-Lt,o=r>0?`${n} (+${r} more)`:n;return`${e} declares ${t.length} inputSchema fields the component does not accept: ${o}. Add them to the component's props, or remove them from the schema.`}function Sr(e){if(!e||typeof e!="object")return null;let t=e.properties;return!t||typeof t!="object"||Array.isArray(t)?null:Object.keys(t)}var br=["anyOf","oneOf","allOf","$ref","not"];function ke(e,t,n){if(Array.isArray(e)){e.forEach((s,i)=>ke(s,`${t}[${i}]`,n));return}if(!e||typeof e!="object")return;let r=e;for(let s of br)s in r&&n.unionPaths.push(`${t}.${s}`);let o=r.properties;if(o&&typeof o=="object"&&!Array.isArray(o))for(let[s,i]of Object.entries(o))n.fields+=1,ke(i,`${t}.${s}`,n);"items"in r&&ke(r.items,`${t}[]`,n)}function It(e){let t=e.manifest?.inputSchema;if(!t||typeof t!="object")return[];let n={bytes:Buffer.byteLength(JSON.stringify(t),"utf8"),fields:0,unionPaths:[]};ke(t,"inputSchema",n);let r=[];if(n.unionPaths.length>0){let o=n.unionPaths.slice(0,3).join(", "),s=n.unionPaths.length>3?` (+${n.unionPaths.length-3} more)`:"";r.push(`uses ${o}${s} \u2014 declare exactly one type per field; accept alternate shapes in component code instead`)}return n.bytes>8192&&r.push(`is ${(n.bytes/1024).toFixed(1)} KB serialized (limit ${8192/1024} KB)`),n.fields>50&&r.push(`declares ${n.fields} fields (limit 50)`),r.length===0?[]:[{severity:"error",rule:"manifest/input-schema-too-complex",file:e.manifestFile,message:`inputSchema ${r.join("; ")}.
84
- A schema this complex is usually a sign the component is overengineered, and the assistant will fill it unreliably or stop calling the tool altogether. Keep it to a small set of flat, single-type fields (one canonical name per concept \u2014 no aliases), and let component code handle formatting, fallbacks, and edge cases.`}]}function Ft(e){let t=e.manifest?.name;return typeof t!="string"||t===e.name?[]:[{severity:"error",rule:"manifest/name-mismatch",file:e.manifestFile,message:`manifest name "${t}" does not match folder name "${e.name}".`}]}function Nt(e){return e.usesWindowGreatStore?[{severity:"warning",rule:"globals/window-greatstore",file:e.sourceFile,message:"this component reads `window.GreatStore`, the host-page embed API. Components should interact with GreatStore through their injected lifecycle props (`onSendMessage`, `onCallTool`, `onGenerateStructuredContent`, \u2026) instead \u2014 those are wired to the surface the component is mounted in."}]:[]}function pe(e){return e.filter(t=>t.severity==="error")}function Fe(e){return e.filter(t=>t.severity==="warning")}function fe(e){return`${e.severity==="error"?"error":"warning"} ${e.file}: ${e.message}`}var vr=[Ft,It,Ot,Nt];function Pe(e){let{ctx:t,diagnostics:n}=Rt(e);for(let r of vr)n.push(...r(t));return{diagnostics:n,ok:pe(n).length===0}}var W="components";async function Bt(e){let t=process.cwd();if(!b.existsSync(w.join(t,"package.json"))||!b.existsSync(w.join(t,W)))throw new Error(`\`gs apps build\` must run from a project root (contains \`package.json\` and \`${W}/\`). Current dir: ${t}`);let n=kr(t);if(n.length===0){process.stdout.write(`(no components in ./${W} \u2014 run \`gs apps init <name>\` to add one)
83
+ `))}function nr(e){return g.existsSync(k.join(e,"package.json"))&&g.existsSync(k.join(e,".gsrc"))}function rr(e,t,n,r){if(g.mkdirSync(e,{recursive:!0}),!t&&!n&&g.readdirSync(e).filter(a=>a!==".gsrc").length>0)throw new Error(`Refusing to scaffold project root into non-empty directory ${e}. Pass --force to override.`);let o=t?cr():ar({store:r.store}),s=sr(e,o,n);return g.mkdirSync(k.join(e,"components"),{recursive:!0}),s}var or=new Set(["AGENTS.md"]);function sr(e,t,n){let r=[];for(let[o,s]of t){let i=k.join(e,o);g.mkdirSync(k.dirname(i),{recursive:!0});let a=g.existsSync(i);if(!n&&a&&!or.has(o))continue;let l=!a||g.readFileSync(i,"utf8")!==s;g.writeFileSync(i,s),l&&r.push(o)}for(let o of["CLAUDE.md","GEMINI.md"]){let s=k.join(e,o);n&&ht(s)&&g.rmSync(s),ht(s)||(g.symlinkSync("AGENTS.md",s),r.push(o))}return r}function ht(e){try{return g.lstatSync(e),!0}catch{return!1}}function ir(e,t,n){if(g.existsSync(e)&&!n&&g.readdirSync(e).length>0)throw new Error(`Refusing to overwrite existing components/${t}/. Pass --force to override.`);g.mkdirSync(e,{recursive:!0});for(let[r,o]of lr(t))g.writeFileSync(k.join(e,r),o)}function Oe(e,t,n=new Set){let r=dt();return Object.entries(r).filter(([o])=>o.startsWith(e)).map(([o,s])=>[o.slice(e.length),s]).filter(([o])=>!n.has(o)).map(([o,s])=>[o,mt(s,t)])}function ar(e){if(!e.store)throw new Error("internal: rootFiles called without a store slug");return Oe("root/",{store:e.store,version:N})}function cr(){return Oe("root/",{version:N},new Set([".gsrc"]))}function lr(e){return Oe("component/",{name:e,displayName:ur(e)})}function ur(e){let t=e.split("_").filter(Boolean);if(t.length===0)return e;let n=t[0];return n.charAt(0).toUpperCase()+n.slice(1)+(t.length>1?" "+t.slice(1).join(" "):"")}import*as b from"fs";import*as w from"path";import{createRequire as xr}from"module";import*as jt from"fs";import*as U from"path";import{createRequire as pr}from"module";import*as xe from"path";function St(e,t,n){let r=vt(e);if(!r)return{ok:!1,reason:"couldn't check props against the manifest \u2014 `typescript` isn't installed in this project (run `npm install`)"};try{let o=r.createSourceFile(t,n,r.ScriptTarget.Latest,!0,r.ScriptKind.TSX),s=dr(r,o);return s?hr(r,o,s):{ok:!1,reason:"couldn't find a default-exported component function to check props against \u2014 export the component as `export default function \u2026`"}}catch(o){return{ok:!1,reason:`couldn't check props against the manifest \u2014 ${xe.basename(t)} could not be parsed (${o.message})`}}}function bt(e,t,n){let r=vt(e);if(!r)return!1;try{let o=r.createSourceFile(t,n,r.ScriptTarget.Latest,!0,r.ScriptKind.TSX),s=!1,i=a=>{if(!s){if(fr(r,a)){s=!0;return}r.forEachChild(a,i)}};return i(o),s}catch{return!1}}function fr(e,t){if(e.isPropertyAccessExpression(t))return wt(e,t.expression)&&t.name.text==="GreatStore";if(e.isElementAccessExpression(t)){let n=t.argumentExpression;return wt(e,t.expression)&&e.isStringLiteralLike(n)&&n.text==="GreatStore"}return!1}function wt(e,t){return e.isIdentifier(t)&&(t.text==="window"||t.text==="globalThis")}function vt(e){let t=pr(xe.join(e,"package.json"));try{return t("typescript")}catch{return null}}function dr(e,t){let n=null;for(let o of t.statements){if(e.isFunctionDeclaration(o)&&mr(e,o))return o;e.isExportAssignment(o)&&!o.isExportEquals&&(n=o.expression)}if(!n)return null;let r=xt(e,n);return e.isArrowFunction(r)||e.isFunctionExpression(r)?r:e.isIdentifier(r)?gr(e,t,r.text):null}function mr(e,t){return t.modifiers?.some(n=>n.kind===e.SyntaxKind.DefaultKeyword)??!1}function xt(e,t){let n=t;for(;e.isParenthesizedExpression(n)||e.isAsExpression(n)||e.isSatisfiesExpression(n);)n=n.expression;return n}function gr(e,t,n){for(let r of t.statements){if(e.isFunctionDeclaration(r)&&r.name?.text===n)return r;if(e.isVariableStatement(r))for(let o of r.declarationList.declarations){if(!e.isIdentifier(o.name)||o.name.text!==n||!o.initializer)continue;let s=xt(e,o.initializer);if(e.isArrowFunction(s)||e.isFunctionExpression(s))return s}}return null}function hr(e,t,n){let r=n.parameters[0];if(!r)return{ok:!0,props:{names:[],open:!1}};if(r.type){let o=Ie(e,t,r.type,new Set);if(o)return{ok:!0,props:o}}return e.isObjectBindingPattern(r.name)?{ok:!0,props:yr(e,r.name)}:{ok:!1,reason:"couldn't check props against the manifest \u2014 declare the component's props as a local `interface`/`type` or destructure them in the signature"}}function Ie(e,t,n,r){if(e.isTypeLiteralNode(n))return Pt(e,n.members);if(e.isTypeReferenceNode(n)&&e.isIdentifier(n.typeName))return kt(e,t,n.typeName.text,r);if(e.isIntersectionTypeNode(n)){let o=n.types.map(s=>Ie(e,t,s,r));return o.every(s=>s===null)?null:Ct(o.map(s=>s??{names:[],open:!0}))}return null}function kt(e,t,n,r){if(r.has(n))return{names:[],open:!1};r.add(n);for(let o of t.statements){if(e.isInterfaceDeclaration(o)&&o.name.text===n){let s=Pt(e,o.members),i=(o.heritageClauses??[]).flatMap(a=>a.types.map(l=>e.isIdentifier(l.expression)?kt(e,t,l.expression.text,r)??{names:[],open:!0}:{names:[],open:!0}));return Ct([s,...i])}if(e.isTypeAliasDeclaration(o)&&o.name.text===n)return Ie(e,t,o.type,r)}return null}function Pt(e,t){let n=[],r=!1;for(let o of t){if(e.isIndexSignatureDeclaration(o)){r=!0;continue}if(!e.isPropertySignature(o)&&!e.isMethodSignature(o))continue;let s=$t(e,o.name);if(s===null){r=!0;continue}n.push(s)}return{names:n,open:r}}function yr(e,t){let n=[],r=!1;for(let o of t.elements){if(o.dotDotDotToken){r=!0;continue}let s=o.propertyName??o.name,i=$t(e,s);i===null?r=!0:n.push(i)}return{names:n,open:r}}function $t(e,t){return e.isIdentifier(t)||e.isStringLiteral(t)?t.text:null}function Ct(e){let t=[],n=!1;for(let r of e){for(let o of r.names)t.includes(o)||t.push(o);n||=r.open}return{names:t,open:n}}function Rt(e){let{root:t,name:n}=e,r=U.join(t,"components",n),o=e.manifestPath??U.join(r,"manifest.json"),s=e.sourcePath??U.join(r,"component.tsx"),i=At(t,o),a=At(t,s),l=[],c=null,p=Et(o);if(p===null)l.push({severity:"error",rule:"manifest/missing",file:i,message:"manifest not found."});else try{let P=JSON.parse(p);!P||typeof P!="object"||Array.isArray(P)?l.push({severity:"error",rule:"manifest/invalid",file:i,message:"manifest must be a JSON object."}):c=P}catch(P){l.push({severity:"error",rule:"manifest/invalid",file:i,message:`manifest is not valid JSON: ${P.message}`})}let u=Et(s),f=u===null?{ok:!1,reason:`couldn't check props against the manifest \u2014 ${a} not found`}:St(t,s,u),j=u===null?!1:bt(t,s,u);return{ctx:{name:n,manifestFile:i,sourceFile:a,manifest:c,props:f,usesWindowGreatStore:j},diagnostics:l}}function Et(e){try{return jt.readFileSync(e,"utf8")}catch{return null}}function At(e,t){let n=U.relative(e,t);return n.startsWith("..")?t:n.split(U.sep).join("/")}var _t=new Set(["onSendMessage","onClose","onUpdateModelContext","onShowLightbox","onGenerateStructuredContent","storeData","Image"]);var Tt=new Map([["onError",'prop `onError` is deprecated and no longer provided \u2014 prefer an async component to report failures. Drop the prop; see the "Async components" section in AGENTS.md for how to signal errors.']]);function Ot(e){if(!e.manifest)return[];let t=Sr(e.manifest.inputSchema);if(t===null)return[];if(!e.props.ok)return[{severity:"warning",rule:"props/not-analyzable",file:e.sourceFile,message:`${e.props.reason}.`}];if(e.props.props.open)return[];let n=new Set(e.props.props.names),r=new Set(t),o=[];for(let i of e.props.props.names){if(_t.has(i))continue;let a=Tt.get(i);if(a){o.push({severity:"warning",rule:"props/retired-lifecycle",file:e.sourceFile,message:a});continue}r.has(i)||o.push({severity:"warning",rule:"props/undeclared",file:e.sourceFile,message:`prop \`${i}\` is not declared in ${e.manifestFile}#inputSchema.properties, so nothing will ever pass it. Declare it in the schema, or drop it from the component.`})}let s=t.filter(i=>!n.has(i));return s.length>0&&o.push({severity:"error",rule:"props/missing",file:e.sourceFile,message:wr(e.manifestFile,s)}),o}var Lt=8;function wr(e,t){if(t.length===1){let[s]=t;return`${e} declares inputSchema field \`${s}\`, but the component does not accept a \`${s}\` prop. Add it to the component's props, or remove it from the schema.`}let n=t.slice(0,Lt).map(s=>`\`${s}\``).join(", "),r=t.length-Lt,o=r>0?`${n} (+${r} more)`:n;return`${e} declares ${t.length} inputSchema fields the component does not accept: ${o}. Add them to the component's props, or remove them from the schema.`}function Sr(e){if(!e||typeof e!="object")return null;let t=e.properties;return!t||typeof t!="object"||Array.isArray(t)?null:Object.keys(t)}var br=["anyOf","oneOf","allOf","$ref","not"];function ke(e,t,n){if(Array.isArray(e)){e.forEach((s,i)=>ke(s,`${t}[${i}]`,n));return}if(!e||typeof e!="object")return;let r=e;for(let s of br)s in r&&n.unionPaths.push(`${t}.${s}`);let o=r.properties;if(o&&typeof o=="object"&&!Array.isArray(o))for(let[s,i]of Object.entries(o))n.fields+=1,ke(i,`${t}.${s}`,n);"items"in r&&ke(r.items,`${t}[]`,n)}function It(e){let t=e.manifest?.inputSchema;if(!t||typeof t!="object")return[];let n={bytes:Buffer.byteLength(JSON.stringify(t),"utf8"),fields:0,unionPaths:[]};ke(t,"inputSchema",n);let r=[];if(n.unionPaths.length>0){let o=n.unionPaths.slice(0,3).join(", "),s=n.unionPaths.length>3?` (+${n.unionPaths.length-3} more)`:"";r.push(`uses ${o}${s} \u2014 declare exactly one type per field; accept alternate shapes in component code instead`)}return n.bytes>8192&&r.push(`is ${(n.bytes/1024).toFixed(1)} KB serialized (limit ${8192/1024} KB)`),n.fields>50&&r.push(`declares ${n.fields} fields (limit 50)`),r.length===0?[]:[{severity:"error",rule:"manifest/input-schema-too-complex",file:e.manifestFile,message:`inputSchema ${r.join("; ")}.
84
+ A schema this complex is usually a sign the component is overengineered, and the assistant will fill it unreliably or stop calling the tool altogether. Keep it to a small set of flat, single-type fields (one canonical name per concept \u2014 no aliases), and let component code handle formatting, fallbacks, and edge cases.`}]}function Ft(e){let t=e.manifest?.name;return typeof t!="string"||t===e.name?[]:[{severity:"error",rule:"manifest/name-mismatch",file:e.manifestFile,message:`manifest name "${t}" does not match folder name "${e.name}".`}]}function Nt(e){return e.usesWindowGreatStore?[{severity:"warning",rule:"globals/window-greatstore",file:e.sourceFile,message:"this component reads `window.GreatStore`, the host-page embed API. Components should interact with GreatStore through their injected lifecycle props (`onSendMessage`, `onGenerateStructuredContent`, \u2026) instead \u2014 those are wired to the surface the component is mounted in."}]:[]}function pe(e){return e.filter(t=>t.severity==="error")}function Fe(e){return e.filter(t=>t.severity==="warning")}function fe(e){return`${e.severity==="error"?"error":"warning"} ${e.file}: ${e.message}`}var vr=[Ft,It,Ot,Nt];function Pe(e){let{ctx:t,diagnostics:n}=Rt(e);for(let r of vr)n.push(...r(t));return{diagnostics:n,ok:pe(n).length===0}}var W="components";async function Bt(e){let t=process.cwd();if(!b.existsSync(w.join(t,"package.json"))||!b.existsSync(w.join(t,W)))throw new Error(`\`gs apps build\` must run from a project root (contains \`package.json\` and \`${W}/\`). Current dir: ${t}`);let n=kr(t);if(n.length===0){process.stdout.write(`(no components in ./${W} \u2014 run \`gs apps init <name>\` to add one)
85
85
  `);return}let r=e.positional[0],o=r?n.filter(p=>p===r):n;if(r&&o.length===0)throw new Error(`No component named "${r}" in ./${W}`);let s=[],i=[];for(let p of o){let u=Pe({root:t,name:p});for(let f of u.diagnostics)process.stdout.write(` ${fe(f)}
86
86
  `);(u.ok?i:s).push(p)}if(i.length===0){process.stdout.write(`
87
87
  Nothing built \u2014 fix the errors above.
@@ -166,6 +166,32 @@ Did you mean: ${i.join(", ")}?`:""))}if(typeof r!="string"){if(s.kind==="boolean
166
166
  All notable changes to \`@greatstore/cli\` are recorded here. The format
167
167
  follows [Keep a Changelog](https://keepachangelog.com/).
168
168
 
169
+ ## 0.1.15 \u2014 2026-09-17
170
+
171
+ ### Changed
172
+ - The bundled agent skill (\`gs skill\`) calls custom in-chat UI **apps**
173
+ throughout, matching \`gs apps\` and the dashboard, and documents the
174
+ lifecycle a coding agent needs: the assistant picks an app and calls it
175
+ with the props the manifest declares, the app renders, and from there it
176
+ can report what the shopper is doing, send a message on their behalf, run
177
+ a catalog-grounded generation of its own for recommendations or a
178
+ personalized summary, or be called again with revised props. Guidance on
179
+ writing a \`name\` and \`description\` now spells out that they should say
180
+ *when* the assistant should reach for the app, not what the app looks like.
181
+
182
+ ## 0.1.13 \u2014 2026-09-16
183
+
184
+ ### Removed
185
+ - Components are no longer passed an \`onCallTool\` prop. Drop it from your
186
+ component's \`Props\` \u2014 one still declaring it gets an undeclared-prop
187
+ warning from \`gs apps validate\`. To hand off to another component, call
188
+ \`onSendMessage(...)\` with the follow-up you want and let the assistant
189
+ take it from there.
190
+
191
+ ### Changed
192
+ - This release is the minimum version the server accepts \u2014 earlier ones stop
193
+ working. Run \`npm install -g @greatstore/cli@latest\` to upgrade.
194
+
169
195
  ## 0.1.12 \u2014 2026-09-14
170
196
 
171
197
  ### Changed
@@ -288,7 +314,7 @@ follows [Keep a Changelog](https://keepachangelog.com/).
288
314
  ### Changed
289
315
  - Component validation now warns when a component reaches for the page-level
290
316
  \`window.GreatStore\` API. Components should interact with GreatStore through
291
- the lifecycle props passed into them (\`onSendMessage\`, \`onCallTool\`,
317
+ the lifecycle props passed into them (\`onSendMessage\`,
292
318
  \`onGenerateStructuredContent\`, \u2026), which are wired to the surface the
293
319
  component is mounted in; the warning points you there. It's a nudge, not a
294
320
  build failure.
@@ -347,7 +373,7 @@ follows [Keep a Changelog](https://keepachangelog.com/).
347
373
  - New check: a component's props and its \`inputSchema.properties\` must
348
374
  agree. A schema field the component doesn't accept is an error; a prop
349
375
  the schema doesn't declare is a warning, since nothing will ever pass
350
- it. The props GreatStore injects (\`onSendMessage\`, \`onCallTool\`,
376
+ it. The props GreatStore injects (\`onSendMessage\`,
351
377
  \`onUpdateModelContext\`, \`onShowLightbox\`, \`onClose\`, \`storeData\`,
352
378
  \`Image\`) are exempt.
353
379
 
@@ -584,8 +610,8 @@ follows [Keep a Changelog](https://keepachangelog.com/).
584
610
  ## 0.0.15 \u2014 2026-05-24
585
611
 
586
612
  ### Added
587
- - Scaffolded \`component.tsx\` now declares the four injected lifecycle
588
- props (\`onSendMessage\`, \`onCallTool\`, \`onClose\`, \`onError\`) on
613
+ - Scaffolded \`component.tsx\` now declares the injected lifecycle
614
+ props (\`onSendMessage\`, \`onClose\`, \`onError\`) on
589
615
  \`Props\`. Use \`onError(message)\` to report expected failures (failed
590
616
  fetch, host action rejected, invalid host state) so the AI can
591
617
  recover on its next turn. Render-time crashes are reported for you.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: greatstore
3
- description: Build AI-powered shopping experiences with GreatStore on a merchant's website and store. Use when installing the GreatStore chat widget on a site, generating AI content for custom UI with generateStructuredContent, adding chat entry points (sendMessage), letting the assistant act on the page via WebMCP page tools (document.modelContext.registerTool), authoring custom in-chat React components with the gs CLI, administering the store from the CLI (gs configure, gs connectors — origin allowlists, CSP hosts, MCP connectors), setting up web push re-engagement, or connecting AI agents to a store's MCP endpoints. Covers setup, schema design, caching behavior, component authoring, store administration, and ready-made recipes.
3
+ description: Build AI-powered shopping experiences with GreatStore on a merchant's website and store. Use when installing the GreatStore chat widget on a site, generating AI content for custom UI with generateStructuredContent, adding chat entry points (sendMessage), letting the assistant act on the page via WebMCP page tools (document.modelContext.registerTool), authoring custom in-chat apps with the gs CLI, administering the store from the CLI (gs configure, gs connectors — origin allowlists, CSP hosts, MCP connectors), setting up web push re-engagement, or connecting AI agents to a store's MCP endpoints. Covers setup, schema design, caching behavior, app authoring, store administration, and ready-made recipes.
4
4
  ---
5
5
 
6
6
  # Building with GreatStore
@@ -26,10 +26,10 @@ constraints) that the references spell out.
26
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) |
27
27
  | Copy-paste on-page experiences | recipes built on the SDK | the [Recipes](#recipes) table below |
28
28
  | Contextual **conversation entry points** anywhere on the page | `sendMessage(text)`, `open()`, `?gs_chat=open` | [references/embed-api.md](references/embed-api.md) |
29
- | Feed the assistant **invisible page/component state** (current product, cart, selected variant) | `updateModelContext(text)`; component `onUpdateModelContext` | [references/embed-api.md](references/embed-api.md), [references/chat-components.md](references/chat-components.md) |
29
+ | Feed the assistant **invisible page/app state** (current product, cart, selected variant) | `updateModelContext(text)`; an app's `onUpdateModelContext` | [references/embed-api.md](references/embed-api.md), [references/apps.md](references/apps.md) |
30
30
  | Let the assistant **act on the page** (cart, navigation, filters) | WebMCP: `document.modelContext.registerTool(...)` | [references/embed-api.md](references/embed-api.md) |
31
- | Custom **interactive UI inside the chat** (configurators, quizzes, size guides, booking forms) | remote components shipped with the `gs` CLI | [references/chat-components.md](references/chat-components.md) |
32
- | Expand a component's image in an **on-brand full-screen lightbox** | component `onShowLightbox({ src, originRect })` | [references/chat-components.md](references/chat-components.md) |
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
+ | Expand an app's image in an **on-brand full-screen lightbox** | an app's `onShowLightbox({ src, originRect })` | [references/apps.md](references/apps.md) |
33
33
  | **Re-engage shoppers** with browser notifications | merchant-hosted `gs.js` + `enableNotifications()` | [references/push-notifications.md](references/push-notifications.md) |
34
34
  | Connect **AI agents** to the store (shopping tools over MCP, CLI docs for coding agents) | the store's MCP endpoints | [references/agents-and-mcp.md](references/agents-and-mcp.md) |
35
35
  | **Administer the store** — read config/connectors to ground decisions; self-serve origin allowlists and CSP hosts | `gs configure`, `gs connectors` | [references/store-admin.md](references/store-admin.md) |
@@ -77,7 +77,7 @@ The strongest pattern is the **teaser → conversation → action** funnel:
77
77
  `generateStructuredContent` renders a grounded teaser in the merchant's
78
78
  design; each option's click handler calls `sendMessage` with the shopper's
79
79
  choice, dropping them into a conversation with momentum; WebMCP page tools
80
- and custom chat components let that conversation actually do things — add to
80
+ and apps let that conversation actually do things — add to
81
81
  cart, configure a product, book a slot — so it ends in a conversion, not a
82
82
  copy-paste. The [gift finder funnel](recipes/gift-finder-funnel.md)
83
83
  recipe is this funnel end to end.
@@ -18,8 +18,8 @@ CLI commands.
18
18
  claude mcp add --transport http greatstore-admin https://admin.greatstore.ai/mcp
19
19
  ```
20
20
 
21
- Useful when a coding agent is shipping chat components
22
- ([chat-components.md](chat-components.md)) and needs the exact command for
21
+ Useful when a coding agent is shipping apps
22
+ ([apps.md](apps.md)) and needs the exact command for
23
23
  the next step. If this skill is installed, the agent already has the
24
24
  workflow — the MCP is the self-serve alternative for agents that don't.
25
25
 
@@ -27,7 +27,7 @@ workflow — the MCP is the self-serve alternative for agents that don't.
27
27
 
28
28
  - **Building the merchant's site** → this skill's other references (the SDK,
29
29
  structured content, page tools).
30
- - **A coding agent shipping chat components** → the `gs` CLI, with `/mcp`
30
+ - **A coding agent shipping apps** → the `gs` CLI, with `/mcp`
31
31
  as its built-in documentation.
32
32
  - **Reading or changing store settings** (origin allowlists, CSP hosts, MCP
33
33
  connectors, brand config) → the `gs` CLI's admin commands —
@@ -0,0 +1,332 @@
1
+ # Apps — authoring custom in-chat UI with the `gs` CLI
2
+
3
+ An app is interactive UI the assistant renders **inside the conversation** —
4
+ product configurators, quizzes, size guides, booking forms, anything richer
5
+ than text. You write it in React; GreatStore bundles it and serves it to
6
+ every surface the store's assistant runs on.
7
+
8
+ Each app is an AI-callable tool: the manifest's `description` tells the
9
+ assistant *when* to reach for it, its `inputSchema` declares the props the
10
+ assistant fills in, and a `displayMode` picks where it appears.
11
+
12
+ Authoring requires store-owner access (`gs login` signs in with the store
13
+ owner's account).
14
+
15
+ ## How an app actually runs
16
+
17
+ An app is not a page the shopper navigates to. It is a tool the assistant
18
+ calls mid-conversation, and once it is on screen it can talk back — which is
19
+ the part that makes apps worth building.
20
+
21
+ ```
22
+ Shopper Assistant Your app
23
+ │ │ │
24
+ │ "what size am I?" │ │
25
+ ├────────────────────>│ │
26
+ │ │ picks the app by its │
27
+ │ │ name + description │
28
+ │ │ │
29
+ │ │ calls it with props │
30
+ │ │ your inputSchema asked │
31
+ │ │ for (productName, …) │
32
+ │ ├────────────────────────>│
33
+ │ │ ├──┐ onGenerateStructured-
34
+ │ │ │ │ Content(): its own
35
+ │ │ │ │ catalog-grounded
36
+ │ │ │<─┘ generation, if wanted
37
+ │ │ │
38
+ │ │ │ renders the moment your
39
+ │ │ │ happy path has what it
40
+ │ │ │ needs (async: after your
41
+ │<────────────────────┼─────────────────────────┤ promise resolves)
42
+ │ sees the app │ │
43
+ │ │ │
44
+ │ picks size M │ │
45
+ ├─────────────────────┼────────────────────────>│
46
+ │ │ │
47
+ │ │ onUpdateModelContext() │ silent: the assistant
48
+ │ │<────────────────────────┤ now knows the pick
49
+ │ │ │
50
+ │ │ onSendMessage() │ visible: a shopper turn
51
+ │ │<────────────────────────┤ happens right now
52
+ │ │ │
53
+ │ │ calls the app again │ same app, new props —
54
+ │ ├────────────────────────>│ re-rendered in place
55
+ │ │ │
56
+ ```
57
+
58
+ Four consequences worth designing around:
59
+
60
+ 1. **The assistant chooses the app, so the manifest is the interface it
61
+ sees.** Everything under [Writing a `name` and `description` the assistant
62
+ will actually pick](#writing-a-name-and-description-the-assistant-will-actually-pick)
63
+ is about that choice.
64
+ 2. **Control is bidirectional once the app is up.** The app reports what the
65
+ shopper is doing (`onUpdateModelContext`), can speak for the shopper
66
+ (`onSendMessage`), and the assistant can call the app again with revised
67
+ props. Keep the render a function of the props it was given, so a re-call
68
+ is a re-render rather than a reset.
69
+ 3. **The app can run its own generation, not just receive props.**
70
+ `onGenerateStructuredContent(schema, prompt, fallback)` gives it a
71
+ catalog-grounded, shopper-personalized generation of its own, returned as
72
+ an object matching your schema — recommended picks, a personalized
73
+ summary, a reason per option — rendered in the merchant's own markup. Use
74
+ it when the app needs content the assistant didn't (and shouldn't have to)
75
+ pass as props.
76
+ 4. **Render on the happy path, not on a shell.** Whatever the app needs to be
77
+ correct — props, or awaited data in an async app, including a generation
78
+ of its own — should be there before anything paints; GreatStore owns the
79
+ loading state.
80
+
81
+ ## Workflow
82
+
83
+ ```
84
+ npm install -g @greatstore/cli # or npx @greatstore/cli <command>
85
+ gs login # browser sign-in
86
+ gs apps init --store my-store # scaffold a project root
87
+ cd <project> && npm install
88
+ gs apps init size_guide # scaffold components/size_guide/
89
+ # … edit components/size_guide/{component.tsx,manifest.json} …
90
+ gs apps build # bundle every app
91
+ gs apps push # upload changed apps as drafts
92
+ gs apps publish size_guide # promote to live
93
+ ```
94
+
95
+ `gs apps list` shows what's deployed (with dashboard links); `gs apps pull`
96
+ round-trips live apps back to disk. `gs apps push` hashes apps and only
97
+ uploads what changed. (The subcommands also work at the top level —
98
+ `gs push` == `gs apps push`.) On disk each app is a folder under
99
+ `components/`, holding `manifest.json` and `component.tsx`.
100
+
101
+ The scaffold writes an `AGENTS.md` into the project (with `CLAUDE.md` /
102
+ `GEMINI.md` symlinked) containing the complete design rules and brand
103
+ variable table — your coding agent picks it up automatically when working in
104
+ the project. `https://admin.greatstore.ai/mcp` serves the same CLI docs to
105
+ agents over MCP (see [agents-and-mcp.md](agents-and-mcp.md)).
106
+
107
+ ## `manifest.json`
108
+
109
+ ```json
110
+ {
111
+ "name": "size_guide",
112
+ "displayName": "Size guide",
113
+ "description": "Use when a shopper is unsure which size to buy, asks how an item fits, or compares their usual size across brands. Turns fit questions into a confident size choice, and reports the size they settle on back to you.",
114
+ "displayMode": "inline",
115
+ "inputSchema": {
116
+ "type": "object",
117
+ "properties": {
118
+ "productName": { "type": "string" },
119
+ "category": { "type": "string" }
120
+ },
121
+ "required": ["productName"]
122
+ }
123
+ }
124
+ ```
125
+
126
+ | Field | Meaning |
127
+ |---|---|
128
+ | `name` | Tool name, snake_case (`^[a-z][a-z0-9_]*$`), matches the folder under `components/`. |
129
+ | `displayName` | Friendly label shown in chat UI — the only field written for the shopper. |
130
+ | `description` | **Load-bearing** — the assistant's sole basis for choosing this app. See below. |
131
+ | `displayMode` | Where it renders — see below. |
132
+ | `inputSchema` | JSON Schema for the props the assistant fills. Keep it tight; required fields the AI can't infer cause bad calls. |
133
+ | `async` | Set `true` for backend-backed apps (see Async below). |
134
+
135
+ ### Writing a `name` and `description` the assistant will actually pick
136
+
137
+ The assistant never sees your app. It sees a name and a sentence, next to
138
+ every other tool it has, and picks one. So write the description for the
139
+ *caller*, answering one question: **when should I reach for this, and what do
140
+ I get back?**
141
+
142
+ **Describing the UI is the most common mistake.** Layout, sliders, tabs,
143
+ carousels and colors are the shopper's concern. To the assistant they are
144
+ noise — they say nothing about when to call the tool, and a description made
145
+ of them leaves it guessing.
146
+
147
+ | Don't | Do |
148
+ |---|---|
149
+ | "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." |
150
+ | "A carousel of product cards with images and prices." | "Use to show 2–8 specific products you have already chosen, when the shopper wants to see them side by side before deciding." |
151
+ | "Modal with a multi-step form and a progress bar." | "Use when the shopper wants a gift but can't say what — collects budget, recipient and occasion, then reports them back so you can recommend." |
152
+ | "Beautiful, responsive, mobile-friendly booking widget." | "Use when the shopper asks to book, reschedule or check availability for an in-store appointment." |
153
+
154
+ What belongs in a description, in this order:
155
+
156
+ 1. **The trigger** — the shopper situation or intent, in the words a shopper
157
+ would actually use ("unsure which size", "wants to compare", "asks to
158
+ book"). Start with `Use when …`.
159
+ 2. **The boundary** — when *not* to, if a sibling tool overlaps. One clause
160
+ is enough: "Use for in-store appointments; not for delivery scheduling."
161
+ 3. **What the assistant gets back** — if the app reports state or sends
162
+ messages, say so, because that changes whether calling it is useful:
163
+ "reports the size the shopper settles on back to you."
164
+
165
+ Keep it to one or two sentences. If a required prop is subtle, say what it
166
+ means here rather than trusting the schema alone ("`category` is the apparel
167
+ category, e.g. `outerwear`").
168
+
169
+ The same rule governs the **name**: name it after the job, not the widget.
170
+ `size_guide`, `gift_finder`, `book_appointment` read as intents; `size_modal`,
171
+ `quiz_ui`, `product_grid_v2` read as implementation details and get skipped.
172
+ Names also compete — if an upstream tool already does the shopper-facing job,
173
+ name yours for the distinct thing it does (`show_catalog_inline` alongside
174
+ `show_catalog`) so the assistant has a real choice rather than a coin flip.
175
+
176
+ ### Display modes
177
+
178
+ - `inline` — a bubble inside the chat transcript; persists with the message
179
+ log.
180
+ - `over-input` — floats above the chat input (like a question overlay);
181
+ cleared by the next user turn or an explicit close.
182
+ - `fullscreen` — takes over the full preview surface; persists until the
183
+ next widget-emitting tool call or an explicit close.
184
+
185
+ ## The app contract
186
+
187
+ `component.tsx` default-exports a React component. Its props are the
188
+ `inputSchema` fields the assistant filled, plus six GreatStore-injected
189
+ lifecycle props (always present):
190
+
191
+ | Prop | What it does |
192
+ |---|---|
193
+ | `onSendMessage(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?"). |
194
+ | `onUpdateModelContext(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 `onSendMessage` when the assistant should *know* state without a message appearing in the transcript. |
195
+ | `onShowLightbox({ 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). |
196
+ | `onGenerateStructuredContent(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 — no `window.GreatStore` needed. 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. |
197
+ | `onClose()` | Dismiss the host slot. `over-input` clears the overlay, `fullscreen` reverts the pane, `inline` is a no-op. |
198
+
199
+ Reach for `onUpdateModelContext` when the shopper changes something inside
200
+ the app (picks a size, configures a build, advances a quiz) and you want the
201
+ assistant to factor it into the *next* thing they ask — without spamming the
202
+ chat with a visible "I selected M" message. Use `onSendMessage` when you
203
+ actually want a turn to happen now.
204
+
205
+ Reach for `onShowLightbox` whenever your app shows imagery the shopper might
206
+ want to inspect closely — product photos, swatches, a size chart. A
207
+ thumbnail's `onClick` handler is the natural place to call it. Don't build
208
+ your own full-screen modal: an app is sandboxed inside its own bounds and
209
+ shadow root, so a self-rendered overlay can't cover the chat. The shared
210
+ lightbox escapes those bounds and themes itself from the store's CSS
211
+ variables.
212
+
213
+ ```tsx
214
+ import React from "react";
215
+
216
+ interface Props {
217
+ productName: string;
218
+ category?: string;
219
+ onSendMessage: (text: string) => void;
220
+ onUpdateModelContext: (context: string) => void;
221
+ onShowLightbox: (options: { src: string; originRect?: DOMRect }) => void;
222
+ onGenerateStructuredContent: <T = unknown>(
223
+ schema: object,
224
+ prompt: string,
225
+ fallback: T,
226
+ ) => Promise<T>;
227
+ onClose: () => void;
228
+ }
229
+
230
+ export default function SizeGuide({
231
+ productName,
232
+ onSendMessage,
233
+ onUpdateModelContext,
234
+ onShowLightbox,
235
+ }: Props) {
236
+ return (
237
+ <div
238
+ style={{
239
+ padding: "1em",
240
+ border: "1px solid var(--color-border-default)",
241
+ borderRadius: "var(--radius-lg)",
242
+ background: "var(--color-surface)",
243
+ color: "var(--color-foreground)",
244
+ fontFamily: "var(--font-primary)",
245
+ }}
246
+ >
247
+ {/* … sizes for {productName} … */}
248
+ <img
249
+ src={`/size-charts/${productName}.png`}
250
+ alt={`${productName} size chart`}
251
+ style={{ cursor: "zoom-in", width: "100%" }}
252
+ onClick={(e) =>
253
+ onShowLightbox({
254
+ src: `/size-charts/${productName}.png`,
255
+ originRect: e.currentTarget.getBoundingClientRect(),
256
+ })
257
+ }
258
+ />
259
+ <button
260
+ onClick={() =>
261
+ // Silent: the assistant now knows the pick for the shopper's
262
+ // next question, with nothing added to the transcript.
263
+ onUpdateModelContext(`Shopper selected size M of "${productName}".`)
264
+ }
265
+ >
266
+ Select size M
267
+ </button>
268
+ <button onClick={() => onSendMessage(`Size M of "${productName}" — is it in stock?`)}>
269
+ Ask about size M
270
+ </button>
271
+ </div>
272
+ );
273
+ }
274
+ ```
275
+
276
+ ## Design rules (non-negotiable)
277
+
278
+ Apps render inside arbitrary publisher pages *and* the GreatStore
279
+ storefront; you control neither the host's root font size nor its colors.
280
+
281
+ 1. **Size in `em`, never `rem`** — `rem` resolves against the host page's
282
+ root font size, which is arbitrary (`html { font-size: 8px }` breaks every
283
+ `rem` dimension). `em` stays self-consistent anywhere. Borders may stay
284
+ `px`.
285
+ 2. **Never hardcode colors, fonts, or radii** — read the brand CSS variables
286
+ GreatStore injects (`--color-primary`, `--color-surface`,
287
+ `--color-foreground`, `--color-border-default`, `--font-primary`,
288
+ `--radius-lg`, …) so the app restyles itself with the store's theme. The
289
+ scaffolded `AGENTS.md` has the full variable table.
290
+
291
+ ## Async apps (backend-backed data)
292
+
293
+ If an app must load data before it can render correctly, don't render a shell
294
+ and fetch in `useEffect` — set `"async": true` in the manifest and export an
295
+ **async** default. GreatStore shows its own loading state, awaits your
296
+ promise, and renders what it resolves to.
297
+
298
+ A thrown error is a **retry signal**: the assistant sees it and usually
299
+ re-calls the tool. So only throw when a *different* call could help:
300
+
301
+ 1. Validate the AI-passed props first and throw on bad input — the AI can
302
+ fix the args and retry. (Don't validate the API's *output* and throw: the
303
+ AI can't fix your backend, it'll just loop.)
304
+ 2. Throw on failures where retrying differently could succeed, and say what
305
+ to change (e.g. empty search → `"no results for X — try a broader keyword"`).
306
+ 3. For idempotent failures (500, timeout, missing record) render a graceful
307
+ fallback instead of throwing — re-running the same call changes nothing.
308
+
309
+ ```tsx
310
+ export default async function Results(props: Props) {
311
+ if (!props.query?.trim()) throw new Error("missing required prop: query");
312
+ const res = await fetch(`/api/search?q=${encodeURIComponent(props.query)}`);
313
+ if (res.ok) {
314
+ const { results } = await res.json();
315
+ if (results.length === 0)
316
+ throw new Error(`no results for "${props.query}" — try a broader keyword`);
317
+ return <ul>{/* render results */}</ul>;
318
+ }
319
+ return <p>Couldn't load results right now.</p>; // idempotent: don't throw
320
+ }
321
+ ```
322
+
323
+ ## When to build an app vs. the other facets
324
+
325
+ - Content for the **merchant's page** → `window.GreatStore.generateStructuredContent`
326
+ ([structured-content.md](structured-content.md)). Inside an app, use the
327
+ injected `onGenerateStructuredContent` prop instead — same idea, but
328
+ personalized to the shopper and available on every surface without the global.
329
+ - Letting the assistant **act on the page** → WebMCP page tools
330
+ ([embed-api.md](embed-api.md)).
331
+ - Rich, interactive UI **inside the conversation itself**, available on the
332
+ storefront and every embed without page changes → an app.
@@ -170,7 +170,8 @@ Events emitted:
170
170
  Generates JSON matching `schema` from `prompt`, grounded in the store's live
171
171
  catalog. Resolves to the generated data object itself. Rejects with `Error`
172
172
  on any failure (invalid input, decline, validation failure, rate limit,
173
- network). See [structured-content.md](structured-content.md) for the full
173
+ network); a decline sets `error.reason`. See
174
+ [structured-content.md](structured-content.md) for the full
174
175
  contract, schema support, caching, and error semantics.
175
176
 
176
177
  Accepts either a plain JSON Schema object or any object exposing a
@@ -217,9 +218,11 @@ await window.GreatStore.ready; // resolves once the fresh mount is done
217
218
  ## Page tools — WebMCP (`document.modelContext`)
218
219
 
219
220
  The recommended way to expose page capabilities to the assistant is the
220
- WebMCP standard. The GreatStore assistant discovers every tool registered on
221
- `document.modelContext`, re-reading the list on each conversational turn —
222
- so tools registered mid-session appear on the next message without a reload.
221
+ WebMCP standard. The GreatStore assistant uses every tool registered on
222
+ `document.modelContext` **once GreatStore is ready** (see `onGreatStoreReady`
223
+ below), re-reading the list on each conversational turn — so tools
224
+ registered mid-session appear on the next message without a reload. Tools
225
+ registered before GreatStore is ready are ignored.
223
226
 
224
227
  ### Availability
225
228
 
@@ -20,7 +20,7 @@ gs login # one-time browser sign-in (needs a human)
20
20
 
21
21
  Credentials persist across runs. Admin commands take `--store <slug>`
22
22
  directly, or read the nearest `.gsrc` (`{"store":"my-store"}`) — so they work
23
- from any repo, not just a scaffolded component project. Every read supports
23
+ from any repo, not just a scaffolded app project. Every read supports
24
24
  `--json` for machine-readable output.
25
25
 
26
26
  ## Read freely — always safe
@@ -32,7 +32,7 @@ decision:
32
32
  gs configure --store my-store --json # brand config
33
33
  gs connectors --store my-store --json # MCP connectors feeding the assistant
34
34
  gs connectors health --store my-store # live-probe them (reports tool counts)
35
- gs apps list --store my-store --json # deployed custom chat components
35
+ gs apps list --store my-store --json # deployed custom in-chat apps
36
36
  ```
37
37
 
38
38
  What each read is good for:
@@ -60,7 +60,7 @@ make: they're additive, easy to undo, and invisible to shoppers.
60
60
  widget on a new site/staging domain? Add that origin yourself instead of
61
61
  reporting "ask the merchant to allowlist it".
62
62
  - **`cspScriptHosts` / `cspConnectHosts`** — hosts the storefront accepts
63
- for scripts/connections. Add a host when a custom chat component
63
+ for scripts/connections. Add a host when an app
64
64
  legitimately needs a third-party SDK or API.
65
65
 
66
66
  **List flags replace the stored list — always read-merge-write.** Fetch the
@@ -127,5 +127,5 @@ gs connectors maker on|off
127
127
  gs connectors health [<name|id>] [--json]
128
128
 
129
129
  gs apps <init|build|list|pull|push|publish|unpublish|delete>
130
- see chat-components.md for the workflow
130
+ see apps.md for the workflow
131
131
  ```
@@ -200,17 +200,29 @@ cold cache.
200
200
  ## Errors and how to handle them
201
201
 
202
202
  The promise rejects with `new Error(message)`. The message is
203
- developer-facing — never render it to shoppers. Cases:
203
+ developer-facing — never render it to shoppers. Server-side failures also
204
+ carry `error.code`, and a decline carries `error.reason`. Cases:
204
205
 
205
206
  | Case | Message you'll see | Retry? |
206
207
  |---|---|---|
207
208
  | Bad input (empty prompt, non-object schema) | thrown immediately by the SDK | Fix the call |
208
209
  | Invalid schema shape | `Invalid schema: …` | Fix the schema |
209
- | AI declined the request | `The assistant declined to generate content for this request.` | No — permanent for that prompt/schema. Rework the prompt. |
210
+ | AI declined the request | `The assistant declined to generate content for this request.` with `error.reason` (below) | No — permanent for that prompt/schema. Rework the prompt. |
210
211
  | Output couldn't satisfy the schema | `Failed to produce valid structured content` | No — usually `required`/constraints demand data the catalog lacks. Loosen the schema. |
211
212
  | Rate limit (~20/min per visitor) | rate-limit message | Later — and consolidate calls |
212
213
  | Network / server | varies | Next page load |
213
214
 
215
+ A decline is only ever one of these `error.reason` values — anything else
216
+ (vague wording, missing data for optional fields, marketing copy) is served:
217
+
218
+ | `reason` | Declined because the request… |
219
+ |---|---|
220
+ | `off_topic` | has nothing to do with the store or shopping there (homework, code, news, another business's products) |
221
+ | `harmful` | asks for unsafe, hateful, sexual, or illegal content, or advice that could hurt someone |
222
+ | `deceptive` | asks for fake reviews, invented discounts or scarcity, claims the catalog contradicts, or impersonating/disparaging a named brand or person |
223
+ | `system_probe` | asks about or tries to override the assistant's own instructions or tools |
224
+ | `no_data` | depends on specific store facts and research found nothing to fill the required fields — check `gs connectors`, or make those fields optional |
225
+
214
226
  The uniform shopper-facing strategy: render into a hidden-by-default
215
227
  container, reveal on success, leave hidden (or show your static fallback) on
216
228
  any rejection. One `try/catch`, no case analysis needed unless you're
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@greatstore/cli",
3
- "version": "0.1.12",
3
+ "version": "0.1.15",
4
4
  "description": "CLI for administering GreatStore stores and authoring custom components.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -1,224 +0,0 @@
1
- # Custom chat components — authoring with the `gs` CLI
2
-
3
- Remote components are React components the assistant renders **inside the
4
- conversation** — product configurators, quizzes, size guides, booking forms,
5
- anything richer than text. Each component is an AI-callable tool: the
6
- manifest's `description` tells the assistant *when* to show it, its
7
- `inputSchema` declares the props the assistant fills in, and a `displayMode`
8
- picks where it appears.
9
-
10
- Authoring requires store-owner access (`gs login` signs in with the store
11
- owner's account).
12
-
13
- ## Workflow
14
-
15
- ```
16
- npm install -g @greatstore/cli # or npx @greatstore/cli <command>
17
- gs login # browser sign-in
18
- gs apps init --store my-store # scaffold a project root
19
- cd <project> && npm install
20
- gs apps init size_guide # scaffold components/size_guide/
21
- # … edit components/size_guide/{component.tsx,manifest.json} …
22
- gs apps build # bundle every component
23
- gs apps push # upload changed components as drafts
24
- gs apps publish size_guide # promote to live
25
- ```
26
-
27
- `gs apps list` shows what's deployed (with dashboard links); `gs apps pull`
28
- round-trips remote components back to disk. `gs apps push` hashes components
29
- and only uploads what changed. (The subcommands also work at the top level —
30
- `gs push` == `gs apps push`.)
31
-
32
- The scaffold writes an `AGENTS.md` into the project (with `CLAUDE.md` /
33
- `GEMINI.md` symlinked) containing the complete design rules and brand
34
- variable table — your coding agent picks it up automatically when working in
35
- the project. `https://admin.greatstore.ai/mcp` serves the same CLI docs to
36
- agents over MCP (see [agents-and-mcp.md](agents-and-mcp.md)).
37
-
38
- ## `manifest.json`
39
-
40
- ```json
41
- {
42
- "name": "size_guide",
43
- "displayName": "Size guide",
44
- "description": "Interactive size guide. Show when the shopper asks about sizing or fit for apparel.",
45
- "displayMode": "inline",
46
- "inputSchema": {
47
- "type": "object",
48
- "properties": {
49
- "productName": { "type": "string" },
50
- "category": { "type": "string" }
51
- },
52
- "required": ["productName"]
53
- }
54
- }
55
- ```
56
-
57
- | Field | Meaning |
58
- |---|---|
59
- | `name` | Tool name, snake_case (`^[a-z][a-z0-9_]*$`), matches the folder under `components/`. |
60
- | `displayName` | Friendly label shown in chat UI. |
61
- | `description` | **Load-bearing** — how the assistant decides when to render the component. Say what it shows *and* when to use it, like any good tool description. |
62
- | `displayMode` | Where it renders — see below. |
63
- | `inputSchema` | JSON Schema for the props the assistant fills. Keep it tight; required fields the AI can't infer cause bad calls. |
64
- | `async` | Set `true` for backend-backed components (see Async below). |
65
-
66
- ### Display modes
67
-
68
- - `inline` — a bubble inside the chat transcript; persists with the message
69
- log.
70
- - `over-input` — floats above the chat input (like a question overlay);
71
- cleared by the next user turn or an explicit close.
72
- - `fullscreen` — takes over the full preview surface; persists until the
73
- next widget-emitting tool call or an explicit close.
74
-
75
- ## The component contract
76
-
77
- `component.tsx` default-exports a React component. Its props are the
78
- `inputSchema` fields the assistant filled, plus six GreatStore-injected
79
- lifecycle props (always present):
80
-
81
- | Prop | What it does |
82
- |---|---|
83
- | `onSendMessage(text)` | Send text into the chat as if the shopper typed it — lets the component drive the conversation ("Selected size M, what's the return policy?"). |
84
- | `onCallTool(name, args)` | Chain into another remote-component tool by name. |
85
- | `onUpdateModelContext(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 `onSendMessage` when the assistant should *know* state without a message appearing in the transcript. |
86
- | `onShowLightbox({ src, originRect? })` | Expand an image in the chat's shared full-screen lightbox — an on-brand zoom overlay you can't render yourself (your component 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). |
87
- | `onGenerateStructuredContent(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 — no `window.GreatStore` needed. Best for async components that build their render from a generated payload. `fallback` is **required**: a schema-shaped object you provide that the component preview renders (no live store there), validated against the schema — a mismatch throws. |
88
- | `onClose()` | Dismiss the host slot. `over-input` clears the overlay, `fullscreen` reverts the pane, `inline` is a no-op. |
89
-
90
- Reach for `onUpdateModelContext` when the shopper changes something inside
91
- the component (picks a size, configures a build, advances a quiz) and you
92
- want the assistant to factor it into the *next* thing they ask — without
93
- spamming the chat with a visible "I selected M" message. Use `onSendMessage`
94
- when you actually want a turn to happen now.
95
-
96
- Reach for `onShowLightbox` whenever your component shows imagery the shopper
97
- might want to inspect closely — product photos, swatches, a size chart. A
98
- thumbnail's `onClick` handler is the natural place to call it. Don't build
99
- your own full-screen modal: a remote component is sandboxed inside its own
100
- bounds and shadow root, so a self-rendered overlay can't cover the chat. The
101
- shared lightbox escapes those bounds and themes itself from the store's CSS
102
- variables.
103
-
104
- ```tsx
105
- import React from "react";
106
-
107
- interface Props {
108
- productName: string;
109
- category?: string;
110
- onSendMessage: (text: string) => void;
111
- onCallTool: (name: string, args: Record<string, unknown>) => void;
112
- onUpdateModelContext: (context: string) => void;
113
- onShowLightbox: (options: { src: string; originRect?: DOMRect }) => void;
114
- onGenerateStructuredContent: <T = unknown>(
115
- schema: object,
116
- prompt: string,
117
- fallback: T,
118
- ) => Promise<T>;
119
- onClose: () => void;
120
- }
121
-
122
- export default function SizeGuide({
123
- productName,
124
- onSendMessage,
125
- onUpdateModelContext,
126
- onShowLightbox,
127
- }: Props) {
128
- return (
129
- <div
130
- style={{
131
- padding: "1em",
132
- border: "1px solid var(--color-border-default)",
133
- borderRadius: "var(--radius-lg)",
134
- background: "var(--color-surface)",
135
- color: "var(--color-foreground)",
136
- fontFamily: "var(--font-primary)",
137
- }}
138
- >
139
- {/* … sizes for {productName} … */}
140
- <img
141
- src={`/size-charts/${productName}.png`}
142
- alt={`${productName} size chart`}
143
- style={{ cursor: "zoom-in", width: "100%" }}
144
- onClick={(e) =>
145
- onShowLightbox({
146
- src: `/size-charts/${productName}.png`,
147
- originRect: e.currentTarget.getBoundingClientRect(),
148
- })
149
- }
150
- />
151
- <button
152
- onClick={() =>
153
- // Silent: the assistant now knows the pick for the shopper's
154
- // next question, with nothing added to the transcript.
155
- onUpdateModelContext(`Shopper selected size M of "${productName}".`)
156
- }
157
- >
158
- Select size M
159
- </button>
160
- <button onClick={() => onSendMessage(`Size M of "${productName}" — is it in stock?`)}>
161
- Ask about size M
162
- </button>
163
- </div>
164
- );
165
- }
166
- ```
167
-
168
- ## Design rules (non-negotiable)
169
-
170
- Components render inside arbitrary publisher pages *and* the GreatStore
171
- storefront; you control neither the host's root font size nor its colors.
172
-
173
- 1. **Size in `em`, never `rem`** — `rem` resolves against the host page's
174
- root font size, which is arbitrary (`html { font-size: 8px }` breaks every
175
- `rem` dimension). `em` stays self-consistent anywhere. Borders may stay
176
- `px`.
177
- 2. **Never hardcode colors, fonts, or radii** — read the brand CSS variables
178
- GreatStore injects (`--color-primary`, `--color-surface`,
179
- `--color-foreground`, `--color-border-default`, `--font-primary`,
180
- `--radius-lg`, …) so the component restyles itself with the store's
181
- theme. The scaffolded `AGENTS.md` has the full variable table.
182
-
183
- ## Async components (backend-backed data)
184
-
185
- If a component must load data before it can render correctly, don't render a
186
- shell and fetch in `useEffect` — set `"async": true` in the manifest and
187
- export an **async** default. GreatStore shows its own loading state, awaits
188
- your promise, and renders what it resolves to.
189
-
190
- A thrown error is a **retry signal**: the assistant sees it and usually
191
- re-calls the tool. So only throw when a *different* call could help:
192
-
193
- 1. Validate the AI-passed props first and throw on bad input — the AI can
194
- fix the args and retry. (Don't validate the API's *output* and throw: the
195
- AI can't fix your backend, it'll just loop.)
196
- 2. Throw on failures where retrying differently could succeed, and say what
197
- to change (e.g. empty search → `"no results for X — try a broader keyword"`).
198
- 3. For idempotent failures (500, timeout, missing record) render a graceful
199
- fallback instead of throwing — re-running the same call changes nothing.
200
-
201
- ```tsx
202
- export default async function Results(props: Props) {
203
- if (!props.query?.trim()) throw new Error("missing required prop: query");
204
- const res = await fetch(`/api/search?q=${encodeURIComponent(props.query)}`);
205
- if (res.ok) {
206
- const { results } = await res.json();
207
- if (results.length === 0)
208
- throw new Error(`no results for "${props.query}" — try a broader keyword`);
209
- return <ul>{/* render results */}</ul>;
210
- }
211
- return <p>Couldn't load results right now.</p>; // idempotent: don't throw
212
- }
213
- ```
214
-
215
- ## When to build a component vs. the other facets
216
-
217
- - Content for the **merchant's page** → `window.GreatStore.generateStructuredContent`
218
- ([structured-content.md](structured-content.md)). Inside a chat component, use
219
- the injected `onGenerateStructuredContent` prop instead — same idea, but
220
- personalized to the shopper and available on every surface without the global.
221
- - Letting the assistant **act on the page** → WebMCP page tools
222
- ([embed-api.md](embed-api.md)).
223
- - Rich, interactive UI **inside the conversation itself**, available on the
224
- storefront and every embed without page changes → a chat component.