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
npm install agentlock-sdk-nodeRequires 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:
import { generateKeypair } from 'agentlock-sdk-node';
const { publicKey, privateKey } = generateKeypair();Both keys are base64 encoded. The dashboard shows the agent ID after registration.
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!,
});| Option | Default | Description |
|---|---|---|
baseUrl | https://app.agentlock.net. Must be HTTPS; http://localhost is accepted for local development. | |
agentId | The agent's UUID. | |
privateKey | The agent's base64 Ed25519 private key. | |
timeout | 30000 | Timeout of each HTTP call in milliseconds. |
createClient(options) is equivalent to new AgentLockClient(options).
Submitting actions
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? }.statusisALLOWED,PENDINGorBLOCKED. It throws when the gateway answers with an error status.awaitResult(requestId, { pollIntervalMs?, timeoutMs? })polls until the status isSUCCEEDED,FAILED,DENIED,EXPIRED,BLOCKEDorUNDONEand returns{ status, result?, error? }. Defaults: poll every 2000 ms, give up after 300000 ms with an error.- Call
awaitResultforALLOWEDas well asPENDING: 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.
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
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.
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);| Method | Description |
|---|---|
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
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? })requestsssh.open, waits for approval and returns anSshSession. Host, user and port always come from the credential.ttlMsis 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 throwsApprovalDeniedError. It throwsSshSessionClosedErrorafterclose()andSshSessionExpiredErroronce the session has expired.session.close()is idempotent and safe to call fromfinally.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.
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
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
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 }.serveris the name of anmcpcredential.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
| Class | Thrown when |
|---|---|
AgentLockError | Base class of the errors below; also thrown when listing SSH sessions fails and by toolWrapper when an action is blocked, fails or is undone. |
ApprovalDeniedError | An approver denied the request (requestId, denialReason). |
ApprovalTimeoutError | The approval expired (requestId, waitedMs: how long the client waited). |
SshSessionExpiredError | run on an expired session. |
SshSessionClosedError | run 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