API Reference

Complete SDK documentation for TypeScript and Python.

Initialization

Phantom.init()

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)
  }
});

Missions

Phantom.createMission()

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.

mission.run()

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;
});

context.action()

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:

  • User permissions and ownership
  • Subscription entitlements
  • Budget constraints
  • Intent alignment

Decorators

@Phantom.Protect

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);
}

Ghost Tokens

Phantom.issue()

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
  }
});

Phantom.revoke()

Instantly revoke a Ghost Token.

await Phantom.revoke(tokenId: string);

// Revoke all tokens for a user
await Phantom.revokeAll(userId: string);

Shadow Sync

PhantomPrismaMiddleware

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
      }
    }
  })
);

Phantom.stripe.processWebhook()

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');
}

Phantom.graph.addEdge()

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'
});

Policy Management

Phantom.definePolicy()

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.
  `
});

Monitoring & Logs

Phantom.missions.list()

List active missions with filters.

const missions = await Phantom.missions.list({
  userId?: string,
  status?: 'running' | 'paused' | 'completed' | 'failed',
  startedAfter?: Date,
  limit?: number
});

Phantom.audit.query()

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, context

Error Handling

Exception Types

import {
  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);
  }
}

SDK Downloads