Docs
Contents

Functions

Overview and use cases

Server-side serverless functions respond to HTTP / SDK calls, platform events, and scheduled tasks, running in an isolated sandbox (the managed environment runs on ACS Agent Sandbox; local Docker is based on OpenRuntimes). Suitable for backend logic proxies, event-driven processing, scheduled tasks, and lightweight APIs; for complex authorization scenarios, first read Permissions Explanation.

Prerequisites

Usage workflow

  1. Check capabilities: before creating or modifying, query the languages and specifications actually enabled on the target instance — only the intersection of functions.listRuntimes() and functions.listSpecifications() is a submittable value; SDK enums are merely candidates and do not guarantee the instance has them enabled.

  2. Create the function: call functions.create, specifying the identifier, name, runtime, and permissions; configuration options are in the parameter table below. The following is a schematic of the parameter structure, where ? marks optional items; for complete calls, see Examples by language.

    functions.create({
      functionId, name, runtime,
      execute?, events?, schedule?, timeout?, enabled?, logging?,
      entrypoint?, commands?, scopes?, runtimeSpecification?,
      runtimeReplicas?, runtimeKeepAliveMode?, ...
    })
  3. Deploy: upload the source archive and create a Deployment.

    functions.createDeployment({
      functionId,
      code: InputFile.fromPath('code.tar.gz', 'code.tar.gz'),
      activate: true,
      entrypoint,
      commands,
    });

    The status transitions through waiting → processing → building → ready, with failed / canceled as failure paths. After cancellation or a long wait, you should re-read the Deployment and judge based on the build logs — do not rely on a single API response.

  4. Invoke:

    • Client / Server SDK: functions.createExecution({ functionId, body, async, xpath, method, headers, scheduledAt }) (xpath, method, headers, scheduledAt are all optional).

    • Synchronous (async: false) waits at most 30 seconds (client-side wait); the function's own timeout is controlled by timeout (capped at 900 seconds); asynchronous returns an execution ID immediately, poll with getExecution; scheduledAt supports future schedules (ISO 8601, minute precision).

    • HTTP direct access to the function URL (requires the execute permission to include the corresponding origin).

  5. Call Agentbase from within the function: use a dynamic API Key (req.headers['x-appwrite-key'], permissions = the function's scopes parameter, from the administrator's perspective) or the caller's JWT (x-appwrite-user-jwt, subject to row-level permissions); for Client, use the runtime-injected APPWRITE_FUNCTION_API_ENDPOINT endpoint (do not assemble an external domain yourself — DNS cannot resolve it inside the self-hosted sandbox).

  6. Events and schedules: subscribe to platform events with the events array (e.g., tablesdb.*.tables.*.rows.*.create, users.*.create); fill schedule with a Cron expression.

  7. Variables: createVariable / listVariables / updateVariable / deleteVariable (secret: true is stored encrypted and read at runtime via process.env).

  8. Switch active deployment: updateFunctionDeployment({ functionId, deploymentId }) switch the active deployment.

Key parameters and returns

Multi-language / multi-runtime / multi-replica

ConfigurationValuesDescription
runtimee.g. node-22, python-3.9, go-1.23 (subject to listRuntimes())Corresponds to the SDK Runtime enum
runtimeSpecificatione.g. s-0.5vcpu-1gb, s-1vcpu-2gb, s-2vcpu-4gb, s-4vcpu-8gb, s-8vcpu-16gbPass the slug string directly; it must appear in listSpecifications()'s enabled list; the Node SDK has no such enum
runtimeReplicas1 / 2 / 3 / 5 / 10, default 1Can reuse the runtime replica desired value
runtimeKeepAliveModedisabled / always / schedulewarm strategy; schedule requires runtimeKeepAliveStart/End (HH:mm) + IANA runtimeKeepAliveTimezone

The warm configuration is a Function-level desired value and does not equal the environment's shared warm pool inventory; shared pool verification (warmPoolReplicas, inventory ready/available, createOnNoStock) belongs to operations, and the SDK provides no query for it.

Two independent permission sets

ConfigurationWhat it controlsTypical values
executewho may trigger (Client SDK / HTTP)['users'], ['any'], ['team:xxx']
scopesResources the function runtime's dynamic API Key can accessMinimize based on actual in-function calls, e.g. databases.read/write, tables.read/write, rows.read/write, users.read

This is distinct from "the API Key scopes used by the deployment script"; do not substitute one for the other.

Execution returns

$id, functionId, deploymentId, trigger (http/schedule/event), status (waiting/processing/completed/failed/scheduled), responseStatusCode, responseBody, duration, logs/errors (visible only with an API Key; usually empty via the Client SDK).

Errors and boundaries

SDK Category Differences

Java 17 prebuilt JAR (Node.js Server)

The management script pins the exact version agentbase-node-sdk@2.10.0. The target Function must already have selected java-17.0; the JAR's manifest declares Main-Class and the package contains that class, the app listens on port 3000 and provides /__opr/health. The deploy Key requires functions.write, and lookup additionally requires functions.read; actually triggering execution further requires execution.write.

import { Client, Functions, ArtifactMode } from 'agentbase-node-sdk';
import { InputFile } from 'agentbase-node-sdk/file';

const client = new Client()
    .setEndpoint(process.env.APPBASE_ENDPOINT) // Includes /v1
    .setProject(process.env.APPBASE_PROJECT_ID)
    .setKey(process.env.APPBASE_API_KEY);
const functions = new Functions(client);

const deployment = await functions.createDeployment({
    functionId: process.env.APPBASE_FUNCTION_ID,
    code: InputFile.fromPath('./app.jar', 'app.jar'),
    artifactMode: ArtifactMode.Javajar,
    activate: false,
});
console.log(deployment.$id, deployment.status);

ArtifactMode.Javajar corresponds to java-jar. In this mode you do not fill in source entrypoint or build commands; the JAR's real entry point comes from the manifest, and Index.java in the response is a compatibility identifier. The default JAR cap is 100,000,000 bytes, also subject to the plan's deployment cap. The SDK handles chunked upload; do not treat an upload progress of 100% as successful deployment creation.

The example uses activate: false so the artifact can be inspected first. After receiving the deployment ID, use getDeployment({ functionId, deploymentId }) for bounded polling and check the logs; once ready is reached, call updateFunctionDeployment according to the business release schedule. Use get({ functionId }) to look up the Function's deploymentId, confirm it matches the target deployment, then run one business request and check the actual response. If failed / canceled or the wait times out, stop the release and troubleshoot; a deployment being ready does not mean it is activated, nor does it guarantee business request success.

Filtering execution records (Node.js Server)

Reading execution records requires execution.read. The HTTP parameter name is path; in Node Server 2.10.0 the object parameter name is xpath; pathMatch defaults to exact matching. The following combines a path regex with the GET method, limiting one page to at most 20 records:

import { Client, Functions, Method, PathMatch, Query } from 'agentbase-node-sdk';

const client = new Client()
    .setEndpoint(process.env.APPBASE_ENDPOINT)
    .setProject(process.env.APPBASE_PROJECT_ID)
    .setKey(process.env.APPBASE_API_KEY);
const functions = new Functions(client);

const page = await functions.listExecutions({
    functionId: process.env.APPBASE_FUNCTION_ID,
    xpath: '^/articles/[0-9]+$',
    pathMatch: PathMatch.Regex,
    method: Method.GET,
    queries: [Query.limit(20)],
});
console.log(page.executions.map(({ $id, status }) => ({ $id, status })));

The path includes the query string; the expression above will not match /articles/42?draft=1 — use ^/articles/[0-9]+([?].*)?$ instead if the query string should be included. The regex carries no /…/ delimiters. Use Query.cursorAfter to continue paginating as needed, and clear the original cursor when changing filter conditions; do not treat the current page's or total: false's zero count as the full result set.

listExecutionPaths returns matching full paths, and listExecutionsByPath returns the execution records for that condition; both also support these filter conditions. Do not rewrite a waiting or processing execution as failed on the client merely because the timeout has passed, and do not delete it; the actual terminal state is determined by the server's record.

Examples by language

The following provides examples by language, item by item along the usage workflow; each card can switch languages (synced across the page).

Query capabilities and create functions

import { Client, Functions } from 'agentbase-node-sdk';

const client = new Client()
    .setEndpoint(process.env.APPBASE_ENDPOINT!)   // Must include /v1
    .setProject(process.env.APPBASE_PROJECT_ID!)
    .setKey(process.env.APPBASE_API_KEY!);        // functions.write minimal scope
const functions = new Functions(client);

const runtimes = await functions.listRuntimes();          // The runtimes actually available on the instance
const specs = await functions.listSpecifications();       // Build/run specs actually available on the instance
// The intersection of the two is the submittable value; SDK enums are only candidates
const fn = await functions.create({
    functionId: 'send-mailer',
    name: '发送邮件',
    runtime: 'node-22',            // Refer to the actual return of listRuntimes()
    execute: ['users'],            // Who can trigger it; no roles granted by default
    entrypoint: 'src/main.ts',
    commands: 'npm install',
    scopes: ['users.read'],        // Permissions of dynamically used API keys inside functions should be minimized as needed
});

Deploy the code package

createDeployment uploads the .tar.gz code package (multipart/form-data); the build runs asynchronously (waiting → processing → building → ready) and a deployment record in building state is returned immediately. Code package upload is provided only on the Node and REST surfaces; Java / Python / Go omit this tab.

import { Functions } from 'agentbase-node-sdk';
import { InputFile } from 'agentbase-node-sdk/file';

const dep = await functions.createDeployment({
    functionId: 'send-mailer',
    code: InputFile.fromPath('code.tar.gz', 'code.tar.gz'),
    activate: true,
    entrypoint: 'src/main.ts',
    commands: 'npm install',
});
// After cancellation or a long wait, re-read the deployment record and combine it with build logs; do not trust a single API response alone

Trigger execution and poll

Synchronous (async: false) clients wait at most 30 seconds; asynchronous returns an execution ID immediately, poll with getExecution; scheduledAt supports future scheduling (ISO 8601, minute precision); you can also trigger via the function URL over direct HTTP (requires the execute permission to include the corresponding origin).

const sync = await functions.createExecution({
    functionId: 'send-mailer',
    body: JSON.stringify({ to: 'a@b.c' }),
    async: false,              // Synchronous, capped at 30s; for long tasks use true + polling
    xpath: '/',
    method: 'POST',
    headers: { 'X-Custom-Header': 'value' },
});

const bg = await functions.createExecution({ functionId: 'send-mailer', body: '', async: true });
const done = await functions.getExecution({ functionId: 'send-mailer', executionId: bg.$id });   // Poll until completed / failed

Execution path query (2.9.0)

Look up execution records by request path: listExecutionPaths lists the deduplicated request paths that have produced execution records (string ascending, paginated); listExecutionsByPath paginates the executions under a path by request path (the HTTP parameter path is required, ≤2048 characters; the Node.js object parameter is xpath). Both require execution.read. From 2.10.0 the two methods gain filters: HTTP path (Node.js xpath, with listExecutionPaths optional), pathMatch (exact / regex, default exact), and method (exact HTTP method filter).

const paths = await functions.listExecutionPaths({ functionId: 'send-mailer' });   // { paths, total }
const onPath = await functions.listExecutionsByPath({
    functionId: 'send-mailer',
    xpath: '/webhook',          // Exact match on the full path
});                            // { executions, total }

Calling Agentbase again from within a function

This is the in-function capability surface, not a management API call — this card only covers the Node (function runtime) tab; other language runtimes and REST have no corresponding tab. The Client's endpoint uses the runtime-injected APPWRITE_FUNCTION_API_ENDPOINT (external domains cannot be resolved inside the self-hosted sandbox); choose one of two credentials: the dynamic API Key (permissions = the function's scopes parameter, admin perspective) or the caller's JWT (subject to row-level permissions).

// Inside the function code (Node runtime)
import { Client } from 'agentbase-node-sdk';

export default async ({ req, res }) => {
    // Method One: dynamic API key (permissions = the function's scopes parameter)
    const admin = new Client()
        .setEndpoint(process.env.APPWRITE_FUNCTION_API_ENDPOINT!)   // Injected at runtime, always takes priority
        .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID!)
        .setKey(req.headers['x-appwrite-key']!);

    // Method Two: caller's JWT (present when triggered by the SDK; constrained by row-level permissions)
    const jwt = req.headers['x-appwrite-user-jwt'];
    if (jwt) {
        const asUser = new Client()
            .setEndpoint(process.env.APPWRITE_FUNCTION_API_ENDPOINT!)
            .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID!)
            .setJWT(jwt);
    }
    return res.json({ ok: true });
};

Events and schedules

events subscribes to platform events (e.g. users.*.create, tablesdb.*.tables.*.rows.*.create); schedule takes a CRON expression; both can also be passed in when creating the function.

await functions.update({
    functionId: 'send-mailer',
    events: ['users.*.create', 'tablesdb.*.tables.*.rows.*.create'],
    schedule: '0 8 * * *',
});

Environment variables

Build and runtime inject the function process via environment variables (read inside the function through process.env); secret: true secret variables can be updated/deleted but their plaintext cannot be read back; changes take effect for subsequent executions only after redeploying (or reactivating a deployment).

await functions.createVariable({
    functionId: 'send-mailer',
    key: 'DATABASE_URL',
    value: 'postgres://...',
    secret: true,            // true = encrypted storage, cannot be read back
});
const vars = await functions.listVariables({ functionId: 'send-mailer' });
await functions.updateVariable({
    functionId: 'send-mailer',
    variableId: '<variableId>',
    key: 'DATABASE_URL',
    value: 'postgres://new',
});
await functions.deleteVariable({ functionId: 'send-mailer', variableId: '<variableId>' });

Switch the active deployment

updateFunctionDeployment switches the activation deployment pointer to an existing deployment; from then on, all access and execution of that function uses the newly activated deployment's code.

await functions.updateFunctionDeployment({
    functionId: 'send-mailer',
    deploymentId: '<deploymentId>',
});

Example Guide