> ## Documentation Index
> Fetch the complete documentation index at: https://docs.puntego.com/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK reference

> Every window.Puntego method, the control namespace, the on/off event map, and the React hooks — with exact signatures and return types.

The browser SDK is the typed control surface the runtime exposes on `window.Puntego`. Use it to point at elements, run guided tours, send messages, register page targets and actions, and listen for what the guide does. This page is the exact signature reference, generated from the published types.

Every signature below comes from `@puntego/embed`. Importing the package augments the global `Window`, so `window.Puntego` is fully typed with no extra setup:

```ts theme={null}
import '@puntego/embed';
// window.Puntego is now typed as PuntegoApi
```

Prefer explicit imports? The same types are available as named exports from `@puntego/embed/types`, and the [React hooks](#react-hooks-puntego-react) re-export the ones you need.

<Note>
  The npm packages (`@puntego/embed`, `@puntego/react`) are rolling out to the registry and may still 404 until they are published. The single boot script install works today — see [Install](/install).
</Note>

## Get a reference to the SDK

The runtime boots from the page's boot script and assigns `window.Puntego` once it is ready. From plain JavaScript you can read it directly, but it is `undefined` until boot completes. The cleanest way to wait is the loader helper.

<CodeGroup>
  ```ts loader.ts theme={null}
  import { loadPuntego, whenPuntegoReady } from '@puntego/embed/loader';

  // Inject the boot script imperatively (no-op on the server, deduped per page).
  loadPuntego({
    appId: 'gp_your_app_id',
    apiUrl: 'https://worker.puntego.com',
  });

  const sdk = await whenPuntegoReady(); // PuntegoApi | null (null on timeout)
  sdk?.point('#checkout-button', 'Finish here');
  ```

  ```ts global.ts theme={null}
  // If the boot script tag is already on the page, read the global once it exists.
  const sdk = window.Puntego;
  sdk?.point('#checkout-button', 'Finish here');
  ```
</CodeGroup>

<ParamField path="loadPuntego(options)" type="(options: LoadPuntegoOptions) => HTMLScriptElement | null">
  Injects exactly one boot script per page. Returns the script element on the client, or `null` during server rendering. Options: `appId` (required), `apiUrl`, `baseUrl`, `src`, `nonce`. A reachable worker needs `apiUrl` (the `data-gp-api` origin); for strict CSP, `nonce` is propagated to both `nonce` and `data-nonce`.
</ParamField>

<ParamField path="whenPuntegoReady(timeoutMs?)" type="(timeoutMs?: number) => Promise<PuntegoApi | null>">
  Resolves with `window.Puntego` once the runtime has booted, immediately if it is already present, or `null` if `timeoutMs` (default 8000) elapses first.
</ParamField>

## Shared types

These types appear across the method signatures below.

```ts theme={null}
// Anything the SDK can resolve to an on-page element.
type PublicGuideTarget = Element | PuntegoGuideTarget | string;

interface PuntegoGuideTarget {
  gp_id?: string;
  href?: string;
  route?: string;
  selector?: string;
  target_id?: string;
  xy?: { x: number; y: number };
}

interface PuntegoMarker {
  accent?: string;
  label: string;
  target: PublicGuideTarget;
}

interface PuntegoStep {
  label?: string;
  narration: string;
  target?: PublicGuideTarget;
  text?: string;
  type?: 'caption' | 'point' | 'scroll' | 'spotlight';
}

interface PuntegoWorkflow {
  steps: PuntegoStep[];
  title?: string;
}

interface PuntegoWorkflowResult {
  actionId?: string;
  details?: Record<string, unknown>;
  durationMs?: number;
  status: 'cancelled' | 'completed' | 'failed';
  workflowId?: string;
}
```

A string `PublicGuideTarget` is treated as a CSS selector. Pass a live `Element` when you already hold a node, or a `PuntegoGuideTarget` object to resolve by `gp_id`, `target_id`, `route`, `href`, `selector`, or raw `xy` coordinates.

## window\.Puntego methods

`window.Puntego` implements the `PuntegoApi` interface. Methods are grouped below by what they do. Pay attention to the return column: the visual helpers return `void` synchronously, while the messaging, voice, and lifecycle methods return a `Promise` you should `await`.

### Pointing and captions

| Method      | Signature                                                                    | Returns |
| ----------- | ---------------------------------------------------------------------------- | ------- |
| `point`     | `point(target: PublicGuideTarget, label?: string)`                           | `void`  |
| `caption`   | `caption(text: string)` / `caption(target: PublicGuideTarget, text: string)` | `void`  |
| `highlight` | `highlight(target: PublicGuideTarget, label?: string)`                       | `void`  |
| `scrollTo`  | `scrollTo(target: PublicGuideTarget, label?: string)`                        | `void`  |
| `markers`   | `markers(markers: PuntegoMarker[], durationMs?: number)`                     | `void`  |
| `clear`     | `clear()`                                                                    | `void`  |

<Warning>
  `point()` and `caption()` return `void` — they are not promises. Do not write `await sdk.point(...)`; there is nothing to await.
</Warning>

`markers` draws a labeled set of pins; pass `durationMs` to auto-clear after a delay. `clear` removes the current pointer, caption, highlight, and markers.

### Steps and tours

| Method      | Signature                              | Returns |
| ----------- | -------------------------------------- | ------- |
| `showSteps` | `showSteps(workflow: PuntegoWorkflow)` | `void`  |
| `tour`      | `tour(workflow: PuntegoWorkflow)`      | `void`  |

`showSteps` renders a static step list; `tour` walks the visitor through each `PuntegoStep` in sequence.

### Messaging and voice

| Method        | Signature                                                       | Returns         |
| ------------- | --------------------------------------------------------------- | --------------- |
| `sendMessage` | `sendMessage(prompt: string, opts?: PuntegoSendMessageOptions)` | `Promise<void>` |
| `speak`       | `speak(text: string)`                                           | `Promise<void>` |

```ts theme={null}
interface PuntegoSendMessageOptions {
  initiatedBy?: 'system' | 'visitor';
  source?: string;
}
```

<Info>
  `sendMessage` and `speak` are async — `await` them. `speak` uses the workspace voice; see [Configuration](/configuration) for enabling voice. When voice provider credentials are absent, the runtime falls back to an internal mock voice.
</Info>

### Lifecycle and visibility

| Method    | Signature                            | Returns               |
| --------- | ------------------------------------ | --------------------- |
| `init`    | `init(options?: PuntegoInitOptions)` | `Promise<PuntegoApi>` |
| `open`    | `open()`                             | `void`                |
| `close`   | `close()`                            | `void`                |
| `show`    | `show()`                             | `void`                |
| `hide`    | `hide()`                             | `void`                |
| `destroy` | `destroy()`                          | `void`                |

`init` is async and resolves with the SDK; the boot script calls it for you, so you only call it when you opt into manual init with extra options. `show`/`hide` toggle the launcher's visibility; `open`/`close` toggle the conversation panel; `destroy` tears the runtime down.

```ts theme={null}
interface PuntegoInitOptions {
  actions?: GuideActionManifestEntry[];
  autoAsk?: boolean;
  behavior?: PuntegoBehaviorOptions;
  context?: () => Record<string, unknown>;
  launcher?: PuntegoLauncherOptions;
  targets?: GuideActionManifestTarget[];
}
```

### Targets, actions, and sensitivity

These methods feed the guide's grounding and action registry. See the [Guide Tools SDK](/guide-tools-sdk) for the full grounding model and how registered targets and actions are used.

| Method               | Signature                                                                            | Returns                             |
| -------------------- | ------------------------------------------------------------------------------------ | ----------------------------------- |
| `registerTarget`     | `registerTarget(target: PublicGuideTarget, registration: PuntegoTargetRegistration)` | `GuideActionManifestTarget \| null` |
| `unregisterTarget`   | `unregisterTarget(id: string)`                                                       | `boolean`                           |
| `registerAction`     | `registerAction(action: GuideActionManifestEntry)`                                   | `GuideActionManifestEntry`          |
| `unregisterAction`   | `unregisterAction(id: string)`                                                       | `boolean`                           |
| `registerShadowRoot` | `registerShadowRoot(root: ShadowRoot)`                                               | `void`                              |
| `markSensitive`      | `markSensitive(target: PublicGuideTarget, sensitive?: boolean)`                      | `boolean`                           |
| `getActionRegistry`  | `getActionRegistry()`                                                                | `GuideActionManifest`               |

```ts theme={null}
interface PuntegoTargetRegistration {
  allowedActions?: PuntegoGuideActionType[];
  description?: string;
  href?: string;
  id: string;
  route?: string;
  sensitive?: boolean;
}
```

<Tip>
  The guide cannot see into a shadow DOM (open or closed) unless you register it with `registerShadowRoot`. Call it for each shadow root you want the guide to reach. See [what the guide can and cannot see](/security) for the full visibility model.
</Tip>

### Outcomes

| Method                 | Signature                                             | Returns         |
| ---------------------- | ----------------------------------------------------- | --------------- |
| `reportWorkflowResult` | `reportWorkflowResult(result: PuntegoWorkflowResult)` | `Promise<void>` |

`reportWorkflowResult` is async — `await` it. It records an outcome trace for owner review (completed, cancelled, or failed). It does not create repair drafts or feed a learning loop.

### Events

| Method | Signature                                           | Returns |
| ------ | --------------------------------------------------- | ------- |
| `on`   | `on<K>(event: K, handler: PuntegoEventHandler<K>)`  | `void`  |
| `off`  | `off<K>(event: K, handler: PuntegoEventHandler<K>)` | `void`  |

See [Events](#events) below for the full event map.

## The control namespace

`window.Puntego.control` is a parallel surface for product-owned helpers — the visual primitives, mirrored so your own UI code can drive the guide without touching the conversation lifecycle. It implements `PuntegoControlApi`:

```ts theme={null}
interface PuntegoControlApi {
  caption(text: string): void;
  caption(target: PublicGuideTarget, text: string): void;
  clear(): void;
  highlight(target: PublicGuideTarget, label?: string): void;
  markers(markers: PuntegoMarker[], durationMs?: number): void;
  point(target: PublicGuideTarget, label?: string): void;
  scrollTo(target: PublicGuideTarget, label?: string): void;
  showSteps(workflow: PuntegoWorkflow): void;
  speak(text: string): Promise<void>;
  tour(workflow: PuntegoWorkflow): void;
}
```

The signatures match their top-level counterparts: `point`, `caption`, `highlight`, `scrollTo`, `markers`, `showSteps`, and `tour` return `void`; `speak` returns `Promise<void>`. Registration, messaging, lifecycle, and events live only on the top-level `window.Puntego`, not on `control`.

## Events

Subscribe with `on` and unsubscribe with the same handler reference via `off`. Handlers are fully typed against the event name — each payload below is the exact `PuntegoEventMap` shape.

```ts theme={null}
const onReady = (e: { appId: string; conversationId: string; visitorId: string }) => {
  console.log('guide ready', e.conversationId);
};
window.Puntego?.on('ready', onReady);
window.Puntego?.off('ready', onReady);
```

| Event                     | Payload                                                                   | Fires when                                     |
| ------------------------- | ------------------------------------------------------------------------- | ---------------------------------------------- |
| `ready`                   | `{ appId: string; conversationId: string; visitorId: string }`            | The runtime has booted and the guide is live.  |
| `bubble:update`           | `{ text: string }`                                                        | The guide bubble text changes.                 |
| `chat:user`               | `{ text: string }`                                                        | The visitor sends a message.                   |
| `chat:assistant-chunk`    | `{ delta: string }`                                                       | A streamed token chunk arrives from the guide. |
| `chat:assistant-complete` | `{ fullText: string }`                                                    | The guide finishes a streamed reply.           |
| `point:detected`          | `{ id: string \| null; label: string \| null; selector: string \| null }` | The guide resolves an element to point at.     |
| `point:unreachable`       | `{ label: string; reason: string }`                                       | The guide cannot reach the requested target.   |
| `guide-action:proposed`   | `{ action: PuntegoGuideAction }`                                          | An action is proposed to the visitor.          |
| `guide-action:started`    | `{ action: PuntegoGuideAction }`                                          | An action begins executing.                    |
| `guide-action:completed`  | `{ action: PuntegoGuideAction }`                                          | An action finishes successfully.               |
| `guide-action:failed`     | `{ action: PuntegoGuideAction; reason: string }`                          | An action fails.                               |
| `opt-out`                 | `Record<string, never>` (empty object)                                    | The visitor opts out.                          |
| `destroy`                 | `{ reason: 'destroy' \| 'opt-out' }`                                      | The runtime is torn down.                      |
| `error`                   | `{ cause?: unknown; code: string; message: string }`                      | A runtime error is surfaced.                   |

```ts theme={null}
interface PuntegoGuideAction {
  id: string;
  label?: string;
  risk: 'commit' | 'input' | 'navigation' | 'visual';
  target?: PuntegoGuideTarget;
  type: PuntegoGuideActionType;
}
```

## Runtime-only methods

The runtime also exposes `getPageContext()` and `locateTarget()`. These exist at runtime but are not part of the public TypeScript types, so a typed consumer needs a cast to reach them. Treat them as advanced and unstable.

```ts theme={null}
// Not in the public PuntegoApi type — cast to call them.
const sdk = window.Puntego as unknown as {
  getPageContext(): unknown;
  locateTarget(target: PublicGuideTarget): unknown | null;
};
const ctx = sdk.getPageContext();
const located = sdk.locateTarget('#checkout-button'); // null if unresolved
```

`getPageContext()` returns a snapshot of the current page the guide can see; `locateTarget()` resolves a `PublicGuideTarget` to its on-page location, or `null` when it cannot. Because they are untyped, their return shapes may change without notice — prefer the typed methods above for anything you ship.

## React hooks (@puntego/react)

`@puntego/react` wraps the same SDK for React apps. Mount `PuntegoProvider` once near the root, then call the hooks from any descendant. The provider is SSR-safe (the loader only runs in a client effect), so it works with the Next.js App Router. For the full provider setup, see [Frameworks](/frameworks).

| Hook               | Signature                                                                                            | Returns                                            |
| ------------------ | ---------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| `usePuntego`       | `usePuntego()`                                                                                       | `PuntegoApi \| null` (null until the SDK is ready) |
| `usePuntegoTarget` | `usePuntegoTarget<T extends Element>(ref: RefObject<T \| null>, options: PuntegoTargetRegistration)` | `void`                                             |
| `usePuntegoAction` | `usePuntegoAction(options: GuideActionManifestEntry)`                                                | `void`                                             |

* `usePuntego` returns the booted `window.Puntego` SDK for imperative calls (`point`, `sendMessage`, `on`/`off`, ...), or `null` until it is ready.
* `usePuntegoTarget` registers the element behind a ref as a guide target while the component is mounted, and unregisters it on unmount. Pass the same `id` you reference from an action's `target_id`.
* `usePuntegoAction` declares an action while the component is mounted and removes it on unmount.

```tsx theme={null}
import { usePuntego, usePuntegoTarget } from '@puntego/react';
import { useRef } from 'react';

function CheckoutButton() {
  const ref = useRef<HTMLButtonElement>(null);
  usePuntegoTarget(ref, { id: 'checkout-button', description: 'Place the order' });

  const sdk = usePuntego();
  return (
    <button ref={ref} onClick={() => sdk?.point('#checkout-button', 'Finish here')}>
      Check out
    </button>
  );
}
```

<Note>
  `PuntegoProvider` props mirror the loader: `appId` (required), `apiUrl` (required for a reachable worker), plus optional `baseUrl`, `src`, and `nonce` (propagated to both `nonce` and `data-nonce`). See [Frameworks](/frameworks).
</Note>

## Next steps

<CardGroup cols={2}>
  <Card title="Guide Tools SDK" icon="wrench" href="/guide-tools-sdk">
    The grounding model behind targets, actions, and the visual primitives.
  </Card>

  <Card title="Frameworks" icon="component" href="/frameworks">
    Full PuntegoProvider setup for React and the App Router.
  </Card>

  <Card title="What the guide can see" icon="eye" href="/security">
    Visibility limits, shadow DOM, iframes, and canvas mode.
  </Card>

  <Card title="Install" icon="plug" href="/install">
    The boot script, attributes, and route targeting.
  </Card>
</CardGroup>
