Integration Guide — Gao AI OS
Connect your application, agent framework, or external AI system to Gao AI OS via the Gao SDK (L3).
Prerequisites
Before integrating with Gao AI OS, you need:
-
A registered Gao Domain (see Gao Domain docs)
-
A Gao Developer account with SDK access
-
A signed CAP token from your domain owner
-
@gao/sdkinstalled (npm install @gao/sdk)
CAP Token Issuance Flow
Before any agent can execute, a domain owner must issue a signed CAP token. This is a one-time setup per agent deployment.
Developer Domain Owner GAR v1
│ │ │
│── define capability ──▶️│ │
│ manifest │ │
│ │ │
│◀️── reviews scope ─────│ │
│ and risk tier │ │
│ │ │
│ │── signs CAP token ────▶️│
│ │ (wallet signature) │
│ │ │
│◀️────────────────── cap_id + token returned ─────│
│ │
│── set GAO_CAP_TOKEN in env ──────────────────── │
│── initialize runtime with cap token ──────────▶️ │
│ │
│ runtime validates:
│ - aud == gar.gao.systems
│ - domain ownership (L5)
│ - nonce not replayed
│ - not expired
│ - signature valid
│
│◀️── ACTIVE (ready to execute) ────────────────── │
Key points:
-
The domain owner (not the developer) signs the CAP token with their wallet
-
CAP tokens are scoped to a specific
agent_idand cannot be transferred between agents -
Re-issuance is required if the permitted scope, risk tier, or ceiling needs to change
-
Token revocation is immediate via the
revocation_endpointin the token
Quick Start (5 minutes)
1. Install the SDK
npm install @gao/sdk
2\. Initialize the Runtime
import { GaoAgentRuntime } from '@gao/sdk';
const runtime = new GaoAgentRuntime({
domain: 'yourdomain.gao',
capToken: process.env.GAO_CAP_TOKEN,
});
3\. Define Your Agent
const agent = runtime.createAgent({
agentId: 'my-first-agent',
riskTier: 1,
tools: ['read:inventory', 'write:orders', 'notify:customers'],
});
4\. Execute
const result = await agent.execute({
input: { action: 'check_order_status', orderId: '12345' },
maxDuration: 60, // seconds
});
console.log(result.output); // agent output
console.log(result.receipt); // GAR receipt (immutable audit record)
That’s it. Your agent executed, and you have a signed receipt.
---
Core SDK Modules
`GaoAgentRuntime`
The primary entry point for all Gao AI OS integrations.
const runtime = new GaoAgentRuntime({
domain: string, // Your Gao Domain
capToken: string, // Signed CAP token
environment?: 'production' | 'testnet', // Default: 'production'
logLevel?: 'debug' | 'info' | 'warn', // Default: 'info'
});
Agent.execute()
Executes an agent action within a bounded window.
const result = await agent.execute({
input: `Record<string, unknown>`, // Agent input payload
maxDuration?: number, // Execution window in seconds (default: 300)
idempotencyKey?: string, // Optional: prevents duplicate executions
});
// Result shape:
{
output: `Record<string, unknown>`, // Agent output
receipt: GARReceipt, // Signed, canonical receipt
status: 'success' | 'failure' | 'timeout',
}
`gao.memory`
Access to the domain-scoped Memory Store.
// Read
const value = await gao.memory.get('key:name');
// Stage write (committed after receipt emission)
await gao.memory.stage({ key: 'key:name', value: {...}, ttl: 86400 });
// List with prefix
const keys = await gao.memory.list({ prefix: 'orders:' });
gao.receipts
Query and verify past execution receipts.
// Get a specific receipt
const receipt = await gao.receipts.get('receipt_id');
// List recent receipts
const recent = await gao.receipts.list({
agentId: 'my-agent',
since: '2026-01-01T00:00:00Z',
limit: 50,
});
// Verify receipt integrity
const isValid = await gao.receipts.verify('receipt_id');
---
### Tool Registration
Agents access external capabilities through **registered tools**. Tools must be registered in the agent manifest and permitted by the CAP token.
#### Built-in Tool Categories
Category
Permitted Actions
Settlement Required
`read:*`
Query data, read state
No
`write:*`
Mutate data, create records
No
`notify:*`
Send notifications
No
`settle:payment`
Initiate payment request
Yes (user-signed)
`publish:*`
Publish to external endpoints
Depends
Custom Tool Registration
runtime.registerTool('myapp:check-weather', {
description: 'Fetch current weather for a location',
inputSchema: { location: 'string' },
outputSchema: { temperature: 'number', condition: 'string' },
handler: async (input) => {
// Your tool implementation
return { temperature: 22, condition: 'sunny' };
},
});
Custom tools are executed within the agent sandbox. They inherit all sandbox restrictions — no direct network access, no filesystem access.
Handling Risk Tiers in Your Integration#
Tier 0 & Tier 1 — Automatic
No special handling required. Executions proceed automatically without confirmation.
Tier 2 — In-Band Confirmation
Your application must handle the AWAITING_CONFIRMATION status before execution continues:
const result = await agent.execute({ input: {...} });
if (result.status === 'awaiting_confirmation') {
// Present confirmation UI to user
const confirmed = await presentConfirmationUI(result.pendingAction);
if (confirmed) {
await agent.confirmExecution(result.executionId);
} else {
await agent.abortExecution(result.executionId);
}
}
Tier 3 — Out-of-Band Human Authorization
Tier 3 pauses execution entirely. Your integration must route the authorization request to the designated human contact defined in the CAP token’s override_contacts:
-
GAR emits
execution:tier3_escalationevent withpendingActiondetails -
Your system notifies the human contact (email, Slack, Workspace notification)
-
Human reviews and signs authorization via Gao Workspace or SDK
-
Resume:
agent.authorizeExecution(executionId, signedAuth) -
If authorization times out: execution aborts with a failure receipt
runtime.on('execution:tier3_escalation', async (event) => {
await notifyHumanContact({
contact: event.escalationContact,
action: event.pendingAction,
executionId: event.executionId,
expiresAt: event.authorizationDeadline,
});
});
Webhooks & Event Streaming
Subscribe to agent lifecycle events:
runtime.on('execution:complete', (event) => {
console.log('Receipt:', event.receipt);
});
runtime.on('execution:tier3_escalation', (event) => {
console.log('Human auth required:', event.pendingAction);
notifyHumanOperator(event);
});
runtime.on('settlement:requested', (event) => {
console.log('Settlement pending user signature:', event.settlementRequest);
});
Webhook Signature Verification
All webhook payloads from GAR v1 are signed. Always verify the signature before processing.
import { verifyWebhookSignature } from '@gao/sdk';
app.post('/hooks/gao', (req, res) => {
const isValid = verifyWebhookSignature({
payload: req.rawBody,
signature: req.headers['x-gao-signature'],
secret: process.env.GAO_WEBHOOK_SECRET,
});
if (!isValid) {
return res.status(401).send('Invalid signature');
}
// safe to process
const event = req.body;
handleGaoEvent(event);
res.status(200).send('ok');
});
Webhook secrets are configured in Gao Workspace (L1) → Developer Settings → Webhooks.
---
Idempotency
All `agent.execute()` calls accept an optional `idempotencyKey`. If a request with the same key is received within the execution window, the runtime returns the existing execution result rather than starting a new one.
const result = await agent.execute({
input: { action: 'process_order', orderId: '12345' },
idempotencyKey: `order-process-${orderId}`, // deterministic, order-scoped
maxDuration: 60,
});
Semantics:
-
Idempotency keys are scoped to
(domain, agent_id)— the same key in different agents is independent -
Keys expire after 24 hours; after expiry a new execution is started
-
If the original execution is still in-flight, the call blocks until completion and returns the same receipt
-
On failure, the same key can be retried — only successful completions are deduplicated
Retries & Backoff
The SDK does not automatically retry failed executions. Application-level retry logic should follow this pattern:
async function executeWithRetry(agent, input, maxAttempts = 3) {
const baseDelay = 1000; // ms
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const result = await agent.execute({
input,
idempotencyKey: `${input.orderId}-attempt-${attempt}`,
});
if (result.status === 'success') return result;
// Do not retry Tier 3 auth timeout or policy mismatch — these require human action
if (['GAR_003', 'GAR_008'].includes(result.errorCode)) throw result;
if (attempt < maxAttempts) {
await sleep(baseDelay * Math.pow(2, attempt - 1)); // exponential backoff
}
}
throw new Error('Max retry attempts reached');
}
---
### Rate Limits & Quotas
Limit
Default
Notes
Executions per agent per minute
60
Configurable via domain policy
Concurrent in-flight executions per agent
1
Configurable up to 10
Memory store reads per execution
500
Hard limit
Memory store staged writes per execution
100
Hard limit
Webhook delivery attempts
5
With exponential backoff
Rate limit responses return HTTP 429 with a `Retry-After` header. The SDK surfaces this as `GAR_009: RATE_LIMIT_EXCEEDED`.
---
### Version Compatibility Matrix
SDK Version
GAR Runtime
Status
Notes
`@gao/sdk@1.x`
GAR v1
✅ Current
Full support
`@gao/sdk@0.9.x`
GAR v0.9
⚠️ Deprecated
Receipts not cross-compatible with v1
The `runtime_version` field in every receipt identifies which GAR version produced it. Receipts are versioned and the schema is backward-compatible within a MAJOR version.
To pin to a specific runtime version during the transition to future releases:
const runtime = new GaoAgentRuntime({
domain: 'yourdomain.gao',
capToken: process.env.GAO_CAP_TOKEN,
runtimeVersion: '1', // pin to GAR v1 family
});
Testing
Testnet Environment
const runtime = new GaoAgentRuntime({
domain: 'yourapp.testnet.gao',
capToken: process.env.GAO_TESTNET_CAP_TOKEN,
environment: 'testnet',
});
Testnet receipts are not written to the production ledger. All other behaviors are identical to production.
Unit Testing Agents
import { MockGaoRuntime } from '@gao/sdk/testing';
const mockRuntime = new MockGaoRuntime({
domain: 'test.gao',
capToken: 'mock_cap_token',
});
mockRuntime.mockTool('read:inventory', async () => ({
items: [{ id: 'item-1', qty: 10 }]
}));
const result = await mockRuntime.execute({ input: { action: 'check_stock' } });
expect(result.status).toBe('success');
Error Reference#
Error Code
Meaning
Resolution
GAR_001
CAP token expired
Issue new CAP token from domain owner
GAR_002
CAP token invalid or forged
Verify token signing; contact support
GAR_003
Policy mismatch
Check policy state in Workspace
GAR_004
Execution timeout
Increase maxDuration or optimize agent logic
GAR_005
Settlement ceiling exceeded
Adjust ceiling in CAP token or split execution
GAR_006
Cross-domain memory access denied
Request cross-domain CAP grant
GAR_007
Receipt emission failure
Retry; check ledger status at status.gao.systems
GAR_008
Tier 3 auth timeout
Re-trigger with fresh escalation
Further Reading#
-
GAR v1 Specification — full runtime reference
-
Agent Lifecycle — registration to retirement
-
Seal SMB Framework — pre-built templates
-
Memory & State Model — persistent state management
-
Security Model — threat model and invariants
The Gao SDK is the only officially supported integration path for Gao AI OS. Direct calls to internal GAR APIs are not supported and not guaranteed stable. Always integrate via _@gao/sdk_.