Writing a script
The script editor is the workspace where you write code, test it on live data and set up the schedule. The screen is split into two parts: on the left — the code editor with the console under it, on the right — the settings panel: the Active toggle and the Save button, then the sections Metadata and Schedule and, for a saved script, State, Runs and Facebook calls. On a wide screen the border between the editor and the console can be dragged with the mouse, and so can the border between the editor and the panel when the window is wide enough for the panel to stand beside the editor. The AI assistant is not a part of this page: it is the assistant panel of the window (see AI assistant).
In a narrow window the settings panel is folded: Save moves to the header of the window, and the sections open in a sheet from the "…" menu of the header — the Settings item.

How to create a script
-
Open the Scripts section and click + Create script. The editor opens with a code template — the same example as in the QubApp SDK section below: it pauses for 24 hours the ads with spend over $10 and ROAS below 0.5.

The template: // Script runs on cron schedule or manually via the Run now button. // SDK: QubApp.ads()/adsets()/campaigns() + ctx.state/fetch/now + console. function main() { const ads = QubApp.ads() .withCondition('spend_24h > 10 AND roas_24h < 0.5') .get() for (const ad of ads) { console.log('pausing', ad.name, 'roas24h=', ad.roas_24h) ad.pause({ duration: '24h', reason: 'low roas' }) } }
-
In the right panel, in the Metadata section, fill in the script Name (an empty field shows the hint My script) and Description (the hint What this script does).
-
In the central editor, write the body of the
main()function — exactly what the script should do (see the QubApp SDK section below). Settings and helpers can be declared next to it — see What a script is made of. -
In the Schedule section, set how often the script will run automatically (see Schedule). You can leave it empty if you will only run it manually.
-
Click the Run now button below the editor to test the script on live data — the result appears in the console (see Testing the script).
-
Turn on the Active toggle in the top-right corner and click Save.
You can save with the keyboard shortcut Ctrl + S (on macOS — Cmd + S) right from the editor, without moving the cursor to the button.
Under the Active toggle a short line shows how the script will run:
- inactive — the toggle is off: the script does not run on its own, and the Run now button does not run it either;
- scheduled — the toggle is on and at least one schedule is correct;
- manual — the toggle is on, but there is no correct schedule, so the script runs only at the Run now button.
For a saved script the toggle saves the whole draft at once, with the code, the same way Save does.
If the script is a task rule, the line shows the kind of the rule — On a task event, Transition check or Task card action — in place of manual; see Task rules.
The settings panel of a script also has the Task rule section; a built-in script does not have it. It turns the script into a task rule; its fields are described in Task rules. A hint under the section repeats what the chosen kind does. For On a task event: The script runs when the chosen events happen to the tasks of the chosen projects; the events arrive in ctx.events. A change made by the script wakes the other rules and the script itself too, no further than the chain length limit. For Transition check: The script decides before the change is saved whether the task may change its status: ctx.deny(reason) refuses the transition, and the person sees the reason. A script error or running out of time is a check failure. For Task card action: The script is an item of the "…" menu in the task card; a press runs it on that task.
AI assistant
The editor has no chat of its own: the assistant is the assistant panel of the window, which opens with the "AI" button in the title bar. The button is shown to those whose permission template grants the AI chat right; the other conditions are in AI assistant and Desktop. The panel sees the code that stands in the editor at this moment, even if it is not saved. Describe the task in plain words ("stop ads with ROAS below 0.5 and spend over $20"), and the assistant writes code against the Qubix SDK.
A block of JavaScript code in the answer has an insert button with an icon in its header. Its tooltip reads "Insert into editor:" and names the screen. The button replaces the whole code in the editor with the code of the block; nothing is saved by it — click Save yourself. The button appears only if you may change the code of this script. An answer the assistant gave on another screen, another script included, has no such button; an answer restored from the history of the chat has it in any script editor.
The assistant can also come up with a Name and Description for the script from its code. The buttons are in the Metadata section: each of the two fields has a sparkle icon at its right edge. Its tooltip is AI: suggest a name from the code for the name and AI: generate a description for the description. A click opens a small window with a choice of the model (the choice is remembered) and a line for your request; the hint in the line gives an example — e.g. "shorter, mention FB" for the name and e.g. "one line, what it does" for the description. Type the request and press Enter: the answer replaces the text of the field, and the text that stood there is passed to the assistant as the current one. Esc or a click aside closes the window without a request. The assistant is asked for a name of three to five words and a description of one or two sentences. If the assistant returns an empty answer, the field stays as it was and the panel says so: AI Assistant returned an empty answer. The field is left unchanged — try again or refine your request.
The sparkle icons are shown only to those whose permission template grants the AI chat right and only while a model is available for them; without them the fields are filled in by hand.
What a script is made of
A run starts with the main() function. It is declared at the top level of the script exactly once and takes no parameters; both function main() { … } and const main = () => { … } work.
Next to main(), the top level can hold declarations of functions, const, let, var and class — the settings and helpers that main() uses. There must be no standalone actions at the top level: a function call on its own line, an assignment, a loop or a condition goes inside main() or inside a function it calls.
const ROAS_FLOOR = 0.5 // a setting
function isWeak(ad) { // a helper
return ad.spend_24h > 20 && ad.roas_24h < ROAS_FLOOR
}
function main() {
for (const ad of QubApp.ads().withCondition('spend_24h > 20').get()) {
if (isWeak(ad)) console.log('weak ad', ad.name)
}
}
The check runs on save, and the code is compiled in full along the way, so a mistake in how it is written is caught right away rather than on the first run. A script that fails the check is not saved: the reason appears next to the Save button in the right panel, and in full — in its tooltip.
| Reason | What to fix |
|---|---|
| "At the top level you may declare functions and values, but not perform actions. Move this line inside main()." | there is an action at the top level — move it inside main() |
"The script has no main(). Declare function main() { ... } at the top level." | declare the entry point |
| "main is declared at the top level more than once. Keep one declaration." | keep one main declaration |
| "main() must take no parameters." | remove the parameters of main |
| "main must be a function: …" or "main must be a function, not a class." | the name main is given to a value or a class — make it a function |
| "The name fb is already defined by the platform, and declaring it at the top level would replace it. Pick another name." | rename your declaration. Every name the platform already provides is taken — for example, the Qubix commands (sql, ctx, QubApp, console, fb, Qubix), the timers (setTimeout and its relatives) and the JavaScript built-in objects (JSON, Math); the refusal names the exact name that is taken |
| "The script does not parse: …" | a mistake in how the code is written; after the colon — its description and location |
| "The script is empty. …" | write the main() function |
| "The server is busy checking other code right now, so this script was not checked. Save it again a little later." | the server was busy — save the script again |
Saving also fails when the code was changed without you: if someone else saved the script's code while you had it open, the same place shows "The script's code was changed after you opened it. Reload the script and make your change again." This way your edit does not silently overwrite someone else's: open the script again, look at what changed and repeat your edit. The same refusal also comes when you click the Active toggle: it saves the whole draft together with the code.
An administrator can append a shared layer of helpers to every script — Convenience layer over fb (JavaScript) on the JavaScript tab (see System). A clash with the names of the built-in layer, like fb in the table above, is caught already on save. But if the administrator has changed the layer, the clash shows only at run time: the script works, and the console of every run warns "… is declared both at the top level of this script and in the wrapper layer; one silently replaces the other, so rename yours." If the clash kept the layer from being attached, the layer is switched off for that run, and fb along with the layer's other helpers is unavailable — a line in the console says so too.
What main() returns
main() may return nothing. If it returns an array of plain objects, Qubix takes it as the table of the run: every object is a row, its keys are the columns in the order they first appear, and a row without some key gets an empty cell there. A nested object or array goes into a cell as JSON text, a date — as a time in UTC. An async function main() works the same way: the table is taken from the value its promise settles with.
function main() {
return QubApp.campaigns().withCondition('spend_24h > 0').get()
.map((c) => ({ campaign: c.name, spend: c.spend_24h, roas: c.roas_24h }))
}
The table is used in two places:
- the AI Assistant shows it when it runs the script, and in a spreadsheet open for editing its answer can be inserted as a sheet bound to the script;
- every scheduled run rewrites the sheets bound to the script with the fresh table — see A sheet filled by a script.
The Run now button runs the script but does not show the table — only the console. A value other than an array of plain objects is not a table: the assistant says so, and a bound sheet is not updated.
QubApp SDK
The Server SDK is synchronous: every command returns its value right away, so a script is written as a plain sequence. What happens if you do write async, await or .then — in the Auto-rule and script SDK reference.
A script is a main() function, inside which you work with ad data through the QubApp set of commands. Three levels are available:
QubApp.ads()— ads,QubApp.adsets()— ad sets,QubApp.campaigns()— campaigns.
Each of them returns a selection that can be filtered and iterated over. The selection has methods:
.withCondition('...')— select by a condition on metrics (for example,'spend_24h > 10 AND roas_24h < 0.5');.orderBy('field', 'desc')— sort;.withLimit(n)— limit the count;.get()— get an array of items;.first()— get the first item.
Every ad, ad set or campaign has actions:
.pause({ duration: '24h', reason: '...' })— pause for the specified period;.activate({ reason: '...' })— turn back on;.getStatsFor('24h')— get metrics for a period.
.pause() and .activate() are carried out after the run ends, not at the moment of the call. What this changes, how long a pause lasts and which ad networks the commands reach — in When pause and activate take effect. The full list of selection methods, the rules of withCondition conditions and the offers (QubApp.offers()) — in QubApp selectors.
Basic example: pause ads with spend over $10 and ROAS below 0.5 over the past day.
function main() {
const ads = QubApp.ads()
.withCondition('spend_24h > 10 AND roas_24h < 0.5')
.get()
for (const ad of ads) {
console.log('pausing', ad.name, 'roas24h=', ad.roas_24h)
ad.pause({ duration: '24h', reason: 'low roas' })
}
}
More ready-made snippets are in the Script examples section.
Autocomplete works in the editor: start typing ad. or QubApp. — Qubix will suggest the available fields and methods with descriptions. That way you won't have to keep the list of metrics in your head.
Submitting spend: QubApp.submitSpend
The spend of a platform that has no export of its own into Qubix can be written by the script itself — with the QubApp.submitSpend command. This is the same intake that a request with a key and the assistant use: the spend shows up in the same reports as the spend Qubix imports itself.
function main() {
try {
const res = QubApp.submitSpend({
traffic_source_id: 'a1b2c3d4-0000-4000-8000-000000000001',
currency: 'EUR',
tz: 'Europe/Berlin',
rows: [
// a platform ad. If it is not in Qubix yet, the first batch creates the ad and the campaign;
// the campaign's owner is the person whose name pattern appears in the campaign name (here — anna)
{ date: '2026-09-28', hour: 10, ad_id: '84512', campaign_id: '3071', campaign_name: 'push RU 28.09 anna', ad_name: 'banner 1', spend: 12.5, impressions: 1000, clicks: 40 },
// spend of a whole website
{ date: '2026-09-28', hour: 10, website_id: 'a1b2c3d4-0000-4000-8000-000000000002', spend: 3 },
],
})
console.log('Rows written:', res.written, res.currency, res.tz)
} catch (e) {
console.error('Spend not submitted:', e.message)
}
}
One call is one batch of one traffic source:
| Field | What to pass |
|---|---|
traffic_source_id | the identifier of the traffic source the spend is written to |
currency | the currency code of all amounts in the batch: USD, EUR… |
tz | the time zone in which the rows' dates and hours are given: UTC, Europe/Moscow… |
rows | an array of spend rows |
All four fields are required: unlike a request with a key, there are no defaults for the currency and the time zone here.
A row carries the date date (YYYY-MM-DD), the hour hour (from 0 to 23), the amount spend and at most one of the two — an ad's ad_id or a website's website_id; a row with neither is spend of the traffic source: of the channel named in channel, or of the source as a whole. A new ad also requires its campaign identifier campaign_id. Optional: impressions impressions, clicks clicks, and for a new ad — the names campaign_name and ad_name. This is the same row shape as in a request with a key: what each field means, why repeating the same cell replaces the previous numbers instead of adding to them, how the amounts are converted into dollars, and which sources, ads and websites you may write to — in the Spend intake by key article. Values are passed with their own types: identifiers, the currency, the time zone, the date and the names — as strings, the amount — as a number, the hour, impressions and clicks — as whole numbers.
The call returns an object:
| Field | What it holds |
|---|---|
written | how many rows were written |
currency | the batch currency code in capital letters |
tz | the rows' time zone |
On any refusal, no row of the batch is written.
A new ad is created only if its campaign gets an owner into whose ads the script's owner may write: the owner becomes the person whose name pattern appears in the campaign name, or the person an administrator assigned to that campaign ID. Otherwise the intake refuses — "new campaign … gets no owner". A campaign without an owner is created only by a script whose owner is an administrator. More — Spend per ad.
Where the command works
QubApp.submitSpend works in scripts of the Scripts section — both on a schedule and via the Run now button. Website page handlers and Britva rules do not have this command. In system scripts (marked System in the list) it always answers with the error QubApp.submitSpend is not available here: a system script has no human owner on whose behalf the spend could be written.
On whose behalf the spend is written
The spend is written on behalf of the script's owner — whoever clicked Run now and whoever edited the code:
- the owner must have the Manage traffic sources right in their permission template; an owner who is an administrator needs no separate right;
- the traffic source, the ads and the websites are checked against the owner's rights — the same way as for a key issued to the owner;
- if the owner is no longer among the users or their account is deactivated, the call answers with a refusal.
Only code saved by the owner
A script with an owner runs with that owner's rights, whoever pressed the button or edited the script. That is why its code is guarded: only the owner and an administrator change it.
What the others can do. A team lead — or anyone whose permission template lets them edit the scripts of the owner's team or of all teams — opens such a script, runs it with the Run now button, switches it on and off and changes its Name, Description and Schedule. The code of the script and its visibility (the switch in the header of the window) and the Task rule section are changed only by the owner and an administrator. For anyone else the code editor is read-only with the note Only the script's author or an administrator can edit its code., and an attempt to save changed code or a changed rule of tasks, or to run changed code from the editor, is refused with the same words; a change of the visibility is refused too.
An exception — a script without an owner, such as the built-in ones, or a team script that has no owner. It runs with nobody's rights, and its code is changed by an administrator and, for a team script, also by those whose permission template lets them edit that team's scripts. QubApp.submitSpend does not work in such a script at all: there is nobody to write the spend on behalf of.
So that someone else's code does not write spend on the owner's behalf, QubApp.submitSpend works only in code that was last confirmed by the owner themselves or by an administrator:
- the code of a new script is confirmed at once: whoever created the script is its owner;
- the owner or an administrator changed the code in the editor and clicked Save — the new code is confirmed. The Active toggle confirms it the same way: it saves the whole draft together with the code;
- a save through the
script_savetool over MCP confirms it the same way, if the owner or an administrator passed thecode_fpof the version they read and changed the code; - code that was saved by someone else, or saved without the fingerprint of the version that was read, is not confirmed: it does not submit spend until the owner or an administrator changes it in the editor and saves it. To accept someone else's edit, it is enough for the owner to change at least one character in the code;
- a save without changes to the code confirms nothing — neither with the Save button nor with the Active toggle;
- an edit of the code from the Qubix Drive desktop app does not confirm the code. A script created from there as a new file is confirmed at once, like any new one;
- the Run now button runs the code from the editor, and spend is submitted only by code that matches the last confirmed version. So an unsaved edit does not submit spend — save it first;
- scripts saved before this command appeared have no confirmed code yet: submitting opens for them with the first code edit by the owner or an administrator.
In unconfirmed code the call answers with the refusal "QubApp.submitSpend works only in code the script's owner or an administrator changed and saved. This code was saved by someone else or is not saved: the owner has to change the code and save the script in the panel (a save from Qubix Drive does not confirm it)." If it is not caught, the run stops: in the run history it gets the error status, and the refusal text stands as a red line under the console output.
Limits and refusals
Calls per run — no more than the submitSpend calls per run setting in the Spend submission (QubApp.submitSpend) group on the JavaScript tab allows (see System). One call carries one source, so a script that submits the spend of several sources may need a higher limit — an administrator raises it. Every call that received an object with a rows array counts, even if it then ended in a refusal.
Any refusal is thrown as an exception: you can catch it with try…catch, as in the example above, and when it is not caught, it stops the run with the error status. Qubix refusal texts come in the language of the script owner's profile — Russian or English, and with any other profile language — in English. Always in English come: a message about a value of the wrong kind (TypeError), QubApp.submitSpend is not available here, the refusal when the owner is not among the users — then there is no profile to take the language from — and the refusal for an ad of another traffic source.
| Refusal | What happened |
|---|---|
QubApp.submitSpend expects an object: …, QubApp.submitSpend: rows must be an array, QubApp.submitSpend: rows[0].hour must be a whole number and the like (TypeError) | the call is built wrong: something other than an object was passed, rows is not an array, a field value is of the wrong kind |
| "QubApp.submitSpend: at most N calls in one run. …" | the limit of calls per run is used up |
QubApp.submitSpend: the script's owner is not among the users, so there is nobody to write the spend for. | the script's owner is not among the Qubix users |
| "QubApp.submitSpend: the script's owner is deactivated." | the owner's account is deactivated |
| "You do not have the right to do this. Ask an administrator to add it to your permission template." | the owner does not have the Manage traffic sources right |
| "QubApp.submitSpend works only in code the script's owner or an administrator changed and saved. …" | the code is not confirmed — see above |
| "QubApp.submitSpend: rows[0].ad_id is longer than N bytes." | the value is longer than Qubix accepts |
cost intake: outside the writer's scope: ad "…" belongs to another traffic source — an ad has exactly one, and its spend is accepted only under it | the ad already belongs to another traffic source: an ad has exactly one, and its spend is accepted only under it |
| "The spend was not stored: …" | the spend intake did not accept the batch. After the colon — the reason, for example "the currency is not named: …" or "no traffic source … you may write"; rows in the reason are numbered from zero, as in the rows array |
Qubix tools: QubApp.mcp
QubApp.mcp calls the tools of this Qubix installation — the same ones an external program reaches over MCP/API — with the rights of the script's owner and with no key: QubApp.mcp.get_dashboard({…}), QubApp.mcp.campaign_save({…}) and every other tool the owner may use. It works only in code the owner or an administrator saved, like QubApp.submitSpend. All of it — in Qubix tools from code; a complete example — Tracker campaign auto-optimization.
Database queries
Besides the current ads available through QubApp, a script can read data straight from the Qubix database with the sql command. It is a read-only query written as a tagged template:
const rows = sql`
SELECT primary_country AS country, sum(spend_24h) AS spend
FROM v_ads_stats
WHERE spend_24h > ${10}
GROUP BY primary_country`
for (const row of rows) console.log(row.country, row.spend)
A query returns an array of rows; each row is an object whose keys are the column names. Values you pass through ${…} are sent as safe parameters — you do not escape anything by hand, and SQL injection is not possible. Queries are read-only: a script can read data but cannot change anything. What a query can reach is limited to the data your role is allowed to see.
Your own databases: Qubix.db
Besides the Qubix database, a script can read and change your own database with the Qubix.db command — which databases it connects to is listed in Which databases:
const db = Qubix.db.connect('postgres://report:[email protected]:5432/crm')
const rows = db.query('SELECT id, email FROM customers WHERE country = $1', ['DE'])
db.close()
The database host must be on the Database hosts for scripts list, which an administrator maintains. Instead of a connection string, Qubix.db.connect takes the name of a connection saved in the Secrets panel — then the password stays out of the code. The connection string, saved connections, the query, exec and close methods, the limits and refusals — in the Your own databases: Qubix.db article.
State between runs
A script can remember values between runs through ctx.state — this is its personal memory:
ctx.state.set('key', value)— save;ctx.state.get('key')— read;ctx.state.delete('key')— delete.
For example, this lets you remember which ads have already been processed and not touch them again. The current contents of the memory are visible in the right panel in the State section of a saved script; the number of entries stands next to the section name. The table has two columns: Key and Value — a string is shown as it is, any other value as JSON text, and an empty value as null. The Delete link at the end of a row deletes that entry at once, without a confirmation. After every run started with the Run now button the table is refreshed by itself.
A saved value must fit into JSON: numbers, strings, true/false, null, arrays and plain objects. NaN, Infinity, a function, a date outside years 0–9999, an object that refers to itself, or nesting deeper than 10,000 levels cannot be saved: ctx.state.set() then throws an error right away and the previously saved value stays. If the error is not caught, it stops the run — in the run history the run gets the error status, and the values the script managed to save earlier stay. If the run must go on anyway, wrap the call in try…catch.
Requests to external services
The ctx.fetch(url, opts) command makes an HTTP request to the outside — for example, to send
a notification to a messenger or to call someone else's API.
AI mode
Open the assistant panel of the window — the "AI" button in the title bar — and describe
the task in plain words: "Send a Telegram notification when a campaign's ROAS drops below
0.5 — through the proxy socks5://…". It writes the code with ctx.fetch and the proxy, and
the insert button in the header of the code block puts it right into the editor (see AI assistant).
Manual mode
const res = ctx.fetch('https://api.telegram.org/bot<TOKEN>/sendMessage', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chat_id: 123456, text: 'ROAS dropped below 0.5' }),
})
console.log(res.status, res.ok)
opts accepts:
| Field | What it sets |
|---|---|
method | the HTTP method; GET by default |
headers | request headers, an object |
body | the request body as a string |
timeout_ms | the response timeout for this call, in milliseconds |
proxy | a proxy for this call — see below |
The answer comes back as an object: res.status (the code), res.body (the body as a
string), res.headers (the response headers), res.ok (true on codes 200–299).
A request through your own proxy
So that the outside service doesn't see your server's address, any ctx.fetch call can go
through a proxy — it is set right in the call, in the proxy field:
const res = ctx.fetch('https://api.example.com/check', {
proxy: 'socks5://user:[email protected]:1080',
timeout_ms: 10000,
})
The proxy address is written as scheme://user:password@host:port (the user and password —
when the proxy requires them). Supported schemes:
http://andhttps://;socks5://andsocks5h://.
The proxy host is given by its IP address — a name is refused. A proxy at the server's own address or in its internal network is refused too, unless an administrator has added that network to the Internal networks for proxies, mail, postbacks and task import list (Services and jobs).
The proxy is set per call: within one run, different requests can go through different proxies or through none at all.
Requests through the fb command go through the browser profile's proxy automatically —
nothing to set there. The proxy field applies only to ctx.fetch, that is, to your own
outbound requests.
"Raise the budget of a profitable campaign on a condition" is a job not for ctx.fetch but
for the fb command: it sends your request to the Graph API through the connected browser
profile and can change what the profile has the rights to change — the daily budget included.
An example is in the "Requests to Facebook" section right below, and in
Facebook Qubix Bridge.
A saved key for an address
If a service wants a key in the Authorization header, the key need not stand in the code. Save it once in the Secrets panel: open the "…" menu in the header of the script (its tooltip says Actions) and choose Secrets; pick the Mine or the Shared tab (what they mean — in Saved connections), click Add and choose Address key. Two fields are filled in:
- Address — the address of the service: a host name without the scheme, the port and the path. Under the field: For example, api.example.com
- Key — the key itself: one line of Latin letters, digits and signs without spaces, up to 2048 characters. Under the field: Qubix adds it to code's requests to this address as the Authorization: Bearer header — only over https or over http to 127.0.0.1 or ::1 of this machine.
From then on Qubix adds the header Authorization: Bearer with this key to every request the code makes to that address, and replaces an Authorization header the code wrote itself, in any spelling. Qubix does not hand the key to the code: it is added to the outgoing request. A key is sent only over https; over http it goes only to 127.0.0.1 or ::1 of this machine and only when the request goes without a proxy, and a request by http to any other address with a key is refused and not sent. If the answer redirects the request, the key goes on only to the same address. The key of the owner of the script is looked up first among Mine, then among Shared.
In the list of the panel a key is shown by its address and, when the key is longer than eight characters, by its last four characters ("…" and four characters); the key itself is never shown, and the end of a shared key is not shown to those who may not manage shared secrets. A saved key is changed by entering a new value in the key field: under the field it says Enter a new value: it replaces the saved one. The address of a saved key is read-only: to change it, delete the key and add another. One person keeps up to 20 keys of their own.
Saving a key does not open the address for requests. If the address is not on the Fetch host list list (Qubix settings → JavaScript), the row of the key carries a red line. Until an administrator adds the address, requests to it are closed — the key waits.
Limits
- Outbound requests are only allowed to addresses from the allowlist. The administrator configures it in Qubix settings → JavaScript. If the list is empty, outbound requests are off; on an address not on the list the script gets a clear hint in the console.
- The number of outbound requests is limited by the Calls per run setting — see System.
In website server handlers and in Britva auto-rules the outbound request is the global
fetch(...) function — no ctx.. Its settings are the same: the same address allowlist and
the same proxy field. More — Landing page backend.
Requests to Facebook
The fb command sends your own request to Facebook — to Graph API or to any other *.facebook.com address — through a connected browser profile: with its access token, cookies, proxy and browser signature. A script can read from Facebook what our reports do not have, and change what the profile has the rights to change — for example, check a campaign's daily budget and raise it:
const res = fb.campaign(campaignId).request({
url: `https://graph.facebook.com/${campaignId}`,
params: { fields: 'name,daily_budget' },
})
The call form, the two ways to choose the executor profile, the answer shape, refusals, the fb.batch batch (many subrequests in one exchange) and the limits are covered in the dedicated Facebook Qubix Bridge section, along with ready-made building blocks for common requests.
Which standard JavaScript is available
A script runs on a JavaScript engine of its own — not in a browser and not in Node — so the set of global names differs from both. The list below was taken from a run on the very engine that runs your scripts.
The language itself is modern: class, arrow functions, for...of, spread ..., optional chaining ?., ??, destructuring with defaults, tagged templates, getters and setters.
The standard built-ins are all there: JSON, Date, RegExp, Math, Map, Set, WeakMap, WeakSet, Symbol, Proxy, Reflect, BigInt, Error, ArrayBuffer, Uint8Array and the rest of the typed arrays, encodeURIComponent and decodeURIComponent, and the modern methods along with them — Object.entries, Object.values, Object.fromEntries, Object.assign, Array.from, Array.prototype.flat / flatMap / at / includes, String.prototype.padStart / replaceAll / matchAll / trimStart / at, Number.isInteger.
Addresses: URL and URLSearchParams
Both names are available and behave the way you are used to, so code that parses links carries over from the browser almost as it is:
const link = new URL('https://track.example/hook?token=abc=def==&pixel=1&next=https%3A%2F%2Fshop.io%2Fa%3Fb%3D1')
link.searchParams.get('token') // 'abc=def==' — the '=' inside the value is kept
link.searchParams.get('next') // 'https://shop.io/a?b=1'
link.hostname // 'track.example'
Object.fromEntries(link.searchParams) // the whole query as an object
const out = new URLSearchParams({ piuid: '42', status: 'dep' })
out.append('sub1', 'a+b') // 'piuid=42&status=dep&sub1=a%2Bb'
Repeated parameters, an = inside a value, a percent-encoded nested address, append / set / delete / sort / forEach, iteration with for...of and the spread operator all work.
+ in a value is a spaceIn a query string + means a space — here, in the browser and in Node alike. So new URL('https://h/p?k=a+b').searchParams.get('k') gives a b, not a+b. On the way out we do the reverse and write a real plus as %2B, so out.append('k', 'a+b').toString() gives k=a%2Bb, and reading that back returns a+b. Trouble only comes from the outside: if a partner sends you a bare + inside an identifier, it arrives as a space, and that is the partner's way of encoding, not ours.
The behavior in each such case has been checked against Node — both on the way in and on the way out, for every printable ASCII character. The same URL and URLSearchParams are available in Britva rules and in website page handlers.
What the engine does not have
These names belong to the browser and to Node, not to the language, so a script does not get them: TextEncoder, TextDecoder, structuredClone, Intl, crypto, Buffer, process, require. You do not need modules here anyway: requests to the outside world go through ctx.fetch, a query to the Qubix database through sql, to your own database through Qubix.db, ad data through QubApp.
Of the browser's names, atob and btoa are there (Base64 to a byte string and back, the same as in the browser).
Building code at run time is off as well: eval is unavailable, and so is the function constructor behind functions. The name Function exists, so Function.prototype and instanceof Function work, but calling it — Function(...) or new Function(...) — throws EvalError: code generation from strings is not allowed on the Qubix server.
Schedule
In the right panel, the Schedule section sets when the script runs automatically. There can be several schedules — for example, once an hour and additionally at a specific time.
- Enter the schedule in cron format (for example,
*/5 * * * *— every 5 minutes) and click +. - Below the line, Qubix immediately shows a plain-words explanation — check that you understood each other correctly.
- To avoid recalling the cron syntax, click the AI icon in the line and describe the schedule in words ("every day at 9 a.m.") — Qubix will fill in the ready-made expression.
A script holds at most 100 schedule lines, each at most 512 bytes long (512 Latin characters); a longer list or line is not saved. A line is accepted in one of two forms: five fields that can be read — for example */5 * * * * — or a descriptor that starts with @ — for example @daily or @every 5m. Anything else is not saved: a line of six fields (with seconds), five fields that cannot be read, an empty line. The panel and the server check a line by the same rule; next to the Save button the panel shows Invalid schedule: …. Use 5 fields or an @-expression. — the dots stand for the line itself. The same refusal meets an attempt to switch such a script on with the Active toggle; switching a script off needs no valid schedule.
If no schedule is set, the script will not run on its own — only via the Run now button. For auto-run to work, the Active toggle must be on.
Testing the script with the "Run now" button
Below the code editor there is a console and a ▶ Run now button. It executes the code currently in the editor (if you may not change the code of the script — the saved one) on live data; a script with the Active toggle off is not run by the button — switch it on first. This is a safe way to test the logic without waiting for the schedule. Everything the script outputs via console.log appears in the console along with the run time, status and duration.
A value that is too large or too deeply nested is shown shortened in the console: a very long string is replaced by a mark with its size ([string, … bytes]), a cut-off part of an object or an array — by [Object] or [Array], and an object's reference to itself — by [Circular].

What the console shows:
- When you open a saved script, the console already holds the output of its latest run, if there is one, and says No runs yet if there is none. For a script that is not saved yet it says Save the script to see run console output, and the Run now button is switched off.
- Above the output stands a line: the start time, the status, the duration and, after it, the time of your code alone — … ms js, where the dots stand for the number of milliseconds. The whole duration is larger: it also counts the compilation and the preparation of the run.
- While the script runs, the console shows Running... A run that wrote nothing is marked Empty — the script logged nothing.
- Lines written with
console.logcome as plain text;console.info,console.warnandconsole.errorcarry a coloured level mark in front (INFO,WARN,ERROR). - If the run ended with an error, its text stands under the output in red. When the error is a refusal of an outbound request — the address is not on the allowed list or the list is empty — the red line is replaced by a block with the explanation (The script tried to reach …, but this host is not in the allowlist. or The script tried to call ctx.fetch(...), but fetch is disabled — the allowlist is empty.), a link to the settings of the list (Add … to allowlist or Open allowlist settings) and the Details toggle, which opens the original text of the error.
- Clear at the right end of the console toolbar hides the output of the run on the screen. Nothing is deleted: the run stays in the history, and the next run is shown as usual. After the click the console says Console cleared. Press ▶ Run now to see a fresh run.
- A run keeps at most 10 000 lines of the console and 2 MiB of their text. What does not fit is not stored. At the place of the cut the console shows the line … +… lines hidden (showing first …): the first dots stand for the number of hidden lines, the second for the number of lines shown above; the notes Qubix itself added after the cut stand below the line.
The Run now button performs real actions. If the code contains pause(), activate(), a changing fb request (POST), a write to your database through Qubix.db, a spend submission with QubApp.submitSpend or a QubApp.mcp tool that changes data, ads will actually be stopped or turned on, the change will go to the real Facebook, rows in the database will change, the spend will be written to the reports, and the tool will change what it changes — a campaign, an offer, a rule. To test the logic without consequences, first comment out the lines with actions and leave only console.log.
The Run now button becomes available after the script is saved for the first time.
Run history
The Runs section in the right panel keeps the history of the executions of a saved script for the last 180 days; the number of rows stands next to the section name. The table has three columns: Started (the time), Status and Duration. The status is one of:
- executed — the run finished without an error;
- error — the run stopped with an error;
- timeout — the time ran out (see Time limit of a run);
- compile error — the code could not be compiled, so nothing was executed.
The list shows 50 runs. The Show more button under it loads twice as many each time, up to 1000.
Clicking a row expands the detail of the run right under it — handy for figuring out why the script behaved unexpectedly:
- a line with the start time, the status, the duration and how the run started: on schedule for a run on schedule, manually for a run with the Run now button (older runs, from before the way of starting was recorded, show nothing here);
- the console output of that run, in the same form as in the console under the editor. A long output is first shown cut at a short height; the Show all button shows it whole and Collapse cuts it again — the button appears only when the output does not fit;
- under the output, in red, the text of the error, if the run ended with one (a refusal of an outbound request is shown as in the console — see Testing the script);
- the × in the corner folds the detail back.
For the runs of task rules the detail also lists the events the run was given: a line for each event with the task key, the event and, for a change, the field, and, when the change was made by a script inside a chain, step …, where the dots stand for the number of the step. The start of such a run can be task event, transition check or card action. The history also gets a line with the start gap in the change log and the status skipped: it says that a change of a task was not saved in the change log and the rule may not have received it. More — Task rules.
Time limit of a run
One time limit covers the whole run: the top level of the code, main() and everything it left waiting — timers (setTimeout, setInterval, setImmediate) and promises. The run ends when nothing is left waiting; if something still waits when the time is up, the run is stopped and gets the timeout status — so a setInterval that is never cleared always ends in timeout. A run has 30 seconds, unless the script was saved with a limit of its own (the max_runtime_ms field of the script_save tool over MCP); such a limit cannot be higher than Maximum script runtime (see System).
The number of timers a run may hold at once is limited too — 256 by default; a call beyond the limit throws an error. The memory of a run is limited by Memory per script.
The time limit also reaches code stuck inside a built-in operation: parsing a huge JSON, repeat with a huge number of repetitions, walking a huge array with empty slots with methods like forEach and map. A search by a complex regular expression that could not be completed does not answer "no matches" but throws the error Regular expression match failed: …; it can be caught with try…catch.
Deleting a script
To delete a script, open its card, open the "…" menu in the header (its tooltip says Actions) and choose Delete. The window asks: Delete script "…"? It will be deactivated and removed from the list. The dots stand for the name of the script. After you confirm, the script is switched off and disappears from the list. If you may not change the script, the deletion is refused. A built-in script has no such item: it is only switched off with the Active toggle.
If the card does not open
When a script cannot be loaded, the window shows the reason in place of the editor and two buttons: Retry tries to load the card again, Back to list returns to the list of scripts.