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.

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:

  1. Create a platform adapter specific to your environment
  2. Create a permission handler to manage security permissions
  3. Initialize the ScriptaClient with the adapter and permission handler
  4. Connect to the server to create a session
  5. Set up event listeners for responses, tool requests, etc.
  6. Send messages to the AI
  7. Disconnect when done to clean up resources

Quick Start

example.ts
"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

Client
Main entry point for the SDK

The ScriptaClient class manages connections, sessions, and communication with the server.

Events
Real-time communication

Server-sent events provide real-time updates for responses, thinking status, and tool requests.

Tools
Environment interaction

Tools allow the AI to interact with the system - files, shell commands, and more.

Permissions
Security system

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.

POST
/api/conversations

Parameters

NameTypeRequiredDescription
userIdstringOptional user identifier
orgIdstringOptional organization identifier
conversationTypestringType of conversation (defaults to general)
workingDirectorystringWorking directory for the conversation

Response

{
  "success": true,
  "sessionId": "sess_123456789"
}
POST
/api/conversations/{sessionId}/messages

Parameters

NameTypeRequiredDescription
contentstringMessage 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.

SSE
/api/events/{sessionId}

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

TypeDescription
THINKING_UPDATEStatus updates while the AI is processing
ASSISTANT_RESPONSEText response from the assistant
TOOL_REQUESTRequest to execute a tool
ERRORError message
CONVERSATION_COMPLETESignals the end of a conversation turn

Tool Results

Endpoint for submitting tool execution results back to the AI.

How Tools Work

  1. Tool Request: The AI sends a tool request through the SSE channel when it needs to interact with the environment
  2. Client Execution: The client application executes the requested tool (file read, shell command, etc.)
  3. Result Submission: The client submits the tool result back to the server using this endpoint
  4. AI Processing: The AI processes the tool result and continues the conversation
POST
/api/conversations/{conversationId}/tools/{toolUseId}/results

Parameters

NameTypeRequiredDescription
resultanyResult of tool execution
errorstringError 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

custom-permission-handler.ts
"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

ScopeDescription
oncePermission granted for this one operation only
sessionPermission granted for the duration of the current session
permanentPermission 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.

1

Tool Definition

Each tool has a well-defined interface with specific parameters and return types. Tools include file operations, shell commands, and environment queries.

2

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.

3

Permission Check

The client's permission handler evaluates the tool request and determines whether to allow it, potentially prompting the user for approval.

4

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.

5

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.

Filesystem Tools
Interact with files and directories
  • 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
Notebook Tools
Work with Jupyter notebooks
  • NotebookReadTool - Read notebook content and outputs
  • NotebookEditTool - Edit notebook cells
Shell Tools
Execute system commands
  • BashTool - Execute shell commands with security constraints
Memory Tools
Store and retrieve persistent data
  • MemoryReadTool - Read from persistent memory
  • MemoryWriteTool - Write to persistent memory
Agent Tools
Advanced agent capabilities
  • ThinkTool - Internal reasoning without user display
  • AgentTool - Delegate tasks to specialized sub-agents
  • ArchitectTool - System architecture planning
External Tools
Integrate with external services
  • MCPTool - Multi-capability platform integration

Common Filesystem Tools

View (FileReadTool)
Read file contents
ParameterTypeDescription
file_pathstringPath to the file to read
Edit (FileEditTool)
Edit file contents
ParameterTypeDescription
file_pathstringPath to the file to edit
old_stringstringText to replace (empty for new file)
new_stringstringReplacement text
Bash (BashTool)
Execute shell commands
ParameterTypeDescription
commandstringShell command to execute
cwdstringWorking directory (optional)
timeoutnumberTimeout in milliseconds (optional)
GlobTool
Find files by pattern
ParameterTypeDescription
patternstringGlob pattern (e.g., "**/*.js")
ignorestring[]Patterns to ignore (optional)
GrepTool
Search file contents
ParameterTypeDescription
patternstringSearch pattern
pathstringDirectory to search (optional)
includestringFile pattern to include (optional)

Advanced Agent Tools

ThinkTool
Internal reasoning without user visibility

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.

// Example usage
think("Let me analyze this code structure...
1. First, I need to understand the entry points
2. Then examine how the modules are connected
3. Finally determine where the bug might be")
AgentTool
Delegate tasks to specialized sub-agents

Enables the main AI to delegate complex tasks to specialized sub-agents that have specific expertise or capabilities, improving efficiency and task specialization.

// Example usage
agent("code-analyzer", "Analyze this React component")
agent("db-expert", "Design a schema for this data model")
agent("security-reviewer", "Review these API endpoints")

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

custom-platform-adapter.ts
"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 } }