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.
Before you start
Section titled “Before you start”- You have an agent with a Signal Emitter on it; see Creating an agent.
- Listening uses
on(signal, callback)andEventType; see Scripting. - Async code:
sendreturns a promise, so call it withawaitinside anasyncfunction, and catch its errors.
The conversation
Section titled “The conversation”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. |
send |
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(message |
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. |
Messages and commands
Section titled “Messages and commands”- A message (
send('text'), or{ kind: 'message', text }) is ordinary visitor input: it appears in the chat, sendsAIAgent::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 nopromptevent, 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.
The snapshot
Section titled “The snapshot”getSnapshot() returns:
| Field | What it holds |
|---|---|
messages |
Every entry: { id, turn, 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, speech, speech, speechPhase, speechError |
The state of the reply’s speech. |
Agent events
Section titled “Agent events”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'.
Conversation events
Section titled “Conversation events”| 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-, -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.
Activity events
Section titled “Activity events”The model service reports what happens inside a turn:
| Group | Events |
|---|---|
| Turns | turn-started, turn-, turn-failed, turn- |
| Instructions | instructions-, instructions-, skill-updated, tool-updated |
| Skills | skill-, skill-loaded, skill- |
| Tools | tool-, tool-, tool-, tool-, tool-failed, tool- |
| Memory | memory-, memory-read, memory-, memory-, memory-, memory- |
| Context | context- |
Order of events
Section titled “Order of events”| Outcome | Events, in order |
|---|---|
| Success | prompt (messages only), thinking, writing (once per chunk), response, turn-, idle |
| Cancelled | cancelled, turn-, 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.
Examples
Section titled “Examples”1. Ask the guide with a key
Section titled “1. Ask the guide with a key”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.
#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));}Pressing Q sends a question to an AI agent from a script with conversation.send; the agent's thinking, response and error events arrive through its Signal Emitter and are logged.
Click the scene, then press Q to ask the guide a question and read the answer in the log. The answer comes from the AI service: without one, the log shows why the guide could not answer.
getConversation()andgetSnapshot()work without contacting the model, so the startup line shows even when no AI service is reachable.sendstarts a turn; the reply arrives asThinking, thenResponse, through the Signal Emitter onguide:ai. A failed turn sendsError, whose text is safe to show.- Checking
activeTurnIdfirst avoids sending while a turn runs, and.catchlogs 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.
Snippets
Section titled “Snippets”1. Ask a question from game logic
Section titled “1. Ask a question from game logic”#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
activeTurnIdfirst avoids the “Conversation is busy.” error; thetry/catchstill covers other failures. subscribecalls back on every change, including each streamed chunk, so the listener waits for an assistant message whosestatusiscomplete. 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.
2. Stream replies into your own label
Section titled “2. Stream replies into your own label”#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
Writingevent carries one chunk, so the script appends it totextand shows the whole so far. Responsecarries the full reply, which replaces the assembled text, so a lost chunk never leaves the label wrong.Errortext is written to be safe to show the visitor.
3. Tell the agent what just happened
Section titled “3. Tell the agent what just happened”#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: truekeeps 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.
4. Stop and replay buttons
Section titled “4. Stop and replay buttons”#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.CancelledandTalkingconfirm what happened, for example to update a button’s icon.
Common mistakes
Section titled “Common mistakes”- Replacing text on each
Writingevent. Each event carries only its own chunk. Append chunks, or wait forResponse. - Sending while a turn runs.
sendthrows “Conversation is busy.” CheckgetSnapshot().activeTurnId, or wait forAIAgent::idle. - Forgetting the Signal Emitter. Without one on the agent,
onnever hears anyAIAgent::…event. - Not checking
getConversation(). It isundefinedin 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
talkingfor the reply text.talkingmeans audio started; the text arrives withresponse.