Docs
Contents

Functions

Functions are the event-driven, multi-language Serverless server-side code execution engine provided by Agentbase. They support direct invocation via HTTP requests, automatic triggering by internal business events (such as new support tickets in the database, user registration, or file uploads), or scheduled execution via Cron expressions, and offer complete production-grade capabilities spanning source code builds (.tar.gz / Git) to direct deployment of pre-built Java 17 JAR packages (artifactMode=java-jar), deduplicated execution path queries (Execution Paths), and resource monitoring for cloud sandbox (ACS Sandbox) container groups.

Function list in the test project

A sample function in the test project; it is disabled and has no deployed or executed code.

Feature Overview

When building enterprise-grade AI and agent applications (such as project 企业智能客服与知识中台 enterprise-ai-hub-210), many custom business logic components need to run in a secure, controlled server-side sandbox: for example, when a customer submits an urgent support ticket (TK-20261022-001) in the customer_tickets table, a function can be automatically triggered to call the enterprise's internal ERP API to verify the contract tier; or complex Java 17 WeCom/DingTalk encryption/decryption logic can be packaged as standalone utility functions for agents to call.

Agentbase Functions provides four core features built around enterprise standards for high concurrency and high security:

  1. Multi-language runtimes and direct upload of pre-built Java 17 JARs (2.10.0 enhancement): Supports Node.js, Python, PHP, Ruby, Deno, and other runtimes such as java-17.0; for Java 17 enterprise projects, in addition to traditional source code archive builds, a new artifactMode=java-jar pre-built JAR direct deployment mode is added (default JAR configuration limit of 100 MB, also constrained by the plan's deployment limit), eliminating long Maven/Gradle compilation waits in the cloud.

  2. Execution environments: Supports local OpenRuntimes and multi-instance, multi-replica cloud sandboxes (ACS Sandbox). The restricted execution paths for ACS E2B and OpenSandbox check runtime identity and privileges; verify identity and isolation for other executors in the target deployment. Pass credentials through request headers rather than URL query parameters.

  3. Deduplicated execution path lookup with regex/method filtering (2.9.0 / 2.10.0 enhancement): Supports deduplicated aggregation by the actual HTTP request paths received by a function (path), combined with exact match/regex match (pathMatch=exact|regex) and HTTP method (method) filtering to quickly retrieve the historical execution durations and logs of specific business endpoints.

  4. Investigate failed executions: use execution records, status codes, logs, and runtime context to investigate application or platform issues. A 5xx code alone does not identify the cause; execution and build logs may be truncated.

Core capability dimensionConsole tab locationKey technical specifications (2.10.0 baseline)Applicable development and operations scenarios
Create and Deploy (Deployments)Function details DeploymentsThree sources: Git repository, template library, manual upload (.tar.gz source code or java-17.0 pre-built .jar)Continuous integration releases, one-click activation switching (Activate), and rollback to historical versions
Executions and Path Lookup (Executions)Function details ExecutionsSupports immediate/scheduled manual triggering; supports paginated deduplicated execution paths with path/pathMatch/method filteringOnline API integration testing, precise troubleshooting of slow requests and errors by specific REST subpath (such as /webhook/erp-sync)
Compute Specifications and Monitoring (Usage)Function details Usage · SettingsSupports configuring CPU/memory specifications (runtimeSpecification) and replica count (runtimeReplicas); supports platform default specificationsObserve execution counts, average duration, and real-time CPU/memory/network/disk curves of ACS cloud sandbox container groups
Triggers and Variables (Settings)Function details Settings · DomainsEvent triggers (Events), scheduled tasks (Cron Schedule), function-level variables (automatically merged and injected with project global variables)Orchestrating event-driven automation workflows, binding function-specific custom domains

Core Concepts and Architecture

1. Definitions of the Four Core Object Models

Core objectLifecycle and unique identifierKey attributes and architecture notes
Function (function definition)Belongs to a Project and has a unique $idDefines the runtime language (runtime, updatable through the function update API), compute specification (runtimeSpecification), instance replica count (runtimeReplicas), execution permissions (execute ACL), timeout (timeout), trigger events, and Cron schedule.
Deployment (deployment version)Belongs to a Function; each upload/commit generates a new $idCarries a specific code artifact or pre-built JAR artifact. Goes through waiting → building → ready / failed build transitions; only one ready deployment can be in the Active (currently activated) state at any given time to serve traffic.
Execution (single execution)Belongs to a Function; each trigger generates a unique recordRecords the request method (method), request path (path), duration (duration), HTTP response status code (responseStatusCode), standard output (logs), and error output (errors) of a single call.
Execution Path (deduplicated execution path)Automatically aggregated server-side by request pathDeduplicates and classifies massive Execution records by the actual accessed subpath (such as /v1/sync, /v1/callback), supporting server-side pagination and regex/method filtering.

2. Comparison of Source Code Build Mode (source) and Java 17 Pre-built JAR Mode (java-jar)

In Agentbase, for the java-17.0 runtime widely used by enterprises, two fundamentally different deployment artifact modes are provided (artifactMode):

Comparison dimensionSource archive build mode (artifactMode = source)Java 17 pre-built JAR mode (artifactMode = java-jar, new in 2.10.0)
Applicable runtimesAll supported runtimes (Node.js, Python, PHP, Ruby, Deno, Go, java-17.0, etc.)Limited to the java-17.0 runtime only
Upload artifact format.tar.gz Source code archive.jar file pre-compiled and packaged in advance on the local machine or in an enterprise CI pipeline
Build and entry mechanismExecutes install command inside the container to pull dependencies and compile source code, starting per the custom entrypointSkips cloud source compilation and directly uses the pre-built JAR as the deployment artifact, using the manifest's Main-Class; Index.java serves only as a compatibility identifier for the deployment record
Package size limit and meteringConstrained by the general compute source archive limit (_APP_COMPUTE_SIZE_LIMIT / plan deploymentSize)Jointly limited by _APP_FUNCTIONS_JAR_SIZE_LIMIT (default 100,000,000 bytes) and the plan's deploymentSize, with the effective limit taking precedence

Roles, Entry Points, and Relationships

1. Console Navigation Path and Permission Requirements

  1. Enter the Functions module: Click Functions in the left navigation bar of the project Console to enter /console/project-{region}-{project}/functions (as shown in Figure 1).

  2. Permission and Scope mapping:

    • Creating, modifying configurations, or uploading deployment packages in the Console requires a project write role (owner / admin / developer / editor, corresponding to functions.write).

    • Grant server API key scopes per operation: both execution-path queries require execution.read; function reads and changes use the corresponding functions.read or functions.write. Requests with the enabled AppBase marker, Web SDK name, and client platform are blocked by the execution-record read guard; passing that guard still requires other applicable authentication and authorization.

    • Direct invocation of functions by client end users (POST /v1/functions/{functionId}/executions) is governed by the role selector (such as any, users, team:support_team) configured in the function's Settings → Execute access.

2. Injection Priority of Function-Level Variables vs. Project Global Variables

When a function executes, the platform automatically injects environment variables into the container process from two sources of variables:

Feature Details and Operation Guide

1. Creating a cloud function (three sources and compute spec configuration)

Click Create function in the upper-right corner of the Functions list page to enter the creation wizard (/functions/create-function). The wizard offers exactly the following three creation methods:

Method One: Upload a code package (.tar.gz source or Java 17 .jar)

  1. Select Upload code package on the creation page.

  2. Fill in the core form parameters step by step:

Configuration fieldRequired/OptionalParameter constraints and production configuration recommendations
Name (function name)RequiredEnter a clear business name (e.g. erp-ticket-escalation-fn); you may optionally customize a Function ID ($id).
RuntimeRequiredSelect from the runtime list allowed by the current deployment instance (e.g. node-18.0, python-3.11, java-17.0). The function update API supports changing the runtime subject to runtime and execution-plan validation; verify deployment and activation behavior in the target environment.
Artifact ModeRequired (Java 17)When the runtime is java-17.0, you can choose source package (source) or pre-built JAR (java-jar):
• Choose source: upload a .tar.gz source package and fill in entrypoint and install command;
• Choose java-jar: upload a .jar package within the valid size limit; the application entry point is taken from the manifest's Main-Class.
CPU / memory spec (runtimeSpecification)RequiredSelect the compute spec of the function execution container (e.g. 0.5C / 1G, 1C / 2G, etc.). If the platform administrator has configured a default execution spec (defaultRuntimeSpecification), the wizard preselects it automatically; if no spec is available, contact an administrator to publish an execution profile.
Replica count (runtimeReplicas)RequiredSet the number of sandbox instance replicas serving concurrent requests. Warming depends on the keep-alive policy, deployment status, and available resources; more replicas do not guarantee the absence of cold starts. Measure latency in the target environment.
Execute AccessOptionalConfigure the client roles allowed to trigger this function directly (e.g. users); if it is only triggered by a backend API Key or internal events, keeping it empty (client direct calls denied by default) is the safest option.

Method Two: Create from official templates (Templates)

Method Three: Create by connecting a Git repository (Git Repository)

2. Managing deployment versions (Deployments) and one-click rollback

Go to the specific function detail page (/functions/function-{function}), which shows the Deployments tab by default:

  1. Publish a new version: click Create deployment in the upper-right corner and choose Manual (manually upload .tar.gz or .jar), Git (pull a specified branch/commit), or CLI as needed.

  2. Track build status and logs:

    • While a build is in progress, you can click Cancel at any time to cancel the build.

    • If the build status becomes failed, open the Deployment to inspect recorded build output, such as dependency or package errors. Logs may be truncated. After fixing the issue, use Redeploy to rebuild.

  3. Activate for release and one-click rollback (Activate):

    • After the build succeeds (status ready), if auto-activation was not checked, click the Activate button to the right of that deployment to switch it to the currently effective live version.

    • Production rollback: if a business anomaly is found after the new version goes live, simply locate the previous historical deployment with status ready in the Deployments list and click Activate to switch the active deployment without recompiling; then check the execution results of new requests. No guarantee is made regarding switching duration or losslessness of in-flight requests.

3. Online trigger execution (Execute) and deduplicated execution path queries (Execution Paths)

Switch to the Executions tab on the function detail page (path /functions/function-{function}/executions):

A. Online manual debugging or scheduled execution

  1. Click the Execute button in the upper-right corner to open the execution wizard dialog.

  2. Fill in the simulated request parameters:

    • Path: the request sub-path (e.g. /tickets/validate).

    • Method: select from GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD.

    • Headers and Body: add custom request headers and a JSON request body payload.

    • Execution timing: choose Run now (execute asynchronously immediately) or Scheduled at (single execution at a specific future date and time).

  3. Important security notice: Execute actually runs the container code and may read from or write to the current project's databases or storage buckets; before clicking submit in a production project, be sure to confirm the target environment and request parameters.

B. Search and troubleshoot by deduplicated execution paths (Execution Paths) (enhanced in 2.10.0)

When a single function carries dozens of business sub-interfaces through internal routing, use execution path queries to quickly locate the execution status of a specific interface:

  1. On the Executions page, switch to or expand the path query view (corresponding to the server endpoint GET /v1/functions/{functionId}/execution-paths).

  2. The system automatically deduplicates the request paths of the function's existing execution records and displays them page by page in ascending lexicographic order.

  3. Use advanced filters from 2.10.0:

    • Path match mode (pathMatch): supports exact (exact full-path match, default) or regex (regular expression match, e.g. ^/api/v1/tickets/[0-9]+$).

    • Path keyword (path): enter the target path string or regular expression.

    • HTTP method filter (method): precisely filter a specific method (e.g. view only POST requests).

  4. After clicking a target path, you can invoke GET /v1/functions/{functionId}/execution-paths/executions to list all execution details under that path.

C. Investigating failed executions

Use execution records, status codes, errors, logs, and runtime context together. Both application responses and the platform execution path can produce 5xx codes; logs and errors may be truncated, so neither status alone nor missing logs establish the cause.

Response status codeTroubleshooting clues
500 / 502 / 503 / 504May originate in an application response or execution path. Check execution details, available logs, timeouts and platform status; if the outcome is unknown, check side effects before retrying.

D. Additional sandbox diagnostics and missing logs

If the deployment has enabled the updated sandbox diagnostics, the platform stores runtime, build, and execution evidence in isolated files that business code cannot read or write directly. Functions may emit business logs, but their content and any self-reported project, execution, or Trace identifiers are correlation hints, not authorization to access other resources.

Diagnostics use fixed rotation and bounded queues. Producers retry in the background if the collector starts late; full queues, storage failures, forced termination, or shutdown timeouts may still lose logs. New diagnostic writes stop when available disk space falls below the reserve and may resume after space recovers; this does not provide a hard disk quota for the function. If an execution exists but logs are missing, retain its execution ID, time, and platform status for an administrator to correlate with lifecycle and collector health records. Missing logs do not prove the business code did not run.

When execution logging is disabled (logging=false), the request adds no business logger content, and subsequent runtime raw capture stays disabled for that instance. Queued content not yet accepted by the collector is rejected; content already queued for disk writing may still be written. Legacy execution log return rules retain their existing behavior; later explicit logger events with logging enabled follow the runtime semantics. A successful function response, a completed file write, or a local closing summary does not prove diagnostics were uploaded. The platform must update runtime and collection components together; a tag alone does not prove these behaviors are deployed.

4. Configuring scheduled tasks (Schedule), event triggers, monitoring, and custom domains

  1. Scheduled execution (Cron Schedule): go to the function's Settings tab, enter a standard Cron expression in the Schedule card (the UI includes real-time Cron syntax validation, e.g. 0 */2 * * * means once at the top of every 2 hours); after saving, the platform scheduler triggers it automatically on a periodic basis.

  2. Event triggers (Events): add an internal event subscription (e.g. databases.enterprise_biz_db.tables.customer_tickets.rows.create) in Settings → Events; when a new support ticket row is added to the business database, the row data automatically triggers the function as the request body.

  3. ACS container group compute monitoring (Usage): switch to the Usage tab; besides viewing execution counts and average duration trends, for functions running on the cloud sandbox (ACS), the page provides a dedicated ACS container group resource monitoring panel at the bottom, showing in real time the container instances' CPU utilization, memory usage, network throughput, and disk read/write, providing quantitative evidence for tuning runtimeSpecification and runtimeReplicas.

  4. Function-specific domains (Domains): switch to the Domains tab to independently bind a custom domain (e.g. webhook-erp.enterprise.example.com) to the current function; external systems can send requests directly to that domain to trigger the function.

Confirm the execution spec

The creation wizard preselects the platform default spec available for the current project first. Before submitting, check whether the CPU, memory, and replica count suit the actual workload; a manually selected valid spec takes precedence over the default. If no platform default spec is available, choose from the available specs listed on the page rather than copying another project's configuration.

Default values only affect newly created Functions; existing functions do not change when platform defaults change. When editing an existing function, make sure to keep the original execution spec, and in particular do not change the spec incidentally when only adjusting the replica count. Execution specs and build resources are different configurations; adjusting the execution spec does not mean build resources change at the same time, nor that instances are pre-warmed.

Uploading a Java 17 pre-built JAR

Applies to Java HTTP services already built locally or in CI. Prepare an executable JAR supporting Java 17: the manifest must declare Main-Class, the package must contain the corresponding entry class; the application listens on port 3000 and provides a /__opr/health health check. Command-line JARs that only execute and exit cannot be used as function HTTP services.

  1. Open Functions → Create function → Upload code package and select Java 17 as the runtime; existing Java 17 functions can access manual upload from the deployment list.

  2. Confirm the upload mode is pre-built JAR and select the .jar file. To build source online, switch back to source mode and upload .tar.gz; do not merely rename the file extension to JAR.

  3. Confirm the execution spec, replica count, variables, and execute access. JAR mode does not require a source entry point, install command, or build spec; the application entry point is taken from the manifest. The Index.java in the deployment record is a compatibility identifier; there is no need to additionally create a source file with that name.

  4. After submitting, wait for the deployment record to appear, note the deployment ID, and check the build status and logs. The default JAR size limit is 100 MB (100,000,000 bytes), further constrained by the plan's deployment limit; if the limit is exceeded, shrink the artifact or contact an administrator to confirm the effective limit.

  5. Once the deployment reaches ready, confirm it has become the currently active deployment; use Activate if needed. Then initiate an actual request via Execute and check the returned status code, response body, and logs.

CheckpointWhat it can confirmNext step
Upload progress reaches 100%File transfer finishedWait for the create deployment request to return; do not re-upload
Deployment record returnedThe service has accepted the deploymentWait for status to reach ready; check logs on failed/canceled
Deployment readyArtifact preparation completeCheck whether the currently active deployment is this deployment
Active deployment matches and request results meet expectationsThis code has actually been executedThen enable production traffic or scheduled tasks

If you cannot submit, first check the runtime, upload mode, JAR size, and manifest; if the deployment fails, check the build logs; if the deployment is ready but calls fail, check the port, health checks, variables, execution permissions, and execution logs. Do not treat a successful upload as a successful release.

Troubleshooting Executions by Path and Method

In the function detail page, under Executions → Custom filter, fill in the Path, choose exact match or regex match, then select the Method as needed, apply the filter, and review results from the first page. Refreshing preserves the filter conditions; after troubleshooting, use the clear action to restore the full list.

Troubleshooting targetExample conditionNotes
A specific complete request pathPath exact match /articles/42The query string participates in matching; /articles/42?draft=1 is a different path
A group of numbered pathsPath regex ^/articles/[0-9]+$Do not add extra /…/ delimiters; this expression does not match paths with query strings
View only read requestsMethod selection GETThe method and path conditions take effect simultaneously; verify the actual request method first

An empty list only means the current conditions matched nothing; first clear the filters to confirm the records exist, then add the conditions back one by one. waiting / processing still indicates waiting or processing, and cannot be treated as failed merely because the timeout has passed. Records only enter the failure filter after the service has actually recorded a failure. Running records cannot be deleted; completed and failed records can be deleted, and deleting a scheduled record cancels the corresponding scheduled execution.

FAQ and Troubleshooting

Q1: Why does calling a protected cloud function via URL Query String (e.g., ?key=standard_xxx) from an external system return 401 authentication failure?

Cause and troubleshooting steps: Due to strict security and compliance requirements, Agentbase prohibits passing the Function API Key via URL Query String (because URL parameters easily leak credentials in plaintext in browser history, reverse proxy access logs, and monitoring pipelines). When calling a protected cloud function, you must pass the key in a protected HTTP request header (e.g., X-Appwrite-Key: standard_...), or use the platform-injected runtime internal authentication path.

Q2: When deploying or running a function, why does the error "Restricted Identity security conditions not met" appear, and why does it not automatically run with root privileges?

Cause and troubleshooting steps: The restricted execution paths for ACS E2B and OpenSandbox check non-root identity, capabilities, and NoNewPrivs during startup preparation; a failed security check rejects execution on that path. For an insufficient-permission error, the command and script determine the observed failure behavior. Check the executor, image, and runtime logs, use a writable working directory or /tmp for temporary files, and avoid privilege-escalation commands. Verify runtime identity for other executors in the deployment configuration.

Q3: What should you pay attention to when uploading a deployment package using the Java 17 pre-built JAR mode (artifactMode=java-jar)?

Cause and troubleshooting steps:

  1. Check the runtime type: artifactMode=java-jar is only available when the function Runtime is java-17.0.

  2. Check the entry class convention: In pre-built JAR mode, the manifest must declare Main-Class, and the package must contain the corresponding entry class and runtime dependencies; the application must listen on 3000 and provide /__opr/health. Index.java is merely a compatibility identifier for the deployment record.

  3. Check the JAR file size: Pre-built JARs are jointly constrained by _APP_FUNCTIONS_JAR_SIZE_LIMIT (default 100 MB, i.e., 100,000,000 bytes) and the plan's deployment limit; when the effective limit is exceeded, trim dependencies or contact an administrator to confirm the plan and deployment configuration.

Multiple timers and CPU oriented specifications

A function can have several independent recurring tasks. Each task has its own rule, input and enabled state, and invokes the current ready active deployment. Open Functions → target function → Settings → schedules, check the active deployment, and create a task. Choose its rule type, enter the expression, time zone or interval anchor, select the input type, and explicitly set whether it is active. Save and reopen the task to verify the values.

SettingMeaning and limits
interval1–2147483647 seconds; the anchor is a UTC timestamp with second precision; omission on creation uses creation time
CronFive field expression; UTC is used when the time zone is omitted
QuartzSix fields with an optional year; exactly one of day of month and day of week must be ?; supports IANA zones
JSON inputInvokes POST /; enter valid JSON, or leave the input empty to send no body
Request pathInvokes GET against a relative path and query of the current function, such as /daily-report?region=east; this is not an external URL and sends no body
Active stateIndependent per task; missed ticks while inactive are not replayed; disabling does not cancel an invocation already admitted

When editing an interval, leaving the anchor blank preserves it; entering a new time changes it. The task type is immutable after creation. Create a replacement of the desired type and disable the previous task. A request path starts with a single /, is at most 2048 bytes including its query, and cannot contain a full URL, fragment, whitespace or invalid percent encoding.

The list supports pagination, creation, editing, enabling, disabling and confirmed deletion. After saving, inspect the rule, active state and next scheduled time, then check execution records for the actual result. A next time or a successful create response does not prove that business code ran. The function enabled switch controls direct client invocation; use the task active switch to stop scheduled invocation. Runtime keepalive is separate and survives deletion of business tasks.

The legacy single Cron setting only projects the historical compact task. It does not describe all timers. Historical tasks can be edited or deleted; deleting one does not make the old endpoint recreate it. If nothing runs, check active state, expression and time zone, a ready active deployment, and project write restrictions. On validation failure, correct the retained form input before submitting again.

Runtime specifications add 1 CPU / 1024 MB and 2 CPU / 2048 MB. Select, save and reopen settings to verify. Availability still depends on plan and deployment limits. Changes retain the existing runtime recycling behavior; adjust specifications when there are no active executions.