@greatstore/cli 0.2.13 → 0.2.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.
@@ -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 apps with the gs CLI, administering the store from the CLI (npx greatstore configure, npx greatstore 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.
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 (npx greatstore configure, npx greatstore 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, and store administration.
4
4
  ---
5
5
 
6
6
  # Building with GreatStore
@@ -24,13 +24,13 @@ constraints) that the references spell out.
24
24
  |---|---|---|
25
25
  | Install the widget; control the panel; readiness, events, troubleshooting | `window.GreatStore` SDK | [references/embed-api.md](references/embed-api.md) |
26
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
- | Copy-paste on-page experiences | recipes built on the SDK | the [Recipes](#recipes) table below |
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/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
- | Let the assistant **act on the page** (cart, navigation, filters) | WebMCP: `document.modelContext.registerTool(...)` | [references/embed-api.md](references/embed-api.md) |
27
+ | Contextual **conversation entry points** anywhere on the page | `sendMessage(text)`, `open()`, `?gs_chat=open` | [references/embed-api/send-message.md](references/embed-api/send-message.md) |
28
+ | Feed the assistant **invisible page/app state** (current product, cart, selected variant) | `updateModelContext(text)`; an app's `$.updateModelContext` | [references/embed-api/update-model-context.md](references/embed-api/update-model-context.md), [references/apps.md](references/apps.md) |
29
+ | **Fetch store data into your own UI** from a connector's read-only tool, or open a full-screen app from a button | `callTool(name, args)`; an app's `$.callTool` | [references/embed-api/call-tool.md](references/embed-api/call-tool.md) |
30
+ | Let the assistant **act on the page** (cart, navigation, filters) | WebMCP: `document.modelContext.registerTool(...)` | [references/embed-api/webmcp.md](references/embed-api/webmcp.md) |
31
31
  | Custom **interactive UI inside the chat** (configurators, quizzes, size guides, booking forms) | apps shipped with the `gs` CLI | [references/apps.md](references/apps.md) |
32
32
  | Run one of those apps **on your own page**, outside the conversation | `surfaces: ["embed"]` + the container snippet | [references/apps.md](references/apps.md) |
33
- | 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
+ | Expand an app's image in an **on-brand full-screen lightbox** | an app's `$.showLightbox({ src, originRect })` | [references/apps.md](references/apps.md) |
34
34
  | **Re-engage shoppers** with browser notifications | merchant-hosted `gs.js` + `enableNotifications()` | [references/push-notifications.md](references/push-notifications.md) |
35
35
  | 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) |
36
36
  | **Administer the store** — read config/connectors to ground decisions; self-serve origin allowlists and CSP hosts | `npx greatstore configure`, `npx greatstore connectors` | [references/store-admin.md](references/store-admin.md) |
@@ -51,26 +51,6 @@ constraints) that the references spell out.
51
51
  - Every SDK call is safe immediately after the script tag — pre-mount calls
52
52
  queue and replay in order, and the SDK pre-warms itself in the background.
53
53
 
54
- ## Recipes
55
-
56
- Complete, framework-free implementations, one per file. Shared conventions:
57
- containers start `hidden` and reveal only on success (a failed generation
58
- changes nothing); generated strings render via `textContent`, never
59
- `innerHTML`; every recipe guards on `window.GreatStore`; prompts stay
60
- deterministic per page so repeat renders hit the cache.
61
- Inline real product/page data into prompts where the platform exposes it.
62
-
63
- | Recipe | What it builds | Use it for |
64
- |---|---|---|
65
- | [GreatStore launchers](recipes/launchers.md) | Horizontally scrollable AI-generated chips — engaging first-person questions about the current page; tap to ask the assistant. | Instant engagement on any page type — product, collection, blog, home. Simple yet effective; start here. |
66
- | [Ask-about-this entry points](recipes/ask-about-this.md) | One-line `sendMessage` buttons wired to existing page elements. | Size guides, shipping rows, out-of-stock badges — anywhere a shopper hesitates. |
67
- | [Product FAQ accordion](recipes/product-faq.md) | Grounded pre-purchase Q&A with an "ask us" handoff into chat. | Product pages; answering objections before they cost the sale. |
68
- | [Comparison table](recipes/comparison-table.md) | AI-picked representative products compared on category-relevant criteria. | Collection pages where shoppers weigh options. |
69
- | [Complete the look](recipes/complete-the-look.md) | Catalog-grounded cross-sell strip with a reason per pick. | Product pages; raising order value with genuine pairings. |
70
- | [Campaign hero](recipes/campaign-hero.md) | Seasonal homepage hero copy, cache-keyed to the ISO week. | Fresh homepage/campaign copy without manual rewrites. |
71
- | [Gift finder funnel](recipes/gift-finder-funnel.md) | Quiz teaser → chat handoff → page-tool navigation; the full funnel. | Gifting seasons, guided discovery, homepage engagement. |
72
- | [Page-action suite](recipes/page-action-suite.md) | WebMCP cart/page tools every conversation can use. | Any site where the assistant should act, not just advise. |
73
-
74
54
  ## How the facets combine
75
55
 
76
56
  The strongest pattern is the **teaser → conversation → action** funnel:
@@ -79,5 +59,4 @@ design; each option's click handler calls `sendMessage` with the shopper's
79
59
  choice, dropping them into a conversation with momentum; WebMCP page tools
80
60
  and apps let that conversation actually do things — add to
81
61
  cart, configure a product, book a slot — so it ends in a conversion, not a
82
- copy-paste. The [gift finder funnel](recipes/gift-finder-funnel.md)
83
- recipe is this funnel end to end.
62
+ copy-paste.
@@ -22,14 +22,16 @@ works there too, with these differences:
22
22
  theme: the same CSS variables (`--color-surface`, `--color-primary`,
23
23
  `--font-primary`, …) are set from the host's look, so an app that reads
24
24
  them instead of hardcoding colors fits in unchanged.
25
- - `onSendMessage` posts a message as the shopper in the host's chat, and
26
- `onUpdateModelContext` updates what the host's assistant knows.
25
+ - `$.sendMessage` posts a message as the shopper in the host's chat, and
26
+ `$.updateModelContext` updates what the host's assistant knows.
27
27
  - `over-input` apps render in the conversation like `inline` ones;
28
- `onClose` hides them.
28
+ `$.close` hides them.
29
29
  - `fullscreen` apps show as a card the shopper can expand to the host's
30
- full screen; `onClose` brings them back to the card.
30
+ full screen; `$.close` brings them back to the card.
31
31
  - Links and `window.open` open through the host.
32
- - `onGenerateStructuredContent` works there too, on the store's credits.
32
+ - `$.callTool` always rejects there: an app can't fetch tool data or open
33
+ another app inside another assistant, so give it a path that works without.
34
+ - `$.generateStructuredContent` works there too, on the store's credits.
33
35
  It isn't personalized: the store doesn't know who the shopper is inside
34
36
  another assistant.
35
37
  - An async app runs after the assistant's tool call has returned, so a thrown
@@ -30,7 +30,7 @@ Shopper Assistant Your app
30
30
  │ │ your inputSchema asked │
31
31
  │ │ for (productName, …) │
32
32
  │ ├────────────────────────>│
33
- │ │ ├──┐ onGenerateStructured-
33
+ │ │ ├──┐ $.generateStructured-
34
34
  │ │ │ │ Content(): its own
35
35
  │ │ │ │ catalog-grounded
36
36
  │ │ │<─┘ generation, if wanted
@@ -44,10 +44,10 @@ Shopper Assistant Your app
44
44
  │ picks size M │ │
45
45
  ├─────────────────────┼────────────────────────>│
46
46
  │ │ │
47
- │ │ onUpdateModelContext() │ silent: the assistant
47
+ │ │ $.updateModelContext() │ silent: the assistant
48
48
  │ │<────────────────────────┤ now knows the pick
49
49
  │ │ │
50
- │ │ onSendMessage() │ visible: a shopper turn
50
+ │ │ $.sendMessage() │ visible: a shopper turn
51
51
  │ │<────────────────────────┤ happens right now
52
52
  │ │ │
53
53
  │ │ calls the app again │ same app, new props —
@@ -62,12 +62,12 @@ Four consequences worth designing around:
62
62
  will actually pick](#writing-a-name-and-description-the-assistant-will-actually-pick)
63
63
  is about that choice.
64
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
65
+ shopper is doing (`$.updateModelContext`), can speak for the shopper
66
+ (`$.sendMessage`), and the assistant can call the app again with revised
67
67
  props. Keep the render a function of the props it was given, so a re-call
68
68
  is a re-render rather than a reset.
69
69
  3. **The app can run its own generation, not just receive props.**
70
- `onGenerateStructuredContent(schema, prompt, fallback)` gives it a
70
+ `$.generateStructuredContent(schema, prompt, fallback)` gives it a
71
71
  catalog-grounded, shopper-personalized generation of its own, returned as
72
72
  an object matching your schema — recommended picks, a personalized
73
73
  summary, a reason per option — rendered in the merchant's own markup. Use
@@ -181,6 +181,8 @@ name yours for the distinct thing it does (`show_catalog_inline` alongside
181
181
  cleared by the next user turn or an explicit close.
182
182
  - `fullscreen` — takes over the full preview surface; persists until the
183
183
  next widget-emitting tool call or an explicit close.
184
+ The page can also open one itself with `window.GreatStore.callTool(name,
185
+ props)` (see [embed-api/call-tool.md](embed-api/call-tool.md)).
184
186
 
185
187
  **Safe-zone for `fullscreen` apps.** The floating chat widget sits over the
186
188
  bottom of a fullscreen app, covering whatever is rendered there. Leave
@@ -239,33 +241,36 @@ What to expect:
239
241
  - If the app can't run — not published, not embeddable, or the store is
240
242
  unavailable — the container is emptied and takes no space. The page looks as
241
243
  though it was never there.
242
- - `onClose()` takes the app off the page.
244
+ - `$.close()` takes the app off the page.
243
245
  - The page's domain must be in the store's allowed domains, exactly as for
244
246
  chat.
245
247
 
246
248
  ## The app contract
247
249
 
248
250
  `component.tsx` default-exports a React component. Its props are the
249
- `inputSchema` fields the assistant filled, plus seven GreatStore-injected
250
- lifecycle props (always present):
251
+ `inputSchema` fields the assistant filled, plus one GreatStore prop, `$`
252
+ (always present). Destructure what you need from `$` at the top of the
253
+ component. Never declare a `$` field in `inputSchema` — the build refuses it.
251
254
 
252
- | Prop | What it does |
255
+ | `$` member | What it does |
253
256
  |---|---|
254
- | `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?"). |
255
- | `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. |
256
- | `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). |
257
- | `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. |
258
- | `onClose()` | Dismiss the host slot. `over-input` clears the overlay, `fullscreen` reverts the pane, `inline` is a no-op. |
259
- | `useVoiceCall()` | A hook — call it at the top of your component like any other — returning `{ status, available, start, end }` for a voice call with the store's assistant. `start()` starts the call without opening the chat — it runs in the collapsed chat bar (which stays hidden if the store hides the chat until opened), and the chat opens only when the assistant shows an inline app (call it from a click; it rejects when the store has no voice), `end()` hangs up. `available` says whether the store has voice. `status` is `null` until a call starts, then `started`, `connecting`, `connected`, `listening` / `speaking` / `working` as the conversation goes, `disconnected` while the network drops (the call recovers on its own), and `ended`. Your app re-renders on every change. |
260
- | `Image` | A drop-in for `<img>` — render `<Image src=… alt=… />` and the image is served at the right size for the store. Takes the same props as `<img>`. |
261
-
262
- Reach for `onUpdateModelContext` when the shopper changes something inside
257
+ | `$.sendMessage(text)` | Send text into the chat as if the shopper typed it — lets the app drive the conversation ("Selected size M, what's the return policy?"). |
258
+ | `$.updateModelContext(context)` | Inject **invisible** background context for the model — the variant the shopper selected, the options they configured, the step they're on. Replaces the prior value (never appends); pass `""` to clear. Read on the next chat turn. Use this instead of `$.sendMessage` when the assistant should *know* state without a message appearing in the transcript. |
259
+ | `$.callTool(name, args?)` | The page's `window.GreatStore.callTool`, for the app: run a read-only connector tool and get its result, or open a full-screen app by name — see [embed-api/call-tool.md](embed-api/call-tool.md) for what it reaches, what comes back, and how to look up tools. Never touches the conversation. In the app preview, tools run for real and naming a full-screen app only logs what would open. Inside other AI assistants (ChatGPT, …) it always rejects — handle the rejection. |
260
+ | `$.showLightbox({ src, originRect? })` | Expand an image in the chat's shared full-screen lightbox — an on-brand zoom overlay you can't render yourself (your app is boxed inside its own bounds and shadow root). Pass the image `src`; for a smooth zoom, also pass the clicked element's `getBoundingClientRect()` as `originRect` (omit it and the image grows from the viewport centre). |
261
+ | `$.generateStructuredContent(schema, prompt, fallback)` | Ask the store's assistant for content matching a JSON Schema (or Zod schema) and get back the generated object. Personalized to the shopper. Works the same in the conversation on the storefront and every embed. Best for async apps that build their render from a generated payload. `fallback` is **required**: a schema-shaped object you provide that the app preview renders (no live store there), validated against the schema — a mismatch throws. |
262
+ | `$.close()` | Dismiss the host slot. `over-input` clears the overlay, `fullscreen` reverts the pane, `inline` is a no-op. |
263
+ | `$.useVoiceCall()` | A hook — call it at the top of your component like any other — returning `{ status, available, start, end }` for a voice call with the store's assistant. `start()` starts the call without opening the chat — it runs in the collapsed chat bar (which stays hidden if the store hides the chat until opened), and the chat opens only when the assistant shows an inline app (call it from a click; it rejects when the store has no voice), `end()` hangs up. `available` says whether the store has voice. `status` is `null` until a call starts, then `started`, `connecting`, `connected`, `listening` / `speaking` / `working` as the conversation goes, `disconnected` while the network drops (the call recovers on its own), and `ended`. Your app re-renders on every change. |
264
+ | `$.Image` | A drop-in for `<img>` — render `<Image src=… alt=… />` and the image is served at the right size for the store. Takes the same props as `<img>`. |
265
+ | `$.store` | `{ slug }` — the store the app is running in. |
266
+
267
+ Reach for `$.updateModelContext` when the shopper changes something inside
263
268
  the app (picks a size, configures a build, advances a quiz) and you want the
264
269
  assistant to factor it into the *next* thing they ask — without spamming the
265
- chat with a visible "I selected M" message. Use `onSendMessage` when you
270
+ chat with a visible "I selected M" message. Use `$.sendMessage` when you
266
271
  actually want a turn to happen now.
267
272
 
268
- Reach for `onShowLightbox` whenever your app shows imagery the shopper might
273
+ Reach for `$.showLightbox` whenever your app shows imagery the shopper might
269
274
  want to inspect closely — product photos, swatches, a size chart. A
270
275
  thumbnail's `onClick` handler is the natural place to call it. Don't build
271
276
  your own full-screen modal: an app is sandboxed inside its own bounds and
@@ -279,25 +284,16 @@ import React from "react";
279
284
  interface Props {
280
285
  productName: string;
281
286
  category?: string;
282
- onSendMessage: (text: string) => void;
283
- onUpdateModelContext: (context: string) => void;
284
- onShowLightbox: (options: { src: string; originRect?: DOMRect }) => void;
285
- onGenerateStructuredContent: <T = unknown>(
286
- schema: object,
287
- prompt: string,
288
- fallback: T,
289
- ) => Promise<T>;
290
- onClose: () => void;
291
- Image: React.ElementType<React.ComponentProps<"img">>;
287
+ $: {
288
+ sendMessage: (text: string) => void;
289
+ updateModelContext: (context: string) => void;
290
+ showLightbox: (options: { src: string; originRect?: DOMRect }) => void;
291
+ Image: React.ElementType<React.ComponentProps<"img">>;
292
+ };
292
293
  }
293
294
 
294
- export default function SizeGuide({
295
- productName,
296
- onSendMessage,
297
- onUpdateModelContext,
298
- onShowLightbox,
299
- Image,
300
- }: Props) {
295
+ export default function SizeGuide({ productName, $ }: Props) {
296
+ const { sendMessage, updateModelContext, showLightbox, Image } = $;
301
297
  return (
302
298
  <div
303
299
  style={{
@@ -315,7 +311,7 @@ export default function SizeGuide({
315
311
  alt={`${productName} size chart`}
316
312
  style={{ cursor: "zoom-in", width: "100%" }}
317
313
  onClick={(e) =>
318
- onShowLightbox({
314
+ showLightbox({
319
315
  src: `/size-charts/${productName}.png`,
320
316
  originRect: e.currentTarget.getBoundingClientRect(),
321
317
  })
@@ -325,12 +321,12 @@ export default function SizeGuide({
325
321
  onClick={() =>
326
322
  // Silent: the assistant now knows the pick for the shopper's
327
323
  // next question, with nothing added to the transcript.
328
- onUpdateModelContext(`Shopper selected size M of "${productName}".`)
324
+ updateModelContext(`Shopper selected size M of "${productName}".`)
329
325
  }
330
326
  >
331
327
  Select size M
332
328
  </button>
333
- <button onClick={() => onSendMessage(`Size M of "${productName}" — is it in stock?`)}>
329
+ <button onClick={() => sendMessage(`Size M of "${productName}" — is it in stock?`)}>
334
330
  Ask about size M
335
331
  </button>
336
332
  </div>
@@ -388,10 +384,10 @@ export default async function Results(props: Props) {
388
384
  ## When to build an app vs. the other facets
389
385
 
390
386
  - Content for the **merchant's page** → `window.GreatStore.generateStructuredContent`
391
- ([structured-content.md](structured-content.md)). Inside an app, use the
392
- injected `onGenerateStructuredContent` prop instead — same idea, but
393
- personalized to the shopper and available on every surface without the global.
387
+ ([structured-content.md](structured-content.md)). Inside an app, use
388
+ `$.generateStructuredContent` instead — same idea, but personalized to the
389
+ shopper and available on every surface without the global.
394
390
  - Letting the assistant **act on the page** → WebMCP page tools
395
- ([embed-api.md](embed-api.md)).
391
+ ([embed-api/webmcp.md](embed-api/webmcp.md)).
396
392
  - Rich, interactive UI **inside the conversation itself**, available on the
397
393
  storefront and every embed without page changes → an app.
@@ -0,0 +1,57 @@
1
+ # `callTool(name: string, args?: object): Promise<object | undefined>`
2
+
3
+ The page's own way to reach two things by name, without the shopper asking
4
+ and without touching the conversation (nothing is added to the chat and the
5
+ assistant never learns the call happened).
6
+
7
+ **A full-screen app.** Name one of the store's `fullscreen` apps and pass the
8
+ props its `inputSchema` declares. The app shows straight away, whether or
9
+ not the chat is open (an open chat collapses out of its way), and stays until
10
+ the shopper closes it or the page opens another; the call resolves with
11
+ `undefined` once it is handed over. No `open()` is needed. The app is the
12
+ page's, not the conversation's — a reload drops it. `inline` and
13
+ `over-input` apps can't be opened this way.
14
+
15
+ ```js
16
+ window.GreatStore.callTool("show_size_guide", { category: "boots" });
17
+ ```
18
+
19
+ **A read-only connector tool.** Name any read-only tool from the store's
20
+ connectors (Maker MCP or the merchant's own MCP servers) and it resolves
21
+ with the tool's MCP `tools/call` result exactly as the server returned it:
22
+ `content`, plus `structuredContent` when the tool sends one. Use it to fill
23
+ the page's own UI with the same data the assistant sees.
24
+
25
+ ```js
26
+ const result = await window.GreatStore.callTool("search_catalog", {
27
+ query: "waterproof boots",
28
+ });
29
+ const products = result.structuredContent?.products ?? [];
30
+ ```
31
+
32
+ The shape of `args` and of the result is the connector's own, so look it up
33
+ rather than guessing a tool name or an argument:
34
+
35
+ ```
36
+ npx greatstore connectors --store my-store # the store's connectors (Maker MCP is "maker")
37
+ npx greatstore connectors tools maker --store my-store # every tool: group, access, description, inputs
38
+ npx greatstore connectors tools maker search_catalog --store my-store # one tool in full
39
+ ```
40
+
41
+ `connectors tools` says for each tool whether `callTool` reaches it, and why
42
+ not when it doesn't. Trust that line over your own reading of the tool. It
43
+ also spells out every input: type, whether it's required, allowed values,
44
+ limits and description, nested fields included. Add `--json` for the raw input
45
+ schema. In short, only read-only tools the assistant itself can call are
46
+ reachable. A tool that changes state (cart, checkout) is refused, and so are
47
+ WebMCP page tools (the page already has those). When an app and a tool share
48
+ a name, the app wins. Before writing code against the
49
+ result, call the tool once from the browser console and read what comes back:
50
+ the result's shape is the connector's too, and the listing doesn't describe
51
+ it.
52
+
53
+ It rejects with an `Error` when the name is neither, when an app isn't
54
+ full-screen or the args don't match its schema, when the tool is not
55
+ read-only, when the tool answers with an error (the message is the tool's
56
+ own text), or when the server can't be reached. Loads the chat first if it
57
+ isn't up yet.
@@ -0,0 +1,13 @@
1
+ # `enableNotifications(): Promise<{ ok: boolean }>`
2
+
3
+ Opts this browser into Web Push notifications from the store. Requirements:
4
+
5
+ - Must be called from a user gesture (e.g. a click handler).
6
+ - The site must host GreatStore's `gs.js` service-worker file. By default the
7
+ SDK looks for it at `/gs.js`; if it's hosted elsewhere, point to it via an
8
+ attribute on the embed script tag:
9
+ `<script src="…/embed.js" data-push-sw-path="/path/to/gs.js"></script>`.
10
+
11
+ Resolves `{ ok: true }` on success and `{ ok: false }` on any failure
12
+ (unsupported browser, no service worker hosted, permission denied). It never
13
+ rejects.
@@ -0,0 +1,13 @@
1
+ # `on(event: string, handler: (...args) => void): () => void`
2
+
3
+ Subscribe to SDK events. Returns an unsubscribe function. Listeners attached
4
+ before mount are queued and wired up at mount. Handler exceptions are caught
5
+ and reported — they won't break the chat.
6
+
7
+ Events emitted:
8
+
9
+ | Event | Fired when |
10
+ |---|---|
11
+ | `"open"` | Panel transitions closed → open (including via `sendMessage` or the shopper's own click). |
12
+ | `"close"` | Panel transitions open → closed. |
13
+ | `"voicestatus"` | A voice call's status changes; the handler receives the status. See [voice-call.md](voice-call.md). |
@@ -0,0 +1,15 @@
1
+ # `generateStructuredContent(schema: object, prompt: string): Promise<unknown>`
2
+
3
+ Generates JSON matching `schema` from `prompt`, grounded in the store's live
4
+ catalog. Resolves to the generated data object itself. Rejects with `Error`
5
+ on any failure (invalid input, decline, validation failure, rate limit,
6
+ network); a decline sets `error.reason`. See
7
+ [structured-content.md](../structured-content.md) for the full
8
+ contract, schema support, caching, and error semantics.
9
+
10
+ Accepts either a plain JSON Schema object or any object exposing a
11
+ `.toJSONSchema()` method (e.g. Zod schemas) — the conversion is called for
12
+ you.
13
+
14
+ Throws synchronously (rejects) if `prompt` is not a non-empty string or
15
+ `schema` is not an object.
@@ -0,0 +1,33 @@
1
+ # Panel: `load` / `open` / `close` / `toggle` / `destroy`
2
+
3
+ ## `load(): void`
4
+
5
+ Pre-warms the chat bundle and identity in the background without opening the
6
+ panel. Called automatically when `embed.js` runs, so you rarely need it.
7
+ Idempotent.
8
+
9
+ ## `open(): void` / `close(): void` / `toggle(): void`
10
+
11
+ Open, close, or toggle the chat. It is a drawer rising from the bottom of
12
+ the screen — a bounded, floating card on desktop, full-height under 768px
13
+ viewport width. All three queue if called before mount.
14
+
15
+ ## `destroy(): void`
16
+
17
+ Fully tears down a mounted panel: unmounts the chat UI, closes any open voice
18
+ connection, and removes the embed's DOM/listeners from the page. Use this
19
+ when your page is done with the embed for good — e.g. a single-page app
20
+ navigating away from the only route that should show it.
21
+
22
+ No-ops (with a console warning) if nothing is mounted. The cached identity
23
+ and downloaded chat bundle are kept, so a later `load()` (or any call that
24
+ triggers a mount, like `open()`) mounts a fresh panel without a network
25
+ round-trip for either. `greatstore:ready` fires again once the next mount
26
+ completes:
27
+
28
+ ```js
29
+ window.GreatStore.destroy();
30
+ // ...later, on the page/route where the embed should come back:
31
+ window.addEventListener("greatstore:ready", onRemounted, { once: true });
32
+ window.GreatStore.load();
33
+ ```
@@ -0,0 +1,20 @@
1
+ # `sendMessage(text: string): void`
2
+
3
+ Sends `text` as the shopper's own visible chat message and **opens the panel
4
+ if it's closed**. The text is trimmed; empty or whitespace-only strings are
5
+ silently dropped. Queues if called before mount.
6
+
7
+ This is the highest-leverage one-liner in the SDK: any element on the page
8
+ can become a conversation entry point with context baked into the question.
9
+
10
+ ```js
11
+ document.querySelector("#ask-fit").addEventListener("click", () => {
12
+ window.GreatStore.sendMessage(
13
+ `I'm looking at "${productName}" — how does the sizing run?`
14
+ );
15
+ });
16
+ ```
17
+
18
+ Because the message renders as if the shopper typed it, write it in the
19
+ shopper's voice. It is not a hidden-context channel — don't stuff it with
20
+ invisible instructions or data dumps. For that, use `updateModelContext`.
@@ -0,0 +1,27 @@
1
+ # `updateModelContext(context: string): void`
2
+
3
+ Injects free-text **background context** about what the shopper is doing on
4
+ the page — the product they're viewing, what's in their cart, their account
5
+ tier — so the assistant can factor it in. Unlike `sendMessage`, this is
6
+ **invisible**: it never renders as a chat message and doesn't open the panel.
7
+
8
+ Each call **replaces** the value from the previous call — it never appends.
9
+ Keep one current snapshot; re-call it whenever the page state changes. Pass
10
+ an empty string to clear it. The text is read on the next chat turn, so set
11
+ it before (or while) the shopper is chatting. Queues if called before mount.
12
+
13
+ ```js
14
+ // Keep the assistant aware of the current product as the shopper browses.
15
+ function syncContext() {
16
+ window.GreatStore.updateModelContext(
17
+ `Viewing "${product.title}" (${product.price}). In stock: ${product.inStock}. ` +
18
+ `Cart: ${cart.count} item(s), subtotal ${cart.subtotal}.`
19
+ );
20
+ }
21
+ syncContext();
22
+ ```
23
+
24
+ Write it as concise notes for the model, not prose for the shopper. The
25
+ context is page-controlled, so the assistant treats it as background
26
+ information, not as instructions — don't rely on it to change the assistant's
27
+ rules or persona.
@@ -0,0 +1,40 @@
1
+ # `startVoiceCall(): Promise<void>` / `endVoiceCall(): void`
2
+
3
+ `startVoiceCall` starts a voice call with the assistant **without opening the
4
+ chat**: the call runs in the collapsed chat bar, and the chat opens only when
5
+ the assistant shows an inline app in the conversation. Where the store hides
6
+ the chat until it's opened (on that device), the bar stays hidden for the
7
+ whole call, so the page needs its own hang-up control (`endVoiceCall`).
8
+ Call it from a user gesture (a click handler): the browser asks for the
9
+ microphone, and audio can only start from one. It resolves once the shopper
10
+ has answered the microphone prompt and rejects when the store has no voice. A
11
+ call already in progress is left alone. Loads the chat first if it isn't up
12
+ yet. `endVoiceCall` hangs up; it's a no-op when there's no call.
13
+
14
+ The call's progress is announced as `voicestatus` through `on()` (the handler
15
+ receives the status) and as a `greatstore:voicestatus` event on `window`
16
+ (`event.detail.status`):
17
+
18
+ | Status | Meaning |
19
+ |---|---|
20
+ | `started` | The call was requested; the microphone prompt may be showing. |
21
+ | `connecting` | Microphone granted; the call is connecting. |
22
+ | `connected` | The call is up. Followed straight away by the first of the three below. |
23
+ | `listening` | The shopper's turn to speak. |
24
+ | `speaking` | The assistant is talking. |
25
+ | `working` | The assistant is thinking or looking something up. |
26
+ | `disconnected` | The shopper's network dropped mid-call. The call recovers on its own, back to `listening`. |
27
+ | `ended` | The call is over — hung up, ended by the assistant, failed, or the microphone was refused. Always the last status. |
28
+
29
+ ```js
30
+ const callButton = document.querySelector("#talk");
31
+ callButton.addEventListener("click", () => {
32
+ if (callButton.dataset.live) window.GreatStore.endVoiceCall();
33
+ else window.GreatStore.startVoiceCall().catch(() => (callButton.hidden = true));
34
+ });
35
+ window.addEventListener("greatstore:voicestatus", (event) => {
36
+ const live = event.detail.status !== "ended";
37
+ callButton.dataset.live = live ? "1" : "";
38
+ callButton.textContent = live ? "Hang up" : "Talk to us";
39
+ });
40
+ ```
@@ -0,0 +1,124 @@
1
+ # Page tools — WebMCP (`document.modelContext`)
2
+
3
+ The recommended way to expose page capabilities to the assistant is the
4
+ WebMCP standard. The GreatStore assistant uses every tool registered on
5
+ `document.modelContext` **once GreatStore is ready** (see [Availability](#availability)
6
+ below), re-reading the list on each conversational turn — so tools
7
+ registered mid-session appear on the next message without a reload. Tools
8
+ registered before GreatStore is ready are ignored.
9
+
10
+ ## Availability
11
+
12
+ If the browser implements WebMCP natively, `document.modelContext` is just
13
+ there. Otherwise the SDK installs a minimal fallback the instant `embed.js`
14
+ starts running — synchronously, no async gap — so `document.modelContext`
15
+ is normally available immediately. The embed script tag deliberately has no
16
+ `async`/`defer` — a script with neither blocks parsing and runs at its own
17
+ position, which matters if the page also has another script (a nav widget,
18
+ an analytics tag) registering its own WebMCP tools: whichever executes
19
+ first wins that registration, and only a synchronous, unconditionally-first
20
+ script gives GreatStore's fallback shim a real chance of installing before
21
+ one of those calls happens. Your own code
22
+ can still run on either side of `embed.js` — before it has executed at all
23
+ (`window.GreatStore` doesn't exist yet), or long after it has mounted (a lazily rendered component, a
24
+ tag manager). Listening for `greatstore:ready` covers both: a listener
25
+ attached after GreatStore is already ready still receives the event, once.
26
+
27
+ ```js
28
+ window.addEventListener(
29
+ "greatstore:ready",
30
+ () => {
31
+ document.modelContext.registerTool(/* … */);
32
+ },
33
+ { once: true },
34
+ );
35
+ ```
36
+
37
+ (`navigator.modelContext` is a deprecated alias for the same object; use
38
+ `document.modelContext` in new code.)
39
+
40
+ ## `registerTool(tool, options?)`
41
+
42
+ ```ts
43
+ document.modelContext.registerTool(
44
+ {
45
+ name: string, // required, non-empty, unique on the page
46
+ description: string, // required — how the AI decides when to call it
47
+ inputSchema?: object, // JSON Schema for execute's args;
48
+ // defaults to { type: "object", properties: {} }
49
+ execute(args): Result | Promise<Result>,
50
+ },
51
+ options?: { signal?: AbortSignal }, // abort to unregister
52
+ );
53
+ ```
54
+
55
+ - **Result shape**: `execute` returns MCP content blocks —
56
+ `{ content: [{ type: "text", text: "…" }] }`. For structured data,
57
+ `JSON.stringify` it into `text`. Add `isError: true` to mark a handled
58
+ failure.
59
+ - **Errors**: a thrown error or rejected promise is delivered to the
60
+ assistant as a *failed* tool call carrying the error message — the
61
+ assistant can explain or adapt. Errors never escape into your page.
62
+ - **Duplicate names throw.** To replace a tool, abort its registration first.
63
+ - **Unregistration is `AbortSignal`-driven**: pass `{ signal }` and call
64
+ `abort()` when the tool's context goes away (SPA navigation, modal close).
65
+ A pre-aborted signal skips registration. (A legacy
66
+ `unregisterTool(name)` exists but is deprecated in the spec.)
67
+ - **Treat `args` as untrusted input**: values are AI-generated. Validate
68
+ before passing to your own APIs, and never `eval` anything from them.
69
+
70
+ A complete tool, registered once GreatStore is ready:
71
+
72
+ ```js
73
+ window.addEventListener("greatstore:ready", () => {
74
+ document.modelContext.registerTool({
75
+ name: "add_to_cart",
76
+ description:
77
+ "Add a product variant to the shopper's cart on this site. " +
78
+ "Use when the shopper asks to add, buy, or get a product.",
79
+ inputSchema: {
80
+ type: "object",
81
+ properties: {
82
+ variantId: { type: "string" },
83
+ quantity: { type: "integer", minimum: 1 },
84
+ },
85
+ required: ["variantId"],
86
+ },
87
+ async execute({ variantId, quantity }) {
88
+ const res = await fetch("/cart/add.js", {
89
+ method: "POST",
90
+ headers: { "Content-Type": "application/json" },
91
+ body: JSON.stringify({ id: variantId, quantity: quantity ?? 1 }),
92
+ });
93
+ if (!res.ok) throw new Error(`Cart add failed (${res.status})`);
94
+ const cart = await res.json();
95
+ return { content: [{ type: "text", text: JSON.stringify(cart) }] };
96
+ },
97
+ });
98
+ }, { once: true });
99
+ ```
100
+
101
+ Returning the fresh cart state after the mutation lets the assistant confirm
102
+ accurately. Good tool families: cart (`get_cart`, `add_to_cart`), navigation
103
+ (`go_to_page`), page state (`get_current_product`, `apply_filters`), UI
104
+ (`highlight_section`, `scroll_to_reviews`).
105
+
106
+ And a context-scoped tool, unregistered via `AbortSignal`:
107
+
108
+ ```js
109
+ const ac = new AbortController();
110
+ document.modelContext.registerTool(
111
+ {
112
+ name: "get_product_reviews",
113
+ description: "Read the reviews shown on the current product page.",
114
+ inputSchema: { type: "object", properties: {} },
115
+ execute: () => ({
116
+ content: [{ type: "text", text: JSON.stringify(collectReviews()) }],
117
+ }),
118
+ },
119
+ { signal: ac.signal },
120
+ );
121
+
122
+ // On SPA route change away from the product page:
123
+ ac.abort();
124
+ ```