Relatude.DB.Scripting
1.1.12.44-alpha
dotnet add package Relatude.DB.Scripting --version 1.1.12.44-alpha
NuGet\Install-Package Relatude.DB.Scripting -Version 1.1.12.44-alpha
<PackageReference Include="Relatude.DB.Scripting" Version="1.1.12.44-alpha" />
<PackageVersion Include="Relatude.DB.Scripting" Version="1.1.12.44-alpha" />
<PackageReference Include="Relatude.DB.Scripting" />
paket add Relatude.DB.Scripting --version 1.1.12.44-alpha
#r "nuget: Relatude.DB.Scripting, 1.1.12.44-alpha"
#:package Relatude.DB.Scripting@1.1.12.44-alpha
#addin nuget:?package=Relatude.DB.Scripting&version=1.1.12.44-alpha&prerelease
#tool nuget:?package=Relatude.DB.Scripting&version=1.1.12.44-alpha&prerelease
Relatude.DB.Scripting
Server-side scripts for a site on Relatude.CMS, in three forms:
- Scripts of agents. An AI agent (Claude over MCP, or the agent of the CMS interface) writes one JavaScript program, and the server runs it in a sandbox next to the data. The script calls the site's agent tools in-process, loops, filters and adds up, and answers a summary. One call replaces dozens.
- Scripts people run. A saved script is a button on a node type's form or an item of the CMS interface's menu. The person fills in what it asks for, it runs with their rights, and what it returns is shown to them or put into the form.
- Hooks. A script in the design library's
hooks/folder runs inside every write of the node type it names, to reject the write or set values on the node.
Both run in Jint, an interpreter, with nothing of .NET in reach.
Setup
builder.AddRelatudeCMS()
.AddApi()
.AddModule<McpModule>() // for agents over MCP
.AddModule<ScriptingModule>();
The module is named script. It needs the Templates module (a standard module), as saved scripts and hooks are files of the design library. Its settings are a tab of their own in the database's admin UI, Scripts.
Scripts of agents
script_run
| Argument | |
|---|---|
title |
What the script does, in a few words, for the person |
code |
The JavaScript: the body of an async function, so return gives the result |
file |
A saved script, in place of code |
input |
Any JSON, given to the script as input |
node |
A node as an editor holds it, given to the script as node |
writes |
none (the default), drafts or live |
uses |
The services it calls: ai, translation, sms, email, imaging, fileToText, ipLookup, web |
limits |
{ writes, credits, messages }, lower than the site's own |
project |
A project to work in |
wait |
Seconds to wait before answering running |
The script declares what it will do and is held to it. writes is the most its tool calls may do: with none every change is refused, with drafts publishing, deleting, moving and linking are. A service not named in uses throws when called. The script runs as its caller: the same user, the same areas, the same project.
It answers { status, run, result, error?, log, stats: { ms, toolCalls, writes, credits, messages } }, status being completed, failed or cancelled. A run that takes longer than the wait answers { status: "running", run, progress, log }; script_status { run, wait? } waits again and script_stop { run } stops it. Over MCP the wait is 25 seconds unless said; the agent of the interface waits for the whole run, and its Stop stops the run.
A failed run says what it had done. Outside a project nothing is rolled back, so scripts are written to be safe to run again.
What a script has
const found = tools.content_query({ type: "IArticle", fields: ["Name", "Intro"], pageSize: 200 });
let changed = 0;
for (const item of found.items) {
if (item.values.Intro) continue;
try {
tools.content_write({ actions: [{ do: "update", id: item.id, values: { Intro: "About " + item.values.Name + "." } }] });
changed++;
} catch (e) {
console.log("not changed:", item.id, e.message);
}
progress(changed, found.items.length);
}
return { changed };
tools.<name>(args)for every tool the caller has, andtools.call(name, args). A call answers the tool's answer as an object, at once;awaitin front of one is allowed. A tool that refuses throws anErrorwith the tool's message and astatus.input,console.log/info/warn/error(the last 200 lines come back with the answer),progress(done, total?, text?),sleep(ms),now().node, the content a button runs the script for (below); undefined otherwise.plainText(html): HTML as the text a reader sees, tags gone and a line for each block, for a prompt, an e-mail's text or counting words.services.*andweb.*(below), for a script that names them inuses.- No
fetch, timers,require,importoreval.
Not callable from a script: script_* and the tools of the datamodel area, as a change of the datamodel reopens the database, which waits for running scripts.
The guide scripts (guide("scripts")) teaches an agent all of this with examples, each of which a test runs.
A run
A run is a process of its user's. A run started over MCP or from Settings › Scripts shows in the CMS interface's process dock with its progress, and can be paused and cancelled there; a run of the interface's agent shows in the agent's panel instead (CmsProcessStart.ShownElsewhere), and the agent's Stop stops it. A user runs one script at a time. What script_status answers (the result, the error, the end of the log and the stats) is kept as an IScriptRun node for an hour after the run ended, so an agent gets its answer after a restart too. A run the server stopped in the middle of, by restarting, answers failed and says so. Nothing else of a run is kept unless the log of runs is on. Hooks are no runs: they make neither.
The log of runs
With the setting LogRuns on, every run is an entry of the custom log script-runs (Script runs under Logs in the database's admin UI), written when the run ends, with its code, input, result, console output and the messages it sent. It is off by default, and then no run is kept: Settings › Scripts lists the runs from the log alone. The log has statistics, so the admin UI counts runs by state, source, user, caller and saved script, and sums the time, tool calls, changes, credits and messages.
| Column | |
|---|---|
title, file |
What the script was; the saved script's path |
state, errorKind, error, errorLine, errorColumn |
completed, failed or cancelled; why it failed, and where |
writes, uses |
What it declared |
ms, toolCalls, changes, credits, messages |
What it did and spent |
source |
mcp (an agent over MCP), agent (the agent of the CMS interface), interface (a person, from Settings › Scripts), button (a person, from a button on a form) or menu (a person, from the menu) |
user, userId, caller |
The user it ran as, by name and id; the agent key's name or the interface's agent's name |
client, host |
The program that asked (its User-Agent); the site address the request came to |
conversation, project |
The conversation with the interface's agent; the project it worked in, by name |
run |
The run's id |
code, input, result |
The script, its input and its result as JSON |
output, sent |
The script's console output; the messages it sent, a line each |
The context is a ScriptContext. Texts are cut short: the summary's at 300 characters, the error at 2,000, the code at 100,000, and the input, result, output and messages at 20,000.
Settings
| Setting | Default | |
|---|---|---|
Enabled |
on | Agents may run scripts |
Who |
everyone | Whose agent in the CMS interface has scripts |
AllowWrites |
on | Off: scripts only read |
AllowLiveWrites |
on | Off: scripts write drafts alone |
MaxSeconds |
300 | The longest run |
MaxToolCalls |
2000 | Tool calls of one run |
MaxWrites |
500 | Calls of tools that change things |
MaxAtOnce |
2 | Scripts at once on the server |
LogRuns |
off | Records every run in the log script-runs, with where it came from |
AllowAI, AllowTranslation, AllowImaging, AllowFileToText, AllowIPLookup, AllowSMS, AllowEmail, AllowWeb |
off | Each service, for scripts |
ServicesFor |
administrators | Who may use services: through their agent in the CMS interface, and with the buttons and menu items they run |
MaxCredits |
200 | Credits one run may spend |
MaxMessages |
20 | SMS and e-mails one run may send |
HooksEnabled |
on | Off: no hook runs |
HookMilliseconds |
50 | What one hook may take |
They are read at each run, so a change applies at once.
Services and the web
services.ai.complete(prompt, { instructions?, model?: "fast"|"balanced"|"thorough", maxTokens? }): string
services.ai.chat([{ role: "user"|"assistant", text }], options?): { text, credits }
services.translation.translate(text | text[], to, { from?, html? }): string | string[]
services.translation.detect(text): string
services.sms.send(to, text)
services.email.send(to, subject, body, { html?, replyTo?, attachments?: [{ attachment } | { node, property }, with name?, inline?] })
services.ipLookup.lookUp(ip, userAgent?): object
services.imaging.create(description, { shape?, transparent?, name? }): { attachment }
services.imaging.describe({ node, property } | { attachment }, question?): string
services.fileToText.extract({ node, property } | { attachment }): string
web.fetch(url, { from? }): { url, title, text, from, to, length, links?, images? } | { attachment, name, type, size }
web.crawl(url, { pages?, section?, find? }): { pages, failed, skipped, stopped }
A service costs credits or sends a message, so it passes two gates:
- The setting. Each is off until an administrator turns it on. A script naming a service that is off, or that the database has no provider for, is refused before it starts.
- The question. In the CMS interface the person is asked before a script with
usesruns, a read-only one too: the card says the services and the limits. Over MCP there is no one to ask, so the key'sservicesarea is the consent, given by whoever made the key. A keyless agent on this machine has every area.
What a run spends is counted against MaxCredits and what it sends against MaxMessages; either ends the run when spent. A picture made or a file downloaded is kept in the run (50 MB in all) and named by a handle that tools.content_set_file({ id, property, attachment }) and an e-mail's attachments take; run by the CMS interface's agent, a file of its conversation (one the person gave, or a picture it made) is named by its id the same way. An e-mail's attachments are 20 at most and 20 MB together; one with inline is shown by an HTML body as <img src="cid:…"> rather than listed. A node's file is read as the script's user. The web is the agent's own way to it: public addresses only, robots.txt kept.
Saved scripts and script_api
A script kept in the design library under scripts/ is saved with templates_save like any design file, so it has drafts, projects and history. It opens with its declaration:
/* script: { "title": "Give articles an introduction", "writes": "drafts", "uses": [], "limits": { "writes": 200 },
"input": { "type": "object", "properties": { "type": { "type": "string" } } } } */
script_list lists them, and script_run { file, input } runs one, held to the file's own declaration whatever the call says. In the CMS interface, Settings › Scripts lists the hooks with New hook, the saved scripts with New script, Edit and Run, and the latest runs from the log. New script asks for a name, who runs it and from where (a button on a form, for some types or any; an item of the menu; or a job, run from Scripts or by an agent) and, where the site has an AI, what the script should do, and the AI writes it.
script_api { types? } answers TypeScript definitions: the fixed API, tools made from each callable tool's JSON Schema, and for each node type named an interface of its values. They are for a model to read; nothing checks a script against them.
Scripts people run
A saved script whose declaration says button or menu is run by the people who use the CMS interface, as themselves:
/* script: { "title": "E-mail a copy", "description": "Sends this article to someone.", "writes": "none", "uses": ["email"],
"button": { "types": ["IArticle"], "label": "E-mail a copy", "icon": "mail" },
"input": { "type": "object", "required": ["to"], "properties": {
"to": { "type": "string", "format": "email", "title": "Send it to" },
"note": { "type": "string", "format": "multiline", "title": "A note" } } } } */
const body = plainText(node.values.Body || "");
services.email.send(input.to, node.values.Name, (input.note ? input.note + "\n\n" : "") + body);
return { message: "Sent to " + input.to + "." };
| Declaration | |
|---|---|
description |
A sentence for the person, beside the button and in the dialog |
confirm |
A question asked before it runs |
button |
true for any form, or { types, label, icon }: the types whose forms it is for (a type covers those inheriting it) and what the button says |
menu |
true, or { title, icon, section: "main" \| "system", order, for: "administrators" } |
input |
A JSON Schema, asked for in a dialog before it runs |
Buttons on forms
An administrator places the button: design mode, an item of the type, Button in the bar under the form. Its settings choose the script (those made for the type's forms first, then the other saved scripts), with New script… and Edit it, and its label, help, style (Normal, Stands out, Quiet), icon and width, each the script's own when left empty. The form layout item is:
{ "kind": "button", "id": "b1", "script": "summarize.js", "label": "Summarize", "help": "Writes the summary from the body.", "icon": "sparkle", "style": "primary", "width": 50 }
script is the path below scripts/, style is default, primary or quiet. Every editor of the type sees the button. One whose script is missing is not drawn; one the user may not run is disabled and says why.
Pressed, the button runs the script with node, the content as the form holds it, unsaved changes too: { id, type, name, isNew, culture, values }, id null for content not saved yet and values by property name. What it returns as set: { Property: value } goes into the form as unsaved changes (texts, numbers, yes/no, dates as ISO text, a choice's option, lists of texts; not files, links or embedded content): the first field set is shown and lit, the form is Unsaved, and the message in the corner has Undo. Nothing is saved until the editor saves. A script that changes saved content itself (writes drafts or live, calling tools.content_write) is refused while the form has unsaved changes.
/* script: { "title": "Summarize", "writes": "none", "uses": ["ai"], "button": { "types": ["IArticle"], "icon": "sparkle" } } */
const summary = services.ai.complete("Summarize in two sentences:\n\n" + plainText(node.values.Body || ""), { model: "fast" });
return { set: { Summary: summary.trim() } };
The menu
A script with menu is an item of the menu, and is found by the top bar's search under Scripts. for: "administrators" lists it for administrators alone.
/* script: { "title": "Short articles", "writes": "none", "menu": { "icon": "list", "section": "main" } } */
const rows = [];
for (let page = 0; ; page++) {
const found = tools.content_query({ type: "IArticle", fields: ["Name", "Minutes"], page, pageSize: 200 });
for (const item of found.items) if ((item.values.Minutes || 0) < 3) rows.push({ id: item.id, name: item.values.Name, minutes: item.values.Minutes });
if (!found.more) break;
}
return { message: rows.length + " short articles.", table: rows };
Input
Each property of input is a field of the dialog, named by its title (else its name in words), with description as help, default as its first value, and required:
| Schema | Field |
|---|---|
"type": "string" |
Text; "format": "multiline" a longer text, "email", "uri", "date", "date-time" (ISO text, UTC) |
"type": "number", "integer" |
A number; minimum, maximum |
"type": "boolean" |
A check box |
"enum": [...] |
One of the choices; enumNames their labels |
"format": "node" |
Content of the site, the script getting its id; nodeTypes the types offered |
"type": "object", "format": "file" |
A file |
Anything else (lists, nested objects) is a JSON text box. What a person filled in last is remembered in their browser, files aside. A file is input.<name> = { attachment, name, type, size }, and attachment goes to tools.content_set_file({ id, property, attachment }), an e-mail's attachments: [{ attachment }], services.fileToText.extract({ attachment }) or services.imaging.describe; the files are 20 MB together at most.
The dialog says what the script does before it runs: whether it saves nothing or changes saved content as drafts or live, the services and the most credits, the messages at most. A script with no input runs at once, unless it declares confirm, changes live content or sends SMS or e-mail: then it asks Yes or Cancel.
What it returns
| Key | Shown |
|---|---|
message |
A line in the corner; a text returned alone is one |
set |
Values put into the form (buttons) |
table |
Rows as objects, or { columns: ["name", { key, label }], rows, link }, in a blade pinned beside what is open, with a filter and Download (CSV) and Run it again; a row whose id (or node, nodeId, or the key link names) is content's opens it beside the table |
text |
A longer text to read and Copy |
download |
{ name, text, type }, saved as a file |
open |
A content id, opened in its editor, or { url }, offered to open in a new tab |
return { download: { name: "names.csv", text: "name\nSalmon\nTrout\n", type: "text/csv" } };
Anything else it returns is shown as JSON. A run that takes more than a moment shows a dialog with what progress and console.log say, Hide (it goes on) and Stop; a failure is said in the corner, with the error and what it logged under Details.
Who may run what
A script runs as the person, with their rights, held to what it declares and to the settings: Enabled, AllowWrites, AllowLiveWrites, each service's switch, and ServicesFor, which holds for people's buttons and menu items as for their agent. A user runs one script at a time. Only scripts published in the design library are placed: one saved in a project counts once the project is published.
In the editor, a saved script's Settings says where people run it (in the menu: what it is called, its icon, under Workspace or System, for everyone or administrators; a button: for which types, what it says, its icon), whether it asks first, and What it asks for: the input as fields (what each is called, its kind, required, help, starting value, choices, its name in the code), or As JSON for the schema, which is used by itself when the schema says more than fields can. Run runs it with the people's dialog; for a button's script, Try it on an item… gives it a saved item as node and shows what it would put in the form, changing nothing.
For developers
| Command | |
|---|---|
script.placed |
The saved scripts in force with what they declare: input schema, button, menu, and refused, why this user may not run one |
script.start { file, input, node, files, wait, from, quiet } |
Runs one: files the input's files by field, { name, type, data } with data base64; wait seconds, 30 at most; from button or menu; quiet keeps the run out of the interface's corner. Answers { run, answer, process }, answer as script_run answers |
script.wait { run, wait } |
Waits for a run again |
script.stop { run } |
Stops it |
script.script-draft { title, kind, types } |
A new script's path and text, kind button or menu; nothing is saved |
The SDK has cms.scripts (ScriptService: available(), run(file, { node, input, ask, apply }) resolving { state, result, error }, refresh()), the form item FormButton and NavContribution.description.
Hooks
A file hooks/<name>.js in the design library, opening with its declaration. In the CMS interface, Settings › Scripts has New hook, which asks for the rule's name, the types it guards, when it runs and what a broken hook does, and opens the hook in an editor:
/* hook: { "type": "IArticle", "title": "Article rules", "on": ["insert", "update"], "onError": "reject" } */
if (node.values.Name !== undefined && node.values.Name.trim().length < 3) reject("An article's name is at least three letters.", "Name");
if (node.values.Minutes !== undefined && node.values.Minutes < 0) return { set: { Minutes: 0 } };
- It runs before every insert and update of a node of the type, and of the types inheriting it, whoever writes: the CMS interface, an agent, the site's own code.
typeis one name or a list of names. nodeis{ id, type, isNew, partial, values }.valuesholds what is being written, by property name: texts, numbers, booleans, times and lists of texts. A save of some properties (partial) carries only those, so a hook tests forundefined. A text or list emptied is""or[]. A save in the CMS interface is one write of every value it changes, so a hook sees them together.- It answers nothing,
reject("why")or{ reject: "why" }, or{ set: { Property: value } }. - A rejection may mark fields in the CMS interface's editor:
reject("why", "Name"),reject("why", ["Name", "Intro"])(each marked withwhy),reject({ Name: "At least three letters.", Intro: "Fill it in." })(each with words of its own, which are what the person is told, after the field's name), or both,reject("why", { … }); returned,{ reject: "why", fields }or{ reject: { … } }. A name the type lacks marks nothing and is said in words. onErrorsays what a failing hook does to the write:reject(the default) stops it,ignorelets it through."active": falseturns one hook off: it is kept and does not run. The list of hooks under Settings › Scripts has a switch for it, and so has the editor's Settings tab; both write it into the declaration.- No tools, services or queries. It has
HookMillisecondsand few statements. - Only a hook an administrator last saved is in force. In a project it is in force once the project is published.
HooksEnabledoff is the kill switch for every hook.- A hook can come with the site's code: a
hooks/folder in whatTemplateSeedor a module'sTemplates(folder)seeds. It is in force (server code may seed one), follows the file in the code at every start, and stops following it once it is changed in the CMS. Saved scripts inscripts/follow the same rule.
A rejection is the CMS's InvalidFieldsException (a NodeConstraintException naming the fields), which the CMS API answers with 400, the hook's words and the fields (see the CMS's Refused writes). The guide hooks teaches an agent to write one.
The hook editor
The blade script.file (its param the file's node id) is a code editor for a file of hooks/ or scripts/. A hook has three tabs beside the code: Settings (its declaration as a form, written back into the comment), Try it (the hook as written, saved or not, run on content written there or taken from an item, with what the save would do and the fields it would mark) and Help (what a hook has as code, examples written with the names of the types it guards, each to copy or put into the code with Use, and the values it can read). Over the code it says whether the hook is in force, how it has run, and whether the file follows the site's code. A saved script has Settings (its declaration as a form: the name, what it may change, the services it uses, which says those the site has turned off or not set up, its limits, with the site's own as placeholders, where people run it and what it asks for, written back into the comment), Run and its own Help (what it declares, what it has, examples over one of the site's content types, a part on buttons, the menu and what people see, and the whole API as TypeScript). The text is checked as it is typed, a saved script's declaration too (script.check { script: true }), and saved with templates.save.
Where the site has an AI, the editor's Ask AI writes what is described, a new file or a change to the one open: script.write { kind, path, text, request } gives the CMS's text AI (ICmsAI, model thorough) the guide (scripts or hooks), what a script can call (the definitions script_api answers, with the person's tools and the site's types) or the site's types with the values a hook is given, and the text as the editor holds it. The answer is checked as the editor checks a file, and asked for once more with the problem. Nothing is saved: the editor shows what the AI wrote and what it says it did, and Use it puts it in the editor, which Undo takes back. A hook is an administrator's to have written. New hook's Start from has Describe it for the same.
The editor checks the code as it is typed, with TypeScript's language service running in a worker in the browser. The code stays JavaScript. A hook is checked against declarations made from the types it guards (node.values with each property a hook is given, every one optional, and reject, old, user), a saved script against what script.api answers (tools, services, web). It offers what can be typed next, says what a name is on hover, and marks what does not fit as a warning. The compiler ships with the module (ui/vendor, about 1 MB gzipped, TypeScript's license beside it) and is loaded the first time a script editor opens; Relatude.CMS.UI/tools/generate-script-typescript.mjs packs it again from the typescript npm package.
| Command | |
|---|---|
script.hooks |
The hooks, each with its types, whether it is in force and how it has run (an administrator's) |
script.hook-types |
The node types a hook can name, grouped as content types, the kinds they share and the system's own, each with the properties a hook is given |
script.hook-draft { title, types, on?, onError?, starter? } |
A new hook's path and text; nothing is saved |
script.check { text, hook? } |
The syntax error in a text, and a hook's declaration with its problem; nothing runs |
script.hook-test { path \| text, node } |
A hook tried on a node given as JSON, without writing anything |
script.file { path } |
How a file stands: live or in a project alone, following the site's code or changed, and a hook's state |
The sandbox
ScriptSandbox.Run(source, globals, limits, cancellation) has no CMS types: a new engine per run, data crossing as JSON only, host functions as the only way out.
- Strict mode; no CLR access, no module loader, no
evalornew Function. - Limits on statements, allocations, recursion depth, array size and regular expression time (
ScriptLimits), and the caller's cancellation token for wall time. - A host function throws
ScriptHostExceptionfor an error the script may catch, andScriptStopExceptionfor one that ends the run.
Jint is an in-process interpreter, not an operating system boundary, and its limits are cooperative. Scripts here are written by signed-in agents with one user's rights, behind a setting. Do not accept scripts from visitors without a process or container around them.
Notes
- A run does not outlive the server: a restart stops it, and
script_statusanswers it as failed. ItsIScriptRun(in no index and no change history, read by administrators alone) is deleted when a run starts an hour or more after it ended. - Turn the module off in the CMS settings (Modules:
script) and the tools and commands are gone. Hooks keep running, as a module's transaction plugins guard the data whether or not it is on:HooksEnabledturns them off. IAgentAreaPolicy(Relatude.CMS) is how the module gives the interface's agent theservicesarea byServicesFor.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- Jint (>= 4.18.1)
- Relatude.DB.CMS (>= 1.1.12.44-alpha)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.1.12.44-alpha | 0 | 11/26/2026 |