NNextsAI Docs

Backend and Agent integration

The Web SDK, stdio JSON-RPC, events, cancellation, idempotency, runtime paths, permissions, and main Agent action contract.

Choose a backend using runtime formats. This stdio contract applies to Python, Node, and native managed-worker backends. The UI and main Agent should call one business layer; applications retain ownership of their data and task state.

1. Calling a backend from the UI

Bundle @nextsai/app-sdk@1.0.0, register one lifecycle, and wait for the host:

import { defineApp, nexts } from '@nextsai/app-sdk';
defineApp({ activate() {}, deactivate() {} });
await nexts.ready();
const result = await nexts.backend.invoke<{ text: string }>(
  'demo.echo', { text: 'hello' },
);
console.log(result.text);

demo.echo is implemented by your application. The SDK does not supply business methods, start a development server, or expose worker ports or host credentials. A normal browser needs your own Web API adapter, or an explicit unavailable state.

For events and cancellation:

const unsubscribe = nexts.events.onRuntimeEvent((event) => console.log(event));
const invocation = nexts.backend.request('jobs.start', { inputId: 'input-1' }, {
  idempotencyKey: 'operation-123',
});
// Bind invocation.cancel() to the user's Cancel button.
try {
  console.log(await invocation.result);
} finally {
  unsubscribe();
}

requestId identifies a transport request. idempotencyKey identifies a business operation: reuse it for retries of that operation, and create another key for a new operation.

2. Worker stdio frames

The protocol is nexts-app-rpc-v1: UTF-8 stdin/stdout, one complete JSON object per line, flushed after writing. Reserve stdout for protocol messages and write diagnostics to stderr.

Example host request:

{
  "jsonrpc": "2.0", "id": "request-1", "method": "demo.echo",
  "params": { "text": "hello" },
  "context": {
    "appId": "ai.nexts.demo", "instanceId": "app-instance-1",
    "viewId": "main", "sdkVersion": "1.0.0"
  },
  "idempotencyKey": null
}

Validate the protocol version, string ID, method, parameters, and identity. Match app/instance IDs against host environment variables. Return a stable error for unknown methods; never interpret a method as a shell command or unrestricted path.

Return either success or error with the unchanged string ID:

{"jsonrpc":"2.0","id":"request-1","result":{"text":"hello"}}
{"jsonrpc":"2.0","id":"request-1","error":{"code":"invalid_params","message":"text is required","data":{"field":"text"}}}

The current application RPC uses string error codes, unlike numeric-only error models in some JSON-RPC libraries. data is optional. The host rejects identity mismatches and requests over 4 MiB; maxOutputBytes limits each returned line. Keep large files, media, and models in app-owned files and return business IDs or controlled references.

3. Events, cancellation, and shutdown

Send notifications without an id while handling a request:

{"jsonrpc":"2.0","method":"app.progress","params":{"requestId":"request-1","progress":0.5,"message":"processing"}}
{"jsonrpc":"2.0","method":"app.chunk","params":{"requestId":"request-1","sequence":0,"data":{"text":"partial"}}}
{"jsonrpc":"2.0","method":"app.notification","params":{"name":"jobs.changed","data":{"jobId":"job-1"}}}

Use progress from 0 to 1 and nonnegative integer sequences. The current stdio adapter serializes business requests and forwards notifications while reading the active response. Idle stdout notifications are not guaranteed to reach the UI immediately; persistent tasks need a status method too.

The host sends cooperative cancellation as:

{"jsonrpc":"2.0","method":"$/cancelRequest","params":{"id":"request-1"}}

Keep reading control messages to support cancellation; blocking a single input thread prevents timely handling. Stop new work, release resources, and complete the original request with a result or error. Cancellation does not undo an external effect that already occurred.

The host requests shutdown with:

{"jsonrpc":"2.0","method":"app.shutdown","params":{"reason":"user_requested"}}

This control notification has no business context. Flush data, close databases, and exit. Other reasons include update, uninstall, crash_recovery, and shutdown. After shutdownTimeoutMs, the host terminates the worker. On Windows it closes the Job Object to clear the managed process tree, including descendants of a parent that exited cooperatively.

Worker health currently checks process liveness, not an automatic app.health call. healthTimeoutMs is not an application-readiness handshake; provide your own status method if initialization matters. The response-wait budget is at least the maximum of resources.timeoutMs, healthTimeoutMs, and shutdownTimeoutMs. Treat timeouts, mismatched response IDs, invalid JSON, and closed stdout as failures; never automatically replay writes.

4. Host environment

VariableMeaning
NEXTS_APP_IDStable application ID
NEXTS_APP_INSTANCE_IDCurrent backend instance
NEXTS_APP_VERSIONInstalled application version
NEXTS_APP_RPC_PROTOCOLnexts-app-rpc-v1
NEXTS_APP_DATA_DIRBusiness data, SQLite, and configuration
NEXTS_APP_FILES_DIRPersistent files
NEXTS_APP_CACHE_DIRRebuildable cache
NEXTS_APP_LOG_DIRLogs
NEXTS_APP_PERMISSIONSComma-separated declared and granted capability names
NEXTS_APP_NETWORK_POLICYJSON with outboundDomains and loopback

The host clears inherited environment and supplies these values plus a limited set of OS variables. Do not depend on development-machine PATH, proxies, language configuration, or credentials. Native workers start directly, with no extra command-line arguments, in the package root. Use the provided directories for writes.

Example network declaration:

{"network":{"outboundDomains":["models.example.com"],"loopback":true}}

Defaults are an empty outbound list and loopback: false. The worker must implement this policy, including redirect destination checks. It is a cooperative trusted-process contract, not an OS firewall. It does not grant frontend nexts.fetch() access; that requires network.fetch and meta.domains separately.

The host does not inject app-specific variables such as COMFY_STUDIO_LOCAL_ENGINE. Applications can check their declared business capability, such as engine.local, in NEXTS_APP_PERMISSIONS, then obtain in-app user confirmation before starting an engine. A custom capability name does not create a new host API.

5. Main Agent integration

Declare a capability and a bounded set of business actions in the same manifest:

{
  "permissions": [{
    "key": "agent.integration", "optional": true,
    "reason": "Let the assistant inspect this application's supported actions"
  }],
  "agentIntegration": {
    "enabledByDefault": false,
    "instructions": "Read demo.capabilities before using business actions.",
    "discoveryAction": "demo.capabilities",
    "actions": [{
      "name": "demo.capabilities", "method": "demo.capabilities",
      "description": "List supported business operations", "access": "read",
      "inputSchema": { "type": "object", "properties": {}, "additionalProperties": false }
    }]
  }
}

Keep enabledByDefault: false and optional: true for agent.integration. Actual access depends on installation authorization, enabled state, and the application's selection for that Agent operation. instructions is app-authored usage information, limited to 8192 UTF-8 bytes. discoveryAction must be a declared read action callable with an empty object.

The main Agent uses host-owned applications_list, application_describe, and application_call; applications do not open another MCP port. The host validates the declared action and input schema, then calls its method through the same worker protocol. Business validation, write confirmation, and idempotency remain in the backend.

nexts.agent.createSession() instead starts an Agent session inside your application using ai.agent. This is a separate direction of integration; see SDK development.

6. Durable tasks and idempotency

Persist generation, transcoding, or download tasks in the app's private database and return promptly instead of holding the serialized RPC:

{
  "taskId": "job-1", "status": "running", "terminal": false,
  "next": { "action": "jobs.get", "input": { "id": "job-1" }, "afterMs": 1000 }
}

This is a recommended business result, not a host-generated task system. Implement and declare jobs.get and jobs.cancel. Return terminal: true, next: null, and result references when finished. Persist idempotency keys and outcomes. Check status after ambiguous transport failures before resubmitting; the application also owns recovery after restart.

7. managed-web business RPC

Implement POST /_nexts/rpc with the same request/response objects. Validate Authorization: Bearer <NEXTS_APP_RPC_TOKEN> with constant-time comparison, and check app/instance identity. The token is for host-to-backend calls; never expose it in browser code, pages, or logs.

The host disables proxies and redirects, caps responses at 4 MiB and requests at 60 seconds, and does not replay requests. Ordinary UI business APIs may remain same-origin, with their own authentication and input validation.

Next: develop and package a native worker.

On this page