Skip to content

TypeScript SDK ​

@preworld/guard is the SDK for Node.js agents. It follows the Python SDK: the same control-plane contract, policy hashes, approval digests and cache file. ESM only, Node.js 22.12 or later, no runtime dependencies.

Current hosted production offers @preworld/guard@0.2.0. Version 0.3.0 will use @yilabs/guard; change the package, registry scope and imports only after that version is released and offered by your private index.

Install ​

The package is served only by your private SDK index, at /npm/ on the SDK host, with the same SDK download token as pip. It is not on the public npm registry. Don't install a package of that name from there.

  1. Copy .npmrc.example from the connection package to .npmrc in your project root, and commit it. It sends the @preworld scope to the private index and reads the credential from the environment, so the file holds no secret:
@preworld:registry=https://sdk.guard.example.com/npm/
//sdk.guard.example.com/npm/:_auth=${PREWORLD_GUARD_SDK_NPM_AUTH}
replace-registry-host=npmjs
  1. Set PREWORLD_GUARD_SDK_NPM_AUTH to the base64 of token:<SDK download token>. The console shows this value when it issues the token, also only once. Keep it in the environment or a CI secret, never in .npmrc or Git.
sh
export PREWORLD_GUARD_SDK_NPM_AUTH=$(printf 'token:%s' "$SDK_DOWNLOAD_TOKEN" | base64)  # or the value the console shows
  1. Install with the command from the wizard, for example:
sh
npm install --save-exact --@preworld:registry=https://sdk.guard.example.com/npm/ @preworld/guard@0.2.0
npm install ai zod                                                                     # from the public registry

Without the committed .npmrc, a fresh clone, npm update, Dependabot or Renovate would look for @preworld/guard on the public registry. replace-registry-host=npmjs stops a user or global setting from rewriting the private download addresses. package-lock.json records the download address and the sha512 integrity, never the credential, so commit it. A package with other bytes won't install.

Always run the CLI as npx --no preworld-guard …. Without --no, npx would fetch a same-named package from the public registry when the SDK isn't installed.

Use ​

ts
import { GuardClient, guardRun } from "@preworld/guard";

const guard = await new GuardClient({
  endpoint: process.env.PREWORLD_GUARD_ENDPOINT!,
  token: process.env.PREWORLD_GUARD_TOKEN!,
  projectId: process.env.PREWORLD_GUARD_PROJECT_ID!,
  agentId: process.env.PREWORLD_GUARD_AGENT_ID!,
  backgroundEvents: true,
}).start();

const updateRecord = guard.tool("crm.update", async (args: { id: string; fields: Record<string, string> }) => {
  // the side effect runs only after Guard allowed this exact call
});

await guardRun({ sessionId: conversationId, subjectId: signedInUser }, () => updateRecord({ id, fields }));
await guard.close(); // on shutdown
APIWhat it does
guard.authorize(resource, args, options)Decides one call. Throws GuardDenied (with GuardApprovalRequired and GuardDegradeRequired as subclasses), or GuardError when Guard can't decide. If you run the tool yourself, run it on executionArguments(action), the copy that was decided
guard.tool(name, fn)Wraps a function: records started and completed, runs fallbacks registered with guard.registerFallback for degrade rules, and gives the function a copy of the decided arguments
guard.run(authorized, fn), guard.runStream(...)For adapters: runs exactly what this client's authorize returned, once
guardRun({ sessionId, subjectId, runId, traceId }, fn)Sets the identity for every Guard call inside fn (with AsyncLocalStorage). The subject comes from your application, never from the model
guardApproval(ticketId, ...) or the approvalTicket optionRun an approved call again
guard.approvalStatus(ticketId), guard.cancelApproval(ticketId)Manage a ticket

Arguments are copied once, when authorize or the wrapped tool is called, before anything is awaited. Changing your object afterwards changes neither the decision nor what the tool gets. The copy follows JSON.stringify. Functions, symbols, class instances such as Date, NaN, infinities and cycles are refused, because Guard can't allow what it can't see.

Vercel AI SDK ​

ts
import { generateText } from "ai";
import { guardRun } from "@preworld/guard";
import { guardTools } from "@preworld/guard/ai-sdk";

const { tools, toolApproval } = guardTools({ lookup, transfer }, guard);
const result = await guardRun({ subjectId: user.id, sessionId: chat.id }, () =>
  generateText({ model, tools, toolApproval, messages, experimental_toolApprovalSecret: approvalSecret }));
  • Where Guard decides: in each wrapped tool's execute, right before it runs. The tool gets the arguments that were decided.
  • toolApproval combines Guard's verdict with your own approval rules. The stricter one wins. Guard allows: your rules decide. Guard denies: { type: "denied", reason }. Guard needs approval: { type: "user-approval", reason } with the ticket.
  • Your rules first. No Guard ticket is filed for a call your rules deny. Guard still records its own denial if its policy denies the call too.
  • Resuming: a call is released only if a reviewer approved the ticket in Guard and your own rules agree. An approval response in the messages alone, forged or not, never releases a call Guard requires approval for. Pass experimental_toolApprovalSecret so that ai@7 can tell forged approval responses from real ones.
  • When Guard can't decide, or can't record that the call starts (GUARD_AUDIT_UNAVAILABLE), the call is denied with a GUARD_* reason and no internal error text.
  • Streaming tools (async *execute, or a function returning an async iterable) stream through Guard after the decision. The call is recorded as completed when the stream ends.
  • Tools Guard can't see before they run (provider-executed tools, tools without execute) are refused unless you list them in unguardedTools.
  • Identity comes only from guardRun (or options.identity). An identity callback that throws gives GUARD_IDENTITY_UNAVAILABLE. One whose subject differs from guardRun's gives GUARD_SUBJECT_MISMATCH.

Connection check ​

sh
npx --no preworld-guard connection-check --config guard-connection.json

The token comes from PREWORLD_GUARD_TOKEN (or --token-file), never from the command line. Exit 0 means ready, 2 not ready, 1 the check itself failed.

Network and TLS ​

  • Certificates are always verified; NODE_TLS_REJECT_UNAUTHORIZED=0 has no effect.
  • The trusted roots are Node's bundled Mozilla store. NODE_EXTRA_CA_CERTS, --use-system-ca and --use-openssl-ca add nothing.
  • HTTPS_PROXY and NO_PROXY are ignored. Pass proxy / caBundle, or set PREWORLD_GUARD_PROXY / PREWORLD_GUARD_CA_BUNDLE. A CA bundle replaces the bundled roots.
  • The token and proxy credentials don't show in console.log(guard), util.inspect or JSON.stringify.

Events on disk ​

Redacted events wait next to the policy cache until the control plane accepts them. Several processes, worker threads, clients and agents can share the default .preworld-guard/ folder: each client writes only its own files, named after its project, control plane and agent. Files left by a client that has gone are taken over by another client of the same agent, without losing events.

A closed client refuses every further action.

Where it is stricter than Python ​

Each of these fails closed: the policy is refused, the action denied, or authorize throws.

  • Policies are parsed strictly. A version written as "3" or 3.0, NaN or Infinity in a rule, or versions above 2^53−1 are refused.
  • argument_regex supports a portable subset: literals, classes, groups, alternation and quantifiers, ^ only first and $ only last. \d, \w, \s, \b, lookarounds, inline flags and backreferences are refused when a rule is evaluated.
  • expires_at must be YYYY-MM-DD[(T| )HH:MM[:SS[.fff|.ffffff]][±HH:MM|Z]]. Any other value makes the policy count as expired.
  • argument_path_under follows symlinks. A loop or a NUL byte throws, and the check isn't supported on Windows.
  • Tool arguments must be JSON.