@quarry-systems/drift-contracts
v0.3.0-alpha.3
Published
Zod validation schemas and contracts for Drift (Managed Cyclic Graph)
Maintainers
Readme
@quarry-systems/drift-contracts
TypeScript type definitions and Zod validation schemas for the Drift (Managed Cyclic Graph) ecosystem.
Overview
drift-contracts provides the foundational type system and validation schemas used across all Drift packages. It defines interfaces for graphs, nodes, edges, plugins, services, and infrastructure adapters, ensuring type safety and consistency throughout the ecosystem.
Installation
npm install @quarry-systems/drift-contractsFeatures
- ✅ Comprehensive Type System: Complete TypeScript definitions for all Drift concepts
- ✅ Zod Validation: Runtime validation schemas for configuration and data
- ✅ Plugin Contracts: Interfaces for execution and infrastructure plugins
- ✅ Service Contracts: Type-safe service definitions and injection
- ✅ AI/LLM Types: Complete types for LLM adapters, tools, and streaming
- ✅ Infrastructure Adapters: Contracts for queues, stores, secrets, retrieval, and vectors
- ✅ Zero Runtime Dependencies: Pure types with minimal overhead (only Zod)
Core Concepts
Graph Structure
import type { GraphDef, NodeDef, EdgeDef } from '@quarry-systems/drift-contracts';
const graph: GraphDef = {
id: 'my-graph',
nodes: new Map([
['start', { id: 'start', label: 'Start Node' }],
['end', { id: 'end', label: 'End Node', isEndpoint: true }]
]),
edges: new Map([
['start->end', { from: 'start', to: 'end', guard: 'any' }]
]),
guards: new Map(),
rules: new Map(),
startNodes: ['start']
};Context and Execution
import type { Ctx, Action, Guard, Rule } from '@quarry-systems/drift-contracts';
// Context structure
const ctx: Ctx = {
runId: 'run-123',
data: { userId: '456' },
global: { apiKey: 'secret' },
injected: { timestamp: Date.now() },
errors: [],
events: []
};
// Guard function
const guard: Guard = (ctx) => {
return ctx.data.userId !== undefined;
};
// Action function
const action: Action = async (ctx) => {
return {
...ctx,
data: {
...ctx.data,
processed: true
}
};
};Plugin System
import type { Plugin, NodeHandler } from '@quarry-systems/drift-contracts';
// Node handler
const myHandler: NodeHandler = async (node, ctx, meta) => {
// Process the node
return {
...ctx,
data: {
...ctx.data,
result: 'processed'
}
};
};
// Plugin definition
const myPlugin: Plugin = {
name: 'my-plugin',
version: '1.0.0',
description: 'My custom plugin',
nodes: {
'my-node-type': myHandler
}
};Service Contracts
import type { ServiceContract, ServiceDefinition } from '@quarry-systems/drift-contracts';
// Define a service contract
const MyServiceContract: ServiceContract = {
name: 'my-service',
version: '1.0.0',
capabilities: ['read', 'write'],
methods: {
getData: {
input: { id: 'string' },
output: { data: 'object' }
}
}
};
// Service definition
const myService: ServiceDefinition = {
contract: MyServiceContract,
scope: 'run',
factory: (ctx) => ({
getData: async (id: string) => ({ data: { id } })
})
};Type Categories
Core Types
- Context:
Ctx,AnyCtx,MaybePromise,EvalResult - Graph:
GraphDef,NodeDef,EdgeDef,GraphRule,GraphLimits - Behaviors:
Guard,Rule,Action - Events:
GraphEvent,NodeEvent,GraphEventHandler,NodeEventHandler
AI/LLM Types
- Messages:
ChatMessage,MessageRole,ResponseFormat - Tools:
ToolDefinition,ToolCall - Requests:
LLMRequest,LLMResponse,LLMUsage,LLMError - Streaming:
LLMStreamEvent - Adapters:
LLMAdapter,EmbeddingAdapter - Schema:
MCGJsonSchema
Plugin Types
- Core:
Plugin,NodeHandler,PluginMetadata - Manifest:
PluginManifest,PluginType,PluginCapabilities - Validation:
PluginValidationResult
Infrastructure Adapters
Queue Adapter
import type { QueueAdapter, QueueJob, JobProcessor } from '@quarry-systems/drift-contracts';Store Adapter
import type {
RunStoreAdapter,
ArtifactStore,
RunSnapshot,
RunMetadata
} from '@quarry-systems/drift-contracts';Secrets Adapter
import type { SecretsAdapter, SecretRef } from '@quarry-systems/drift-contracts';Retrieval Adapter
import type {
RetrievalAdapter,
Document,
Chunk,
ChunkMatch
} from '@quarry-systems/drift-contracts';Vector Adapter
import type {
VectorAdapter,
VectorItem,
VectorMatch
} from '@quarry-systems/drift-contracts';Service System
- Contracts:
ServiceContract,ServiceCapabilities,VersionCompatibility - Injection:
ServiceDefinition,ServiceRegistry,ServiceScope - Validation:
ServiceValidationResult
Middleware
import type {
Middleware,
NodeStartEvent,
NodeEndEvent,
ServiceCallStartEvent
} from '@quarry-systems/drift-contracts';Error Handling
import type {
ExecutionError,
TraceEntry,
ExecutionTrace,
DebugOptions
} from '@quarry-systems/drift-contracts';Licensing
import type {
LicenseTier,
LicenseStatus,
LicenseFile,
LicenseOptions
} from '@quarry-systems/drift-contracts';Usage Examples
Building Type-Safe Graphs
import type { GraphDef, NodeDef, Ctx } from '@quarry-systems/drift-contracts';
function createWorkflow(): GraphDef<Ctx, { userId: string }> {
return {
id: 'user-workflow',
nodes: new Map([
['fetch', {
id: 'fetch',
label: 'Fetch User',
meta: { http: { url: '/api/users/${injected.userId}' } }
}],
['process', {
id: 'process',
label: 'Process Data'
}]
]),
edges: new Map([
['fetch->process', { from: 'fetch', to: 'process', guard: 'any' }]
]),
guards: new Map([['any', () => true]]),
rules: new Map(),
startNodes: ['fetch']
};
}Creating Custom Plugins
import type { Plugin, NodeHandler, Ctx } from '@quarry-systems/drift-contracts';
const delayHandler: NodeHandler = async (node, ctx, meta) => {
const ms = node.meta?.delay || 1000;
await new Promise(resolve => setTimeout(resolve, ms));
return ctx;
};
export const delayPlugin: Plugin = {
name: 'delay-plugin',
version: '1.0.0',
description: 'Adds delay nodes',
nodes: {
'delay': delayHandler
}
};Implementing Adapters
import type { SecretsAdapter } from '@quarry-systems/drift-contracts';
class EnvSecretsAdapter implements SecretsAdapter {
async get(key: string): Promise<string | null> {
return process.env[key] || null;
}
async set(key: string, value: string): Promise<void> {
process.env[key] = value;
}
async delete(key: string): Promise<void> {
delete process.env[key];
}
async list(): Promise<string[]> {
return Object.keys(process.env);
}
}Package Structure
drift-contracts/
├── src/
│ ├── ai.ts # AI/LLM types
│ ├── behaviors.ts # Guard, Rule, Action
│ ├── context.ts # Context and state types
│ ├── errors.ts # Error and debugging types
│ ├── events.ts # Event system types
│ ├── graph.ts # Graph structure types
│ ├── license.ts # Licensing types
│ ├── manifest.ts # Plugin manifest types
│ ├── middleware.ts # Middleware types
│ ├── plugin.ts # Plugin system types
│ ├── queue.ts # Queue adapter types
│ ├── retrieval.ts # Retrieval adapter types
│ ├── secrets.ts # Secrets adapter types
│ ├── service-contract.ts # Service contract types
│ ├── service-injection.ts # Service injection types
│ ├── store.ts # Store adapter types
│ ├── vector.ts # Vector adapter types
│ └── index.ts # Main exportsRelated Packages
- @quarry-systems/drift-core - Core graph execution engine
- @quarry-systems/drift-ai-core - AI agent functionality
- @quarry-systems/drift-cli - Command-line interface
- @quarry-systems/drift-testing - Testing utilities
Official Plugins
@quarry-systems/drift-http- HTTP client@quarry-systems/drift-timer- Timers and scheduling@quarry-systems/drift-openai- OpenAI integration@quarry-systems/drift-secrets- Secrets management@quarry-systems/drift-store-sqlite- SQLite storage@quarry-systems/drift-vector-chroma- ChromaDB vectors
TypeScript Configuration
For best results, use these TypeScript compiler options:
{
"compilerOptions": {
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"moduleResolution": "node",
"resolveJsonModule": true
}
}Contributing
This package is part of the Drift monorepo. For contributions, please see the main repository.
License
Dual-licensed under:
- AGPL-3.0 for open source projects
- Commercial License for proprietary use
See LICENSE.md for details.
For commercial licensing inquiries:
- Email: [email protected]
- Web: https://quarry-systems.com/license
