# AI (/docs/pro/api/ai)



This page documents `@luxalgo/vela-pro-ai`, including the `ai()` plugin factory, `AiChatWidget` and `createAiChat`, `createAiHelpers`, `AI_HELPER_SCHEMAS`, and the message and chart-surface types.

Import symbols on this page from `@luxalgo/vela-pro-ai`. Related guides: [AI](/docs/pro/modules/catalog/ai), [Standalone widgets](/docs/pro/modules/widgets).

## Functions [#functions]

### `ai` [#ai]

The AI module as a Vela Pro plugin.

```typescript
function ai(opts: EnableAiOptions): VelaProPlugin<AiApi>
```

See also: [`AiApi`](/docs/pro/api/ai#aiapi-interface), [`EnableAiOptions`](/docs/pro/api/ai#enableaioptions), [`VelaProPlugin`](/docs/pro/api/module-sdk#velaproplugin).

### `aiApi` [#aiapi]

The page's AI API, once [`enableAi`](/docs/pro/api/ai#enableai) or [`ai()`](/docs/pro/api/ai#ai) installed.

```typescript
function aiApi(): AiApi | null
```

See also: [`AiApi`](/docs/pro/api/ai#aiapi-interface).

### `aiSurface` [#aisurface]

The helpers' surface over the shell `ctx` belongs to. It reads the shell's charts afresh at every call, so it stays right across layout changes.

```typescript
function aiSurface(ctx: WidgetContext): AiSurface
```

See also: [`AiSurface`](/docs/pro/api/ai#aisurface-interface). From `@luxalgo/vela/plugin`: `WidgetContext`.

### `chartAt` [#chartat]

The chart a call targets: the one at `slot`, or the active one. A string says why there is none.

```typescript
function chartAt(surface: AiSurface, slot: unknown): AiChartRef | string
```

See also: [`AiChartRef`](/docs/pro/api/ai#aichartref), [`AiSurface`](/docs/pro/api/ai#aisurface-interface).

### `createAiChat` [#createaichat]

The AI chat: the conversation, the suggestions and the prompt. Returns `{ el, tools, update, submit, focus, destroy }`.

```typescript
function createAiChat(props: AiChatProps): AiChatWidget
```

See also: [`AiChatProps`](/docs/pro/api/ai#aichatprops), [`AiChatWidget`](/docs/pro/api/ai#aichatwidget).

### `createAiHelpers` [#createaihelpers]

The helpers over `surface`.

```typescript
function createAiHelpers(surface: AiSurface, options?: AiHelpersOptions): AiHelpers
```

See also: [`AiHelpers`](/docs/pro/api/ai#aihelpers), [`AiHelpersOptions`](/docs/pro/api/ai#aihelpersoptions), [`AiSurface`](/docs/pro/api/ai#aisurface-interface).

### `enableAi` [#enableai]

Enable the AI side panel on every shell built afterwards. Returns the page's [`AiApi`](/docs/pro/api/ai#aiapi-interface). Call ONCE, before constructing shells. Idempotent.

```typescript
function enableAi(opts: EnableAiOptions): AiApi
```

See also: [`AiApi`](/docs/pro/api/ai#aiapi-interface), [`EnableAiOptions`](/docs/pro/api/ai#enableaioptions).

### `normalizeTimeframe` [#normalizetimeframe]

A timeframe as a person writes it, as the chart takes it: minutes are bare numbers (`"15m"` → `"15"`, `"4h"` → `"240"`), longer units are letters (`"1D"` → `"D"`, `"2W"`, `"1M"` → `"M"`). Lowercase `m` is minutes and uppercase `M` months. Null for anything else, seconds included.

```typescript
function normalizeTimeframe(input: string): string | null
```

### `outcomeErrorText` [#outcomeerrortext]

A failed outcome's error with what the helper said about it, as lines.

```typescript
function outcomeErrorText(outcome: Extract<AiOutcome, { ok: false }>): string
```

See also: [`AiOutcome`](/docs/pro/api/ai#aioutcome).

### `registerAiNative` [#registerainative]

Register the bars native. Idempotent; call before charts are built or after, a chart adds it on its first read.

```typescript
function registerAiNative(): void
```

### `schemaProblems` [#schemaproblems]

Why `value` does not fit `schema`, one sentence per problem; empty when it fits.

```typescript
function schemaProblems(schema: JsonSchema, value: unknown, path?: string): string[]
```

Default: `path = 'input'`.

See also: [`JsonSchema`](/docs/pro/api/ai#jsonschema).

## Classes [#classes]

### `AiChatWidget` [#aichatwidget]

```typescript
class AiChatWidget {
    constructor(props: AiChatProps);
    readonly el: HTMLElement;
    readonly tools: HTMLElement;
    readonly status: AiChatStatus;
    readonly busy: boolean;
    readonly model: string | undefined;
    update(next: AiChatState & Partial<Pick<AiChatProps, 'suggestions' | 'models'>>): void;
    submit(text: string): void;
    setModel(id: string): void;
    focus(): void;
    destroy(): void;
}
```

| Member        | Type                                                                                  | Description                                                                                                |
| ------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `constructor` | `(props: AiChatProps)`                                                                |                                                                                                            |
| `el`          | `HTMLElement`                                                                         |                                                                                                            |
| `tools`       | `HTMLElement`                                                                         | Compact controls (new chat): in the widget's top row until lifted into a panel header.                     |
| `status`      | `AiChatStatus`                                                                        | Where the conversation stands: as last given, or `streaming` while a call of the last reply has no result. |
| `busy`        | `boolean`                                                                             | Whether a reply is on its way.                                                                             |
| `model`       | `string \| undefined`                                                                 | The id of the model picked; undefined when no model is listed.                                             |
| `update()`    | `(next: AiChatState & Partial<Pick<AiChatProps, 'suggestions' \| 'models'>>) => void` | Draw the conversation as it now stands, and take new suggestions or models. Only the fields given change.  |
| `submit()`    | `(text: string) => void`                                                              | Send `text` as if the user had typed it. Ignored while a reply is on its way.                              |
| `setModel()`  | `(id: string) => void`                                                                | Show `id` as the model picked. Ignored for a model the picker does not list.                               |
| `focus()`     | `() => void`                                                                          | Put the caret in the prompt.                                                                               |
| `destroy()`   | `() => void`                                                                          |                                                                                                            |

See also: [`AiChatProps`](/docs/pro/api/ai#aichatprops), [`AiChatState`](/docs/pro/api/ai#aichatstate), [`AiChatStatus`](/docs/pro/api/ai#aichatstatus).

## Interfaces and types [#interfaces-and-types]

### `AddIndicatorInput` [#addindicatorinput]

```typescript
interface AddIndicatorInput extends OnChart {
    type?: string;
    inputs?: Readonly<Record<string, AiInputValue>>;
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
```

| Member    | Type                                     | Description                                                                    |
| --------- | ---------------------------------------- | ------------------------------------------------------------------------------ |
| `type?`   | `string`                                 | The built-in type to add. Absent: the helper lists the types the chart offers. |
| `inputs?` | `Readonly<Record<string, AiInputValue>>` | Settings to start it with, by input key or title.                              |

See also: [`AiInputValue`](/docs/pro/api/ai#aiinputvalue).

### `AiApi` interface [#aiapi-interface]

What the AI plugin offers the host and other plugins.

```typescript
interface AiApi {
    helpers(ctx?: WidgetContext): AiHelpers | null;
    chat(ctx?: WidgetContext): AiChatWidget | null;
    ask(ctx: WidgetContext, text?: string): void;
}
```

| Member      | Type                                            | Description                                                                                                                                                                                                    |
| ----------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `helpers()` | `(ctx?: WidgetContext) => AiHelpers \| null`    | The helpers over `ctx`'s shell, or over the shell built last; null without `ctx` before a shell is built. The same ones `connect` was given, so the host's code and its tools queue their changes in one line. |
| `chat()`    | `(ctx?: WidgetContext) => AiChatWidget \| null` | The chat of `ctx`'s shell, or of the shell built last; null before its panel is built.                                                                                                                         |
| `ask()`     | `(ctx: WidgetContext, text?: string) => void`   | Open the AI panel on `ctx`'s shell and, given `text`, send it as the user's message.                                                                                                                           |

See also: [`AiChatWidget`](/docs/pro/api/ai#aichatwidget), [`AiHelpers`](/docs/pro/api/ai#aihelpers). From `@luxalgo/vela/plugin`: `WidgetContext`.

### `AiBar` [#aibar]

```typescript
interface AiBar {
    readonly time: number;
    readonly open: number;
    readonly high: number;
    readonly low: number;
    readonly close: number;
    readonly volume?: number;
}
```

### `AiCallOptions` [#aicalloptions]

```typescript
interface AiCallOptions {
    signal?: AbortSignal;
}
```

| Member    | Type          | Description                                                               |
| --------- | ------------- | ------------------------------------------------------------------------- |
| `signal?` | `AbortSignal` | Aborted when the user stops the reply: a helper that waits stops waiting. |

### `AiChart` [#aichart]

The part of a Vela chart the helpers use.

```typescript
interface AiChart {
    readonly market: { readonly symbol?: string; readonly timeframe?: string; readonly session?: AiMarketSession };
    setMarket(next: { symbol?: string; timeframe?: string; session?: AiMarketSession; visibleRange?: AiRangePreset | { from: number; to: number } }): Promise<unknown>;
    ready(): Promise<unknown>;
    indicators(): readonly AiIndicator[];
    runIndicator(
        source: string,
        options?: { language?: string },
    ): Promise<{ ok: boolean; handle: AiIndicator | null; error: Error | null }>;
    addNativeIndicator(type: string, options?: { inputs?: Record<string, AiInputValue> }): AiIndicator;
    availableNativeIndicators(): Promise<ReadonlyArray<{ readonly type: string; readonly title: string; readonly supported: boolean; readonly present: boolean }>>;
    getVisibleRange(): { from: number; to: number } | null;
    setVisibleRange(range: { from: number; to: number }): unknown;
    setVisibleRangePreset(preset: AiRangePreset): unknown;
    readonly renderer: {
        supports(feature: string): boolean;
        get(feature: string): unknown;
        set(feature: string, value: unknown): unknown;
        screenshot(): string | null;
    };
    readonly data: {
        resolve(symbol: string): { provider: string; ticker: string } | null;
        ready(): Promise<unknown>;
        symbolInfo(symbol: string): Promise<unknown>;
    };
    readonly drawings: AiDrawings;
    readonly replay: { readonly state: { readonly active: boolean } };
}
```

| Member                        | Type                                                                                                          | Description                                                                              |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| `market`                      | `{ readonly symbol?: string; readonly timeframe?: string; readonly session?: AiMarketSession }`               |                                                                                          |
| `setMarket()`                 | `(next: { symbol?: string; timeframe?: string; session?: AiMarketSession; …` (truncated; see declaration)     |                                                                                          |
| `ready()`                     | `() => Promise<unknown>`                                                                                      |                                                                                          |
| `indicators()`                | `() => readonly AiIndicator[]`                                                                                |                                                                                          |
| `runIndicator()`              | `(source: string, options?: { language?: string }) => Promise<{ ok: boolean; …` (truncated; see declaration)  |                                                                                          |
| `addNativeIndicator()`        | `(type: string, options?: { inputs?: Record<string, AiInputValue> }) => AiIndicator`                          |                                                                                          |
| `availableNativeIndicators()` | `() => Promise<ReadonlyArray<{ readonly type: string; readonly title: string; …` (truncated; see declaration) |                                                                                          |
| `getVisibleRange()`           | `() => { from: number; to: number } \| null`                                                                  |                                                                                          |
| `setVisibleRange()`           | `(range: { from: number; to: number }) => unknown`                                                            |                                                                                          |
| `setVisibleRangePreset()`     | `(preset: AiRangePreset) => unknown`                                                                          |                                                                                          |
| `renderer`                    | `{ supports(feature: string): boolean; get(feature: string): unknown; …` (truncated; see declaration)         |                                                                                          |
| `data`                        | `{ resolve(symbol: string): { provider: string; ticker: string } \| null; …` (truncated; see declaration)     |                                                                                          |
| `drawings`                    | `AiDrawings`                                                                                                  |                                                                                          |
| `replay`                      | `{ readonly state: { readonly active: boolean } }`                                                            | Bar replay: while it runs, the chart's last bar is the replay's cursor, not the present. |

See also: [`AiDrawings`](/docs/pro/api/ai#aidrawings), [`AiIndicator`](/docs/pro/api/ai#aiindicator), [`AiInputValue`](/docs/pro/api/ai#aiinputvalue), [`AiMarketSession`](/docs/pro/api/ai#aimarketsession), [`AiRangePreset`](/docs/pro/api/ai#airangepreset).

### `AiChartRef` [#aichartref]

One chart of the shell: `slot` is its place in the layout, 0 first, in reading order.

```typescript
interface AiChartRef {
    readonly slot: number;
    readonly chart: AiChart;
}
```

See also: [`AiChart`](/docs/pro/api/ai#aichart).

### `AiChatHandlers` [#aichathandlers]

What the host's code does when the user acts on the chat.

```typescript
interface AiChatHandlers {
    onSubmit(message: AiChatSubmission): void | Promise<unknown>;
    onStop?(): void;
    onNewChat?(): void;
    destroy?(): void;
}
```

| Member         | Type                                                      | Description                                                                                                                 |
| -------------- | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `onSubmit()`   | `(message: AiChatSubmission) => void \| Promise<unknown>` | The user sent a message: add it to the conversation and ask the model. A rejected promise puts the text back in the prompt. |
| `onStop?()`    | `() => void`                                              | The user pressed stop while a reply was on its way.                                                                         |
| `onNewChat?()` | `() => void`                                              | The user asked for a new conversation. Without it there is no New chat button.                                              |
| `destroy?()`   | `() => void`                                              | The panel is going away with its shell.                                                                                     |

See also: [`AiChatSubmission`](/docs/pro/api/ai#aichatsubmission).

### `AiChatMessage` [#aichatmessage]

One message of the conversation, as the chat draws it.

```typescript
interface AiChatMessage {
    readonly id: string;
    readonly role: 'system' | 'user' | 'assistant';
    readonly parts: readonly AiChatPart[];
}
```

| Member  | Type                                | Description                                                      |
| ------- | ----------------------------------- | ---------------------------------------------------------------- |
| `id`    | `string`                            | Stable for the message's life: the chat follows a message by it. |
| `role`  | `'system' \| 'user' \| 'assistant'` |                                                                  |
| `parts` | `readonly AiChatPart[]`             |                                                                  |

See also: [`AiChatPart`](/docs/pro/api/ai#aichatpart).

### `AiChatPart` [#aichatpart]

One part of a message. The shapes are those of the AI SDK's `UIMessage` parts, so a conversation it keeps is drawn as it is. A part the chat does not know (a step boundary, a data part) draws nothing unless the host's `renderPart` draws it.

```typescript
type AiChatPart =
    | AiTextPart
    | AiReasoningPart
    | AiToolPart
    | AiFilePart
    | AiSourcePart
    | { readonly type: string; readonly [key: string]: unknown };
```

See also: [`AiFilePart`](/docs/pro/api/ai#aifilepart), [`AiReasoningPart`](/docs/pro/api/ai#aireasoningpart), [`AiSourcePart`](/docs/pro/api/ai#aisourcepart), [`AiTextPart`](/docs/pro/api/ai#aitextpart), [`AiToolPart`](/docs/pro/api/ai#aitoolpart).

### `AiChatProps` [#aichatprops]

The chat widget's props. The callbacks and `host` are read once; the state, the suggestions and the models can change through `update`.

```typescript
interface AiChatProps extends AiChatState {
    onSubmit: (message: AiChatSubmission) => void | Promise<unknown>;
    onStop?: () => void;
    onNewChat?: () => void;
    host?: HTMLElement;
    title?: string;
    description?: string;
    suggestions?: readonly string[];
    placeholder?: string;
    highlight?: AiCodeHighlighter;
    models?: readonly AiModel[];
    model?: string;
    modelLogo?: (key: string) => string | Node | null | undefined;
    onModelChange?: (id: string) => void;
    promptTools?: HTMLElement;
    renderPart?: (part: AiChatPart, message: AiChatMessage) => Node | null | undefined;
}
```

| Member           | Type                                                                      | Description                                                                                                                                                                                               |
| ---------------- | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `onSubmit`       | `(message: AiChatSubmission) => void \| Promise<unknown>`                 | The user sent a message. The host adds it to its conversation and asks its model. When the promise it returns rejects, the text goes back into the prompt.                                                |
| `onStop?`        | `() => void`                                                              | The user pressed stop while a reply was on its way.                                                                                                                                                       |
| `onNewChat?`     | `() => void`                                                              | The user asked for a new conversation. Without it there is no New chat button.                                                                                                                            |
| `host?`          | `HTMLElement`                                                             | Where tooltips mount (default: the widget's own element).                                                                                                                                                 |
| `title?`         | `string`                                                                  | What an empty conversation says.                                                                                                                                                                          |
| `description?`   | `string`                                                                  |                                                                                                                                                                                                           |
| `suggestions?`   | `readonly string[]`                                                       | Prompts offered above the input while the conversation is empty; a press sends one.                                                                                                                       |
| `placeholder?`   | `string`                                                                  |                                                                                                                                                                                                           |
| `highlight?`     | `AiCodeHighlighter`                                                       | Highlights the code blocks of a reply; the kit ships no highlighter.                                                                                                                                      |
| `models?`        | `readonly AiModel[]`                                                      | The models the user can pick from. With any, a picker sits in the prompt's footer and `model` is the id picked: the host names it in its requests. Without any, there is no picker.                       |
| `model?`         | `string`                                                                  | The id of the model picked to start with (default: the first of `models`).                                                                                                                                |
| `modelLogo?`     | `(key: string) => string \| Node \| null \| undefined`                    | The logo of a model's maker or of a service, by its key: an address, an element, or null for the key's initial.                                                                                           |
| `onModelChange?` | `(id: string) => void`                                                    | The user picked a model.                                                                                                                                                                                  |
| `promptTools?`   | `HTMLElement`                                                             | A control of the host's in the prompt's footer, after the model picker.                                                                                                                                   |
| `renderPart?`    | `(part: AiChatPart, message: AiChatMessage) => Node \| null \| undefined` | Draw a part of a message yourself: a data part, a tool call with a card of its own. Return a node to draw it, null to draw nothing, undefined to leave it to the chat. Asked again when the part changes. |

See also: [`AiChatMessage`](/docs/pro/api/ai#aichatmessage), [`AiChatPart`](/docs/pro/api/ai#aichatpart), [`AiChatState`](/docs/pro/api/ai#aichatstate), [`AiChatSubmission`](/docs/pro/api/ai#aichatsubmission), [`AiModel`](/docs/pro/api/ai#aimodel). From `@luxalgo/vela-ui/ai-code-block`: `AiCodeHighlighter`.

### `AiChatState` [#aichatstate]

What the chat draws: the host's conversation as it stands.

```typescript
interface AiChatState {
    messages?: readonly AiChatMessage[];
    status?: AiChatStatus;
    error?: Error | string | null;
}
```

| Member      | Type                       | Description                                                                                                                                                                                                        |
| ----------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `messages?` | `readonly AiChatMessage[]` | The conversation, oldest first. Replace a message that changed, or change the last one in place.                                                                                                                   |
| `status?`   | `AiChatStatus`             | Where the conversation stands (default `ready`). While the last reply has a tool call without a result, the chat counts a `ready` conversation as still streaming: the prompt shows stop, and nothing can be sent. |
| `error?`    | `Error \| string \| null`  | Why the last request failed, shown under the conversation.                                                                                                                                                         |

See also: [`AiChatMessage`](/docs/pro/api/ai#aichatmessage), [`AiChatStatus`](/docs/pro/api/ai#aichatstatus).

### `AiChatStatus` [#aichatstatus]

Where the conversation stands: `submitted` once a message is sent and nothing has come back, `streaming` while the reply arrives, `error` when the last request failed.

```typescript
type AiChatStatus = 'ready' | 'submitted' | 'streaming' | 'error';
```

### `AiChatSubmission` [#aichatsubmission]

What the user sent from the prompt, or picked among the suggestions.

```typescript
interface AiChatSubmission {
    text: string;
}
```

### `AiChatView` [#aichatview]

A shell's chat, as the host's code drives it.

```typescript
interface AiChatView {
    update(state: AiChatState): void;
    readonly model: string | undefined;
    focus(): void;
}
```

| Member     | Type                           | Description                                                                                                |
| ---------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------- |
| `update()` | `(state: AiChatState) => void` | Draw the conversation as it now stands: its messages, its status, its error. Only the fields given change. |
| `model`    | `string \| undefined`          | The id of the model the user picked; undefined when no model is listed.                                    |
| `focus()`  | `() => void`                   | Put the caret in the prompt.                                                                               |

See also: [`AiChatState`](/docs/pro/api/ai#aichatstate).

### `AiDrawingGroup` [#aidrawinggroup]

A named bundle of drawings: what the chart's object tree lists as one.

```typescript
interface AiDrawingGroup {
    id: string;
    name: string;
    ids: string[];
    pane?: string;
}
```

### `AiDrawingInit` [#aidrawinginit]

A drawing as a helper asks a chart to add it.

```typescript
interface AiDrawingInit {
    anchors?: Array<{ time: number; price: number }>;
    style?: Record<string, unknown>;
    text?: {
        value: string;
        size: 'small';
        hAlign: 'left' | 'center' | 'right';
        vAlign: 'top' | 'center' | 'bottom';
        color?: string;
        place?: 'start' | 'middle' | 'end';
        side?: 'above' | 'below';
    };
    props?: Record<string, unknown>;
}
```

### `AiDrawings` [#aidrawings]

The part of a chart's drawings the helpers use.

```typescript
interface AiDrawings {
    readonly supported: boolean;
    add(type: string, init?: AiDrawingInit): { readonly id: string } | null;
    removeMany(ids: readonly string[]): unknown;
    lock(id: string, locked?: boolean): unknown;
    bringToFront(id: string): unknown;
    groups(): AiDrawingGroup[];
    setGroups(groups: readonly AiDrawingGroup[]): unknown;
    toolDefaults(): Readonly<Record<string, unknown>>;
    setToolDefaults(map: Readonly<Record<string, unknown>>): unknown;
}
```

| Member              | Type                                                                      | Description                                                         |
| ------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| `supported`         | `boolean`                                                                 | Whether the chart can paint drawings at all.                        |
| `add()`             | `(type: string, init?: AiDrawingInit) => { readonly id: string } \| null` | Null when the chart could not make the drawing.                     |
| `removeMany()`      | `(ids: readonly string[]) => unknown`                                     |                                                                     |
| `lock()`            | `(id: string, locked?: boolean) => unknown`                               |                                                                     |
| `bringToFront()`    | `(id: string) => unknown`                                                 |                                                                     |
| `groups()`          | `() => AiDrawingGroup[]`                                                  |                                                                     |
| `setGroups()`       | `(groups: readonly AiDrawingGroup[]) => unknown`                          |                                                                     |
| `toolDefaults()`    | `() => Readonly<Record<string, unknown>>`                                 | Each tool's remembered settings: what its next drawing starts from. |
| `setToolDefaults()` | `(map: Readonly<Record<string, unknown>>) => unknown`                     |                                                                     |

See also: [`AiDrawingGroup`](/docs/pro/api/ai#aidrawinggroup), [`AiDrawingInit`](/docs/pro/api/ai#aidrawinginit).

### `AiFilePart` [#aifilepart]

A file of a message; an image is drawn.

```typescript
interface AiFilePart {
    readonly type: 'file';
    readonly mediaType: string;
    readonly url: string;
    readonly filename?: string;
}
```

| Member      | Type     | Description               |
| ----------- | -------- | ------------------------- |
| `type`      | `'file'` |                           |
| `mediaType` | `string` |                           |
| `url`       | `string` | A data URL or an address. |
| `filename?` | `string` |                           |

### `AiHelperName` [#aihelpername]

```typescript
type AiHelperName = keyof typeof SPECS;
```

### `AiHelpers` [#aihelpers]

The helpers over one chart shell. Each one checks its input against its schema and answers with an [`AiOutcome`](/docs/pro/api/ai#aioutcome); none throws. A refusal and a failure come back as `{ ok: false, error }`, with the error written for a model to act on. Helpers that change the chart run one at a time, in the order they were called, and a helper that reads runs after the changes asked before it.

```typescript
interface AiHelpers {
    readChart(): Promise<AiOutcome>;
    setChartState(input: SetChartStateInput, options?: AiCallOptions): Promise<AiOutcome>;
    captureChartScreenshot(
        input?: CaptureChartScreenshotInput,
        options?: AiCallOptions,
    ): Promise<AiOutcome>;
    readChartData(input: ReadChartDataInput, options?: AiCallOptions): Promise<AiOutcome>;
    writeScript(input: WriteScriptInput, options?: AiCallOptions): Promise<AiOutcome>;
    editScript(input: EditScriptInput, options?: AiCallOptions): Promise<AiOutcome>;
    readScript(input: ReadScriptInput, options?: AiCallOptions): Promise<AiOutcome>;
    removeScript(input: RemoveScriptInput, options?: AiCallOptions): Promise<AiOutcome>;
    setScriptInputs(input: SetScriptInputsInput, options?: AiCallOptions): Promise<AiOutcome>;
    addIndicator(input?: AddIndicatorInput, options?: AiCallOptions): Promise<AiOutcome>;
    markUpChart(input: MarkUpChartInput, options?: AiCallOptions): Promise<AiOutcome>;
    run(name: AiHelperName, input: unknown, options?: AiCallOptions): Promise<AiOutcome>;
    describe(): AiWorkspace;
}
```

| Member                     | Type                                                                                   | Description                                                                                                                   |
| -------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `readChart()`              | `() => Promise<AiOutcome>`                                                             | What the charts show: each chart's market, chart type, scale, visible range and indicators, with their ids.                   |
| `setChartState()`          | `(input: SetChartStateInput, options?: AiCallOptions) => Promise<AiOutcome>`           | Change a chart's symbol, timeframe, chart type, session, scale or visible range, and wait for the chart to show it.           |
| `captureChartScreenshot()` | `(input?: CaptureChartScreenshotInput, options?: AiCallOptions) => Promise<AiOutcome>` | Capture a chart as an image: the outcome carries it in `images`.                                                              |
| `readChartData()`          | `(input: ReadChartDataInput, options?: AiCallOptions) => Promise<AiOutcome>`           | Read exact values: price bars, a script's plots, a strategy's trades, an indicator's settings, the window in view.            |
| `writeScript()`            | `(input: WriteScriptInput, options?: AiCallOptions) => Promise<AiOutcome>`             | Add a script to the chart, or replace the whole code of one in place. A script the engine refuses leaves the chart as it was. |
| `editScript()`             | `(input: EditScriptInput, options?: AiCallOptions) => Promise<AiOutcome>`              | Change one script with an exact string replacement.                                                                           |
| `readScript()`             | `(input: ReadScriptInput, options?: AiCallOptions) => Promise<AiOutcome>`              | Read a script's code, with line numbers.                                                                                      |
| `removeScript()`           | `(input: RemoveScriptInput, options?: AiCallOptions) => Promise<AiOutcome>`            | Remove one script or built-in indicator from the chart.                                                                       |
| `setScriptInputs()`        | `(input: SetScriptInputsInput, options?: AiCallOptions) => Promise<AiOutcome>`         | Change an indicator's settings, as its settings dialog would.                                                                 |
| `addIndicator()`           | `(input?: AddIndicatorInput, options?: AiCallOptions) => Promise<AiOutcome>`           | Add one of the chart's built-in indicators, or list the ones it offers.                                                       |
| `markUpChart()`            | `(input: MarkUpChartInput, options?: AiCallOptions) => Promise<AiOutcome>`             | Mark the chart up from its own bars (fair value gaps, liquidity, key levels…), as drawings grouped per concept.               |
| `run()`                    | `(name: AiHelperName, input: unknown, options?: AiCallOptions) => Promise<AiOutcome>`  | Run a helper by its name, with an input of unknown shape: what a model sent.                                                  |
| `describe()`               | `() => AiWorkspace`                                                                    | What the charts show now, without a call: what `readChart` answers with, for a host that tells its model with each request.   |

See also: [`AddIndicatorInput`](/docs/pro/api/ai#addindicatorinput), [`AiCallOptions`](/docs/pro/api/ai#aicalloptions), [`AiHelperName`](/docs/pro/api/ai#aihelpername), [`AiOutcome`](/docs/pro/api/ai#aioutcome), [`AiWorkspace`](/docs/pro/api/ai#aiworkspace), [`CaptureChartScreenshotInput`](/docs/pro/api/ai#capturechartscreenshotinput), [`EditScriptInput`](/docs/pro/api/ai#editscriptinput), [`MarkUpChartInput`](/docs/pro/api/ai#markupchartinput), [`ReadChartDataInput`](/docs/pro/api/ai#readchartdatainput), [`ReadScriptInput`](/docs/pro/api/ai#readscriptinput), [`RemoveScriptInput`](/docs/pro/api/ai#removescriptinput), [`SetChartStateInput`](/docs/pro/api/ai#setchartstateinput), [`SetScriptInputsInput`](/docs/pro/api/ai#setscriptinputsinput), [`WriteScriptInput`](/docs/pro/api/ai#writescriptinput).

### `AiHelpersOptions` [#aihelpersoptions]

```typescript
interface AiHelpersOptions {
    language?: string;
}
```

| Member      | Type     | Description                                                                      |
| ----------- | -------- | -------------------------------------------------------------------------------- |
| `language?` | `string` | The key of the engine scripts are written for, and read from (default `'pine'`). |

### `AiImage` [#aiimage]

An image a helper hands back for the model to look at (a chart screenshot).

```typescript
interface AiImage {
    mediaType: string;
    dataUrl: string;
    alt: string;
}
```

| Member      | Type     | Description                                                               |
| ----------- | -------- | ------------------------------------------------------------------------- |
| `mediaType` | `string` |                                                                           |
| `dataUrl`   | `string` | `data:image/png;base64,…`                                                 |
| `alt`       | `string` | What the image shows, for a model or a client that cannot take the image. |

### `AiIndicator` [#aiindicator]

An indicator or a strategy on a chart: a script, or a built-in.

```typescript
interface AiIndicator {
    readonly id: string;
    readonly title: string;
    readonly source?: string;
    readonly nativeType?: string;
    readonly language?: string;
    readonly inputs: readonly AiInputSchema[];
    readonly visible: boolean;
    inputValues(): Record<string, AiInputValue>;
    setInputs(values: Record<string, AiInputValue>): void;
    updateCode(source: string): Promise<{ ok: boolean; error: Error | null }>;
    context(select?: ReadonlyArray<'plots' | 'meta' | 'strategy' | 'trades'>): Promise<AiScriptContext | null>;
    remove(): void;
}
```

| Member          | Type                                                                                                        | Description                               |
| --------------- | ----------------------------------------------------------------------------------------------------------- | ----------------------------------------- |
| `id`            | `string`                                                                                                    |                                           |
| `title`         | `string`                                                                                                    |                                           |
| `source?`       | `string`                                                                                                    | A script's code; absent for a built-in.   |
| `nativeType?`   | `string`                                                                                                    | A built-in's type; absent for a script.   |
| `language?`     | `string`                                                                                                    | The key of the engine that runs a script. |
| `inputs`        | `readonly AiInputSchema[]`                                                                                  |                                           |
| `visible`       | `boolean`                                                                                                   |                                           |
| `inputValues()` | `() => Record<string, AiInputValue>`                                                                        |                                           |
| `setInputs()`   | `(values: Record<string, AiInputValue>) => void`                                                            |                                           |
| `updateCode()`  | `(source: string) => Promise<{ ok: boolean; error: Error \| null }>`                                        |                                           |
| `context()`     | `(select?: ReadonlyArray<'plots' \| 'meta' \| 'strategy' \| 'trades'>) => Promise<AiScriptContext \| null>` |                                           |
| `remove()`      | `() => void`                                                                                                |                                           |

See also: [`AiInputSchema`](/docs/pro/api/ai#aiinputschema), [`AiInputValue`](/docs/pro/api/ai#aiinputvalue), [`AiScriptContext`](/docs/pro/api/ai#aiscriptcontext).

### `AiInputSchema` [#aiinputschema]

One input a script or a built-in indicator declares.

```typescript
interface AiInputSchema {
    readonly key: string;
    readonly title: string;
    readonly type: string;
    readonly defval: AiInputValue;
    readonly min?: number;
    readonly max?: number;
    readonly step?: number;
    readonly options?: readonly string[];
}
```

See also: [`AiInputValue`](/docs/pro/api/ai#aiinputvalue).

### `AiInputValue` [#aiinputvalue]

```typescript
type AiInputValue = number | string | boolean;
```

### `AiMarketSession` [#aimarketsession]

```typescript
type AiMarketSession = 'regular' | 'extended';
```

### `AiModel` [#aimodel]

A model the user can pick: its `id` is what the host names it by.

```typescript
type AiModel = KitAiModel;
```

From `@luxalgo/vela-ui/ai-model-selector`: `KitAiModel`.

### `AiOutcome` [#aioutcome]

What a helper came to. `result` and `details` are plain JSON. A failed one is an answer too: its `error` is written for the model to act on.

```typescript
type AiOutcome =
    | { ok: true; result: unknown; images?: readonly AiImage[] }
    | { ok: false; error: string; details?: unknown };
```

See also: [`AiImage`](/docs/pro/api/ai#aiimage).

### `AiPanelContext` [#aipanelcontext]

What `connect` is given: one shell's chat, its helpers, and the shell itself.

```typescript
interface AiPanelContext {
    chat: AiChatView;
    helpers: AiHelpers;
    ctx: WidgetContext;
}
```

| Member    | Type            | Description                                                       |
| --------- | --------------- | ----------------------------------------------------------------- |
| `chat`    | `AiChatView`    |                                                                   |
| `helpers` | `AiHelpers`     | The helpers over this shell's charts: what the host's tools call. |
| `ctx`     | `WidgetContext` |                                                                   |

See also: [`AiChatView`](/docs/pro/api/ai#aichatview), [`AiHelpers`](/docs/pro/api/ai#aihelpers). From `@luxalgo/vela/plugin`: `WidgetContext`.

### `AiRangePreset` [#airangepreset]

```typescript
type AiRangePreset = '1D' | '1W' | '1M' | '3M' | '6M' | '1Y' | '5Y' | 'YTD' | 'ALL';
```

### `AiReasoningPart` [#aireasoningpart]

The model's reasoning, folded above what follows it.

```typescript
interface AiReasoningPart {
    readonly type: 'reasoning';
    readonly text: string;
    readonly state?: 'streaming' | 'done';
}
```

### `AiScriptContext` [#aiscriptcontext]

The part of a script's execution context the helpers read.

```typescript
interface AiScriptContext {
    readonly plots?: Readonly<Record<string, ReadonlyArray<{ readonly time: number; readonly value: unknown }>>>;
    readonly strategy?: Readonly<Record<string, unknown>> | object;
    readonly trades?: readonly AiStrategyTrade[];
}
```

See also: [`AiStrategyTrade`](/docs/pro/api/ai#aistrategytrade).

### `AiSourcePart` [#aisourcepart]

A page the reply drew on.

```typescript
interface AiSourcePart {
    readonly type: 'source-url';
    readonly url: string;
    readonly title?: string;
}
```

### `AiStrategyTrade` [#aistrategytrade]

```typescript
interface AiStrategyTrade {
    readonly id: string;
    readonly side: 'long' | 'short';
    readonly qty: number;
    readonly entry: { readonly time: number; readonly price: number };
    readonly exit?: { readonly time: number; readonly price: number };
    readonly open: boolean;
    readonly pnl?: number;
}
```

### `AiSurface` interface [#aisurface-interface]

The chart shell, as the helpers see it.

```typescript
interface AiSurface {
    charts(): AiChartRef[];
    activeSlot(): number | null;
    chartTypes?(): readonly string[];
    isInternal(indicator: AiIndicator): boolean;
    bars(chart: AiChart): Promise<readonly AiBar[]>;
    theme?(): 'light' | 'dark';
}
```

| Member          | Type                                            | Description                                                                                                 |
| --------------- | ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `charts()`      | `() => AiChartRef[]`                            | The charts, in layout order. Read afresh at each call: a layout change replaces them.                       |
| `activeSlot()`  | `() => number \| null`                          | The slot of the chart the user works on; null before one exists.                                            |
| `chartTypes?()` | `() => readonly string[]`                       | The chart types a plugin registered beside the built-in ones, when the shell can say.                       |
| `isInternal()`  | `(indicator: AiIndicator) => boolean`           | An indicator a plugin keeps on the chart for its own use: never listed, read or removed.                    |
| `bars()`        | `(chart: AiChart) => Promise<readonly AiBar[]>` | The chart's bars, oldest first. Rejects when the chart cannot hand them over.                               |
| `theme?()`      | `() => 'light' \| 'dark'`                       | Whether the charts sit on a light or a dark background: drawings take colors that read on it. Default dark. |

See also: [`AiBar`](/docs/pro/api/ai#aibar), [`AiChart`](/docs/pro/api/ai#aichart), [`AiChartRef`](/docs/pro/api/ai#aichartref), [`AiIndicator`](/docs/pro/api/ai#aiindicator).

### `AiTextPart` [#aitextpart]

Text of a message. An assistant's is drawn as Markdown.

```typescript
interface AiTextPart {
    readonly type: 'text';
    readonly text: string;
    readonly state?: 'streaming' | 'done';
}
```

| Member   | Type                    | Description                                   |
| -------- | ----------------------- | --------------------------------------------- |
| `type`   | `'text'`                |                                               |
| `text`   | `string`                |                                               |
| `state?` | `'streaming' \| 'done'` | `streaming` while the text is still arriving. |

### `AiToolPart` [#aitoolpart]

One call of a tool: its name is in the type (`tool-write_script`), or in `toolName` when the type is `dynamic-tool`.

```typescript
interface AiToolPart {
    readonly type: `tool-${string}` | 'dynamic-tool';
    readonly toolName?: string;
    readonly toolCallId: string;
    readonly title?: string;
    readonly state: AiToolState;
    readonly input?: unknown;
    readonly output?: unknown;
    readonly errorText?: string;
}
```

| Member       | Type                                     | Description                                                                                                      |
| ------------ | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `type`       | `` `tool-${string}` \| 'dynamic-tool' `` |                                                                                                                  |
| `toolName?`  | `string`                                 |                                                                                                                  |
| `toolCallId` | `string`                                 |                                                                                                                  |
| `title?`     | `string`                                 | What a person reads for the call ("Write script"). Default: the tool's name.                                     |
| `state`      | `AiToolState`                            |                                                                                                                  |
| `input?`     | `unknown`                                |                                                                                                                  |
| `output?`    | `unknown`                                | What the tool returned. A helper's outcome is read as one: its images are drawn, a failed one shows as an error. |
| `errorText?` | `string`                                 |                                                                                                                  |

See also: [`AiToolState`](/docs/pro/api/ai#aitoolstate).

### `AiToolState` [#aitoolstate]

Where a tool call stands.

```typescript
type AiToolState =
    | 'input-streaming'
    | 'input-available'
    | 'approval-requested'
    | 'approval-responded'
    | 'output-available'
    | 'output-error'
    | 'output-denied';
```

### `AiWorkspace` [#aiworkspace]

What the charts show: the layout's charts, and which one the user is working on.

```typescript
interface AiWorkspace {
    activeSlot: number | null;
    charts: DescribedChart[];
}
```

See also: [`DescribedChart`](/docs/pro/api/ai#describedchart).

### `CaptureChartScreenshotInput` [#capturechartscreenshotinput]

```typescript
interface CaptureChartScreenshotInput extends OnChart {
    all?: boolean;
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
```

| Member | Type      | Description                                                             |
| ------ | --------- | ----------------------------------------------------------------------- |
| `all?` | `boolean` | Capture every chart of the layout, one image each (default: one chart). |

### `ChartStatePatch` [#chartstatepatch]

What to change on one chart. Only the fields present change.

```typescript
interface ChartStatePatch extends OnChart {
    symbol?: string;
    timeframe?: string;
    chartType?: string;
    session?: AiMarketSession;
    scale?: { mode?: 'price' | 'percent' | 'indexed'; log?: boolean; invert?: boolean };
    visibleRange?: { preset?: AiRangePreset; from?: string | number; to?: string | number };
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
```

| Member          | Type                                                                            | Description                                                                                                     |
| --------------- | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `symbol?`       | `string`                                                                        | A bare ticker resolves against every data source of the chart; `SOURCE:TICKER` pins one.                        |
| `timeframe?`    | `string`                                                                        |                                                                                                                 |
| `chartType?`    | `string`                                                                        | How the price series is drawn: a built-in type, or another the chart has registered.                            |
| `session?`      | `AiMarketSession`                                                               |                                                                                                                 |
| `scale?`        | `{ mode?: 'price' \| 'percent' \| 'indexed'; log?: boolean; invert?: boolean }` |                                                                                                                 |
| `visibleRange?` | `{ preset?: AiRangePreset; from?: string \| number; to?: string \| number }`    | A range ending now (`preset`), or an absolute window (`from` and `to`: ISO 8601 in UTC, or epoch milliseconds). |

See also: [`AiMarketSession`](/docs/pro/api/ai#aimarketsession), [`AiRangePreset`](/docs/pro/api/ai#airangepreset).

### `DescribedChart` [#describedchart]

```typescript
interface DescribedChart {
    slot: number;
    symbol: string;
    timeframe: string;
    chartType?: string;
    session?: string;
    scale?: { mode?: string; log?: boolean; invert?: boolean };
    visibleRange: { from: string; to: string } | null;
    indicators: Array<Omit<DescribedIndicator, 'slot'>>;
}
```

See also: [`DescribedIndicator`](/docs/pro/api/ai#describedindicator).

### `DescribedIndicator` [#describedindicator]

```typescript
interface DescribedIndicator {
    id: string;
    name: string;
    kind: 'indicator' | 'strategy' | 'builtin';
    slot: number;
    editable: boolean;
    hidden?: true;
}
```

| Member     | Type                                     | Description                                                          |
| ---------- | ---------------------------------------- | -------------------------------------------------------------------- |
| `id`       | `string`                                 |                                                                      |
| `name`     | `string`                                 |                                                                      |
| `kind`     | `'indicator' \| 'strategy' \| 'builtin'` |                                                                      |
| `slot`     | `number`                                 |                                                                      |
| `editable` | `boolean`                                | Its code can be read and changed: a script the helpers' engine runs. |
| `hidden?`  | `true`                                   | On the chart but switched off: not drawn, not computing.             |

### `EditScriptInput` [#editscriptinput]

```typescript
interface EditScriptInput extends OnChart {
    id: string;
    oldString: string;
    newString: string;
    replaceAll?: boolean;
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
```

| Member        | Type      | Description                                                         |
| ------------- | --------- | ------------------------------------------------------------------- |
| `id`          | `string`  | The script, by the id the chart holds it under.                     |
| `oldString`   | `string`  | The exact text to replace: it must occur once, unless `replaceAll`. |
| `newString`   | `string`  |                                                                     |
| `replaceAll?` | `boolean` | Replace every occurrence (default false).                           |

### `EnableAiOptions` [#enableaioptions]

Options for [`enableAi`](/docs/pro/api/ai#enableai) and `ai`.

```typescript
interface EnableAiOptions {
    connect: (panel: AiPanelContext) => AiChatHandlers;
    language?: string;
    title?: string;
    emptyTitle?: string;
    emptyDescription?: string;
    suggestions?: readonly string[];
    placeholder?: string;
    highlight?: AiChatProps['highlight'];
    models?: readonly AiModel[];
    model?: string;
    modelLogo?: AiChatProps['modelLogo'];
    onModelChange?: (id: string, ctx: WidgetContext) => void;
    promptTools?: (ctx: WidgetContext) => HTMLElement;
    renderPart?: AiChatProps['renderPart'];
    width?: number;
    order?: number;
}
```

| Member              | Type                                        | Description                                                                                                                                                                                                                                                                                                 |
| ------------------- | ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `connect`           | `(panel: AiPanelContext) => AiChatHandlers` | Connect a shell's chat to the host's conversation. Called once per shell. The host creates its chat state here (its model calls, its tools over `helpers`), draws it with `chat.update({ messages, status, error })` whenever it changes, and returns what to do when the user sends, stops or starts over. |
| `language?`         | `string`                                    | The key of the engine the script helpers write for, and read from (default `'pine'`).                                                                                                                                                                                                                       |
| `title?`            | `string`                                    | The panel's title, and its rail button's tooltip (default `'AI'`).                                                                                                                                                                                                                                          |
| `emptyTitle?`       | `string`                                    | What an empty conversation says.                                                                                                                                                                                                                                                                            |
| `emptyDescription?` | `string`                                    |                                                                                                                                                                                                                                                                                                             |
| `suggestions?`      | `readonly string[]`                         | Prompts offered while the conversation is empty.                                                                                                                                                                                                                                                            |
| `placeholder?`      | `string`                                    |                                                                                                                                                                                                                                                                                                             |
| `highlight?`        | `AiChatProps['highlight']`                  | Highlights the code blocks of a reply.                                                                                                                                                                                                                                                                      |
| `models?`           | `readonly AiModel[]`                        | The models the user can pick from. With any, a picker sits in the prompt's footer, and `chat.model` is the id picked. Without any, there is no picker.                                                                                                                                                      |
| `model?`            | `string`                                    | The id of the model picked to start with (default: the first of `models`). A choice the user made persists over it.                                                                                                                                                                                         |
| `modelLogo?`        | `AiChatProps['modelLogo']`                  | The logo of a model's maker or of a service, by its key: an address, an element, or null for the key's initial.                                                                                                                                                                                             |
| `onModelChange?`    | `(id: string, ctx: WidgetContext) => void`  | Called when the user picks a model.                                                                                                                                                                                                                                                                         |
| `promptTools?`      | `(ctx: WidgetContext) => HTMLElement`       | A control of the host's in the prompt's footer, built per shell.                                                                                                                                                                                                                                            |
| `renderPart?`       | `AiChatProps['renderPart']`                 | Draws a part of a message the host's way: see `AiChatProps.renderPart`.                                                                                                                                                                                                                                     |
| `width?`            | `number`                                    |                                                                                                                                                                                                                                                                                                             |
| `order?`            | `number`                                    | Place among the sidebar panel buttons (default 6).                                                                                                                                                                                                                                                          |

See also: [`AiChatHandlers`](/docs/pro/api/ai#aichathandlers), [`AiChatProps`](/docs/pro/api/ai#aichatprops), [`AiModel`](/docs/pro/api/ai#aimodel), [`AiPanelContext`](/docs/pro/api/ai#aipanelcontext). From `@luxalgo/vela/plugin`: `WidgetContext`.

### `JsonSchema` [#jsonschema]

The JSON Schema subset the helpers' inputs are written in: what a model API takes as a tool's parameters. Its arrays are plain arrays so a schema passes where JSON Schema's own type is asked for (the AI SDK's `jsonSchema()`).

```typescript
interface JsonSchema {
    type?: 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean';
    description?: string;
    properties?: Record<string, JsonSchema>;
    required?: string[];
    additionalProperties?: boolean;
    items?: JsonSchema;
    enum?: Array<string | number>;
    minimum?: number;
    maximum?: number;
    minLength?: number;
    maxLength?: number;
    minItems?: number;
    maxItems?: number;
}
```

| Member                  | Type                                                                    | Description             |
| ----------------------- | ----------------------------------------------------------------------- | ----------------------- |
| `type?`                 | `'object' \| 'array' \| 'string' \| 'number' \| 'integer' \| 'boolean'` | Absent: any JSON value. |
| `description?`          | `string`                                                                |                         |
| `properties?`           | `Record<string, JsonSchema>`                                            |                         |
| `required?`             | `string[]`                                                              |                         |
| `additionalProperties?` | `boolean`                                                               |                         |
| `items?`                | `JsonSchema`                                                            |                         |
| `enum?`                 | `Array<string \| number>`                                               |                         |
| `minimum?`              | `number`                                                                |                         |
| `maximum?`              | `number`                                                                |                         |
| `minLength?`            | `number`                                                                |                         |
| `maxLength?`            | `number`                                                                |                         |
| `minItems?`             | `number`                                                                |                         |
| `maxItems?`             | `number`                                                                |                         |

### `MarkUpChartInput` [#markupchartinput]

```typescript
interface MarkUpChartInput extends OnChart {
    concepts?: readonly MarkupRequest[];
    replace?: boolean;
    clear?: ReadonlyArray<MarkupConcept | 'all'>;
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
```

| Member      | Type                                    | Description                                                                                    |
| ----------- | --------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `concepts?` | `readonly MarkupRequest[]`              | The concepts to mark, each with its options.                                                   |
| `replace?`  | `boolean`                               | Remove the earlier markup of the same concepts first (default true), so a redraw never stacks. |
| `clear?`    | `ReadonlyArray<MarkupConcept \| 'all'>` | Markups to take off the chart, by concept, or `['all']`. Can be sent alone.                    |

See also: [`MarkupConcept`](/docs/pro/api/ai#markupconcept), [`MarkupRequest`](/docs/pro/api/ai#markuprequest).

### `MarkupConcept` [#markupconcept]

```typescript
type MarkupConcept = (typeof MARKUP_CONCEPTS)[number];
```

See also: [`MARKUP_CONCEPTS`](/docs/pro/api/ai#markup_concepts).

### `MarkupRequest` [#markuprequest]

One concept to mark, with the options that apply to it.

```typescript
interface MarkupRequest {
    concept: MarkupConcept;
    count?: number;
    direction?: 'bullish' | 'bearish' | 'both';
    mitigation?: 'full' | 'ce';
    includeMitigated?: boolean;
    inversions?: boolean;
    includeSwept?: boolean;
    strength?: number;
    breakers?: boolean;
    ote?: boolean;
    quarters?: boolean;
    high?: number;
    low?: number;
    leg?: 'up' | 'down';
    extensions?: number[];
    gapKind?: 'week' | 'day' | 'both';
    only?: string[];
    windows?: Array<{ name: string; start: string; end: string }>;
    days?: number;
    levels?: Array<(typeof KEY_LEVEL_KINDS)[number]>;
}
```

See also: [`KEY_LEVEL_KINDS`](/docs/pro/api/ai#key_level_kinds), [`MarkupConcept`](/docs/pro/api/ai#markupconcept).

### `ReadChartDataInput` [#readchartdatainput]

```typescript
interface ReadChartDataInput extends OnChart {
    kind: 'bars' | 'plots' | 'trades' | 'inputs' | 'visible_range';
    count?: number;
    from?: string | number;
    to?: string | number;
    scriptId?: string;
    plots?: readonly string[];
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
```

| Member      | Type                                                           | Description                                                                                                                  |
| ----------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `kind`      | `'bars' \| 'plots' \| 'trades' \| 'inputs' \| 'visible_range'` | The chart's price bars, a script's plotted values, a strategy's trades, an indicator's settings, or the time window in view. |
| `count?`    | `number`                                                       | bars / plots: how many rows, the latest ones (default 100).                                                                  |
| `from?`     | `string \| number`                                             | bars / plots: a time window, ISO 8601 (UTC) or epoch milliseconds.                                                           |
| `to?`       | `string \| number`                                             |                                                                                                                              |
| `scriptId?` | `string`                                                       | plots / trades / inputs: the indicator, by the id the chart holds it under.                                                  |
| `plots?`    | `readonly string[]`                                            | plots: the plot names to read (default: all).                                                                                |

### `ReadScriptInput` [#readscriptinput]

```typescript
interface ReadScriptInput extends OnChart {
    id: string;
    startLine?: number;
    endLine?: number;
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
```

| Member       | Type     | Description                                                    |
| ------------ | -------- | -------------------------------------------------------------- |
| `id`         | `string` |                                                                |
| `startLine?` | `number` | First line to return (1 = the first line). Default: the first. |
| `endLine?`   | `number` | Last line to return. Default: the last.                        |

### `RemoveScriptInput` [#removescriptinput]

```typescript
interface RemoveScriptInput extends OnChart {
    id: string;
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
```

| Member | Type     | Description                                                           |
| ------ | -------- | --------------------------------------------------------------------- |
| `id`   | `string` | A script or a built-in indicator, by the id the chart holds it under. |

### `SetChartStateInput` [#setchartstateinput]

```typescript
interface SetChartStateInput {
    charts: readonly ChartStatePatch[];
}
```

| Member   | Type                         | Description                    |
| -------- | ---------------------------- | ------------------------------ |
| `charts` | `readonly ChartStatePatch[]` | One entry per chart to change. |

See also: [`ChartStatePatch`](/docs/pro/api/ai#chartstatepatch).

### `SetScriptInputsInput` [#setscriptinputsinput]

```typescript
interface SetScriptInputsInput extends OnChart {
    id: string;
    inputs: ReadonlyArray<{ name: string; value: AiInputValue }>;
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
```

| Member   | Type                                                   | Description                                                                 |
| -------- | ------------------------------------------------------ | --------------------------------------------------------------------------- |
| `id`     | `string`                                               |                                                                             |
| `inputs` | `ReadonlyArray<{ name: string; value: AiInputValue }>` | Each setting by the title its dialog shows, or its key, with its new value. |

See also: [`AiInputValue`](/docs/pro/api/ai#aiinputvalue).

### `WriteScriptInput` [#writescriptinput]

```typescript
interface WriteScriptInput extends OnChart {
    code: string;
    id?: string;
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
```

| Member | Type     | Description                                                                           |
| ------ | -------- | ------------------------------------------------------------------------------------- |
| `code` | `string` | The complete source of the script.                                                    |
| `id?`  | `string` | The id of a script on the chart to overwrite in place. Absent: a new script is added. |

## Constants [#constants]

### `AI_HELPER_NAMES` [#ai_helper_names]

Every helper, by name.

```typescript
const AI_HELPER_NAMES: readonly ('markUpChart' | 'writeScript' | 'editScript' | 'readScript' | 'removeScript' | 'setScriptInputs' | 'addIndicator' | 'readChart' | 'setChartState' | 'captureChartScreenshot' | 'readChartData')[];
```

### `AI_HELPER_SCHEMAS` [#ai_helper_schemas]

The JSON Schema of each helper's input: what the helper checks an input against, and what a host can hand its model as the parameters of the tool that calls the helper.

```typescript
const AI_HELPER_SCHEMAS: Readonly<Record<AiHelperName, JsonSchema>>;
```

See also: [`AiHelperName`](/docs/pro/api/ai#aihelpername), [`JsonSchema`](/docs/pro/api/ai#jsonschema).

### `AI_INSTRUCTIONS` [#ai_instructions]

A system prompt to start from, for a model that works the chart through tools built on the helpers. It names no tool: add what yours are called. The module sends it nowhere: the host's code builds its own requests.

```typescript
const AI_INSTRUCTIONS: string;
```

### `AI_NATIVE_TYPE` [#ai_native_type]

The native every chart the agent reads bars from carries: no legend row, no output, never in a picker.

```typescript
const AI_NATIVE_TYPE: 'vela-pro.ai';
```

### `AI_PANEL_ID` [#ai_panel_id]

```typescript
const AI_PANEL_ID: 'vela-pro.ai';
```

### `KEY_LEVEL_KINDS` [#key_level_kinds]

```typescript
const KEY_LEVEL_KINDS: readonly ['previous-day', 'previous-week', 'midnight-open', 'sessions'];
```

### `MARKUP_CONCEPTS` [#markup_concepts]

```typescript
const MARKUP_CONCEPTS: readonly ['fair_value_gaps', 'liquidity', 'market_structure', 'order_blocks', 'dealing_range', 'opening_gaps', 'killzones', 'macros', 'key_levels', 'support_resistance', 'trendlines', 'pattern', 'range'];
```
