---
id: aikit-javascript-api
title: JavaScript API
slug: /ai-kit/javascript-api
sidebar_position: 40
description: Public runtime surface under globalThis.WpSuite.plugins.aiKit — feature calls, UI injection (renderFeature), and readiness helpers shared across WP Suite.
tags: [ai-kit, javascript, api, wordpress, events]
hide_title: true
---

## JavaScript API

AI‑Kit exposes a public runtime surface under the **WP Suite global**:

- `globalThis.WpSuite.plugins.aiKit` — the plugin object (registered by the AI‑Kit plugin)
- `globalThis.WpSuite.plugins.aiKit.features` — feature methods + UI helpers

All feature methods are async and return a `Promise`.

:::tip Defensive access
Always use optional chaining (`?.`) in case AI‑Kit is not installed on the current site/page.
:::

---

## Runtime helpers (shared WP Suite contract)

WP Suite plugins share a small common runtime contract (from `@smart-cloud/wpsuite-core`), including:

### Helper accessors

If you are bundling `@smart-cloud/wpsuite-core`, you can also use:

- `getWpSuite()` → returns the global `WpSuite` object (or `undefined`)
- `getPlugin("gatey" | "aiKit" | "...")` → returns a plugin object from the registry

(These are thin wrappers around `globalThis.WpSuite`.)


### Plugin status

`WpSuite.plugins.aiKit.status` can be one of:

- `unavailable` — plugin not present / not initialized yet
- `initializing` — booting up
- `available` — ready to use
- `error` — failed to initialize

### Wait until AI‑Kit is ready

You can wait in three common ways:

**1) `onReady(cb)`**

```js
globalThis.WpSuite?.plugins?.aiKit?.onReady?.(() => {
  console.log("AI‑Kit is ready");
});
```

**2) `availability()` (await-ready with timeout)**

Resolves to `available`, `unavailable`, or `error` (it never returns `initializing`).

```js
const res = await globalThis.WpSuite?.plugins?.aiKit?.availability?.();
if (res !== "available") {
  console.warn("AI‑Kit not available:", res);
}
```

**3) AI‑Kit core wrappers (`waitForAiKitReady`)**

If your build includes the AI‑Kit core package, you can use its convenience wrappers:

- `getAiKitPlugin()`
- `waitForAiKitReady(timeoutMs = 8000)`
- `getStore(timeoutMs = 10000)` (awaits readiness, then returns the store promise)

These are thin helpers on top of the events below.

### Readiness / error events

AI‑Kit emits DOM events you can listen to:

- `wpsuite:ai-kit:ready`
- `wpsuite:ai-kit:error`

```js
window.addEventListener("wpsuite:ai-kit:ready", () => console.log("ready"));
window.addEventListener("wpsuite:ai-kit:error", () => console.log("error"));
```

:::note WordPress `wp.events`
Some builds also re-emit these via `WpSuite.events` / `wp.events`. The DOM events above are the safest cross-context option.
:::

---

## Feature APIs (programmatic calls)

The async helpers under `WpSuite.plugins.aiKit.features` mirror the functions exported from `@smart-cloud/ai-kit-core`.

### Shared options (`FeatureOptions`)

- `context`: `"admin" | "frontend"` (defaults to `"admin"`; the front-end wrappers pass `"frontend"` automatically)
- `modeOverride`: force a one-off capability mode — `"local-only" | "backend-fallback" | "backend-only"`
- `onDeviceTimeoutOverride`: override the default 45 s (or 5 s for quick features) on-device timeout when using Chrome APIs
- `signal`, `headers`, `query`: forwarded to the backend dispatcher
- `onStatus(event)`: receive progress steps such as `decide`, `on-device:download`, `backend:request`, `done`
- Feature-specific extras may be read from the same object (for example `maxCandidates` for backend language detection)

### Methods

**`write(args, options?)`** → `{ result: string }`
- `args`: `{ prompt, context?, sharedContext?, tone?, format?, length?, outputLanguage? }`
- Backend calls also honour `knowledgeBaseId` / `disableKB`

**`rewrite(args, options?)`** → `{ result: string }`
- `args`: `{ text, context?, sharedContext?, tone?, format?, length?, outputLanguage? }`

**`summarize(args, options?)`** → `{ result: string }`
- `args`: `{ text, context?, sharedContext?, type?, format?, length?, outputLanguage? }`

**`translate(args, options?)`** → `{ result: string }`
- `args`: `{ text, sourceLanguage, targetLanguage }`

**`detectLanguage(args, options?)`** → `{ result: { candidates: LanguageDetectionResult[] } }`
- `args`: `{ text }`
- For backend-only flows you can add `options.maxCandidates`

**`proofread(args, options?)`** → `{ result: ProofreadResult }`
- `args`: `{ text, expectedInputLanguages?, includeCorrectionTypes?, includeCorrectionExplanations?, correctionExplanationLanguage? }`

**`prompt(args, options?)`** → `{ result: string, sessionId?, metadata? }`
- `args`: `{ messages, sharedContext?, outputLanguage?, images?, responseConstraint?, topK?, temperature?, maxTokens?, knowledgeBaseId?, disableKB? }`
- `metadata.stopReason === "max_tokens"` means the model hit the output cap; `metadata.maxTokens` shows the applied backend limit.

**`sendChatMessage(args, options?)`** → `{ result: string, sessionId?, metadata? }`
- `args`: `{ sessionId?, message, sharedContext?, images?, topK?, temperature?, maxTokens?, knowledgeBaseId?, disableKB? }`
- Saves chat history automatically when `sessionId` is omitted

**`sendFeedbackMessage(args, options?)`** → `{ result: string, sessionId?, metadata? }`
- `args`: `{ feedbackType: "accepted" | "rejected", feedbackMessageId, sessionId }`

**`sendSearchMessage(args, options?)`** → `{ result: string, sessionId?, citations?, metadata? }`
- `args`: `{ query, sessionId?, sharedContext?, knowledgeBaseId?, topK?, temperature?, maxTokens? }`
- Returns a short answer/summary in `result` plus optional `citations` (`docs` + `chunks`) when available.


### Feature option helpers

When you need the raw Chrome API `create()` options (for example to pre-cache models), use:

- `getWriteOptions(partialArgs)` / `getRewriteOptions(partialArgs)`
- `getSummarizeOptions(partialArgs)` / `getTranslateOptions(partialArgs)`
- `getProofreadOptions()` / `getPromptOptions(partialArgs)`

Each helper returns the corresponding `*CreateCoreOptions` structure from Chrome’s built-in AI APIs.

### Example: translate a string

```js
const f = globalThis.WpSuite?.plugins?.aiKit?.features;
if (!f) return;

const { result } = await f.translate({
  text: "Hello world",
  sourceLanguage: "en",
  targetLanguage: "de",
});

console.log(result);
```

### Example: summarize current content (with progress)

```js
const aiKit = globalThis.WpSuite?.plugins?.aiKit;
const f = aiKit?.features;
if (!aiKit || !f) return;

const ok = (await aiKit.availability?.()) === "available";
if (!ok) return;

const { result } = await f.summarize(
  { text: "Long article text...", type: "tldr", length: "short" },
  {
    onStatus: (ev) => {
      // ev.step: "decide" | "on-device:download" | "backend:request" | ...
      console.log(ev.step, ev.progress);
    },
  },
);

console.log(result);
```

---

## UI injection (renderFeature)

For custom themes/plugins, AI‑Kit can render its **interactive UI** into a target element:

- `WpSuite.plugins.aiKit.features.renderFeature(args)` → returns an `AiWorkerHandle`

This is how the **AI‑Kit Feature block / shortcode** can create UI on the front-end.

### Minimal example: render a modal translate UI

```js
const f = globalThis.WpSuite?.plugins?.aiKit?.features;
if (!f) return;

let handle;
handle = await f.renderFeature({
  mode: "translate",
  title: "Translate",
  variation: "modal",
  onClose: () => handle?.close?.(),
  autoRun: false,
  default: {
    text: "Hello world",
    inputLanguage: "en",
    outputLanguage: "de",
  },
});
```

### Cleaning up

The returned handle typically includes:

- `container` — the root element
- `close()` — close the UI (if applicable)
- `unmount()` — unmount + cleanup


---

## UI injection (Doc Search)

For custom themes/plugins, AI‑Kit can also render the **Doc Search** UI into a target element:

- `WpSuite.plugins.aiKit.features.renderSearchComponent(args)` → returns an `AiWorkerHandle`

This is what the **AI‑Kit Doc Search block / shortcode** uses on the front-end.

### Minimal example: render Doc Search into a container

```js
const f = globalThis.WpSuite?.plugins?.aiKit?.features;
if (!f) return;

let handle;
handle = await f.renderSearchComponent({
  target: "#doc-search",
  title: "Search docs",
  autoRun: false,
  topK: 10,
  snippetMaxChars: 160,
});
```

---

## Store access (advanced)

AI‑Kit exposes a lazily created store:

- `WpSuite.plugins.aiKit.features.store` → `Promise<Store>`

This is useful if you build custom UI and want to observe settings/diagnostics.

```js
const storePromise = globalThis.WpSuite?.plugins?.aiKit?.features?.store;
const store = storePromise ? await storePromise : null;
```
