@granular-software/sdk
The official TypeScript SDK for Granular.
Build AI-powered domain models with secure, isolated execution. Granular lets you define ontologies (classes, relationships), attach tools to them, and run AI-generated code that operates on typed domain objects — all in a sandboxed environment with per-user permissions.
Features
- 🏗️ Domain Ontology — Define classes, properties, and relationships as a typed graph
- 🔧 Class-Based Tools — Attach instance methods, static methods, and global tools with typed I/O
- 🤖 Domain Synthesis — Auto-generated TypeScript classes with
get({ path }), list(), relationship accessors, and typed methods
- 🔒 Secure Execution — Run AI-generated code in isolated sandboxes
- 👥 User Permissions — Control what each user can access
- ⚡ Real-time — WebSocket-based streaming and events
- ↩️ Reverse RPC — Sandbox code calls tools that execute on your server
Documentation
Full documentation: docs.granular.dev
Installation
bun add @granular-software/sdk
# or
npm install @granular-software/sdk
Inside this monorepo, prefer the workspace package instead of installing from npm separately.
Endpoint Modes
By default, the SDK resolves endpoints like this:
- Local mode (
NODE_ENV=development): ws://localhost:8787/granular
- Production mode (default):
wss://cf-api-gateway.arthur6084.workers.dev/granular
Overrides:
- SDK option:
endpointMode: 'local' | 'production'
- SDK option:
apiUrl: 'ws://... | wss://...' (highest priority)
- Env:
GRANULAR_ENDPOINT_MODE=local|production
- Env:
GRANULAR_API_URL=... (highest priority)
CLI overrides:
granular --local <command>
granular --prod <command>
granular --env local|production <command>
When the resolved API URL points at localhost or 127.0.0.1, the SDK and CLI automatically swap opaque sk_... WorkOS keys for the local dev key gn_sk_tenant_default_principal_local_e2e_00000000 so local runs work without server-side WorkOS validation. Override with GRANULAR_LOCAL_API_KEY=... or disable with GRANULAR_DISABLE_LOCAL_API_KEY_FALLBACK=true.
Agent documentation (CLI)
Projects created with granular init can include Markdown for coding agents (optional AGENTS.md plus generated guides):
docs/granular-manifest.md — What Granular is, glossary, manifest → version → build run → connect → jobs, granular.json syntax (fields, relationships, effects), @granular-software/sdk map, CLI. Self-contained for agents new to the product. Added when you opt in at init (--agent-docs / --no-agent-docs, or the prompt).
GRANULAR_SANDBOX.md — This sandbox’s ontology snapshot: ids, exact names/keys, effect schemas, snippets. Updated after each successful granular build, granular deploy, and granular dev rebuild, and on granular document (run build to record version/build metadata).
AGENTS.md — Two-step index: manifest guide first, then sandbox doc (merged idempotently with <!-- granular-sdk:begin -->).
Live ontology onboarding
Run the following from the customer product repository:
granular onboard status --json
# When connected:
granular login
granular onboard resume --no-open
granular onboard next --json
# Only when status reports not_connected:
granular onboard start
Startup is status-first. onboard start refuses to duplicate an active run for
the current repository and branch unless --new is explicitly supplied.
onboard resume renews the short-lived, run-scoped token in the gitignored
.granularrc and preserves the same artifacts, directives, and history; an
expired credential is never a reason to start over. onboard heartbeat reports
liveness during long work, onboard next returns the next safe action, and
onboard watch --jsonl --duration 300 keeps Change, Remove, Require, and Protect
directives live in a bounded foreground stream.
A new run opens the focused companion and generates portable Codex, Cursor, and
Claude Code skills. As the coding agent
grounds each class, relationship, workflow, action, or role, it runs
granular onboard propose <kind> --file granular-onboarding/blueprint.json --element <id>
so the companion shows that element and its repository evidence immediately.
Structured discovery events can include the current file, symbol, and cumulative
counts in --data. The agent then publishes the completed blueprint, processes
element-level directives, reports each real build milestone, binds a synthetic
dev environment, creates recognizable example records, generates 30
persona-specific user queries, and publishes observed scenario answers and
evidence. Every passed result carries its runtime session, job, and subject ids
(plus effect invocation or policy-decision ids when relevant), which the server
checks against the bound dev build and environment. A generic successful effect
is not treated as proof that data changed without a durable mutation receipt.
The agent may publish the blueprint as proposed but cannot approve it;
approval belongs to the human in the companion. granular onboard status shows
the same readiness gates from the terminal, and granular onboard open returns
to the companion.
Use granular check before remote builds. It validates the local manifest,
permission profiles, and state-machine graph integrity: duplicate states,
transitions and edges; unknown or unreachable states; non-final dead ends;
outgoing transitions from final states; closed paths that cannot reach a final
state; and exact stateField enum synchronization.
Quick Start
import { Granular, type ManifestContent } from "@granular-software/sdk";
const granular = new Granular({ apiKey: process.env.GRANULAR_API_KEY });
// 1. Connect to the default dev environment for one of your app users
const env = await granular.openEnvironment({
ontology: "my-ontology",
tag: "dev",
userId: "user_123",
permissions: ["allow-all"],
name: "Jane Doe", // optional
email: "jane@example.com", // optional
});
// 2. Define your domain ontology
const manifest: ManifestContent = {
schemaVersion: 2,
name: "my-app",
volumes: [
{
name: "schema",
scope: "sandbox",
imports: [{ alias: "@std", name: "standard_modules", label: "prod" }],
operations: [
// Define classes with typed properties
{
create: "customer",
extends: "@std/class",
has: {
name: { type: "string", description: "Customer name" },
email: { type: "string", description: "Email address" },
tier: { type: "string", description: "Subscription tier" },
},
},
{
create: "order",
extends: "@std/class",
has: {
total: { type: "number", description: "Order total" },
status: { type: "string", description: "Order status" },
},
},
// Define relationships
{
defineRelationship: {
left: "customer",
right: "order",
leftSubmodel: "orders",
rightSubmodel: "customer",
leftIsMany: true,
rightIsMany: false,
},
},
],
},
],
};
await env.applyManifest(manifest);
// 3. Record object instances
await env.recordObject({
className: "customer",
id: "cust_42",
label: "Acme Corp",
fields: { name: "Acme Corp", email: "billing@acme.com", tier: "enterprise" },
});
// 4. Register live effect handlers for effects already declared in the ontology manifest
await granular.ontology(env.sandboxId).effects.registerMany([
{
name: "get_billing_summary",
description: "Get billing summary for a customer",
className: "customer", // Attached to Customer class
// static omitted → instance method (receives object ID automatically)
inputSchema: {
type: "object",
properties: {
period: {
type: "string",
description: 'Billing period (e.g. "2024-Q1")',
},
},
},
outputSchema: {
type: "object",
properties: {
total: { type: "number", description: "Total billed amount" },
invoices: { type: "number", description: "Number of invoices" },
period: { type: "string", description: "The billing period" },
},
required: ["total", "invoices"],
},
handler: async (customerId: string, params: any, ctx: any) => {
// customerId comes from `this.id` in sandbox code
console.log("Running for subject:", ctx.user.subjectId);
return {
total: 4250.0,
invoices: 3,
period: params?.period || "current",
};
},
},
]);
// 6. Submit a job — the sandbox gets fully typed OOP classes!
const session = await env.sessions.create();
const job = await session.submitJob(`
import { Customer } from "@granular/domain/Customer";
// list() discovers instances; get({ path }) hydrates a specific graph object
const customers = await Customer.list();
const acme = customers.find((customer) => customer.name === 'Acme Corp');
if (!acme) throw new Error('Customer not found');
console.log(acme.name); // "Acme Corp"
console.log(acme.email); // "billing@acme.com"
// Instance method — typed input AND output
const billing = await acme.get_billing_summary({ period: '2024-Q1' });
// billing.total, billing.invoices, billing.period are all typed
// Navigate relationships
const orders = await acme.get_orders();
return { customer: acme.name, billing, orderCount: orders.length };
`);
const result = await job.result;
Effects must be declared ahead of time in the ontology version manifest with withEffect. Live registration only makes already-declared effects available at runtime.
Agent-selected result columns
When an agent needs to show records with fields or calculations chosen for the
current question, it can project a result table in the job runtime:
import { relativeTime, showAgentResponse, table } from "@granular/agent";
showAgentResponse({
reply: "Two recent orders need attention.",
show: table(
recentOrders,
[
{ label: "Order", value: (record) => record.label },
{
label: "Status change",
value: (record) => `${record.before_status} → ${record.after_status}`,
},
{ label: "Updated", value: (record) => relativeTime(record.timestamp) },
],
{ label: "Latest order changes" },
),
});
The callbacks run only inside the sandbox job. Granular persists the resolved
column labels, primitive cells, typed dates, relative times, and grounded row
references—not executable functions—so the conversation remains durable and
safe to reopen in another browser.
Core Flow
declare effects in the manifest → `granular build` creates or reuses a version → `openEnvironment({ ontology, tag, userId })` resolves the user's environment → `recordObject()` or `recordObjects()` → `granular.ontology(...).effects.registerMany()` → `environment.sessions.create()` → `session.submitJob()`
openEnvironment() — Resolve or create an ontology environment for a given userId, returning an Environment
recordUser() — Optional explicit user upsert when you want the returned granularId
applyManifest() — Define your domain ontology (classes, properties, relationships)
recordObject() / recordObjects() — Use recordObject() for one targeted upsert. Use recordObjects() for immediate multi-record writes with chunk progress.
granular.ontology(...).effects.registerMany() — Register ontology-scoped live handlers for effects declared in the ontology manifest
environment.sessions.create() / session.submitJob() — Open a live session and execute code against the sandbox runtime
Defining the Domain Ontology
Use applyManifest() to declare classes, typed properties, and relationships:
const manifest: ManifestContent = {
schemaVersion: 2,
name: "library-app",
volumes: [
{
name: "schema",
scope: "sandbox",
imports: [{ alias: "@std", name: "standard_modules", label: "prod" }],
operations: [
// Classes with typed properties
{
create: "author",
extends: "@std/class",
has: {
name: { type: "string", description: "Author full name" },
birth_year: { type: "number", description: "Year of birth" },
},
},
{
create: "book",
extends: "@std/class",
has: {
title: { type: "string", description: "Book title" },
isbn: { type: "string", description: "ISBN number" },
published_year: { type: "number", description: "Year published" },
},
},
// Relationships (bidirectional, with cardinality)
{
defineRelationship: {
left: "author",
right: "book",
leftSubmodel: "books",
rightSubmodel: "author",
leftIsMany: true,
rightIsMany: false,
// → author.books (one-to-many), book.author (many-to-one)
},
},
],
},
],
};
await env.applyManifest(manifest);
Recording Object Instances
After defining the ontology, connect as a user and populate it with data:
const env = await granular.openEnvironment({
ontology: "library-app",
tag: "dev",
userId: "user_123",
permissions: ["allow-all"],
});
const [tolkien, lotr] = await env.recordObjects(
[
{
className: "author",
id: "tolkien", // Real-world ID (unique per class)
label: "J.R.R. Tolkien",
fields: { name: "J.R.R. Tolkien", birth_year: 1892 },
},
{
className: "book",
id: "lotr",
label: "The Lord of the Rings",
fields: {
title: "The Lord of the Rings",
isbn: "978-0-618-64015-7",
published_year: 1954,
},
relationships: { author: "tolkien" }, // Real-world ID — SDK resolves it automatically
},
],
{
onChunkComplete(info) {
console.log(`Committed chunk ${info.chunkIndex + 1}/${info.totalChunks}`);
},
},
);
// tolkien.path → 'author_tolkien' (internal graph path, unique globally)
// tolkien.id → 'tolkien' (real-world ID)
// lotr.created → true (false means the record already existed and was updated)
Cross-class ID uniqueness: Two objects of different classes can share the same real-world ID (e.g., an author "tolkien" and a publisher "tolkien"). The SDK derives unique graph paths internally (author_tolkien, publisher_tolkien) so they never collide.
For one-off writes, recordObject(...) is still the clearest choice. For large fire-and-forget imports, use enqueueRecordImport(...) and poll getRecordImport(...) / getRecordImportSummary() for aggregate progress.
Effect Definitions
Effects are declared in the manifest with withEffect, then their live handlers are registered at ontology scope. Effects can be instance methods, static methods, or global functions. Both inputSchema and outputSchema use JSON Schema: