Skip to main content

TypeScript SDK

@datalayer/personal-agent-protocol provides portable discovery, validation, Reactor integration, and PAP session primitives. The generated TypeScript API reference inventories the portable entry and the explicit ./server subpath from their source exports.

Install and buildโ€‹

npm install @datalayer/personal-agent-protocol

The package is ESM and publishes TypeScript declarations.

Incoming protocol JSON is decoded with parseJsonStrict, which rejects duplicate member names at every depth, including names that become equal only after JSON escape decoding. Discovery uses this parser automatically before wire-model validation.

Discoveryโ€‹

import {
buildPapReactor,
discoverCompany,
} from "@datalayer/personal-agent-protocol";

const reactor = buildPapReactor({
assertSafeUrl: async (url) => serverDnsPolicy.assertSafe(url),
});
const company = await discoverCompany("example.com", { reactor });

All network operations accept an AbortSignal. Pass it to discovery when the calling task, request, or UI owns cancellation:

const controller = new AbortController();
const company = await discoverCompany("example.com", {
reactor,
signal: controller.signal,
});

The published portable ESM entry bundles Reactor's framework-neutral core so it can run directly in Node and in browser bundlers. JoseSigner, the company's checks of Session JWTs and assertions, replay-cache contracts, and Node network policy are exported only by the explicit ./server entry. Platform signing keys must remain on a server or KMS; they must never be shipped in a browser or desktop bundle.

The SDK exports the same contribution points as Python (Clocks, RandomSources, Signers, SessionSigners, DpopProvers, TokenStores, Caches, BrowserHandoffs, BrowserJoins, PairwiseUserIdStores, AuthorizationStateStores, and the rest; see Contribution points). Security-dependent services have no fallback and resolution fails closed when missing or ambiguous.

BrowserSessionClient joins the agent's own browser (the BrowserJoins contribution) to a Session: the browser loads the company's join form, the client authorizes its one-time code at {endpoint}/authorize in a request of its own, with the Session header and, signed in, the access token, and the browser submits the form, the code alone. See the Browser Session flow.

DelegatedSessionSigner over a DelegatedKeyCustody (InMemoryDelegatedKeys for tests) keeps one delegated P-256 key per User ID, never shared across User IDs, with a delegation from the pap.signer key in jwks_uri of at most 24 hours, and signs each Session JWT with it; it rotates the key before the delegation expires and never signs past it. jwkThumbprint is the RFC 7638 thumbprint in a Session JWT's kid.

SessionFetchClient owns the Poppy-Session, Authorization and DPoP headers for API and conversation requests. Each request carries a fresh Session JWT, and with a DPoP token a fresh proof; a session_ended answer starts a new Session once, and a use_dpop_nonce challenge sends the request again once, the latest nonce kept per origin. It refuses every redirect (redirect_refused): no token or body goes to the URL a protocol endpoint redirects to. See the Session transport flow.

ConversationClient composes that transport to start and continue PAP conversations. generateRequestId() uses Reactor's cryptographic random source to create a user-global idempotency key. Retain the complete message and reuse it unchanged when retrying an ambiguous request. The client parses immediate receipts or waited event pages and propagates AbortSignal without exposing credentials. readEvents() and events() add ordered JSON long polling, backlog draining, cursor-expiry recovery, and duplicate suppression. See Conversation messages and Conversation events.

Agent identityโ€‹

AgentIdentityClient gives companies the same hardened metadata and JWKS boundary as the Python SDK:

import {
AgentIdentityClient,
buildPapReactor,
} from "@datalayer/personal-agent-protocol";

const identity = new AgentIdentityClient({ reactor });
const metadata = await identity.fetchMetadata(
"https://agent.example/agent.json",
{ signal: controller.signal },
);
const jwks = await identity.fetchJwks(metadata.client_id, {
signal: controller.signal,
});

Client metadata is fetched without redirects and its client_id must equal the exact fetched URL. The client validates same-domain redirect and JWKS URLs, bounds responses, rejects duplicate JSON members, and retrieves keys through the configured Reactor transport and URL-safety policy. JWKS redirects cannot leave the client host. Only complete public P-256/ES256 and RSA/PS384 signing keys are accepted; symmetric and private JWK members are rejected.

Session primitivesโ€‹

import {
SessionClient,
resolvePairwiseUserId,
} from "@datalayer/personal-agent-protocol";

const pairwiseUserId = await resolvePairwiseUserId(reactor, {
tenantId: "application-42",
localUserId: "local-user-42",
companyIssuer: "https://auth.example.com",
});
// A Session is local: no request is sent, its `sid` is random, and it starts signed out.
const session = await new SessionClient({ reactor }).start({
clientId: "https://agent.example/agent.json",
pairwiseUserId,
issuer: "https://auth.example.com",
tenantId: "application-42",
});
console.log(session.sid, session.handle);

SecretValue renders as [REDACTED] in strings and JSON. Calling reveal() is an explicit boundary for authorization and token requests; keep that value out of logs, UI state, analytics, and model-visible tools.

SessionClient starts a PapSession and sends token requests with a fresh client assertion. It requires a host-provided pap.signer contribution, supports AbortSignal on token requests, and rejects redirects and malformed token responses. tokenRequest takes the tenantId whose key proves and the issuer's dpopSigningAlgs; a DPoP token type with no proof sent is unsupported_token_type. See Signed-out sessions for usage and the exact security boundary.

JoseSigner signs client assertions and delegations with ES256 or PS384. It and the company's verifySessionJwt, verifyDelegation, and verifyAssertion come from @datalayer/personal-agent-protocol/server. They use the maintained jose package and Web Crypto. BlindJoseSigner writes the same JWTs on the user's device and has the key sign them blindly (RFC 9474), over a BlindSigningKey such as RsaBlindSigningKey, so the key holder never sees them; the result is an ordinary PS384 signature. See Cryptography for key and replay-cache requirements.

DirectSignInClient implements browser handoff, atomic one-use state, the code exchange, cancellation, and partial-scope reporting. The package also retains the lower-level buildDirectSignInRequest and validateDirectSignInCallback primitives. See Direct Sign-In for usage and the trusted-host boundary. DeviceSignInClient and MediatedSignInClient sign in the same way; each stores the refresh token behind a reference, which RefreshTokenClient uses.

DPoPโ€‹

A company that binds its access tokens lists ES256 in its metadata's dpop_signing_alg_values_supported. Pass what the metadata says to whatever sends a token request; a DPoP token then needs nothing more from the host:

  • DeviceSignInClient.begin and DirectSignInClient.begin take dpopSigningAlgs, with the pairwiseUserId whose key proves: one DPoP key per User ID (spec 4.5);
  • so does RefreshTokenContext, for refreshes and tokens for one service;
  • MediatedSignInClient.signIn reads it from company, and takes the tenantId and pairwiseUserId whose key proves.

With a list that doesn't include ES256, or none, no proof goes. The default pap.dpopProver (DpopProvers, contribution in-memory) keeps its keys in memory: a host whose tokens outlive a process contributes JoseDpopProver with a durable DpopKeyCustody (keyFor, forget, by tenant, issuer and sub), below the default's order of 100. A lost key means refreshing: refresh tokens aren't bound. See DPoP.

pap.operatorSigner (OperatorSigners) has no default: contribute a WebBotAuthSigner, and every request with the Session header carries an operator signature. See Operator signatures.

A company built with CompanyConfig binds its tokens with dpopBinding (off, optional or required) and asks for nonces with dpopNonces; verifyDpopProof comes from @datalayer/personal-agent-protocol/server.

Client, conversation, and Operations modelsโ€‹

Use parseClientMetadata, parseJsonWebKeySet, parseMessage, parseConversationEvent, parseConversationEventPage, and parseOperation at trust boundaries. These parsers preserve unknown compatible fields and future event types while enforcing the required shapes of known version 0.4 and Operations version 3 objects.

The models are aligned with Python through shared fixtures. Conversation creation, continuation, JSON event polling, SSE streaming, handoff, Direct Conversations, and closing are implemented in ConversationClient, and OperationsClient asks the user through pap.approvalSurface and sends the approval (see the Operations guide). Parsing an object alone does not perform durable cursor persistence or approval.

Decksโ€‹

The entry @datalayer/personal-agent-protocol/decks ships the four cases as decks: PAP_DECKS, PAP_DECK_IDS and papDeck(id), each with its yaml and the same deck parsed as spec. It brings in yaml and nothing of the SDK.

Server-side URL safetyโ€‹

The portable default rejects obvious local and private literal addresses. It cannot resolve DNS without importing platform-specific APIs into browser bundles. Node services can use the separate server entry:

import { buildPapReactor } from "@datalayer/personal-agent-protocol";
import {
JoseSigner,
NodeUrlSafetyPolicy,
createResolvingFetch,
verifySessionJwt,
} from "@datalayer/personal-agent-protocol/server";

const urlPolicy = new NodeUrlSafetyPolicy();
const reactor = buildPapReactor({
fetch: createResolvingFetch(),
assertSafeUrl: (url) => urlPolicy.assertSafe(url),
});

NodeUrlSafetyPolicy resolves every A and AAAA result and rejects the URL if any address is loopback, private, link-local, shared, documentation-only, multicast, or reserved. Literal IP addresses use the same classification without DNS. Private-network access is disabled by default and must be enabled explicitly for a controlled deployment.

NodeUrlSafetyPolicy alone is a DNS preflight, not connection pinning: createResolvingFetch resolves and vets again for each request and dials only the vetted address, keeping the URL's name for SNI, certificate checks, and Host, so a name that rebinds after the check reaches no private address. The Node company (buildCompany) uses it unless given its own fetch.

OpenAPI and MCPโ€‹

ApiClient calls a company's OpenAPI API through SessionFetchClient, as Python's ApiClient does. A read answers its JSON body; a consequential call answers 403 with approval_required and an operation, performing nothing until the same request comes back with the user's approval (see OperationsClient). A refusal is an ApiError carrying the company's code only: insufficient_scope says in details.scope which scope the request needs, and a 429 says in details.retry_after how long to wait (it is never retried for a write).

import { ApiClient, SessionFetchClient } from "@datalayer/personal-agent-protocol";

const api = new ApiClient({ transport: new SessionFetchClient({ reactor }) });
const orders = await api.call("GET", "https://shop.example/api/orders", { session, token });
const proposed = await api.call(
"POST",
"https://shop.example/api/orders/ord_7Hk2/exchanges",
{ session, token, body: {} },
);
console.log(proposed.status, proposed.operation?.summary);

For MCP the personal agent gets a token for the MCP server's url from discovery alone (ยง4.5). fetchMcpServerMetadata reads the server's protected resource metadata, and RefreshTokenClient.tokenForMcp asks for a token with resource set to its url, as a refresh (the refresh token rotates as on any other). MCP's baseline is Bearer: a proof goes only when that metadata lists dpop_signing_alg_values_supported with ES256, whatever the issuer lists. ServiceTokens does the same for any service: one access token per resource a service asks for. McpSessionAuth.fetch sends that token, with the Session header, only to that exact URL (scheme, host, port and path), and refuses every other request before it is made (token_not_for_this_url). McpClient is a minimal Streamable HTTP client (initialize, listTools, callTool) over it; a tool that needs an approval returns the operation as result.operation, the same Operation as an API's 403:

import { McpClient, RefreshTokenClient, fetchMcpServerMetadata, mcpApi } from "@datalayer/personal-agent-protocol";

const mcpUrl = mcpApi(company.document)!.url;
const served = await fetchMcpServerMetadata(mcpUrl, { issuer });
const refreshed = await new RefreshTokenClient({ reactor }).tokenForMcp(refreshTokenReference, {
context: { tokenEndpoint, issuer, clientId, tenantId },
server: served,
});
const mcp = new McpClient({ url: mcpUrl, session, token: refreshed.token, reactor });
const tools = await mcp.listTools();
const result = await mcp.callTool("exchange_jacket");
console.log(tools.length, result.operation?.operation_id);

To use another MCP client, hand it new McpSessionAuth(mcpUrl, { session, token, reactor }).fetch. An MCP refusal is an McpError: the token error from the Bearer challenge (insufficient_scope with details.scope, invalid_token). invalid_token with details.resource_metadata means a token wasn't issued for that service: staleResourceMetadata tells so, and the agent reads the metadata again. A tool that needs Operations, which the agent did not negotiate, answers an ordinary tool error. operationFrom reads the one operation from an API body, an MCP result or a message.

Browser sessions at the companyโ€‹

The TypeScript reference company serves the website as the Python one does when its configuration sets web: true: discovery lists web.browser_session_endpoint, whose GET answers the join form (a one-time code tied to the browser by a __Host-poppy_join cookie). The agent authorizes the code at {endpoint}/authorize with the Session header (204), and the browser's POST of that code answers 303 with the company's own __Host-poppy_session cookie (Secure, HttpOnly, SameSite=Strict, no lifetime of its own, valid only while the Session is). A code from another browser, or one the agent never authorized, joins nothing.

import { CompanyConfig } from "@datalayer/personal-agent-protocol/server";

const config = new CompanyConfig({
name: "Example Shop",
domain: "shop.example",
scopes: ["orders:read", "orders:write"],
agentDescription: "Anything about your orders and returns",
scopeDescriptions: {
"orders:read": "See your orders",
"orders:write": "Exchange or return items in your orders",
},
writeScopes: ["orders:write"],
web: true,
});
console.log(config.browserSessionEndpoint); // https://shop.example/poppy/browser-session