Get started
Quickstart: protect an agent with TypeScript
Authorize and execute agent actions through the gateway with @gebsecure01/sdk — allowed, approval-gated and denied — in about ten minutes.
This quickstart walks through the TypeScript example agent, a support agent that issues refunds. Every snippet below is taken from that example, which the documentation test suite runs against a real api, gateway and worker.
1. Run GebSecure and get credentials#
Start a local stack with the self-hosting quickstart (npm run setup && npm run dev
from the repository root). npm run setup prints the console login admin@gebsecure.local and its password once.
The example's provisioning script signs in as that administrator through the SDK and creates everything the agent needs: it deploys the policy, registers the agent with a client-secret credential and installs a connection to the billing API.
// An administrator signs in with a user session (the refresh token is returned in the body).
const session = await new GebSecure({ apiUrl, gatewayUrl, auth: unauthenticated() }).login({
email: env('GEBSECURE_ADMIN_EMAIL'),
password: env('GEBSECURE_ADMIN_PASSWORD'),
});
const admin = new GebSecure({ apiUrl, gatewayUrl, auth: staticToken(session.accessToken) });let clientSecret: string;
const agents = await admin.listAgents({ environmentId: environment.id, q: AGENT_NAME });
const agent = agents.data.find((a) => a.name === AGENT_NAME);
if (agent) {
clientSecret = (await admin.createAgentCredential(agent.id, { type: 'client_secret', name: `example-${Date.now()}` })).clientSecret!;
// A previous run's injected article tainted the agent for 30 minutes; start clean.
await fetch(`${apiUrl}/v1/injection/taint/${agent.id}`, { method: 'DELETE', headers: { authorization: `Bearer ${token}` } });
} else {
const created = await admin.createAgent({
environmentId: environment.id,
name: AGENT_NAME,
description: 'Customer-support agent that issues refunds (examples/typescript-agent)',
framework: 'custom',
tags: ['support'],
credential: { type: 'client_secret', name: 'example' },
});
clientSecret = created.credential!.clientSecret!;
}You can also register an agent in the console (Agents → New agent) or with the CLI
(gebsecure agents create billing-bot --credential-file ./billing-bot.json). The client secret (gsa_…) is
shown once.
2. Install the SDK and create a client#
npm install @gebsecure01/sdkThe SDK runs on Node.js ≥ 20 and any runtime with fetch and WebCrypto, has no runtime dependencies and ships
ESM and CommonJS builds. Without options, the client reads GEBSECURE_GATEWAY_URL, GEBSECURE_API_URL and
GEBSECURE_API_KEY or GEBSECURE_CLIENT_SECRET:
// Reads GEBSECURE_GATEWAY_URL, GEBSECURE_API_URL and GEBSECURE_CLIENT_SECRET (or GEBSECURE_API_KEY).
// Client-secret credentials are exchanged for short-lived access tokens, cached and refreshed by the SDK.
const gs = new GebSecure({ maxRetries: 3 });
const connection = process.env.BILLING_CONNECTION ?? 'billing-api';
const approvalTimeoutMs = Number(process.env.APPROVAL_TIMEOUT_SECONDS ?? 600) * 1000;A client secret is exchanged at POST {api}/v1/auth/token for an access token, which the SDK caches and refreshes
before it expires. For keys that never leave a KMS or HSM, use privateKeyJwt() instead (see the
TypeScript SDK reference).
3. Authorize, then act#
When your code performs the action itself, ask first. guard() calls POST /v1/authorize and returns
allowed: true only for ALLOW; a denial is a result, not an exception.
// 2. Authorize-only: the agent reads the ticket from its own store, but only if policy allows it.
const planStart = Date.now();
const read = await gs.guard('support:tickets.read', 'ticket:T-1042', { channel: 'email' }, { traceparent });
if (!read.allowed) throw new Error(`cannot read tickets: ${read.decision.reason}`);
outcomes.readTicket = read.decision.decision;
// The scripted "model" turns the ticket into a plan (a real agent would call its LLM here).
const plan = ticketForModel.includes('ch_0977') ? ['refund-small', 'refund-large', 'delete-customer'] : ['refund-small'];
const planSpan = buildSpan('agent.plan', planStart, Date.now(), { traceparent, kind: 'internal', status: 'ok', attributes: { steps: plan.length } });
spans.push(planSpan);
const child = { traceparent: traceparentOf(planSpan) }; // later calls are children of the plan spanIf the decision is APPROVAL_REQUIRED, wait for the approval and authorize again with its id — the approval is
bound to this exact request and consumed once:
async function refund(chargeId: string, amount: number) {
const { allowed, decision } = await gs.guard('refunds:create', `stripe:charge/${chargeId}`, { amount, currency: 'USD' });
if (decision.decision === 'APPROVAL_REQUIRED') {
console.log(`Needs human approval: ${decision.approval?.url}`);
const approval = await gs.waitForApproval(decision.approval!.id, { timeoutMs: 15 * 60_000 });
if (approval.status !== 'approved') throw new PolicyDeniedError({ status: 403, code: 'policy_denied', detail: `Approval ${approval.status}` });
// Re-authorize with the approval id: consumes the approval (it is bound to this exact action).
const retry = await gs.authorize({ action: 'refunds:create', resource: `stripe:charge/${chargeId}`, context: { amount, currency: 'USD' }, approvalId: approval.id });
if (retry.decision !== 'ALLOW') throw new Error(`Still not allowed: ${retry.reason}`);
} else if (!allowed) {
console.log(`Denied (risk ${decision.risk.score}/${decision.risk.level}): ${decision.reason}`);
return;
}
console.log(`Allowed by ${decision.explanation?.grantingPolicyId}; performing refund…`);
// … call your payment provider here …
}4. Execute through GebSecure#
To keep the external system's credentials away from the agent, execute the action through a connection.
The example installs the billing API as a generic rest connection whose operations become actions
rest:refunds.create and rest:customers.delete:
{
"$comment": "Configuration of the 'billing-api' REST connection used by the example agents. Each operation becomes an action rest:<name>; contextFields are visible to policies as context.<field>. The provisioning scripts set baseUrl from BILLING_API_URL.",
"baseUrl": "http://127.0.0.1:4300",
"operations": [
{
"name": "refunds.create",
"method": "POST",
"path": "/v1/refunds",
"inputSchema": {
"type": "object",
"required": ["chargeId", "amount"],
"properties": {
"chargeId": { "type": "string" },
"amount": { "type": "number" },
"currency": { "type": "string" }
}
},
"bodyFields": ["chargeId", "amount", "currency"],
"resource": "billing:charge/{chargeId}",
"contextFields": ["amount", "currency"],
"risk": { "category": "write", "sensitivity": 40, "financial": true }
},
{
"name": "customers.delete",
"method": "DELETE",
"path": "/v1/customers/{customerId}",
"inputSchema": {
"type": "object",
"required": ["customerId"],
"properties": { "customerId": { "type": "string" } }
},
"resource": "billing:customer/{customerId}",
"risk": { "category": "delete", "sensitivity": 70, "destructive": true }
}
]
}The agent names the connection and the action; GebSecure authorizes, runs the connector in a sandbox, injects the connection's credential only for its allowed hosts, sanitizes and inspects the output and audits the call.
// 3. A small refund: allowed by policy and executed through the billing-api connection.
// GebSecure injects the connection's credentials; the agent never sees them.
const small = await gs.execute({ connection, action: 'refunds.create', input: { chargeId: 'ch_1043', amount: 40, currency: 'USD' } }, child);
summarize('refund $40', small);
outcomes.smallRefund = small.status;execute() resolves to an ExecuteResult for every runtime outcome: succeeded and simulated (HTTP 200),
awaiting_approval and running (202), denied (403) and failed (502/504). With retries enabled the SDK adds
an idempotencyKey, so a retried execution never runs twice.
5. Wait for a human approval#
The deployed policy allows refunds up to 500 but requires an owner's approval above 100:
policy "support-refunds" {
description "Refunds up to 500; above 100 a human approves; at most 2000 per agent per day"
effect permit
principal agent where "support" in principal.tags
action "rest:refunds.create"
resource any
when has(context.amount) && context.amount > 0 && context.amount <= 500
limit sum(context.amount) <= 2000 per 24h by agent
require approval when context.amount > 100 {
approvers role "owner"
expires 1h
}
}A $400 refund therefore comes back as awaiting_approval. A reviewer approves it in the console (the
approval.url), from Slack, or through the API; the GebSecure worker then resumes the stored execution with the
approval. The agent waits for the decision and follows the execution:
// 4. A larger refund needs a human approval (policy: amount > 100). The execution is stored as
// awaiting_approval; once a reviewer approves, the GebSecure worker resumes it with the approval
// (consumed exactly once, only for this exact request). The agent waits and follows the execution.
const large = await gs.execute({ connection, action: 'refunds.create', input: { chargeId: 'ch_0977', amount: 400, currency: 'USD' } }, child);
if (large.status === 'awaiting_approval' && large.approval && large.executionId) {
console.log(`refund $400: waiting for approval ${large.approval.id} (${large.approval.url ?? 'console'})`);
try {
const approval = await gs.waitForApproval(large.approval.id, { ...child, timeoutMs: approvalTimeoutMs, pollIntervalMs: 2_000 });
// "consumed" means the worker already resumed the execution with it.
if (approval.status !== 'approved' && approval.status !== 'consumed') throw new ApprovalNotGrantedError(approval);
const done = await waitForExecution(large.executionId);
console.log(`refund $400: ${done.status} ${JSON.stringify(done.output ?? done.error)}`);
outcomes.largeRefund = done.status;
} catch (e) {
if (e instanceof ApprovalNotGrantedError) outcomes.largeRefund = `approval ${e.approval.status}`;
else if (e instanceof ApprovalTimeoutError) outcomes.largeRefund = 'approval timed out';
else throw e;
console.log(`refund $400: ${outcomes.largeRefund}`);
}
} else {
summarize('refund $400', large);
outcomes.largeRefund = large.status;
}const ACTIVE = new Set(['pending', 'running', 'awaiting_approval', 'cancelling']);
/** Polls an execution until it reaches a final status (succeeded, failed, denied, cancelled). */
async function waitForExecution(id: string, timeoutMs = 120_000): Promise<Execution> {
const deadline = Date.now() + timeoutMs;
for (;;) {
const e = await gs.getExecution(id);
if (!ACTIVE.has(e.status)) return e;
if (Date.now() > deadline) throw new Error(`execution ${id} still ${e.status}`);
await new Promise((r) => setTimeout(r, 1_000));
}
}The reviewer side of the example uses the management API:
// The inbox lists pending approvals this reviewer can decide right now; this reviewer handles refunds only.
const inbox = await reviewer.listApprovals({ inbox: true, status: 'pending' });
const refunds = inbox.data.filter((a) => a.action === 'rest:refunds.create');
for (const a of refunds) {
// Decide on exactly what was reviewed: the snapshot hash binds the decision to the request.
const details = await reviewer.getApprovalDetails(a.id);
console.log(`${verdict} ${a.id}: ${details.action} on ${details.resource} — ${details.reason ?? ''}`);
const result = await reviewer.decideApproval(a.id, {
decision: verdict,
snapshotHash: details.snapshotHash!,
comment: verdict === 'approve' ? 'Verified the duplicate charge' : 'Refund not justified',
channel: 'api',
});
console.log(` → ${result.status}`);
}6. See a denial#
forbid beats every permit. A denied execution is a result with status: "denied" and the deciding policy in
reason:
// 5. Deleting a customer is forbidden. A denial is a result (status "denied"), not an exception.
const del = await gs.execute({ connection, action: 'customers.delete', input: { customerId: 'cus_dana' } }, child);
summarize('delete customer', del);
outcomes.deleteCustomer = del.status;7. Inspect untrusted content and report spans#
Text the model will read — emails, web pages, retrieved documents, tool output — goes through inspect() first.
It returns an action (ALLOW, FLAG, SANITIZE, MASK, REDACT, REQUIRE_APPROVAL or BLOCK), the
prompt-injection score and a sanitized content to hand to the model instead of the original:
// 1. The ticket is untrusted input: inspect it before the model reads it.
const inspected = await gs.inspect({ content: TICKET, source: 'email', origin: 'mailto:dana@example.com' }, { traceparent });
if (inspected.action === 'BLOCK') throw new Error(`ticket blocked: injection ${inspected.injection.level}`);
const ticketForModel = String(inspected.content ?? TICKET); // sanitized/masked text, safe for the prompt
console.log(`ticket inspection: ${inspected.action} (injection score ${inspected.injection.score})`);
outcomes.ticketInspection = inspected.action;// 6. Retrieved content (RAG, web, tool output) is inspected too. Injected instructions are flagged,
// sanitized or blocked; a flagged result also taints the agent, so its next write actions need approval.
const kb = await gs.inspect({ content: KB_ARTICLE, source: 'rag', origin: 'kb://refund-policy' }, child);
console.log(`knowledge-base inspection: ${kb.action} (injection ${kb.injection.level}, score ${kb.injection.score}, tainted: ${kb.injection.tainted ?? false})`);
outcomes.kbInspection = kb.action;Finally the agent reports its own spans, so the trace shows its planning next to GebSecure's decisions:
// 7. Report the agent's own spans; GebSecure joins them with its authorization and execution spans.
// The run span is the root of the trace: same trace id, the span id every traceparent above points to.
spans.push({ ...buildSpan('agent.run', planStart, Date.now(), { spanId: rootSpanId, kind: 'internal', status: 'ok' }), traceId });
const reported = await gs.reportSpans(spans);
console.log(`trace ${traceId}: ${reported.accepted} agent spans reported`);Run it#
npx tsx examples/typescript-agent/src/billing-api.ts &
eval "$(npx tsx --tsconfig examples/typescript-agent/tsconfig.json examples/typescript-agent/src/setup.ts)"
npx tsx --tsconfig examples/typescript-agent/tsconfig.json examples/typescript-agent/src/agent.ts
# while it waits: npx tsx --tsconfig examples/typescript-agent/tsconfig.json examples/typescript-agent/src/approve.ts --watchSee the example's page for the expected output.
Next steps#
- Write your own policies and test them with the CLI.
- Wrap an existing framework's tools: TypeScript integrations.
- Every method, error and retry rule: TypeScript SDK reference.