Scripta Client & API Documentation
Complete reference documentation for the Scripta client SDK and API.
Overview
The Scripta Client SDK provides a framework for building AI-powered applications that can interact with the user's environment. It enables secure access to the file system, shell command execution, and other system resources through a permissions-based system.
This documentation covers the client SDK, which provides communication with the Scripta Server, as well as the API reference.
Secure by design
Installation
Install the Scripta Client SDK using npm, yarn, or pnpm:
"text-blue-500">npm install @scripta/client-sdk
Client SDK
The Scripta Client SDK provides a high-level interface for interacting with the Scripta Server. It handles communication, event streaming, permissions, and tool execution.
Key Components
The SDK consists of several main components working together:
- ScriptaClient: The main entry point that manages sessions, communication, and event handling
- ScriptaApiClient: Handles REST API communication with the server
- ScriptaEventStream: Manages Server-Sent Events (SSE) for real-time updates
- ToolExecutor: Executes tool requests from the AI and sends results back
- PermissionHandler: Manages security permissions for sensitive operations
- PlatformAdapter: Abstracts platform-specific operations for cross-platform compatibility
Event-Driven Architecture
The SDK uses an event-driven architecture to handle communication with the server. Events include:
- response: Triggered when the AI responds with text
- thinking: Provides status updates while the AI is processing
- toolRequest: Triggered when the AI needs to execute a tool
- error: Triggered when an error occurs
- complete: Indicates the end of a conversation turn
- connected: Indicates a successful connection to the server
Lifecycle
The typical SDK interaction involves these steps:
- Create a platform adapter specific to your environment
- Create a permission handler to manage security permissions
- Initialize the ScriptaClient with the adapter and permission handler
- Connect to the server to create a session
- Set up event listeners for responses, tool requests, etc.
- Send messages to the AI
- Disconnect when done to clean up resources
Quick Start
"text-pink-500">import {
ScriptaClient,
PlatformAdapter,
PermissionHandler
} "text-pink-500">from '@scripta/client-sdk';
// Create platform adapter (implementation depends on your environment)
"text-pink-500">const adapter = "text-pink-500">new YourPlatformAdapter();
// Create permission handler (implementation depends on your UI framework)
"text-pink-500">const permissionHandler = "text-pink-500">new YourPermissionHandler();
// Initialize the client
"text-pink-500">const client = "text-pink-500">new ScriptaClient(
adapter,
permissionHandler,
{ serverUrl: 'http://localhost:3456/api' }
);
// Connect to the server
"text-pink-500">const session = "text-pink-500">await client.connect();
// Listen "text-pink-500">for events
client.on('response', (message) => {
console.log('Received response:', message);
});
client.on('toolRequest', (request) => {
console.log('Tool request:', request);
});
// Send a message
"text-pink-500">await client.sendMessage('Hello, Scripta!');
Core Concepts
The ScriptaClient class manages connections, sessions, and communication with the server.
Server-sent events provide real-time updates for responses, thinking status, and tool requests.
Tools allow the AI to interact with the system - files, shell commands, and more.
Permission handlers ensure that sensitive operations require explicit user approval.
API Reference
The Scripta API is a RESTful API that provides the backend services for the Scripta platform. It enables client applications to create conversation sessions, send messages to the AI, and receive real-time updates.
API Architecture
The API is designed with two primary communication channels:
- REST Endpoints: For stateful operations like creating sessions, sending messages, and submitting tool results
- Server-Sent Events (SSE): For real-time streaming of AI responses, thinking updates, and tool requests
Base URL
http://localhost:3456/api
This is the default URL when running the server locally. For production deployments, you'll need to configure the appropriate server URL.
Authentication
Authentication is handled via standard HTTP headers. The specific implementation depends on your deployment configuration, but typically involves:
- API keys for server-to-server communication
- JWT tokens for authenticated user sessions
- Custom headers for organization and project context
Sessions
API endpoints for managing conversation sessions.
Parameters
Name | Type | Required | Description |
---|---|---|---|
userId | string | Optional user identifier | |
orgId | string | Optional organization identifier | |
conversationType | string | Type of conversation (defaults to general) | |
workingDirectory | string | Working directory for the conversation |
Response
{
"success": true,
"sessionId": "sess_123456789"
}
Parameters
Name | Type | Required | Description |
---|---|---|---|
content | string | Message content to send |
Response
{
"success": true,
"conversationId": "conv_987654321"
}
Events
Server-sent events endpoint for real-time updates. This is the core of Scripta's real-time architecture.
Understanding Server-Sent Events
Server-Sent Events (SSE) provide a one-way channel from server to client that allows the server to push data to the client in real-time. Unlike WebSockets, SSE connections are simpler, only allow server-to-client communication, and automatically reconnect if the connection is lost.
The events endpoint uses Server-Sent Events (SSE) to stream real-time updates for a session. Events include assistant responses, thinking updates, tool requests, and errors.
Event Types
Type | Description |
---|---|
THINKING_UPDATE | Status updates while the AI is processing |
ASSISTANT_RESPONSE | Text response from the assistant |
TOOL_REQUEST | Request to execute a tool |
ERROR | Error message |
CONVERSATION_COMPLETE | Signals the end of a conversation turn |
Tool Results
Endpoint for submitting tool execution results back to the AI.
How Tools Work
- Tool Request: The AI sends a tool request through the SSE channel when it needs to interact with the environment
- Client Execution: The client application executes the requested tool (file read, shell command, etc.)
- Result Submission: The client submits the tool result back to the server using this endpoint
- AI Processing: The AI processes the tool result and continues the conversation
Parameters
Name | Type | Required | Description |
---|---|---|---|
result | any | Result of tool execution | |
error | string | Error message if tool execution failed |
Response
{
"success": true
}
Permissions
Scripta uses a permission system to protect sensitive operations. The permission handler is responsible for requesting user approval before executing potentially risky operations.
Security-First Architecture
Scripta is built with a security-first approach, with permissions as a core design principle rather than an afterthought. All potentially sensitive operations require explicit user permission before execution.
Protected Operations
- File system access (read/write)
- Shell command execution
- Network requests
- System configuration changes
- Access to sensitive information
Permission Features
- Fine-grained control over resource access
- Different permission scopes (once, session, permanent)
- Automatic risk assessment
- Detailed operation descriptions
- Customizable permission UI
Permission Handler
"text-pink-500">import {
BasePermissionHandler,
PermissionContext,
PermissionResponse,
PermissionScope
} "text-pink-500">from '@scripta/client-sdk';
"text-pink-500">export "text-pink-500">class MyPermissionHandler "text-pink-500">extends BasePermissionHandler {
// Check "text-pink-500">if permission is already stored
protected "text-pink-500">async checkStoredPermission(
toolName: string,
parameters: any,
context: PermissionContext
): Promise<boolean> {
// Implement your storage check here
"text-pink-500">return false;
}
// Request permission "text-pink-500">from the user
"text-pink-500">async requestPermission(
toolName: string,
parameters: any,
context: PermissionContext
): Promise<boolean> {
// Get a description of the operation
"text-pink-500">const description = "text-pink-500">this.getToolDescription(toolName, parameters);
// Assess risk level
"text-pink-500">const risk = "text-pink-500">this.assessRisk(toolName, parameters);
// Show UI to request permission (implementation depends on your UI framework)
"text-pink-500">const userResponse = "text-pink-500">await showPermissionDialog({
toolName,
description,
risk
});
// Store the permission "text-pink-500">if granted
"text-pink-500">if (userResponse.granted && userResponse.scope !== 'once') {
"text-pink-500">await "text-pink-500">this.storePermission(
toolName,
parameters,
true,
context,
userResponse.scope
);
}
"text-pink-500">return userResponse.granted;
}
// Store permission decision
"text-pink-500">async storePermission(
toolName: string,
parameters: any,
granted: boolean,
context: PermissionContext,
scope: PermissionScope | boolean
): Promise<void> {
// Implement your storage mechanism here
// This could use localStorage, cookies, or a server API
}
}
Permission Scopes
Scope | Description |
---|---|
once | Permission granted for this one operation only |
session | Permission granted for the duration of the current session |
permanent | Permission granted permanently for similar operations |
Tools
Tools allow the AI to interact with the system environment. The Scripta SDK includes a tool executor that handles tool requests, manages permissions, and submits results back to the server.
Tool Architecture
Scripta's tool system follows a request-execute-respond pattern that enables the AI to safely interact with the client's environment through well-defined interfaces.
Tool Definition
Each tool has a well-defined interface with specific parameters and return types. Tools include file operations, shell commands, and environment queries.
Tool Request
When the AI needs to interact with the environment, it sends a tool request with a specific tool name and parameters via the SSE channel.
Permission Check
The client's permission handler evaluates the tool request and determines whether to allow it, potentially prompting the user for approval.
Tool Execution
If approved, the tool executor uses the platform adapter to execute the operation (read/write files, run commands, etc.) in a platform-specific way.
Result Submission
The tool's result (or error) is submitted back to the server, allowing the AI to process the outcome and continue the conversation.
Tool Categories
Scripta includes a rich set of tools that enable the AI to interact with different aspects of the environment. These tools are organized into logical categories based on their function.
- FileReadTool - Read file contents
- FileWriteTool - Create or overwrite files
- FileEditTool - Modify existing files
- GlobTool - Find files matching patterns
- GrepTool - Search file contents
- LSTool - List directory contents
- NotebookReadTool - Read notebook content and outputs
- NotebookEditTool - Edit notebook cells
- BashTool - Execute shell commands with security constraints
- MemoryReadTool - Read from persistent memory
- MemoryWriteTool - Write to persistent memory
- ThinkTool - Internal reasoning without user display
- AgentTool - Delegate tasks to specialized sub-agents
- ArchitectTool - System architecture planning
- MCPTool - Multi-capability platform integration
Common Filesystem Tools
Parameter | Type | Description |
---|---|---|
file_path | string | Path to the file to read |
Parameter | Type | Description |
---|---|---|
file_path | string | Path to the file to edit |
old_string | string | Text to replace (empty for new file) |
new_string | string | Replacement text |
Parameter | Type | Description |
---|---|---|
command | string | Shell command to execute |
cwd | string | Working directory (optional) |
timeout | number | Timeout in milliseconds (optional) |
Parameter | Type | Description |
---|---|---|
pattern | string | Glob pattern (e.g., "**/*.js") |
ignore | string[] | Patterns to ignore (optional) |
Parameter | Type | Description |
---|---|---|
pattern | string | Search pattern |
path | string | Directory to search (optional) |
include | string | File pattern to include (optional) |
Advanced Agent Tools
Allows the AI to perform complex reasoning steps without showing the intermediate steps to the user. Useful for detailed analysis of code, planning steps, or working through complex problems.
Enables the main AI to delegate complex tasks to specialized sub-agents that have specific expertise or capabilities, improving efficiency and task specialization.
Platform Adapters
Platform adapters provide a consistent interface for platform-specific operations, making the Scripta SDK work across different environments.
Cross-Platform Design
Scripta was designed to be environment-agnostic, running seamlessly across different platforms and execution contexts. The PlatformAdapter interface abstracts away platform-specific details, enabling the same core code to run in:
Desktop Applications
- • Native file system access
- • Shell command execution
- • Local environment integration
- • Better security controls
Web Browsers
- • Browser File System API
- • WebWorkers for isolation
- • Sandboxed execution
- • Permission dialogs
Server Environments
- • Node.js file system access
- • Server-side process management
- • Containerized execution
- • Remote workspace support
Creating a Custom Adapter
"text-pink-500">import {
PlatformAdapter,
ShellResult,
GrepResult,
ListFilesOptions,
GlobOptions,
GrepOptions,
ShellOptions,
PermissionRequest
} "text-pink-500">from '@scripta/client-sdk';
"text-pink-500">export "text-pink-500">class MyPlatformAdapter "text-pink-500">implements PlatformAdapter {
// Filesystem operations
"text-pink-500">async readFile(path: string): Promise<string> {
// Implement based on your platform
}
"text-pink-500">async writeFile(path: string, content: string): Promise<void> {
// Implement based on your platform
}
"text-pink-500">async listFiles(path: string, options?: ListFilesOptions): Promise<string[]> {
// Implement based on your platform
}
"text-pink-500">async glob(pattern: string, options?: GlobOptions): Promise<string[]> {
// Implement based on your platform
}
"text-pink-500">async grep(pattern: string, path: string, options?: GrepOptions): Promise {
// Implement based on your platform
}
// Shell operations
"text-pink-500">async executeCommand(command: string, options?: ShellOptions): Promise {
// Implement based on your platform
}
// Path operations
"text-pink-500">async resolvePath(path: string): Promise<string> {
// Implement based on your platform
}
"text-pink-500">async isAbsolutePath(path: string): Promise<boolean> {
// Implement based on your platform
}
"text-pink-500">async joinPaths(...paths: string[]): Promise<string> {
// Implement based on your platform
}
// Configuration operations
"text-pink-500">async getConfigPath(): Promise<string> {
// Implement based on your platform
}
// Permission operations
"text-pink-500">async requestPermission(request: PermissionRequest): Promise<boolean> {
// Implement based on your platform
}
}