Complete SDK documentation for TypeScript and Python.
Initialize the Phantom SDK. Call once at application startup.
import { Phantom } from '@vanishlabs/phantom';
Phantom.init({
apiKey: string, // Your Phantom API key
projectId: string, // Your project ID
environment?: 'production' | 'staging' | 'development',
temporal?: {
host: string, // Temporal server (default: cloud)
namespace: string, // Temporal namespace
},
redis?: {
url: string, // Redis connection (for Shadow Sync cache)
}
});Create a new mission for an agent to execute.
const mission = await Phantom.createMission({
userId: string, // User the agent acts on behalf of
intent: string, // Natural language mission description
constraints?: {
maxSpend?: number, // Maximum spend in cents
maxActions?: number, // Maximum action count
allowedActions?: string[], // Whitelist of allowed actions
timeout?: string, // Max duration (e.g. "5 minutes", "2 days")
},
durable?: boolean, // Use Temporal for durability (default: false)
metadata?: Record<string, unknown>, // Custom metadata
});Returns
Mission object with run() method.
Execute the mission with permission verification.
const result = await mission.run(async (context) => {
// context.action() for protected operations
// context.user for user info
// context.entitlements for subscription/credits
const data = await context.action('operation_name', {
// operation parameters
});
return data;
});Perform a protected action within a mission.
await context.action(
name: string, // Action identifier
params: object, // Action parameters
options?: {
requireApproval?: boolean, // Pause for human approval
riskLevel?: 'low' | 'medium' | 'high',
}
);Phantom automatically verifies:
Wrap existing functions with Phantom authorization.
@Phantom.Protect({
intent: string, // Required mission intent
requiresOwnership?: boolean, // Verify resource ownership
allowedRoles?: string[], // Required user roles
riskLevel?: 'low' | 'medium' | 'high',
})
async function yourFunction(userId: string, ...args) {
// If execution reaches here, all checks passed
}Example:
@Phantom.Protect({
intent: 'data_deletion',
requiresOwnership: true,
riskLevel: 'high'
})
async function deleteUserData(userId: string, dataId: string) {
await database.delete(dataId);
}Issue a temporary Ghost Token for specific intent.
const token = await Phantom.issue(agent, {
intent: string, // Token-specific intent
constraints: {
maxAccess?: string, // Time limit (e.g. "5 minutes")
scope?: string, // Permission scope
maxActions?: number, // Action limit
}
});Instantly revoke a Ghost Token.
await Phantom.revoke(tokenId: string);
// Revoke all tokens for a user
await Phantom.revokeAll(userId: string);Automatically sync Prisma operations to Phantom's graph.
import { PhantomPrismaMiddleware } from '@vanishlabs/phantom';
const prisma = new PrismaClient().$extends(
PhantomPrismaMiddleware({
models: {
document: { ownerField: 'userId' },
project: { ownerField: 'creatorId' },
team: {
ownerField: 'adminId',
memberField: 'members' // Many-to-many relation
}
}
})
);Process Stripe webhooks to sync billing entitlements.
export async function POST(req: Request) {
const event = await stripe.webhooks.constructEvent(
await req.text(),
req.headers.get('stripe-signature'),
process.env.STRIPE_WEBHOOK_SECRET
);
// Phantom handles subscription_created, subscription_deleted, etc.
await Phantom.stripe.processWebhook(event);
return new Response('OK');
}Manually add relationships to the permission graph.
await Phantom.graph.addEdge({
from: 'user:123', // Subject
relation: 'owner', // Relationship type
to: 'resource:doc_456' // Object
});
// Check if relationship exists
const hasAccess = await Phantom.graph.check({
subject: 'user:123',
relation: 'viewer',
object: 'resource:doc_456'
});Define authorization policies in code or natural language.
Phantom.definePolicy("Researcher", {
can: ["read_docs", "search_web"],
cannot: ["delete_data", "modify_billing"],
maxSpend: "$5.00",
durable: true,
requireApproval: (intent) => intent.risk === 'high'
});
// Natural language policies (converted to Cedar/Rego)
await Phantom.definePolicy("Sales Agent", {
natural: `
Can read customer data and send emails.
Cannot access financial records.
Spending over $50 requires approval.
`
});List active missions with filters.
const missions = await Phantom.missions.list({
userId?: string,
status?: 'running' | 'paused' | 'completed' | 'failed',
startedAfter?: Date,
limit?: number
});Query audit logs for compliance and debugging.
const logs = await Phantom.audit.query({
userId?: string,
action?: string,
missionId?: string,
decision?: 'ALLOW' | 'BLOCK',
startDate?: Date,
endDate?: Date
});
// logs contains: timestamp, user, action, decision, reason, contextimport {
PhantomSecurityError, // Permission denied
PhantomIntentError, // Intent alignment failed
PhantomBudgetError, // Budget constraint exceeded
PhantomEntitlementError, // Subscription/credits insufficient
} from '@vanishlabs/phantom';
try {
await mission.run(async (ctx) => {
// ...
});
} catch (error) {
if (error instanceof PhantomSecurityError) {
console.error('Blocked:', error.reason);
console.error('Context:', error.context);
} else if (error instanceof PhantomBudgetError) {
console.error('Budget exceeded:', error.limit);
}
}