Skip to content
Browse the documentation

Node.js SDK

Install and use agentlock-sdk-node: signed requests, approvals, results, browser and SSH sessions and messaging from Node.js agents.

Node.js SDK for AgentLock. It signs every request with the agent's Ed25519 key, submits actions to the AgentLock gateway, waits for approvals and returns the results. The agent never receives the credentials AgentLock uses on its behalf.

Full API reference: https://app.agentlock.net/docs/api

Installation

bash
npm install agentlock-sdk-node

Requires Node.js 18 or later.

Setup

Create a key pair once, register the public key when you create the agent in the AgentLock dashboard, and keep the private key in the agent's environment:

typescript
import { generateKeypair } from 'agentlock-sdk-node';

const { publicKey, privateKey } = generateKeypair();

Both keys are base64 encoded. The dashboard shows the agent ID after registration.

typescript
import { AgentLockClient } from 'agentlock-sdk-node';

const client = new AgentLockClient({
  baseUrl: 'https://app.agentlock.net',
  agentId: process.env.AGENT_ID!,
  privateKey: process.env.AGENT_PRIVATE_KEY!,
});
OptionDefaultDescription
baseUrlhttps://app.agentlock.net. Must be HTTPS; http://localhost is accepted for local development.
agentIdThe agent's UUID.
privateKeyThe agent's base64 Ed25519 private key.
timeout30000Timeout of each HTTP call in milliseconds.

createClient(options) is equivalent to new AgentLockClient(options).

Submitting actions

typescript
const submitted = await client.requestAction({
  action_type: 'write',
  tool: 'http',
  payload: {
    method: 'POST',
    url: 'https://api.example.com/orders',
    body: { item: 'widget', quantity: 10 },
    credential_name: 'example-api',
  },
  idempotency_key: 'order-2026-12-02-001',
});

if (submitted.status === 'BLOCKED') {
  throw new Error(`Blocked: ${submitted.message}`);
}

const final = await client.awaitResult(submitted.request_id);
if (final.status !== 'SUCCEEDED') {
  throw new Error(`Action ended with ${final.status}: ${final.error ?? ''}`);
}
console.log(final.result);
  • requestAction(action) sends the action and returns { request_id, decision, status, message?, expires_at? }. status is ALLOWED, PENDING or BLOCKED. It throws when the gateway answers with an error status.
  • awaitResult(requestId, { pollIntervalMs?, timeoutMs? }) polls until the status is SUCCEEDED, FAILED, DENIED, EXPIRED, BLOCKED or UNDONE and returns { status, result?, error? }. Defaults: poll every 2000 ms, give up after 300000 ms with an error.
  • Call awaitResult for ALLOWED as well as PENDING: an allowed action runs asynchronously, and its output is only available from the result endpoint.

Tools, payloads and policy behavior are described in the API reference.

Wrapping a function

toolWrapper(fn, { action_type, tool, cost_estimate?, idempotencyKey? }) returns a function that takes a payload, submits it, waits for the result and calls fn with the result. Every call is submitted with its own idempotency key. Pass idempotencyKey, a function of the payload, to derive the key instead: calls that return the same key share one action, because the gateway answers a repeated key with the first request. A key has at most 128 characters. Only a SUCCEEDED action reaches fn. A denial throws ApprovalDeniedError, an expiry ApprovalTimeoutError, and a blocked, failed or undone action AgentLockError.

typescript
const createOrder = client.toolWrapper(
  async (result) => result.body,
  { action_type: 'write', tool: 'http' },
);

const order = await createOrder({
  method: 'POST',
  url: 'https://api.example.com/orders',
  body: { item: 'widget' },
  credential_name: 'example-api',
});

HTTP requests

typescript
const res = await client.httpRequest({
  method: 'GET',
  url: 'https://api.example.com/items',
});
// { status, headers, body, durationMs }

httpRequest accepts GET, POST, PUT, PATCH and DELETE (type HttpMethod), declares read for GET and write otherwise, waits for approval when the policy requires it and throws ApprovalDeniedError, ApprovalTimeoutError or an Error when the action does not succeed. approvalTimeoutMs sets how long it waits (default 300000). durationMs is 0 when the execution did not report it.

The credentialId option has no effect: the gateway selects HTTP credentials by name. To send a vault credential, use requestAction with payload.credential_name as shown above.

Browser sessions

A browser session runs on AgentLock's servers. Opening one always needs approval; actions inside an open session run immediately when the policy allows them.

typescript
const session = await client.browserOpen('https://shop.example.com/login', {
  allowedDomains: ['accounts.example.com'],
});

await client.browserFillCredentials(session.session_id, 'shop-login', {
  '#email': 'username',
  '#password': 'password',
});
await client.browserAction(session.session_id, 'click', { selector: 'text=Sign in' });

const snap = await client.browserSnapshot(session.session_id);
// { html, url, title, screenshot? }  html holds the accessibility snapshot

await client.browserClose(session.session_id);
MethodDescription
browserOpen(url, { allowedDomains? })Requests browser.open, waits for approval and returns { session_id, snapshot, page_url, page_title }.
browserAction(sessionId, tool, params?)Runs browser.<tool> in the session, for example click, type, navigate, select, press_key, scroll, snapshot or screenshot, and returns { session_id, snapshot, page_url, page_title, action_performed, screenshot? }.
browserFillCredentials(sessionId, credentialName, fieldMapping)Fills a login credential. fieldMapping maps CSS selectors to username, password or totp.
browserSnapshot(sessionId)Returns { html, url, title, screenshot? }.
browserClose(sessionId)Closes the session.

selector takes a Playwright selector. Under the default policy only snapshot, screenshot, scroll and close are allowed inside a session; an action the policy would send for approval is refused, and browserAction throws. Add ALLOW rules for the browser tools the agent should use.

SSH sessions

typescript
const session = await client.ssh.open({ credentialId: '<ssh credential UUID>' });
try {
  const r = await session.run('uname -a');
  console.log(r.exitCode, r.stdout);
} finally {
  await session.close();
}
  • client.ssh.open({ credentialId, ttlMs?, approvalTimeoutMs? }) requests ssh.open, waits for approval and returns an SshSession. Host, user and port always come from the credential. ttlMs is capped at the plan maximum (20 minutes on Pro, 60 minutes on Team; Free has no persistent sessions), which is also the default.
  • session.run(command) returns { stdout, stderr, exitCode, signal, truncated, durationMs }. Every command is checked against the policy and waits for approval when the policy requires it; a denial throws ApprovalDeniedError. It throws SshSessionClosedError after close() and SshSessionExpiredError once the session has expired.
  • session.close() is idempotent and safe to call from finally.
  • session.isExpired() checks the expiry locally.
  • client.ssh.list() returns the agent's open sessions, including those opened by another process.
  • client.ssh.adopt(sessionId) returns a handle for a known session ID without a network call.
typescript
const sessions = await client.ssh.list();
const s = sessions.find((x) => x.host === 'build-01.example.com');
if (s) await s.run('tail -n 50 /var/log/nginx/access.log');

client.sshRun({ credentialId, host, user, command, port? }) runs a single command without a persistent session and is available on every plan. host, user and port must match the credential. It is deprecated in favor of client.ssh.open() for more than one command.

Messages

typescript
const { messages } = await client.getMessages();
for (const m of messages) {
  await client.sendMessage(m.thread_id, `Received: ${m.content}`);
}

await client.createThread('Deploy finished.', { subject: 'Deploy' });

const stop = client.onMessage((m) => console.log(m.content), {
  pollIntervalMs: 5000,
  onError: (err) => console.error(err),
});
// later: stop();
  • getMessages({ since?, limit?, includeRead?, threadId? }) returns { messages }. By default it returns unread messages from people and marks them as read.
  • sendMessage(threadId, content, metadata?) replies in a thread and returns the message.
  • createThread(content, { subject?, metadata? }) starts a thread and returns { thread, message }.
  • onMessage(callback, { pollIntervalMs?, maxBackoffMs?, onError? }) polls in the background (default every 5000 ms, backing off after errors up to 60000 ms) and returns a function that stops it.

MCP servers

typescript
const { tools } = await client.mcpListTools('github-mcp');
const res = await client.mcpCallTool('github-mcp', 'create_issue', { title: 'Bug' });
console.log(res.is_error, res.text);
  • mcpListTools(server) returns { server, tools }. server is the name of an mcp credential.
  • mcpCallTool(server, method, args?, actionType = 'write') returns { server, method, content, text?, is_error }.

Both methods throw an Error when the action does not succeed.

Errors

ClassThrown when
AgentLockErrorBase class of the errors below; also thrown when listing SSH sessions fails and by toolWrapper when an action is blocked, fails or is undone.
ApprovalDeniedErrorAn approver denied the request (requestId, denialReason).
ApprovalTimeoutErrorThe approval expired (requestId, waitedMs: how long the client waited).
SshSessionExpiredErrorrun on an expired session.
SshSessionClosedErrorrun on a closed session.

Other failures, such as an error status from the gateway, throw a plain Error whose message carries the gateway's reason.

Retries

requestAction and the methods built on it, getMessages and ssh.list retry HTTP 429, 502, 503 and 504 up to three times. An action without idempotency_key gets a random one that stays the same for every attempt, and the gateway answers a repeated key with the first request (idempotent: true), so a retry cannot create a second action. browserAction and other browser tools inside a session, sendMessage and createThread cannot be deduplicated and retry only HTTP 429, which the gateway sends before it processes a request. Each retry is signed anew with a fresh nonce. awaitResult signs every poll anew and waits through 429 and 5xx responses.

License

MIT

Node.js SDK | AgentLock Docs