Remote messages and events
Section titled “Remote messages and events”A running Hoody Exec script can publish events to listening clients, receive messages from them, and answer calls to functions it exposes. Everything happens on the script’s own URL: a request header (or one query parameter) turns an ordinary request into a remote operation. Each capability is off until a magic comment switches it on.
Save this script as /hoody/storage/hoody-exec/scripts/default/1/jobs/build.js, so it answers at /jobs/build on exec-1 (routing).
// @mode worker// @remote-messages// @remote-token dashboard dash-7f3a9c2e5b1d4f60 messages
remote.on('message', (message) => { if (message.type !== 'start') return { accepted: false }; runJob(); // not awaited: the reply goes back at once return { accepted: true };});
async function runJob() { for (let pct = 0; pct <= 100; pct += 25) { remote.emit('progress', { pct }); await new Promise((resolve) => setTimeout(resolve, 500)); } remote.emit('done', { at: new Date().toISOString() });}
return { status: 'ready' };A client that listens on this script’s URL receives every progress and done event; a client that sends { "type": "start" } starts the job.
| Operation | Request on the script’s URL | Needs |
|---|---|---|
events | GET with X-Hoody-Remote: events, answered with a Server-Sent Events stream | @remote-messages |
send | POST with X-Hoody-Remote: send | @remote-messages |
call | POST with X-Hoody-Remote: call | @remote-call |
| attach | WebSocket offering the subprotocol hoody-remote.v1 | @remote-messages |
eval | POST with X-Hoody-Remote: eval | @remote-eval and an eval-scoped token |
capabilities | GET with X-Hoody-Remote: capabilities | nothing |
In the Hub, open Scripts, open the script and go to its Settings tab. Under Magic comments, open More settings. The Remote control group has switches for Remote messages, Remote calls and Remote code. Press Check changes, then the Save button showing the number of changes. Change remote keys in the code.
Publish events
Section titled “Publish events”remote.emit(event, data) sends one frame to every client listening to the script at that moment, from any run of the script. Events are not stored, so a client receives only those emitted while it is connected.
Listeners are grouped in rooms: one script, with one set of route parameter values, on one deployment. An event emitted while handling /rooms/42 reaches clients on /rooms/42, not /rooms/43 (rules).
Background work that outlives the request, like runJob() above, belongs in worker mode.
Listen for events
Section titled “Listen for events”Set DASHBOARD_TOKEN to the secret on the script’s @remote-token line (dash-7f3a9c2e5b1d4f60 in this example).
# The token is read from HOODY_EXEC_REMOTE_TOKEN (or --remote-token-file)export HOODY_EXEC_REMOTE_TOKEN="$DASHBOARD_TOKEN"hoody exec remote events stream jobs/build --tail info --count 20 --timeout 30s -c "$COMPUTER_ID"import { HoodyClient } from 'hoody-sdk';
const client = new HoodyClient({ baseURL: 'https://api.hoody.com', token: process.env.HOODY_TOKEN });const computerClient = await client.withComputer({ id: COMPUTER_ID, project_id: PROJECT_ID, server: SERVER});const conn = computerClient.exec.remote('jobs/build', { token: process.env.DASHBOARD_TOKEN });
for await (const frame of conn.streamEvents({ tail: 'info' })) { if (frame.event === 'progress') console.log('progress', frame.data); if (frame.event === 'done') break; // ends the stream}curl -N "https://$PROJECT_ID-$COMPUTER_ID-exec-1.$SERVER.computers.hoody.com/jobs/build?tail=info" \ -H "X-Hoody-Remote: events" \ -H "X-Token: $DASHBOARD_TOKEN"The server first sends an attached frame; the SDK and CLI validate it without displaying it. No job events arrive until the job runs. To start it, send { "type": "start" } from a second terminal, with HOODY_EXEC_REMOTE_TOKEN set to the same dashboard token:
hoody exec remote send jobs/build '{"type":"start"}' -c "$COMPUTER_ID"EventSource cannot set headers, so a browser uses the query form; close it on end, or it reconnects:
const url = 'https://PROJECT_ID-COMPUTER_ID-exec-1.SERVER.computers.hoody.com/jobs/build' + '?hoody-remote=events&token=dash-7f3a9c2e5b1d4f60';const source = new EventSource(url);source.onmessage = (e) => { const frame = JSON.parse(e.data); if (frame.event === 'end') source.close(); // stop EventSource from reconnecting else console.log(frame.event, frame.data);};Each frame is a JSON object named by its event member, from attached to end (frames, endings). ?tail= adds console output at or above the level named (error, warn, info or debug). Opening a stream does not run the script.
The SDK and CLI do not reconnect, and events emitted while a client is disconnected are lost: fetch current state through send or call after reconnecting.
Send messages and call functions
Section titled “Send messages and call functions”Register handlers with remote.on('message', fn) and remote.expose(name, fn). Each receives the message (or the call’s arguments) and a context object.
Save this script as /hoody/storage/hoody-exec/scripts/default/1/bots/worker.js, so it answers at /bots/worker on exec-1 (routing).
// @mode worker// @remote-messages// @remote-call// @remote-token bot env:BOT_TOKEN
globalThis.paused ??= false;
remote.on('message', async (message, ctx) => { remote.emit('received', { message, from: ctx.from }); return { paused: globalThis.paused };});
remote.expose('pause', (reason) => { globalThis.paused = true; remote.emit('paused', { reason }); return true;});
return { paused: globalThis.paused };Put BOT_TOKEN in an .env companion of bots/worker, at least 16 characters, and set the same value as an environment variable on the client. Without its @remote-token line, the script would need no token at all.
export HOODY_EXEC_REMOTE_TOKEN="$BOT_TOKEN"hoody exec remote send bots/worker '{"type":"ping"}' -c "$COMPUTER_ID"hoody exec remote call bots/worker pause '"maintenance"' --timeout-ms 5000 -c "$COMPUTER_ID"const conn = computerClient.exec.remote('bots/worker', { token: process.env.BOT_TOKEN });
const sent = await conn.send({ type: 'ping' });console.log(sent.reply); // { paused: false }
const called = await conn.call('pause', ['maintenance'], { timeoutMs: 5000 });console.log(called.result); // truecurl -X POST "https://$PROJECT_ID-$COMPUTER_ID-exec-1.$SERVER.computers.hoody.com/bots/worker" \ -H "X-Hoody-Remote: send" -H "X-Token: $BOT_TOKEN" -H "Content-Type: application/json" \ -d '{"message": {"type": "ping"}}'# {"ok":true,"reply":{"paused":false},"durationMs":3,"generation":"…"}
curl -X POST "https://$PROJECT_ID-$COMPUTER_ID-exec-1.$SERVER.computers.hoody.com/bots/worker" \ -H "X-Hoody-Remote: call" -H "X-Token: $BOT_TOKEN" -H "Content-Type: application/json" \ -d '{"name": "pause", "args": ["maintenance"], "timeoutMs": 5000}'# {"ok":true,"result":true,"durationMs":2,"generation":"…"}Sends the message, then calls pause.
# Sendhttps://PROJECT_ID-COMPUTER_ID-curl-1.SERVER.computers.hoody.com/api/v1/curl/request?url=https://PROJECT_ID-COMPUTER_ID-exec-1.SERVER.computers.hoody.com/bots/worker&method=POST&header=X-Hoody-Remote:%20send&header=X-Token:%20BOT_TOKEN&json={"message":{"type":"ping"}}&response=transparent
# Callhttps://PROJECT_ID-COMPUTER_ID-curl-1.SERVER.computers.hoody.com/api/v1/curl/request?url=https://PROJECT_ID-COMPUTER_ID-exec-1.SERVER.computers.hoody.com/bots/worker&method=POST&header=X-Hoody-Remote:%20call&header=X-Token:%20BOT_TOKEN&json={"name":"pause","args":["maintenance"],"timeoutMs":5000}&response=transparentOne request, one link
cURL runs inside your computer and can wrap any HTTP request into a single GET URL. The call stops being something you need a client for and becomes something you can paste into a browser, send in a chat, bookmark, schedule with cron, or drop into a no-code tool.
Nothing is installed on the machine that opens it. The link does carry whatever credentials the call needs, so treat it as you would treat those credentials. It also appears in the cURL service's request log, not only the target's. Prefer a delegated token with minimal permissions and an expiry: see API tokens.
Slashes, colons and braces pass through as they are. The one character you must
encode is an & inside a value, which happens when the wrapped URL
carries its own query string. Left raw it ends the value early, and the rest is
read as cURL's own parameters, so you get a 200 on a request you did
not make.
How the wrapping works Chaining calls into one link Turning a link into a shortcut
If no run of the current version has registered a handler in the room, the first send or call runs the script once (a REMOTE_INIT run), so register handlers once everything they use is ready (details).
Attach over one WebSocket
Section titled “Attach over one WebSocket”One socket carries events, send and call for a client that listens and sends; eval is refused on it. It needs @remote-messages, and a @remote-token used for it needs the messages scope: give a call token messages,call to call over the socket.
# Prints each frame and sends each stdin line as a message; the session ends with stdinexport HOODY_EXEC_REMOTE_TOKEN="$BOT_TOKEN"echo '{"type":"ping"}' | hoody exec remote connect bots/worker -c "$COMPUTER_ID"const conn = computerClient.exec.remote('bots/worker', { token: process.env.BOT_TOKEN });const session = await conn.connect();
// Print every frame, as the CLI does, and send one messageconst reading = (async () => { for await (const frame of session.streamEvents()) console.log(frame);})();const sent = await session.send({ type: 'ping' });console.log(sent.reply);session.close();await reading;There is no curl form: open a WebSocket offering hoody-remote.v1 and write the attach frames.
With ws: true on exec.remote(), the SDK shares one socket for send, call and streamEvents instead. A streamEvents call with tail opens its own socket, which closes when the iteration ends.
Evaluate code in a running script
Section titled “Evaluate code in a running script”eval runs an expression in the scope of the script’s latest run of its current version, so it can read and change top-level variables while you debug a live script. It needs @remote-eval and a @remote-token with the eval scope; @token never unlocks it. bots/worker also needs // @remote-eval and a // @remote-token ops env:OPS_EVAL_TOKEN eval line. Put OPS_EVAL_TOKEN in its .env companion next to BOT_TOKEN, at least 16 characters, and set the same value as an environment variable on the client before running the examples.
export HOODY_EXEC_REMOTE_TOKEN="$OPS_EVAL_TOKEN"hoody exec remote evaluate bots/worker 'globalThis.paused' --start -c "$COMPUTER_ID"const conn = computerClient.exec.remote('bots/worker', { token: process.env.OPS_EVAL_TOKEN });
const out = await conn.evaluate('globalThis.paused', { start: true });console.log(out.result, out.logs);curl -X POST "https://$PROJECT_ID-$COMPUTER_ID-exec-1.$SERVER.computers.hoody.com/bots/worker" \ -H "X-Hoody-Remote: eval" -H "X-Token: $OPS_EVAL_TOKEN" -H "Content-Type: application/json" \ -d '{"expression": "globalThis.paused", "start": true}'eval has no link: it would store the eval token in the URL.
The edit made a new version with no run yet, so these examples pass start to run the script once first. Without it, eval answers 409 REMOTE_NO_RUN until the script has run (fields).
Protect the channel with tokens
Section titled “Protect the channel with tokens”Remote operations (events, send, call, attach, eval and the REMOTE_INIT run) do not run the directory’s pre.ts or post.ts, so a login check in pre.ts does not protect them. Protect them with tokens, and check anything else inside your handlers.
Tokens are checked before capabilities, in this order:
- If the script declares any
@remote-token, only those tokens admit remote operations. The script’s@tokenno longer does. - Otherwise, the script’s
@tokenadmitsevents,send,calland attach. - Otherwise, remote operations need no token. Anyone who can reach the computer URL can use the enabled capabilities, subject to your proxy permissions.
@remote-token <name> <secret|env:NAME> [scope] declares a token; scope is a comma list of messages, call and eval, and is messages,call when left out. Give a listening dashboard a messages token, and call and eval their own. A @remote-token line whose values do not parse matches nothing, yet it still turns off @token and unauthenticated access; other valid remote tokens are still accepted. A misspelled // @remote-token protects nothing (rules). Prefer a header, the SDK or the CLI to ?token=, because a URL can end up in browser history. Keep secrets in .env companions and emit small frames.
Removing or rotating a token ends its open streams within about 15 seconds, unless another current token accepts them. Removing the last @remote-token line falls back to @token, or to no token when the script has none, so to cut every client off, remove @remote-messages or replace the token.
Check what a script allows
Section titled “Check what a script allows”capabilities reports what the script enables, its token names and scopes (never the secrets), its handlers and exposed functions, and the fix for each disabled capability. Without a valid token, a script with @token or @remote-token lines answers 200 with token_required: true and the names of its @remote-token lines only (an empty list when it has only @token); a script with neither answers in full to anyone.
export HOODY_EXEC_REMOTE_TOKEN="$BOT_TOKEN"hoody exec remote capabilities get bots/worker -c "$COMPUTER_ID"const conn = computerClient.exec.remote('bots/worker', { token: process.env.BOT_TOKEN });
const caps = await conn.getCapabilities();console.log(caps.capabilities?.call?.exposed); // ['pause']curl "https://$PROJECT_ID-$COMPUTER_ID-exec-1.$SERVER.computers.hoody.com/bots/worker" \ -H "X-Hoody-Remote: capabilities" -H "X-Token: $BOT_TOKEN"Shows what bots/worker allows. Replace BOT_TOKEN.
https://PROJECT_ID-COMPUTER_ID-curl-1.SERVER.computers.hoody.com/api/v1/curl/request?url=https://PROJECT_ID-COMPUTER_ID-exec-1.SERVER.computers.hoody.com/bots/worker&method=GET&header=X-Hoody-Remote:%20capabilities&header=X-Token:%20BOT_TOKEN&response=transparentOne request, one link
cURL runs inside your computer and can wrap any HTTP request into a single GET URL. The call stops being something you need a client for and becomes something you can paste into a browser, send in a chat, bookmark, schedule with cron, or drop into a no-code tool.
Nothing is installed on the machine that opens it. The link does carry whatever credentials the call needs, so treat it as you would treat those credentials. It also appears in the cURL service's request log, not only the target's. Prefer a delegated token with minimal permissions and an expiry: see API tokens.
Slashes, colons and braces pass through as they are. The one character you must
encode is an & inside a value, which happens when the wrapped URL
carries its own query string. Left raw it ends the value early, and the rest is
read as cURL's own parameters, so you get a 200 on a request you did
not make.
How the wrapping works Chaining calls into one link Turning a link into a shortcut
Advanced
Section titled “Advanced”- Version header:
X-Hoody-Remote-Version: 1on an answer shows the server supports remote operations. See operations. - Script versions: the
generationonattachedand event frames names the script version that produced them, so a listener can tell when an edit took over. See frames. - Eval targets:
target: "globals"evaluates in a worker’s globals with no earlier run, when the script has no run or no usable run scope;functionwithargspasses arguments to code you send. See eval. - Comments through the API: a refusal for a disabled capability carries
details.fix, with the comment and themagic-comments/updatecall that adds it. - Find remote scripts: the script list filters by
remote(any,none,messages,call,eval), and reading a script returns its enabled operations, token names and URL. - Errors in scripts: CLI exit codes and typed SDK errors separate a missing or wrong token from a disabled capability. See CLI and SDK.
Reference
Section titled “Reference”The reference holds frames, errors, token rules, limits and troubleshooting.
What’s Next
Section titled “What’s Next”- Magic Comments
- Authentication
- Execution Modes
- Writing Scripts:
res.sse()for event streams the script answers itself