@variant96/pia-sdk
v0.1.1
Published
Official SDK for building agents on the Personal Identity Agent (PIA) platform
Maintainers
Readme
@variant96/pia-sdk
Official SDK for building agents on the Personal Identity Agent (PIA) platform.
📦 NPM: @variant96/pia-sdk 🏠 Platform: pia-xi.vercel.app 🔗 Live Examples: See agents built with this SDK below ↓
Installation
From NPM
npm install @variant96/pia-sdkFrom GitHub
# Install directly from GitHub
npm install github:eliotalders0n/Digital-Embodiments#main:packages/pia-sdk
# Or clone and link locally
git clone https://github.com/eliotalders0n/Digital-Embodiments.git
cd Digital-Embodiments/packages/pia-sdk
npm install
npm run build
npm link
# In your agent project
npm link @variant96/pia-sdkTypeScript
The SDK is written in TypeScript and includes type definitions. No additional @types packages needed.
Quick Start
1. Initialize the Client
import { PIAClient } from '@variant96/pia-sdk';
const pia = new PIAClient({
piaUrl: 'https://pia-xi.vercel.app',
agentId: 'my-email-agent',
agentName: 'My Email Agent',
redirectUri: 'https://my-agent.vercel.app/callback',
permissions: ['READ_EMAIL', 'SEND_EMAIL'],
});2. Get Authorization
Redirect your user to PIA for authorization:
// In your route handler
app.get('/connect-pia', (req, res) => {
const authUrl = pia.getAuthorizationUrl();
res.redirect(authUrl);
});3. Handle Callback
Process the authorization callback:
app.get('/callback', (req, res) => {
try {
pia.handleCallback(req.url);
// Store token securely in your database
const token = pia.getToken();
await db.storeToken(req.user.id, token);
res.send('Connected to PIA successfully!');
} catch (error) {
res.status(400).send(error.message);
}
});4. Verify Actions
Before performing actions on behalf of the user, verify them with PIA:
// Check if action is allowed
const result = await pia.verify({
action: 'SEND_EMAIL',
description: 'Send birthday reminder to [email protected]',
actionData: {
to: '[email protected]',
subject: 'Happy Birthday!',
from: '[email protected]'
}
});
if (result.decision === 'APPROVED') {
// Proceed with sending email
await sendEmail(actionData);
} else {
// Action was denied
console.log('Denied:', result.reason);
}5. Verify or Throw
For simpler error handling, use verifyOrThrow:
try {
await pia.verifyOrThrow({
action: 'SEND_EMAIL',
description: 'Send birthday reminder to [email protected]',
actionData: { to: '[email protected]' }
});
// If we get here, action was approved
await sendEmail(actionData);
} catch (error) {
if (error instanceof PIAError && error.statusCode === 403) {
// Action was denied by user's policy
console.log('Action denied:', error.message);
} else {
// Network or other error
console.error('Verification failed:', error);
}
}API Reference
PIAClient
Main client for interacting with PIA.
Constructor
new PIAClient(config: PIAConfig)Methods
getAuthorizationUrl(): string- Get URL to redirect user for authorizationhandleCallback(callbackUrl: string): void- Process authorization callbacksetToken(token: string): void- Manually set access tokengetToken(): string | undefined- Get current tokenisAuthorized(): boolean- Check if client has a tokenverify(request: VerificationRequest): Promise<VerificationResult>- Verify an actionverifyOrThrow(request: VerificationRequest): Promise<VerificationResult>- Verify and throw if denied
Types
AgentPermission
type AgentPermission =
| 'READ_EMAIL'
| 'SEND_EMAIL'
| 'READ_CALENDAR'
| 'WRITE_CALENDAR'
| 'MAKE_PURCHASE'
| 'READ_FINANCIAL'
| 'WRITE_FINANCIAL'
| 'ACCESS_DOCUMENTS'
| 'WRITE_DOCUMENTS'
| 'MANAGE_CONTACTS'
| 'MAKE_CALLS'
| 'SEND_SMS'
| 'POST_SOCIAL'
| 'READ_LOCATION'
| 'BOOK_APPOINTMENTS';VerificationRequest
interface VerificationRequest {
action: AgentPermission;
description: string;
actionData?: Record<string, any>;
}VerificationResult
interface VerificationResult {
decision: 'APPROVED' | 'DENIED';
reason: string;
auditLogId: string;
}Best Practices
1. Store Tokens Securely
Never expose tokens to the frontend. Store them in your backend database:
// ❌ Bad - token exposed to frontend
localStorage.setItem('pia_token', token);
// ✅ Good - token stored in backend
await database.tokens.create({
userId: user.id,
piaToken: token,
expiresAt: result.expiresAt
});2. Verify Before Every Action
Always verify actions before performing them:
// ❌ Bad - no verification
await sendEmail(to, subject, body);
// ✅ Good - verified first
await pia.verifyOrThrow({
action: 'SEND_EMAIL',
description: `Send email to ${to}`,
actionData: { to, subject }
});
await sendEmail(to, subject, body);3. Handle Errors Gracefully
try {
await pia.verify(request);
} catch (error) {
if (error instanceof PIAError) {
// PIA-specific error
if (error.statusCode === 401) {
// Token expired or invalid - redirect to re-auth
} else if (error.statusCode === 403) {
// Action denied by policy
}
} else {
// Network or other error
}
}Example Agents
Live Production Agents Built with PIA SDK
See these agents in action to understand what you can build:
📧 Email Assistant - digital-embodiments.vercel.app
- Permissions:
READ_EMAIL,SEND_EMAIL - Manages email tasks with user policy verification
- Permissions:
📅 Calendar Assistant - calendar-assistant-one.vercel.app
- Permissions:
READ_CALENDAR,WRITE_CALENDAR,BOOK_APPOINTMENTS - Smart scheduling and event management
- Permissions:
👤 Contacts Manager - contacts-manager-beta.vercel.app
- Permissions:
MANAGE_CONTACTS,READ_EMAIL - Contact organization and relationship management
- Permissions:
📁 File Browser - file-browser.vercel.app
- Permissions:
ACCESS_DOCUMENTS,WRITE_DOCUMENTS - Secure document access and management
- Permissions:
✅ Task Manager - task-manager-woad-ten-94.vercel.app
- Permissions:
WRITE_CALENDAR,SEND_EMAIL - Task tracking with automated reminders
- Permissions:
Code Examples
See examples/basic-agent.js for a complete implementation pattern used in the agents above.
License
MIT
