Skip to content

Scripting AI

Updated

Behavior scripts make an agent part of your game. A script can ask the agent questions, tell it what just happened without the visitor seeing the prompt, show its replies in your own UI, stop it, and replay its speech. It follows the conversation in two ways: by reading the conversation object the AI Model provides, and by listening to the agent events the agent sends through its Signal Emitter. This page documents both.

  • You have an agent with a Signal Emitter on it; see Creating an agent.
  • Listening uses on(signal, callback) and EventType; see Scripting.
  • Async code: send returns a promise, so call it with await inside an async function, and catch its errors.

Each agent has one shared conversation: the dialog shows it, and every script sees the same one. Get it from the AI Model:

const conversation = findEntity('Guide').getComponent(AIModelComponent).getConversation();

getConversation() returns undefined in the editor, while the agent or its AI Model is switched off, or when the application offers no AI. Check it before use.

Member What it does
send(prompt, { signal? }) Send a prompt and stream the reply into the history. prompt is a string (an ordinary visitor message) or { kind, text, persist? }. Resolves when the turn ends. Throws when a turn is already running (“Conversation is busy.”) or the agent is unavailable. Aborting signal cancels only this turn.
sendCommand(text, { persist?, signal? }) Send a hidden command: the visitor never sees the prompt, only the agent’s reply.
cancel() Cancel the running turn. The partial reply stays in the history.
getSnapshot() The current state; see below.
subscribe(listener) Call listener() on every change. Returns the function that stops it.
replay(messageId?, { audio? }) Speak a finished reply through AI Text To Speech: the latest one when messageId is omitted. audio ('global' or 'positional') overrides the component for this playback.
stopSpeech() Stop the reply’s speech.
  • A message (send('text'), or { kind: 'message', text }) is ordinary visitor input: it appears in the chat, sends AIAgent::prompt, and is kept in the Context by default (persist: true).
  • A command (sendCommand(text), or { kind: 'command', text }) is hidden input from your application: “The visitor picked up the key.” It creates no chat entry and no prompt event, and is not kept by default (persist: false). The agent’s reply is shown and spoken like any other.

Both use the persona’s instructions, the skills and the tools as usual.

getSnapshot() returns:

Field What it holds
messages Every entry: { id, turnId, role, text, status }, with role 'user' or 'assistant' and status one of streaming, complete, cancelled, error.
phase idle, thinking, writing or error.
activeTurnId Set while a turn runs. Check it before sending.
agentName The agent’s display name.
error A message for the last failure, when there is one.
speechEnabled, speechAvailable, speechUnavailableReason, speechPhase, speechError The state of the reply’s speech.

An agent sends AIAgent::<kind> events to the Signal Emitters on its own entity. Add one with a signal, optionally narrowed with an eventFilter, and listen with on(signal, …). Each event is { entityId, eventType, data }, and EventType.AIAgent names every kind in PascalCase: EventType.AIAgent.Writing is 'AIAgent::writing'.

Event When Data
AIAgent::prompt An ordinary message reached the agent. Commands never send it. text: the prompt
AIAgent::thinking The agent is working and has no text yet. —
AIAgent::writing A chunk of the reply arrived. text: this chunk only; partial; sequence, its position from 0
AIAgent::response The reply is complete. text: the whole reply
AIAgent::talking The reply’s speech started playing. bytes and mimeType when generated audio is available
AIAgent::cancelled The turn was cancelled. —
AIAgent::error The turn failed or was refused, or a reply’s speech failed. text: a message safe to show the visitor
AIAgent::idle Nothing is in flight. Sent after each response, cancellation or turn error. —
AIAgent::translation-requested, -completed, -failed, -cancelled The steps of a translation. See Translation and memory

Turn events also carry conversationId, turnId, messageId, contextId and operationId to match them up, and every event carries sceneId, the scene of the agent that sent it.

The model service reports what happens inside a turn:

Group Events
Turns turn-started, turn-completed, turn-failed, turn-cancelled
Instructions instructions-used, instructions-updated, skill-updated, tool-updated
Skills skill-requested, skill-loaded, skill-load-failed
Tools tool-definition-loaded, tool-definition-failed, tool-requested, tool-completed, tool-failed, tool-cancelled
Memory memory-read-requested, memory-read, memory-read-failed, memory-write-requested, memory-written, memory-write-failed
Context context-updated
Outcome Events, in order
Success prompt (messages only), thinking, writing (once per chunk), response, turn-completed, idle
Cancelled cancelled, turn-cancelled, idle
Failed turn-failed, error, idle

writing arrives once per chunk, not once per reply, and each chunk carries only its own text: append them. A cancellation never sends error. A speech failure sends error but leaves the text reply complete and sends no extra idle. Memory events come once per read or write, so one turn can send several.

The smallest round trip from game logic: press Q and a script sends a fixed question, then logs the agent’s events as the answer comes back.

AskGuide.jx
#pragma lifecycle(startup, update)
const QUESTION = 'In one sentence, what can I see in this gallery?';
let conversation;
function startup() {
conversation = findEntity('Guide').getComponent(AIModelComponent).getConversation();
if (!conversation) return log('The guide is not available here.');
log('The guide is ready. Messages so far:', conversation.getSnapshot().messages.length);
on('guide:ai', (event) => {
if (event.eventType === EventType.AIAgent.Thinking) log('The guide is thinking…');
if (event.eventType === EventType.AIAgent.Response) log('Answer:', event.data.text);
if (event.eventType === EventType.AIAgent.Error) log('No answer:', event.data.text);
});
}
function update() {
if (!conversation || !Input.keyboard.isKeyReleased(Key.Q)) return;
if (conversation.getSnapshot().activeTurnId) return log('The guide is still answering.');
log('Asking:', QUESTION);
conversation.send(QUESTION).catch((error) => log('Could not ask:', error.message));
}
  • getConversation() and getSnapshot() work without contacting the model, so the startup line shows even when no AI service is reachable.
  • send starts a turn; the reply arrives as Thinking, then Response, through the Signal Emitter on guide:ai. A failed turn sends Error, whose text is safe to show.
  • Checking activeTurnId first avoids sending while a turn runs, and .catch logs any other failure instead of leaving an unhandled rejection.
  • The answer needs the project’s AI service. Without one, pressing Q logs why the guide could not answer.
QuizAsk.jx
#pragma lifecycle(startup, dispose)
// Scene: an AI Agent named "Guide". Other scripts emit 'quiz/ask' with a question string.
let conversation;
let stopWatching;
async function ask(question) {
if (conversation.getSnapshot().activeTurnId) {
log('The guide is still answering; try again in a moment.');
return;
}
try {
await conversation.send(question);
} catch (error) {
log('The guide could not answer:', error.message);
}
}
function startup() {
conversation = findEntity('Guide').getComponent(AIModelComponent).getConversation();
if (!conversation) return log('The guide is not available here.');
stopWatching = conversation.subscribe(() => {
const snapshot = conversation.getSnapshot();
const last = snapshot.messages[snapshot.messages.length - 1];
if (last && last.role === 'assistant' && last.status === 'complete') log('Answer:', last.text);
});
on('quiz/ask', (question) => ask(question));
}
function dispose() {
if (stopWatching) stopWatching();
}
  • Checking activeTurnId first avoids the “Conversation is busy.” error; the try/catch still covers other failures.
  • subscribe calls back on every change, including each streamed chunk, so the listener waits for an assistant message whose status is complete. It may log the same answer more than once if other changes follow; use events (next example) when you need exactly one call per reply.
  • The subscription is released in dispose.
LiveReply.jx
#pragma lifecycle(startup)
// Scene: an AI Agent named "Guide" with a Signal Emitter on 'guide:ai',
// and a UI Label named "Reply" on the player's HUD.
let text = '';
function startup() {
const label = findEntity('Reply').getComponent(UILabelComponent);
on('guide:ai', (event) => {
switch (event.eventType) {
case EventType.AIAgent.Thinking:
text = '';
label.setProps({ text: '…' });
break;
case EventType.AIAgent.Writing:
text += event.data.text;
label.setProps({ text });
break;
case EventType.AIAgent.Response:
label.setProps({ text: event.data.text });
break;
case EventType.AIAgent.Error:
label.setProps({ text: event.data.text });
break;
}
});
}
  • Each Writing event carries one chunk, so the script appends it to text and shows the whole so far.
  • Response carries the full reply, which replaces the assembled text, so a lost chunk never leaves the label wrong.
  • Error text is written to be safe to show the visitor.
GuideNarrator.jx
#pragma lifecycle(startup)
// Scene: an AI Agent named "Guide" with an AI Dialog. Other scripts emit
// 'inventory/picked' with an item name, and 'quest/done' when a quest ends.
let conversation;
async function tell(text, persist) {
if (!conversation || conversation.getSnapshot().activeTurnId) return;
try {
await conversation.sendCommand(text, { persist });
} catch (error) {
log('The guide missed it:', error.message);
}
}
function startup() {
conversation = findEntity('Guide').getComponent(AIModelComponent).getConversation();
on('inventory/picked', (item) => tell(`The visitor picked up the ${item}. React in one short sentence.`, false));
on('quest/done', () => tell('The visitor finished the lighthouse quest. Remember this for later.', true));
}
  • A command never shows the prompt to the visitor; only the guide’s reaction appears in the dialog and is spoken.
  • persist: true keeps the second command in the Context, so the guide can mention the finished quest in later answers. The first is a passing remark and is not kept.
  • Commands also skip AIAgent::prompt, so scripts that count visitor questions are not affected.
GuideControls.jx
#pragma lifecycle(startup)
// Scene: an AI Agent named "Guide" with AI Text To Speech and a Signal Emitter on 'guide:ai',
// and two UI Buttons with Signal Emitters on 'guide/stop' and 'guide/replay'.
let conversation;
function startup() {
conversation = findEntity('Guide').getComponent(AIModelComponent).getConversation();
if (!conversation) return;
on('guide/stop', (event) => {
if (event.eventType !== EventType.UIButton.Press) return;
if (conversation.getSnapshot().activeTurnId) conversation.cancel();
conversation.stopSpeech();
});
on('guide/replay', (event) => {
if (event.eventType !== EventType.UIButton.Press) return;
conversation.replay().catch((error) => log('Nothing to replay:', error.message));
});
on('guide:ai', (event) => {
if (event.eventType === EventType.AIAgent.Cancelled) log('Stopped.');
if (event.eventType === EventType.AIAgent.Talking) log('The guide is speaking.');
});
}
  • cancel() stops the reply being written and keeps the part already shown; stopSpeech() silences a reply being spoken. Together they make one Stop button.
  • replay() speaks the latest finished reply again; the button press unlocks browser audio.
  • Cancelled and Talking confirm what happened, for example to update a button’s icon.
  • Replacing text on each Writing event. Each event carries only its own chunk. Append chunks, or wait for Response.
  • Sending while a turn runs. send throws “Conversation is busy.” Check getSnapshot().activeTurnId, or wait for AIAgent::idle.
  • Forgetting the Signal Emitter. Without one on the agent, on never hears any AIAgent::… event.
  • Not checking getConversation(). It is undefined in the editor and while the agent is off.
  • Calling dispose() on the conversation. It ends the conversation for the dialog and every script. Stop your own subscriptions instead.
  • Waiting on talking for the reply text. talking means audio started; the text arrives with response.