# Install AI Autocomplete (Vanilla JS): agent instructions

> For the complete documentation index, see [llms.txt](https://magicx.ai/llms.txt). A markdown version of any page on this site is available by appending `.md` to its URL path (the homepage is at `/index.md`).

You are an AI coding agent installing **AI Autocomplete** into the user's web app using the framework-agnostic vanilla JS SDK. Follow these steps in order. Do not skip the "Hand off to the user" section; those steps are not yours to perform.

Reference docs: https://magicx.ai/intent-1/docs/vanilla/getting-started

AI Autocomplete uses two key types:

- **Public keys** (`pk_v1_...`): safe to ship in client bundles. Sent as a Bearer token directly from the browser. Use this for the basic install path below.
- **Secret keys** (`sk_v1_...`): server-only. Your server exchanges a secret key for a short-lived access token (`at_v1_...`) that the SDK consumes. Recommended for production. See the "Production: secret key + access token" section at the end.

---

## Step 0: Read the SDK README

Before any code changes, run:

```
npm view @magicx-eng/ai-autocomplete-vanilla readme
```

Read the output end-to-end. It documents the full options surface, both auth modes, the CSS variables, and the stable `data-aia-*` selector hooks. You'll need it in Steps 2 and 5. If you can't run shell commands, fetch `https://unpkg.com/@magicx-eng/ai-autocomplete-vanilla/README.md` instead (same content).

## Step 1: Ask the user which integration tier

The SDK ships three tiers. **Stop, ask the user, and wait for their answer.** Do not pick on their behalf.

> "AI Autocomplete ships three integration tiers. Which do you want?
>
> **Tier 1: Full component (`renderMode: "full"`, the default)**
> Drop-in. The SDK creates and owns the textarea, pills, dropdown, and all state inside a container element you provide. This is the right choice for most apps.
>
> **Tier 2: Dropdown only (`renderMode: "dropdown"`)**
> You own the input element. The SDK renders only the dropdown (with pills inside) into a container you provide. You forward keystrokes / focus events to the SDK. Pick this if you have a custom input (a rich-text editor, a styled search bar, an existing form field) that you want to keep.
>
> **Tier 3: Headless (`renderMode: "headless"`)**
> No DOM. The SDK gives you state, actions, and a `subscribe()` callback. You render every pixel yourself. Pick this only if you're building a framework wrapper or need total control over rendering; most apps don't need this.
>
> Which one: full, dropdown-only, or headless?"

If the user says "you decide" or seems unsure, recommend Tier 1. Tier 3 is rarely the right answer for application code. If they're considering it because they want a custom input, Tier 2 is almost always what they actually want.

## Step 2: Install and wire up the SDK

Sanity-check the project: there should be a `package.json` at the root and the project should already have a bundler set up (Vite, Webpack, esbuild, etc.), since this SDK is distributed as an npm package and is consumed via `import`. If there's no bundler, ask the user where their app lives or to set one up first.

Install the SDK with the project's package manager:

- pnpm: `pnpm add @magicx-eng/ai-autocomplete-vanilla`
- yarn: `yarn add @magicx-eng/ai-autocomplete-vanilla`
- npm: `npm install @magicx-eng/ai-autocomplete-vanilla`
- bun: `bun add @magicx-eng/ai-autocomplete-vanilla`

Then add the integration code for the tier the user picked. **Hardcode the public key as the literal string `"PASTE_PUBLIC_KEY_HERE"`**, and leave that placeholder in the code. The user will replace it after Step 3. Do **not** invent a key, and do **not** create a `.env`/`.env.local` entry for it. Once the install is verified end-to-end it's the user's call how to manage the key long-term.

If onboarding gave you css_variables, apply them as CSS custom properties on a class on your container element before matching the surrounding input (see https://magicx.ai/onboard.md, "install", for how to apply the light and dark sets).

If onboarding gave you sdk_options, pass each one as an option to `new AIAutocomplete`: `allOption`, `seeAllResults` and `showChipRemove`, all `true`. `seeAllResults` adds a "See all results" button that submits like Enter, through `onSubmit`, so point `onSubmit` at the site's search results page. To build that URL from what the shopper picked, follow https://magicx.ai/install/search-results.md.

If you don't know where to mount the widget, ask the user before guessing.

**Tier 2 / Tier 3 rule: keep the page's own submit, and call `ac.reset()` at the end of the code path that reads the input.** Tier 1 (full component) handles this automatically. In Tier 2 and Tier 3 the consumer owns the input element and the submit flow:

- `handleKeyDown` takes Enter for the dropdown and reports it only through `onSubmit`, so pass an `onSubmit` that runs the page's own submit (for a form, `form.requestSubmit()`). It prevents Enter's default every time, so the browser never submits the form on its own. The one Enter it leaves alone, while an IME is composing, commits the IME's text instead of reaching the form. Without `onSubmit`, Enter submits nothing.
- Call `ac.reset()` at the end of the code path that reads the input, never before it. `reset()` clears the input, so calling it inside a submit button's click handler sends an empty query. It also rotates the per-session `session_id` so the server's history stays accurate; skipping it degrades suggestion quality on subsequent submissions.
- The SDK records Enter submits itself. If the page has its own submit button, call `ac.recordSubmit(ac.getResult())` once per click.

### Tier 1: Full component

Add a container element to the user's HTML where the widget should appear:

```html
<div id="autocomplete-root"></div>
```

Then mount the SDK:

```ts
import { AIAutocomplete } from "@magicx-eng/ai-autocomplete-vanilla";

const root = document.getElementById("autocomplete-root");
if (!root) throw new Error("Missing #autocomplete-root container");

const ac = new AIAutocomplete(root, {
  apiConfig: {
    apiKey: "PASTE_PUBLIC_KEY_HERE",
  },
  mode: "dark", // pins dark; omit to follow prefers-color-scheme
  onSubmit: (result) => {
    console.log(result.query);
    console.log(result.completed_params);
  },
});
```

The `mode` option accepts `"light"`, `"dark"` or `"auto"` and defaults to `"auto"` (follows `prefers-color-scheme`). Match the surrounding page: light theme → `mode: "light"`; dark theme → `mode: "dark"`; unsure → leave it at the default.

### Tier 2: Dropdown only

The user provides their own input element; you wire its events into the SDK and provide a container for the dropdown. This snippet assumes the input sits inside a `<form>` the browser submits; for a page without one, see the note after it:

```ts
import { AIAutocomplete } from "@magicx-eng/ai-autocomplete-vanilla";

const input = document.getElementById("my-input") as HTMLInputElement | null;
const dropdownContainer = document.getElementById("my-dropdown");
const form = input?.closest("form");
if (!input || !dropdownContainer || !form) {
  throw new Error("Missing input, dropdown container, or form");
}

const ac = new AIAutocomplete(dropdownContainer, {
  renderMode: "dropdown",
  apiConfig: { apiKey: "PASTE_PUBLIC_KEY_HERE" },
  onChange: (text) => {
    if (input.value !== text) input.value = text;
  },
  // Enter reaches the SDK first; hand it back to the page's own submit.
  onSubmit: () => form.requestSubmit(),
});

input.addEventListener("input", () => ac.handleTextChange(input.value));
input.addEventListener("keydown", (e) => ac.handleKeyDown(e));
input.addEventListener("focus", () => ac.setFocused(true));
input.addEventListener("blur", () => ac.setFocused(false));
form.addEventListener("submit", (event) => {
  // The SDK records Enter submits itself; record a click on the page's own button.
  if (event.submitter) ac.recordSubmit(ac.getResult());
  // The browser reads the form's fields after submit listeners return, so reset on the next task.
  setTimeout(() => ac.reset(), 0);
});
```

If the page reads `input.value` in its own code instead (a submit handler that calls `preventDefault()`, a handler that awaits before reading, or a page with no form), call that code from `onSubmit` and from its button (recording that click with `ac.recordSubmit(ac.getResult())`), and call `ac.reset()` at the end of it instead of the `setTimeout`. A timer can fire before an async read and clear the query first. When the form navigates to another page, that page starts a new session anyway; the reset matters when the page stays.

The focus wiring (`setFocused`) is required: with `dropdownTrigger: "auto"` (the default) the dropdown only opens while the input is focused, and the SDK has no way to know that without you telling it.

### Tier 3: Headless

The SDK exposes state, actions, and a `subscribe()` callback; you render everything yourself.

```ts
import { AIAutocomplete } from "@magicx-eng/ai-autocomplete-vanilla";

const ac = new AIAutocomplete(document.createElement("div"), {
  renderMode: "headless",
  apiConfig: { apiKey: "PASTE_PUBLIC_KEY_HERE" },
  // Enter reaches the SDK first; hand it back to your submit.
  onSubmit: () => handleSubmit(),
});

const handleSubmit = () => {
  const state = ac.getState();
  console.log(state.text, state.completedParams);
  ac.reset();
};

const unsubscribe = ac.subscribe((state) => {
  // render input, pills, dropdown, segments using state
});

// forward user events into the SDK
myInput.addEventListener("input", () => ac.handleTextChange(myInput.value));
myInput.addEventListener("keydown", (e) => ac.handleKeyDown(e));
myInput.addEventListener("focus", () => ac.setFocused(true));
myInput.addEventListener("blur", () => ac.setFocused(false));
mySubmitButton.addEventListener("click", () => {
  // The SDK records Enter submits itself; record a click on your own button.
  ac.recordSubmit(ac.getResult());
  handleSubmit();
});
```

The full `CoreState` shape (text, completedParams, suggestions, segments, filteredOptions, isDropdownOpen, activeDropdownIndex, isLoading, isReady, error, …), `getResult()` (the structured query `onSubmit` receives), and the action methods (`selectOption`, `setActiveDropdownIndex`, `setActivePill`, `removeLastParam`, `reset`, `recordSubmit`, `destroy`, …) are documented in the SDK README you read in Step 0. Confirm with the user how they want pills, segments, and the dropdown rendered before committing to a layout. Tier 3 is open-ended by design.

## Step 3: Hand off to the user (you cannot do this)

> **Skip this if agent onboarding already ran.** Go straight to Step 4. If you
> followed https://magicx.ai/onboard.md, the product exists and you
> already hold a public key; use it in place of the placeholder above.

After your code changes are complete, **stop** and print the following to the user verbatim, including the bullets and URLs. These are browser tasks; the agent cannot perform them.

> **Two browser steps you need to do before this works:**
>
> 1. Go to **https://ai-autocomplete.com/edit** and create your product. This configures what your autocomplete will suggest (the prompts, parameter types, and option lists).
> 2. Go to **https://ai-autocomplete.com/account/keys**, create a **public key**, copy it, and paste it in place of `PASTE_PUBLIC_KEY_HERE` in the code. The public key starts with `pk_v1_`.
>
> Once both are done, reload the page (or restart the dev server if hot reload didn't pick it up). Reply when you've confirmed it works (or share what's failing).

Do not pretend you can open URLs, create the product, or generate the key on the user's behalf. Wait for their reply before moving to Step 4.

## Step 4: Verify it works

Once the user replies that they've pasted the key, walk them through verification:

Before declaring installation verified, identify the application's original submit handler, navigation or request path in code and check that it still runs with the intended input after installing the box. Exercise that path where possible and report the observation; if it cannot be checked, say what remains unverified. A build, rendered widget or suggestion response alone is insufficient. Downstream search results or generated content belong to the application and are outside this installation check.

1. Reload the page (or restart the dev server).
2. Confirm the autocomplete renders inside the container without console errors.
3. If the network tab shows **401 Unauthorized** on `/api/suggest`, the key is wrong or it isn't a public key. Ask the user to re-copy it from `/account/keys` and confirm it starts with `pk_v1_`.
4. If you see **404** or "no suggestions returned", the product likely wasn't created yet. Ask the user to confirm they finished Step 3.1.
5. **Tier 2/3 only:** submit with Enter as well as with the page's button. If Enter submits nothing, `new AIAutocomplete(...)` got no `onSubmit`; if the query arrives empty, `ac.reset()` ran before the submit read the input.
6. **Tier 2/3 only:** if the dropdown never opens, confirm that the input's `focus`/`blur` listeners are calling `ac.setFocused(true)` / `ac.setFocused(false)`. Without those, `dropdownTrigger: "auto"` will never trigger.

Wait for an explicit "yes, it works" before moving on.

## Step 5: Offer to customize the styling

Once the user confirms the autocomplete works, offer to customize the styling, but derive the look from what's already on the page first, rather than starting from a blank slate.

**Derive the look from the surrounding UI.** The goal is a widget that looks native to the page, not a generic drop-in. Inspect the page you mounted into and its neighbors for an existing text input, `<textarea>`, or search field, and read the styling the app already uses:

- **Corner radius**, **border/stroke** (color + width), **background color**, **text color**, **font family**, **font size**, and **padding**, pulled from the nearest input's CSS (stylesheet, `<style>` block, or utility classes like Tailwind).
- **Design tokens / theme**: check for CSS custom properties (`:root { --… }`) or a `tailwind.config`. Prefer wiring the SDK's CSS variables to those tokens (e.g. `var(--color-border)`) over hardcoded values, so the widget tracks the theme automatically, including light/dark flips.

Map what you find onto the SDK's CSS variables (names in the README from Step 0). If you can't find a nearby input to copy, fall back to asking the user before guessing.

Then make the offer, and briefly show the user the concrete values you pulled and where each came from, e.g. "matched the field radius to your `.input` `border-radius: 8px`, border to `var(--color-border)`":

> "Want to customize the look? I've matched it to your app automatically. I pulled the corner radius, border, background, font, and colors from your existing input/theme so the widget blends in. Want anything specific changed (e.g. 'match my brand primary', 'tighten the pill padding', 'switch to a solid dropdown'), or does it look fine?"

If the user wants changes, refer to the **CSS Variables** and **Selector Hooks** tables in the SDK README you read in Step 0.

Apply overrides via a class on the container element you passed to `new AIAutocomplete(...)`. All defaults use `:where()` (zero specificity) so any class you write wins. For per-mode overrides, target `[data-mode="light"]` / `[data-mode="dark"]` on that element, and also as a descendant (`.my-class [data-mode="dark"]`) for a standalone dropdown (Tier 2/3), which carries its own `data-mode`.

For changes the variables don't cover, target the `data-aia-*` selector hooks (e.g. `[data-aia-dropdown]`, `[data-aia-pill]`, `[data-aia-textarea]`). Those are the stable public surface. Don't target hashed CSS-module class names.

In Tier 3 (headless) you own the DOM, so most styling is just your own CSS; the variables and selector hooks only apply to the dropdown DOM the SDK still renders.

If the user says "looks fine" or doesn't want changes, you're done. Mention briefly that for production they may want to switch to the access-token flow below, but don't build it unless asked.

---

## Production: secret key + access token (recommended)

Public keys work, but for production browser apps we recommend the access-token flow:

- The **secret key** (`sk_v1_...`) lives **only on the user's backend server**, never in the browser bundle, never in client-side env vars (no `VITE_` prefix), never accessible from frontend code.
- The user's **backend** exchanges the secret key for a short-lived **access token** (`at_v1_...`) by calling AI Autocomplete.
- The **frontend** SDK fetches that access token from a route on the user's *own* backend and uses it. The browser never touches the secret key.

Only build this once the basic install above is verified, and confirm with the user before adding server code. **If the project has no backend (e.g. a static site or pure SPA with no server runtime), STOP and tell the user: you cannot do the secret-key flow without a server. Stay on public keys.**

### A. Add server-side env vars

These live in the user's **backend** environment (host shell, Docker secrets, PaaS env config, or wherever the server runs). They must NOT have a `VITE_` prefix (or any other client-side prefix), since that would expose them to the browser.

```
MAGICX_SECRET_KEY=sk_v1_...
MAGICX_PRODUCT_ID=<the product UUID from /edit>
```

The product UUID is visible in the URL of the product editor at `/edit`. Ask the user to copy it.

### B. Add the token-exchange route on the backend

> **This code runs on the user's backend server, not in the browser.** The secret key is read from server-side `process.env` and used in an outbound `fetch` from the server. The browser never sees it.

The backend hits `POST https://api.ai-autocomplete.com/api/auth/token` with the secret key as a Bearer token and the `product_id` in the body. The endpoint returns `{ access_token, expires_at, token_type }`, where `expires_at` is Unix seconds. Forward that response to the browser unchanged.

Generic Node example, in `server/ac-token.ts`:

```ts
// SERVER-ONLY
export async function getAccessToken() {
  const res = await fetch("https://api.ai-autocomplete.com/api/auth/token", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.MAGICX_SECRET_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ product_id: process.env.MAGICX_PRODUCT_ID }),
  });

  if (!res.ok) {
    // 401 with error.code === "INVALID_SECRET_KEY" means a config problem
    // on the user's end, so don't surface it to the browser as 401.
    throw new Error("Token exchange failed");
  }

  // { access_token, expires_at, token_type }
  return res.json();
}
```

Wire this into whatever HTTP framework the user runs (Express, Fastify, Hono, serverless handler) under a path like `/api/ac-token`, always on the **backend** side of the codebase.

### C. Switch the SDK to access-token mode (browser-side)

> **This code runs in the browser.** It contains no secret key, only the path of the user's own backend route from Step B.

```ts
// BROWSER
new AIAutocomplete(container, {
  apiConfig: {
    type: "accessToken",
    getAccessToken: async () => {
      const res = await fetch("/api/ac-token");
      const { access_token, expires_at } = await res.json();
      // expires_at is Unix seconds; the SDK's expiresAt is Unix milliseconds.
      return { accessToken: access_token, expiresAt: expires_at * 1000 };
    },
  },
  onSubmit: handleSubmit,
});
```

### D. Remove the public key

Once the access-token flow is verified, drop the hardcoded public key (or whatever the user moved it into) from your code; you don't need it anymore.

Full docs: https://magicx.ai/intent-1/docs/vanilla/authentication
