Skip to content

diesel Object

The diesel global is the main API surface available to every script. It provides access to the database, cryptographic utilities, file I/O, external services, the registry, and more.

Database (JDBC)

diesel.prepareStatement(sql)

Create a JDBC prepared statement for parameterized queries. Use ? placeholders for parameters.

  • Parameters: sql: string — SQL query with ? placeholders
  • Returns: PreparedStatement
javascript
const ps = diesel.prepareStatement(
  'SELECT id, data FROM engine."users" WHERE id = ?'
);
ps.setLong(1, userId);
const rs = ps.executeQuery();

TIP

Always use prepared statements for queries with user input to prevent SQL injection.

diesel.createStatement()

Create a raw JDBC statement (no parameters). Use for DDL or trusted queries.

  • Returns: Statement
javascript
const stmt = diesel.createStatement();
stmt.execute('CREATE TABLE IF NOT EXISTS engine."items" (id SERIAL PRIMARY KEY, data JSONB)');

diesel.createArrayOf(sqlType, items)

Create a PostgreSQL array parameter for use with ps.setArray().

  • Parameters:
    • sqlType: string — SQL type name (e.g., "text", "integer")
    • items: any[] — Array of values
  • Returns: java.sql.Array
javascript
const arr = diesel.createArrayOf("text", ["admin", "editor", "viewer"]);
ps.setArray(1, arr);

See the Database service guide for full JDBC documentation.

Crypto & Encoding

diesel.sha512hash(toHash, salt)

Compute a SHA-512 hash with a salt.

  • Parameters: toHash: string, salt: string
  • Returns: string — hex-encoded hash
javascript
const hash = diesel.sha512hash("password123", "random-salt");

diesel.randomUUID()

Generate a random v4 UUID string.

  • Returns: string
javascript
const id = diesel.randomUUID();
// → "a1b2c3d4-e5f6-7890-abcd-ef1234567890"

diesel.stringToBase64(string)

Encode a string to Base64.

  • Parameters: string: string
  • Returns: string — Base64-encoded
javascript
const encoded = diesel.stringToBase64("Hello, World!");
// → "SGVsbG8sIFdvcmxkIQ=="

diesel.base64ToString(b64string)

Decode a Base64 string.

  • Parameters: b64string: string
  • Returns: string — decoded
javascript
const decoded = diesel.base64ToString("SGVsbG8sIFdvcmxkIQ==");
// → "Hello, World!"

File I/O

diesel.readFile(path)

Read a file from the DieselEngine virtual filesystem (Postgres-backed). The path is resolved against the virtual tree. Throws IOException if the file is not found.

  • Parameters: path: string — absolute file path
  • Returns: string — file contents
javascript
const template = diesel.readFile("/assets/email-template.html");

diesel.deleteDirectory(path)

Recursively delete a directory from the host filesystem.

  • Parameters: path: string — absolute directory path
  • Returns: booleantrue if deleted
javascript
diesel.deleteDirectory("/tmp/cache/old-exports");

Registry (Key-Value Store)

The registry is a global JSONB key-value store backed by PostgreSQL. Use it for configuration, secrets, and shared state.

diesel.getRegistryValue(key)

Read a value from the registry.

  • Parameters: key: string
  • Returns: any — the stored value, or null if the key doesn't exist
javascript
const apiKey = diesel.getRegistryValue("STRIPE_API_KEY");
const config = diesel.getRegistryValue("APP_CONFIG"); // can be a JSON object

diesel.setRegistryValue(key, value)

Write a value to the registry.

  • Parameters: key: string, value: string
  • Returns: void
javascript
diesel.setRegistryValue("LAST_SYNC_TIME", new Date().toISOString());

Service Accessors

diesel.getRedisService()

Get the Redis service for caching, key-value storage, and pub/sub.

  • Returns: RedisService
javascript
const redis = diesel.getRedisService();
redis.connect("redis://localhost:6379");
redis.set("key", "value");

See the Redis guide for full documentation.

diesel.getMinIOService()

Get the MinIO service for S3-compatible object storage.

  • Returns: MinIOService
javascript
const minio = diesel.getMinIOService();
minio.connect("http://localhost:9000", "minioadmin", "minioadmin");

See the MinIO guide for full documentation.

diesel.getKanbanService()

Get the Kanban service for managing boards, columns, and ideas.

  • Returns: KanbanService

See the Kanban API for full documentation.

diesel.getAgentService()

Get the Agent service for managing autonomous LLM-powered agent runs.

  • Returns: AgentService

See the Agent API for full documentation.

diesel.getWebSocketService()

Get the WebSocket service for server-side room broadcasting and session discovery. Works from any script context — not just WebSocket handler scripts.

  • Returns: WebSocketService
javascript
const ws = diesel.getWebSocketService();

// Broadcast to a room
ws.room("stock-updates").broadcast(JSON.stringify({ type: "price", data: stockData }));

// Send to a specific session
const session = ws.getSession("abc-123");
if (session && session.isOpen()) {
    session.send(JSON.stringify({ type: "hello" }));
}

// Discover connected sessions
console.log("Active:", ws.getActiveSessionCount());
console.log("Rooms:", ws.listRooms());

See the WebSocket Session API for the full WebSocketService, WebSocketServiceRoom, and WebSocketSessionInfo reference.

diesel.getBuilderService()

Get the Builder service for driving the build sidecar. Enables running npm, node, git, and other allow-listed commands in an isolated container.

  • Returns: BuilderService
javascript
const builder = diesel.getBuilderService();

// Check if builder is available
if (builder.isEnabled()) {
  // Submit a build job
  const jobId = builder.submitJob(["npm", "install"], "/data/diesel/my-app", null, 120000, null);

  // Wait for completion
  const result = builder.waitForJob(jobId, 120000);
  console.log("Build status:", result.status);
}

Key methods: isEnabled(), submitJob(argv, cwd, env, timeoutMs, maxOutputBytes), submitScaffold(framework, name, cwd, flags, timeoutMs), submitDeploy(req), submitGitClone(url, targetDir, extraArgs, env, timeoutMs), getJob(jobId), waitForJob(jobId, timeoutMs), cancelJob(jobId), listJobs(limit), getToolchain().

diesel.getHBCIService()

Get the HBCI/FinTS service for German online banking operations. Provides access to the hbci4java library for account inquiries, transfers, and SEPA operations.

  • Returns: HBCIService
javascript
const hbci = diesel.getHBCIService();
const HBCICallback = Java.type('org.kapott.hbci.callback.AbstractHBCICallback');

// Initialize and use the HBCI library
hbci.init(new java.util.Properties(), new MyCallback());
const bankInfo = hbci.getBankInfo("10000000");

See the HBCI / FinTS guide for full documentation.

Real-Time WebSocket Management

diesel.reloadRealtimeRoute(route)

Reload a real-time WebSocket route by tearing down the existing handler, re-reading the script, and creating a fresh handler. Connected clients are disconnected and must reconnect.

  • Parameters: route: string — the WebSocket route path (e.g., "/ws/game")
  • Returns: string — status message
javascript
const result = diesel.reloadRealtimeRoute("/ws/game");
console.log(result); // "Reloaded real-time WebSocket route '/ws/game' at 60 Hz (persistent)"

diesel.stopRealtimeRoute(route)

Stop a real-time WebSocket route, tearing down the handler and freeing all resources. Connected clients receive a close frame. The route becomes inactive until a client connects again or the server restarts.

  • Parameters: route: string — the WebSocket route path (e.g., "/ws/game")
  • Returns: string — status message
javascript
const result = diesel.stopRealtimeRoute("/ws/game");
console.log(result); // "Stopped real-time WebSocket route '/ws/game'"

Email

diesel.getEmailBuilder()

Start building an email message. Returns a SimpleJavaMail builder that you can chain.

  • Returns: EmailPopulatingBuilder
javascript
const email = diesel.getEmailBuilder()
  .from("noreply@example.com")
  .to("user@example.com")
  .withSubject("Welcome")
  .withHTMLText("<h1>Hello!</h1>");

diesel.getMailerBuilder(host, port, username, password)

Create an SMTP mailer with TLS transport.

  • Parameters: host: string, port: number, username: string, password: string
  • Returns: MailerRegularBuilderImpl
javascript
const mailer = diesel.getMailerBuilder("smtp.example.com", 587, "user", "pass");
mailer.buildMailer().sendMail(email.buildEmail());

See the Email guide for full documentation.

PDF / TeX Rendering

diesel.renderTemplateToPdf(templatePath, assets, debug)

Render a LaTeX template to a PDF file, downloading any required assets.

  • Parameters:
    • templatePath: string — path to the .tex file
    • assets: TeXAsset[] — array of { sourceUrl, outputName } objects
    • debug: boolean — if true, keep intermediate files
  • Returns: JavaFile — the generated PDF
javascript
const pdf = diesel.renderTemplateToPdf(
  "/templates/invoice.tex",
  [{ sourceUrl: "https://example.com/logo.png", outputName: "logo.png" }],
  false
);

diesel.mergeTemplate(templatePath, context)

Merge variables into a template file.

  • Parameters: templatePath: string, context: object — key-value pairs for template variables
  • Returns: JavaFile — the merged file

diesel.mergeTemplateToString(templatePath, context)

Merge variables into a template, returning the result as a string.

  • Parameters: templatePath: string, context: object
  • Returns: string — merged content
javascript
const html = diesel.mergeTemplateToString(
  "/templates/welcome.html",
  { name: "Alice", company: "Acme Corp" }
);

See the PDF / TeX guide for full documentation.

Background Services

diesel.registerService(serviceName, startHandler, stopHandler)

Register a named background service with start and stop lifecycle handlers. If a service with the same name already exists, it is stopped first before the new one is registered.

  • Parameters:
    • serviceName: string — unique name for the service
    • startHandler: () => void — called to start the service
    • stopHandler: () => void — called to stop the service
javascript
diesel.registerService("price-updater",
  () => {
    // Start: initialize connections, warm caches, etc.
    console.log("Price updater service started");
  },
  () => {
    // Stop: clean up resources
    console.log("Price updater service stopped");
  }
);

No setInterval / setTimeout

setInterval(), clearInterval(), setTimeout(), and clearTimeout() are not available in DieselEngine scripts. GraalVM does not provide browser or Node.js timer APIs.

For periodic tasks:

  • Sub-second (game loops, physics): In WebSocket scripts, export tickRate (1--120 Hz) to activate a server-driven tick loop with onTick(room, deltaMs). See Real-Time WebSocket.
  • 1 second or slower: Use a cron job. Create a script in /cronjobs/ and wire it with cron_add_entry. Quartz cron expressions support granularity down to 1 second (e.g. */5 * * * * ? for every 5 seconds).
javascript
// cronjobs/update-prices.js — runs on a schedule, not via setInterval
const ws = diesel.getWebSocketService();
const room = ws.room("price-updates");

if (room.exists()) {
  const prices = fetchLatestPrices();
  room.broadcast(JSON.stringify({ type: "prices", data: prices }));
}

Agent Tasks

diesel.runAgentTask(options)

Start an autonomous agent run and block until it completes or times out. The agent has access to every MCP tool registered on the platform.

  • Parameters: options: object
    • task: string — the task description
    • maxIterations?: number — iteration cap (default: 25, max: 100)
    • timeoutMs?: number — wall-clock timeout in milliseconds
    • model?: string — LLM model to use
    • systemPromptOverride?: string — custom system prompt
    • temperature?: number — sampling temperature
  • Returns: object — the run snapshot with status, result, uuid, etc.
javascript
const run = diesel.runAgentTask({
  task: "Create a GET endpoint at /api/stats returning table row counts",
  maxIterations: 15,
  timeoutMs: 120000
});
console.log(run.status, run.result);

diesel.startAgentTask(options)

Start an agent run and return its UUID immediately (non-blocking).

  • Parameters: same as runAgentTask
  • Returns: string — the run UUID

diesel.getAgentRun(uuid)

Get a snapshot of an agent run.

  • Parameters: uuid: string
  • Returns: object — run snapshot

diesel.cancelAgentRun(uuid)

Request cooperative cancellation of a running agent task.

  • Parameters: uuid: string
  • Returns: void

See the Agent API for full documentation.

Utility

diesel.getURL(url)

Parse a URL string into a java.net.URL object.

  • Parameters: url: string
  • Returns: URL

DieselEngine Scripting Documentation