AI
Enable the AI module, connect your own AI model and conversation state, define tools backed by chart helpers, and mount standalone chat widgets.
The AI module (@luxalgo/vela-pro-ai) adds a chat side panel and a set of chart helpers for building an AI assistant on top of Vela Pro. It is an opt-in module distributed as a standalone workspace package under plugins/ai/ and built with the ai-* components from @luxalgo/vela-ui (0.4.6 or later).
The module is deliberately split into a UI view and chart helpers, with no model client or agent loop of its own:
- The chat panel renders a conversation that your application owns, and forwards user actions (
onSubmit,onStop,onNewChat) back to your code. Messages follow the shape of the AI SDK'sUIMessage, so conversations managed by the AI SDK pass straight in without conversion, while custom message pipelines work the same way. - The chart helpers perform validated chart operations for the tools you expose to your model: reading workspace state, switching symbols and timeframes, capturing screenshots, reading exact bar and indicator data, writing and editing Pine Script® indicators, adjusting inputs, adding built-in studies, and marking up technical structure.
Your application owns the model provider, system prompt, context window, tool definitions (names, descriptions, schemas), and execution loop.
Configuration
See Installation for packing and installing luxalgo-vela-pro-ai-0.1.2.tgz alongside Vela Pro (0.7.0 or later) and @luxalgo/vela-ui (0.4.6 or later). Pass ai({ connect }) in the plugins array of enableVelaPro():
import { VelaWorkspace } from '@luxalgo/vela/workspace';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { enableVelaPro } from '@luxalgo/vela-pro';
import { ai, type AiChatMessage, type AiPanelContext } from '@luxalgo/vela-pro-ai';
declare function streamReply(
messages: readonly AiChatMessage[],
model: string | undefined,
signal: AbortSignal,
): AsyncIterable<string>;
function connect({ chat }: AiPanelContext) {
let messages: AiChatMessage[] = [];
let active: AbortController | null = null;
return {
onSubmit: async ({ text }: { text: string }) => {
active = new AbortController();
const reply: AiChatMessage = {
id: crypto.randomUUID(),
role: 'assistant',
parts: [{ type: 'text', text: '', state: 'streaming' }],
};
messages = [
...messages,
{ id: crypto.randomUUID(), role: 'user', parts: [{ type: 'text', text }] },
];
chat.update({ messages, status: 'submitted', error: null });
messages = [...messages, reply];
try {
let textSoFar = '';
for await (const delta of streamReply(messages, chat.model, active.signal)) {
textSoFar += delta;
messages = [
...messages.slice(0, -1),
{ ...reply, parts: [{ type: 'text', text: textSoFar, state: 'streaming' }] },
];
chat.update({ messages, status: 'streaming' });
}
messages = [
...messages.slice(0, -1),
{ ...reply, parts: [{ type: 'text', text: textSoFar, state: 'done' }] },
];
chat.update({ messages, status: 'ready' });
} catch (error) {
if (active.signal.aborted) {
chat.update({ messages, status: 'ready' });
} else {
chat.update({
messages,
status: 'error',
error: error instanceof Error ? error : 'Request failed.',
});
}
} finally {
active = null;
}
},
onStop: () => active?.abort(),
onNewChat: () => {
active?.abort();
messages = [];
chat.update({ messages, status: 'ready', error: null });
},
destroy: () => active?.abort(),
};
}
enableVelaPro({
plugins: [
ai({
connect,
suggestions: ['Add a 21 EMA', 'Switch to ETHUSDT 15m', 'What is on the chart?'],
models: [
{ id: 'fast', name: 'Fast', group: 'Acme', provider: 'acme', hint: 'Quick replies' },
{ id: 'deep', name: 'Deep', group: 'Acme', provider: 'acme', hint: 'Multi-step builds' },
],
}),
],
});
const workspace = new VelaWorkspace('#chart', {
layout: false,
symbol: 'BTCUSDT',
timeframe: '60',
live: true,
providers: { binance: () => new BinanceProvider() },
persist: true,
});Options
| Option | Default | Description |
|---|---|---|
connect | Required | Called once per workspace shell with { chat, helpers, ctx }. Returns AiChatHandlers ({ onSubmit, onStop?, onNewChat?, destroy? }). |
language | 'pine' | Scripting engine key that script helpers target when adding, reading, or editing scripts. |
title | 'AI' | Panel heading and side rail button tooltip. |
emptyTitle, emptyDescription | Built-in copy | Heading and subtitle displayed while the conversation has no messages. |
suggestions | None | Quick-prompt buttons shown above the input while the conversation is empty. |
placeholder | Built-in copy | Input placeholder text. |
highlight | None | Code block highlighter function (code, language) => Node for assistant Markdown responses. |
models | None | List of selectable AiModel items ({ id, name, group?, provider?, hint?, disabled? }). Renders a searchable model picker in the prompt footer when non-empty. |
model | First enabled entry in models | Initial model ID. User selections persist in workspace state under ext['velapro.ai'] and take precedence over this default. |
modelLogo | Provider initial | (key) => string | Node | null | undefined resolving a logo for each model's provider key. |
onModelChange | None | Callback (id, ctx) invoked when the user selects a different model. |
promptTools | None | (ctx) => HTMLElement inserting custom controls in the prompt footer after the model picker. |
renderPart | None | (part, message) => Node | null | undefined overriding how individual message parts render. |
width | 420 | Initial side panel width in pixels. Resizable between 320 and 760 pixels. |
order | 6 | Sort order among side rail panel buttons. |
Connect context and handlers
connect receives an AiPanelContext for each workspace shell:
chat(AiChatView): exposesupdate(state)to render the latest{ messages, status, error },modelfor the currently selected model ID, andfocus()to focus the prompt.helpers(AiHelpers): chart helpers bound to that shell's charts (see Chart helpers).ctx(WidgetContext): the core workspace context for opening panels, showing toasts, or reading active chart state.
connect returns AiChatHandlers:
onSubmit({ text }): invoked when the user submits a prompt or clicks a suggestion. If it returns a rejected promise, the prompt restores the submitted text.onStop(): invoked when the user clicks Stop while a reply is streaming or awaiting tool output.onNewChat(): invoked when the user clicks the New chat button in the panel header. OmitonNewChatto hide the button.destroy(): invoked when the panel tears down with its workspace.
Conversation format
Call chat.update({ messages, status, error }) whenever your conversation changes. Only changed fields update, unchanged earlier messages are skipped, and streaming text appends in place without rebuilding existing DOM nodes.
| Field | Type | Description |
|---|---|---|
messages | readonly AiChatMessage[] | Messages in chronological order, each { id, role, parts } where role is 'system', 'user', or 'assistant'. |
status | 'ready' | 'submitted' | 'streaming' | 'error' | Current request state controlling the prompt's send/stop button and suggestion availability. |
error | Error | string | null | Error message rendered below the conversation when present. Pass null to clear it. |
Message parts
| Part shape | Rendered as |
|---|---|
{ type: 'text', text, state? } | Preserved plain text for user bubbles; streaming Markdown for assistant messages when state is 'streaming'. |
{ type: 'reasoning', text, state? } | Collapsible reasoning block above the response. |
{ type: 'tool-<name>', toolCallId, state, input?, output?, errorText?, title? } | Collapsible tool card showing parameters and output or error. { type: 'dynamic-tool', toolName, ... } is also supported. title overrides the displayed tool label. |
{ type: 'file', mediaType, url, filename? } | Attachment chips above user messages; inline image or file link inside assistant messages. |
{ type: 'source-url', url, title? } | Deduplicated list of cited sources above assistant messages. |
Any other part (step-start, data-*, custom types) | Ignored unless handled by renderPart. |
Tool part state accepts the standard AI SDK lifecycle values: 'input-streaming', 'input-available', 'approval-requested', 'approval-responded', 'output-available', 'output-error', and 'output-denied'.
Three rendering behaviors are built into the chat view:
- Helper outcomes render directly as tool outputs. If a tool's
outputis anAiOutcomereturned by a chart helper, a successful outcome showsresult(or rendersimagesinline for screenshots) and a failed outcome renders as a tool error with formatted problem or note lines. - Unanswered tool calls keep the chat busy. Client-side tool loops temporarily report
status: 'ready'between the end of a model step and the completion of a browser-side tool call. While the last assistant message contains a pending or running tool call, the chat treatsstatusas'streaming', keeping the Stop button active and preventing a new user message from interrupting an open tool call. - Automatic waiting indicator. A compact loading indicator appears automatically when
statusis'submitted'or'streaming'and no part is actively streaming or executing, with a short delay between parts so transitions do not flicker.
Custom part rendering
Supply renderPart to render custom data-* parts or replace default tool cards. Return a DOM Node to display it, null to suppress the part, or undefined to fall back to the built-in renderer:
import { enableVelaPro } from '@luxalgo/vela-pro';
import { ai, type AiChatHandlers, type AiPanelContext } from '@luxalgo/vela-pro-ai';
declare function connect(panel: AiPanelContext): AiChatHandlers;
enableVelaPro({
plugins: [
ai({
connect,
renderPart: (part) => {
if (part.type !== 'data-quote') return undefined;
const { symbol, price } = part.data as { symbol: string; price: number };
const badge = document.createElement('div');
badge.textContent = `${symbol}: ${price}`;
return badge;
},
}),
],
});Chart helpers
connect supplies an AiHelpers instance scoped to the workspace shell. You define the tools your model sees (their names, descriptions, and schemas) and invoke helpers inside your tool execution handlers.
Every helper validates its input against its JSON Schema (AI_HELPER_SCHEMAS), never throws, and resolves an AiOutcome:
type AiOutcome =
| { ok: true; result: unknown; images?: readonly AgentImage[] }
| { ok: false; error: string; details?: unknown };Pass failed outcomes back to your model as tool errors. Their error and details fields are written so a model can correct invalid inputs, syntax errors, or missing IDs on the next step.
| Helper | Input type | Behavior |
|---|---|---|
readChart() | None | Returns the workspace layout, activeSlot, and each chart's symbol, timeframe, chart type, session, scale, visible range, and indicators with their IDs. |
setChartState(input) | SetChartStateInput | Updates one or more charts' symbol, timeframe, chart type, session, price scale, or visible range, waiting for new market history before resolving. Does not change the grid layout. |
captureChartScreenshot(input?) | CaptureChartScreenshotInput | Captures one chart (or every chart with all: true) as PNG data URLs in outcome.images. |
readChartData(input) | ReadChartDataInput | Reads exact values: OHLCV bars (up to 300), indicator plots (up to 8 plots), strategy trades (last 50 plus summary metrics), indicator inputs, or visible_range. |
writeScript(input) | WriteScriptInput | Adds a complete script to the chart, or replaces an existing script in place when id is provided. Failed compiles leave the chart unchanged and return the engine's error. |
editScript(input) | EditScriptInput | Performs an exact, case-sensitive string replacement (oldString and newString, with optional replaceAll) on a script by id, refusing ambiguous matches. |
readScript(input) | ReadScriptInput | Returns a script's source code with line numbers, optionally bounded by startLine and endLine. |
removeScript(input) | RemoveScriptInput | Removes a script or built-in indicator from the chart by id. |
setScriptInputs(input) | SetScriptInputsInput | Updates an indicator's settings by title or key, validating types, choices, and min/max bounds before applying any change. |
addIndicator(input?) | AddIndicatorInput | Adds a built-in native indicator by type with optional initial inputs, or lists all available built-in types when type is omitted. |
markUpChart(input) | MarkUpChartInput | Detects technical concepts directly from the chart's bars (fair value gaps, liquidity, market structure, order blocks, dealing range, opening gaps, killzones, macros, key levels, support/resistance, trendlines, patterns, range) and places locked drawings grouped by concept. Pass clear to remove specific concepts or ['all']. |
run(name, input, options?) | unknown | Dispatches any helper by its AiHelperName with unvalidated model arguments. |
describe() | None | Synchronously returns the same workspace snapshot as readChart(), intended for attaching fresh chart context to each model request. |
Helper guarantees
- Input validation: Every helper checks its input against
AI_HELPER_SCHEMAS[name]before touching the chart, so tool handlers can forward raw model arguments throughhelpers.run(name, input, options). You can also design narrower tool schemas and map them to typed helper inputs (WriteScriptInput,SetChartStateInput, and so on). - Serialized mutations: Mutating helpers (
setChartState,writeScript,editScript,removeScript,setScriptInputs,addIndicator,markUpChart) execute one at a time in call order. Read helpers wait for any preceding mutation to finish so they always observe updated state. - Multi-chart targeting: All chart-scoped helpers accept an optional
slot(0-indexed in reading order) and default to the active chart when omitted. - Cancellation: Pass
{ signal }inoptionsso long-running helpers (such as market switches or screenshot waits) abort when the user clicks Stop. - Tool-name independence: Helper error messages and schemas never hardcode tool names, so you can name and organize your tools however your prompt requires.
- UTC timestamps: All returned and accepted timestamps use ISO 8601 in UTC (or epoch milliseconds on inputs).
AI_INSTRUCTIONS exports a neutral starter system prompt describing chart workflow rules without referencing specific tool names. Append your own tool guidance as needed.
Using with the AI SDK
Because chart helpers run in the browser where the live VelaWorkspace resides, connect the AI SDK using client-side tool execution:
- Declare your tools on the server without an
executefunction so tool calls stream back to the browser. - In the browser, handle each incoming call inside
onToolCall, run the matching chart helper, and return its outcome withaddToolOutput. - Enable
sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls(gated by your stop signal) so the conversation automatically continues to the next model step once every tool call resolves.
Client wiring
With React, Vue, or Svelte, use the Chat class or useChat hook from @ai-sdk/react, @ai-sdk/vue, or @ai-sdk/svelte. Outside a UI framework, wrap AbstractChat from ai:
import {
AbstractChat,
DefaultChatTransport,
lastAssistantMessageIsCompleteWithToolCalls,
type ChatInit,
type ChatState,
type ChatStatus,
type UIMessage,
} from 'ai';
import { VelaWorkspace } from '@luxalgo/vela/workspace';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { enableVelaPro } from '@luxalgo/vela-pro';
import {
ai,
type AiChatHandlers,
type AiHelperName,
type AiPanelContext,
} from '@luxalgo/vela-pro-ai';
class PageChat extends AbstractChat<UIMessage> {
constructor(init: ChatInit<UIMessage>, onChange: () => void) {
let status: ChatStatus = 'ready';
let error: Error | undefined;
let messages: UIMessage[] = init.messages ?? [];
const state: ChatState<UIMessage> = {
get status() {
return status;
},
set status(next) {
status = next;
onChange();
},
get error() {
return error;
},
set error(next) {
error = next;
onChange();
},
get messages() {
return messages;
},
set messages(next) {
messages = next;
onChange();
},
pushMessage: (message) => {
messages = [...messages, message];
onChange();
},
popMessage: () => {
messages = messages.slice(0, -1);
onChange();
},
replaceMessage: (index, message) => {
messages = [
...messages.slice(0, index),
structuredClone(message),
...messages.slice(index + 1),
];
onChange();
},
snapshot: (thing) => structuredClone(thing),
};
super({ ...init, state });
}
}
const HELPER_OF: Record<string, AiHelperName> = {
read_chart: 'readChart',
set_chart_state: 'setChartState',
capture_chart: 'captureChartScreenshot',
read_chart_data: 'readChartData',
write_script: 'writeScript',
edit_script: 'editScript',
read_script: 'readScript',
remove_script: 'removeScript',
set_script_inputs: 'setScriptInputs',
add_indicator: 'addIndicator',
mark_up_chart: 'markUpChart',
};
function connect({ chat, helpers }: AiPanelContext): AiChatHandlers {
let reply = new AbortController();
const ai: PageChat = new PageChat(
{
transport: new DefaultChatTransport({
api: '/api/agent',
// Attach the selected model and a fresh chart snapshot to every request.
body: () => ({ model: chat.model, chart: helpers.describe() }),
}),
sendAutomaticallyWhen: (options) =>
!reply.signal.aborted && lastAssistantMessageIsCompleteWithToolCalls(options),
onToolCall: ({ toolCall }) => {
const helper = HELPER_OF[toolCall.toolName];
const run = helper
? helpers.run(helper, toolCall.input, { signal: reply.signal })
: Promise.resolve({
ok: false as const,
error: `Unknown tool "${toolCall.toolName}".`,
});
void run.then((outcome) =>
ai.addToolOutput({
tool: toolCall.toolName,
toolCallId: toolCall.toolCallId,
output: outcome,
}),
);
},
},
() => chat.update({ messages: ai.messages, status: ai.status, error: ai.error ?? null }),
);
return {
onSubmit: ({ text }) => {
reply = new AbortController();
void ai.sendMessage({ text });
},
onStop: () => {
reply.abort();
void ai.stop();
},
onNewChat: () => {
reply.abort();
void ai.stop().then(() => {
ai.clearError();
ai.messages = [];
});
},
destroy: () => void ai.dispose(),
};
}
enableVelaPro({
plugins: [
ai({
connect,
suggestions: ['Add a 21 EMA', 'Mark up fair value gaps', 'Capture screenshot'],
models: [
{ id: 'fast', name: 'Fast', group: 'Acme', provider: 'acme', hint: 'Quick replies' },
{ id: 'deep', name: 'Deep', group: 'Acme', provider: 'acme', hint: 'Complex builds' },
],
}),
],
});
const workspace = new VelaWorkspace('#chart', {
layout: false,
symbol: 'BTCUSDT',
timeframe: '60',
live: true,
providers: { binance: () => new BinanceProvider() },
});Server route
Define your tools on the server using AI_HELPER_SCHEMAS with jsonSchema() and a toModelOutput mapper so failed helper outcomes reach the model as error text and chart screenshots reach vision-capable models as image content instead of raw base64 JSON:
import { ToolLoopAgent, createAgentUIStreamResponse, jsonSchema, tool, type LanguageModel } from 'ai';
import { AI_HELPER_SCHEMAS, AI_INSTRUCTIONS, type AiOutcome } from '@luxalgo/vela-pro-ai';
declare const models: Record<string, LanguageModel>;
function toModelOutput({ output }: { output: unknown }) {
const outcome = output as AiOutcome;
if (!outcome.ok) return { type: 'error-text' as const, value: outcome.error };
if (!outcome.images?.length) return { type: 'json' as const, value: outcome.result as never };
return {
type: 'content' as const,
value: [
{ type: 'text' as const, text: JSON.stringify(outcome.result) },
...outcome.images.map((image) => ({
type: 'file' as const,
mediaType: image.mediaType,
data: {
type: 'data' as const,
data: image.dataUrl.slice(image.dataUrl.indexOf(',') + 1),
},
})),
],
};
}
const tools = {
read_chart: tool({
title: 'Read chart',
description: 'Inspect open charts, their markets and styles, and all indicator IDs.',
inputSchema: jsonSchema(AI_HELPER_SCHEMAS.readChart),
toModelOutput,
}),
set_chart_state: tool({
title: 'Change chart',
description: 'Change symbol, timeframe, chart type, session, scale, or visible range.',
inputSchema: jsonSchema(AI_HELPER_SCHEMAS.setChartState),
toModelOutput,
}),
write_script: tool({
title: 'Write script',
description:
'Add a complete Pine Script® indicator or strategy, or replace an existing one in place by id.',
inputSchema: jsonSchema(AI_HELPER_SCHEMAS.writeScript),
toModelOutput,
}),
capture_chart: tool({
title: 'Capture chart',
description: 'Capture a PNG screenshot of the chart to inspect rendered visuals.',
inputSchema: jsonSchema(AI_HELPER_SCHEMAS.captureChartScreenshot),
toModelOutput,
}),
};
export async function POST(request: Request): Promise<Response> {
const { messages, model, chart } = (await request.json()) as {
messages: unknown[];
model?: string;
chart?: unknown;
};
const agentLoop = new ToolLoopAgent({
// Always resolve the client-selected model ID against a server-side allowlist.
model: models[model ?? ''] ?? models.fast!,
instructions: `${AI_INSTRUCTIONS}\n\nCurrent chart state:\n${JSON.stringify(chart)}`,
tools,
});
// Trim, summarize, or filter `messages` here to manage your context window.
return createAgentUIStreamResponse({
agent: agentLoop,
uiMessages: messages,
abortSignal: request.signal,
});
}When importing AI_HELPER_SCHEMAS or AI_INSTRUCTIONS in server code (such as a Next.js route handler), bundle the server entry with Next.js, Vite, or esbuild so tree-shaking drops browser UI imports. Importing the package root directly from unbundled Node.js is not supported.
Programmatic API and headless helpers
aiApi() returns the page's AiApi after enableVelaPro() installs the module, or null beforehand:
| Member | Description |
|---|---|
helpers(ctx?) | Returns the AiHelpers instance for ctx's workspace (or the most recently mounted workspace). Shares the same mutation queue as the panel's tools. |
chat(ctx?) | Returns the AiChatWidget instance for ctx's workspace (or the most recently mounted workspace), or null before the panel mounts. |
ask(ctx, text?) | Opens the AI side panel on ctx's workspace and optionally submits text as a user message. |
To expose chart helpers to an external agent loop or MCP server without mounting the chat panel at all, use createAiHelpers and aiSurface inside a core widget attachment:
import { registerWidgetAttachment } from '@luxalgo/vela/plugin';
import {
AI_HELPER_SCHEMAS,
aiSurface,
createAiHelpers,
type AiHelperName,
} from '@luxalgo/vela-pro-ai';
registerWidgetAttachment({
id: 'acme.ai-bridge',
mount(ctx) {
const helpers = createAiHelpers(aiSurface(ctx));
const socket = new WebSocket('wss://example.com/agent');
socket.addEventListener('open', () =>
socket.send(JSON.stringify({ type: 'schemas', schemas: AI_HELPER_SCHEMAS })),
);
socket.addEventListener('message', (event) => {
const call = JSON.parse(String(event.data)) as {
id: string;
helper: AiHelperName;
input: unknown;
};
void helpers
.run(call.helper, call.input)
.then((outcome) => socket.send(JSON.stringify({ type: 'result', id: call.id, outcome })));
});
return () => socket.close();
},
});You can also pass a custom AiSurface object to createAiHelpers(surface) when integrating with a custom chart container outside VelaWorkspace.
Widgets
createAiChat(props) mounts the AI chat interface anywhere on a page, with or without a workspace (see Standalone widgets):
import { DARK_THEME } from '@luxalgo/vela';
import { ensureUIHost } from '@luxalgo/vela/ui';
import { createAiChat, type AiChatState } from '@luxalgo/vela-pro-ai';
declare function createMyChat(
onChange: (state: AiChatState) => void,
): { send(text: string): void; stop(): void; clear(): void };
const box = document.getElementById('ai')!;
ensureUIHost(box, DARK_THEME);
const mine = createMyChat((state) => chat.update(state));
const chat = createAiChat({
host: box,
suggestions: ['What is on the chart?'],
onSubmit: ({ text }) => mine.send(text),
onStop: () => mine.stop(),
onNewChat: () => mine.clear(),
});
box.append(chat.el);| Prop | Description |
|---|---|
onSubmit | Required callback ({ text }) => void | Promise<unknown> invoked when the user submits a message or clicks a suggestion. |
onStop | Optional callback invoked when the user clicks Stop during a reply. |
onNewChat | Optional callback invoked when the user clicks New chat. Omit to hide the button. |
messages, status, error | Initial conversation state. Update at any time through chat.update({ messages, status, error }). |
host | Portal container for tooltips and the model selector palette. Defaults to the widget's root element. |
title, description | Empty-state title and description. |
suggestions | Quick-prompt items displayed while messages is empty. Mutable via update. |
placeholder | Prompt textarea placeholder text. |
highlight | Code block syntax highlighter (code, language) => Node. |
models, model, modelLogo, onModelChange | Model selector list, initial model ID, logo resolver, and selection callback. models is mutable via update, and setModel(id) updates selection programmatically. |
promptTools | Custom DOM element appended to the prompt footer after the model picker. |
renderPart | Custom message part renderer (part, message) => Node | null | undefined. |
The returned AiChatWidget exposes el, tools (holding the New chat button when onNewChat is supplied), status, busy, model, update(next), submit(text), setModel(id), focus(), and destroy().
The chat inherits Vela UI kit themes automatically. Module-specific styles live in @layer vela.pro and expose data-part hooks (ai-chat, conversation, composer, suggestions, prompt, model, ai-head, text, shots, shot, file, note).