@zkoide/secure-agent-gateway-sdk
v1.19.0
Published
Secure Agent Gateway SDK - Developer-first execution authorization, capability enforcement, and asynchronous approvals for AI Agents
Maintainers
Readme
@zkoide/secure-agent-gateway-sdk
Developer-first SDK for AI Agent governance, atomic tool claims, and execution safety.
The @zkoide/secure-agent-gateway-sdk is an ultra-lightweight, zero-runtime-dependency TypeScript library designed to wrap, protect, and observe tool execution in AI agents.
Installation
npm install @zkoide/secure-agent-gateway-sdkQuickstart
import { GatewayRuntime, HttpGatewayBackendClient, s } from '@zkoide/secure-agent-gateway-sdk';
const backendClient = new HttpGatewayBackendClient({
baseUrl: process.env.GATEWAY_BASE_URL || 'https://gateway.yourdomain.com',
apiKey: process.env.GATEWAY_API_KEY!,
});
const runtime = new GatewayRuntime(backendClient);
export const refundTool = runtime.protect({
tool: {
name: 'payments.refund',
version: '1.0.0',
risk: 'WRITE',
},
inputSchema: s.object({
chargeId: s.string().describe('Stripe charge ID'),
amount: s.number().positive().describe('Refund amount in BRL/USD'),
}),
outputSchema: s.object({
refundId: s.string(),
status: s.string(),
}),
async handler(input, context) {
// Only executes after Edge Policy authorization and Atomic Claim verification
return await stripe.refunds.create({
charge: input.chargeId,
amount: input.amount,
});
},
});Key Capabilities
1. Built-in Schema Validator (s)
Generate clean JSON Schemas directly formatted for LLM prompts with zero external dependencies:
import { s } from '@zkoide/secure-agent-gateway-sdk';
const customerSchema = s.object({
customerId: s.string().min(3).describe('Unique customer ID'),
amount: s.number().positive().max(50000),
category: s.enum(['RETAIL', 'WHOLESALE'] as const),
notify: s.boolean().optional(),
tags: s.array(s.string()).optional(),
});2. Multi-Agent Delegation Chains
Track and audit the entire delegation tree when multiple autonomous sub-agents collaborate on behalf of a human user:
const context = runtime.createContext({
principalId: 'user_maria_123',
agentId: 'sub-agent-payment',
delegationChain: [
{ id: 'user_maria_123', type: 'HUMAN', name: 'Maria Silva' },
{ id: 'master-orchestrator', type: 'AGENT', name: 'Shopping Coordinator' },
{ id: 'sub-agent-payment', type: 'AGENT', name: 'Billing Sub-Agent' },
],
});Para identidades externas como telefone, e-mail ou ID do provedor, use o contexto seguro assíncrono. O SDK aplica separação de domínio e SHA-256; o valor original pode permanecer em local para uso exclusivo do handler:
const context = await runtime.createSecureContext({
traceId: message.id,
agentId: 'support-agent',
principal: { externalId: customer.phone, namespace: 'customer' },
local: { customerPhone: customer.phone },
});Essa pseudonimização evita enviar o identificador bruto e mantém correlação estável. Para identificadores de baixa entropia sujeitos a enumeração, trate SHA-256 como redução de exposição — não como substituto de HMAC ou de um identificador opaco emitido pelo seu provedor de identidade.
Consentimento verificável do cliente
Em canais conversacionais, executeWithCustomerConsent() transforma o evento
autenticado pelo canal em evidência, confirma a decisão pendente e retoma a
mesma execução:
const result = await runtime.executeWithCustomerConsent(
cancelAppointmentTool,
{ appointmentId },
context,
{
channel: 'WHATSAPP',
externalEventId: message.id,
statement: message.text,
occurredAt: message.timestamp,
actor: { externalId: customer.phone, namespace: 'customer' },
},
);O SDK remove policyContext.confirmed antes da primeira decisão, normaliza a
declaração, pseudonimiza o ator e envia somente hashes. Por padrão, eventos com
mais de 24 horas ou mais de 5 minutos no futuro são rejeitados. As janelas podem
ser reduzidas por chamada com maxEvidenceAgeMs e maxFutureSkewMs.
3. Human-in-the-Loop & Async Resumption
When an action requires supervisor approval (PENDING_APPROVAL), the SDK receives a webhook notification and resumes execution atomically:
import express from 'express';
import { createWebhookReceiver } from '@zkoide/secure-agent-gateway-sdk';
const app = express();
const receiver = createWebhookReceiver({ secret: process.env.GATEWAY_WEBHOOK_SECRET! });
app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
const event = receiver.verify(req.body, req.headers['x-gateway-signature'] as string);
if (event.type === 'decision.approved') {
const pending = await db.approvals.findUnique({
where: { decisionId: event.data.decisionId },
});
// Resumes execution using single-use claim lock
const execution = await refundTool.resume(pending.input, context, event.data.decisionId);
console.log('Execution completed:', execution.result);
}
res.json({ received: true });
});4. Universal Multi-LLM Export
Convert protected tools to any major LLM format with a single function call:
Google Gemini
const declaration = refundTool.toGemini();OpenAI
const openAiTool = refundTool.toOpenAI();Anthropic Claude
const claudeTool = refundTool.toAnthropic();Vercel AI SDK & Next.js
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
const result = await generateText({
model: openai('gpt-4o'),
tools: {
refund: refundTool.toAISDK(input =>
runtime.createContext({ principalId: session.userId })
),
},
});5. PII Masking & Telemetry Sanitization
Protect sensitive customer data (LGPD, GDPR, PCI-DSS) by automatically redacting sensitive fields before transmitting audit logs:
const runtime = new GatewayRuntime(client, {
sanitization: {
redactKeys: ['cpf', 'rg', 'creditCard', 'pixKey', 'password'],
presets: {
cpf: true,
cnpj: true,
creditCard: true,
email: true,
phone: true,
},
},
});6. Pipeline Middlewares
Intercept, log, or measure tool execution across all tools in the application:
runtime.use(async (ctx, next) => {
const start = performance.now();
const result = await next();
const duration = performance.now() - start;
metrics.timing(`tool.${ctx.tool.name}.duration`, duration);
return result;
});7. Unit Testing in 3 Lines (testTool)
Validate tool logic and mock gateway decisions without making network requests:
import { testTool } from '@zkoide/secure-agent-gateway-sdk';
import { refundTool } from './refund-tool';
import assert from 'node:assert/strict';
test('executes refund when authorized by policy', async () => {
const { result, decision } = await testTool(refundTool, {
input: { chargeId: 'ch_123', amount: 500 },
mockDecision: 'ALLOW',
});
assert.equal(decision.effect, 'ALLOW');
assert.equal(result.status, 'succeeded');
});Policy Synchronization CLI
Synchronize local declarative policies (gateway/policies.json) with the Control Plane:
# Push local policies to the cloud
npx sag push
# Pull active cloud policies to local repository
npx sag pullPolicy operations are administrative and do not accept an agent API key. Sign in through the browser once; Cloudflare Access validates your identity and the CLI stores only a short-lived, project-scoped session:
npx sag login
npx sag diff --check
npx sag push
npx sag logoutThe terminal and browser display the same one-time code, and PKCE binds the
resulting session to the CLI that started the flow. GATEWAY_API_KEY remains
exclusive to tool decisions and execution; it cannot change policies.
sag diff --check prints the proposed changes and exits with a failure when a
server policy disappears from the JSON, a restrictive effect is weakened, or a
confirmation, consent, approval, or human-review safeguard is removed.
For CI/CD, create a project-scoped management token in the dashboard and store
it as the protected secret SAG_MANAGEMENT_TOKEN. It is accepted only by policy
operations and never by agent execution endpoints:
SAG_MANAGEMENT_TOKEN=sag_management_... npx sag pushGuarantees
| Guarantee | Description | | :--- | :--- | | Zero Runtime Dependencies | The SDK has no external npm runtime dependencies, ensuring maximum performance and zero supply-chain risk. | | Fail-Closed by Default | Any unreachable gateway, invalid schema, or unauthorized state terminates execution immediately. | | Atomic Claim Consumption | Single-use claims prevent double-execution even during network retries or parallel agent forks. | | Type-Safe Context | Full TypeScript type inference for tool inputs, outputs, and local application session context. |
License
Apache-2.0. Maintained by the Secure Agent Gateway Team.
