### Start and Manage Automaton Processes Source: https://github.com/conway-research/automaton/blob/main/_autodocs/README.md Use these commands to start, check the status of, re-run setup, or provision an API key for the Automaton. The `--run` command initiates an interactive setup on the first run and resumes with existing configuration on subsequent runs. ```bash # First run: interactive setup wizard node dist/index.js --run ``` ```bash # Subsequent runs: resume with existing config node dist/index.js --run ``` ```bash # Check status node dist/index.js --status ``` ```bash # Re-run setup node dist/index.js --setup ``` ```bash # Provision API key node dist/index.js --provision ``` -------------------------------- ### Setup Wizard Output Examples Source: https://github.com/conway-research/automaton/blob/main/DOCUMENTATION.md Sample console output during the wallet generation and API key provisioning steps. ```text [1/6] Generating identity (wallet)... Wallet created: 0x1234...abcd Private key stored at: /root/.automaton/wallet.json ``` ```text [2/6] Provisioning Conway API key (SIWE)... API key provisioned: cnwy_k_... ``` -------------------------------- ### Complete Monitoring Setup Source: https://github.com/conway-research/automaton/blob/main/_autodocs/observability.md An example demonstrating a comprehensive monitoring setup for the Automaton. It includes initializing the logger, setting global log level, and setting up callbacks for agent state changes and turn completion. ```typescript import { createLogger, setGlobalLogLevel, StructuredLogger } from "./observability/logger.js"; import { prettySink } from "./observability/pretty-sink.js"; // Setup logging StructuredLogger.setSink(prettySink); setGlobalLogLevel("info"); const logger = createLogger("setup"); logger.info("Automaton starting..."); try { const config = loadConfig(); const db = createDatabase(dbPath); const conway = createConwayClient(options); logger.info("Initialization complete", { name: config.name, version: config.version, }); // Run agent loop with callbacks await runAgentLoop({ // ... onStateChange: (state) => { logger.info(`State changed to: ${state}`); }, onTurnComplete: (turn) => { logger.info(`Turn ${turn.id} complete`, { tools: turn.toolCalls.length, tokens: turn.tokenUsage.totalTokens, cost: turn.costCents, }); }, }); } catch (error) { logger.error("Fatal error", error as Error); process.exit(1); } ``` -------------------------------- ### Clone, Install, and Run Automaton Source: https://github.com/conway-research/automaton/blob/main/README.md Clone the Automaton repository, install its dependencies, build the project, and run the agent. The first run initiates an interactive setup wizard for wallet generation, API key provisioning, and agent configuration. ```bash git clone https://github.com/Conway-Research/automaton.git cd automaton npm install && npm run build node dist/index.js --run ``` -------------------------------- ### Install Skill from URL Source: https://github.com/conway-research/automaton/blob/main/_autodocs/skills.md Use this command to install a skill by providing a direct URL to its definition file. ```bash automaton --install-skill https://example.com/my-skill.md ``` -------------------------------- ### Wallet Setup Flow Source: https://github.com/conway-research/automaton/blob/main/_autodocs/identity-and-wallet.md Guides through the process of obtaining or creating a wallet, provisioning an API key if the wallet is new, and constructing an AutomatonIdentity object for agent usage. ```typescript // 1. Get or create wallet const { account, chainIdentity, isNew } = await getWallet("evm"); if (isNew) { // 2. If new, provision API key const provisionResult = await provision(); console.log(`Provisioned: ${provisionResult.apiKey}`); } // 3. Load API key (from config or credentials) const apiKey = loadApiKeyFromConfig(); // 4. Build automaton identity const identity: AutomatonIdentity = { name: config.name, address: chainIdentity.address, account, // For signing creatorAddress: config.creatorAddress, sandboxId: config.sandboxId, apiKey, createdAt: new Date().toISOString(), chainType: "evm", chainIdentity, }; // 5. Ready to use console.log(`Agent: ${identity.name} at ${identity.address}`); ``` -------------------------------- ### Run Automaton Setup Source: https://github.com/conway-research/automaton/blob/main/_autodocs/README.md Execute the setup command for the Automaton CLI. This is typically used to initialize or configure the agent. ```bash node dist/index.js --setup ``` -------------------------------- ### Install Skill from Git Repository Source: https://github.com/conway-research/automaton/blob/main/_autodocs/skills.md Use this command to install a skill directly from a Git repository URL. ```bash automaton --install-skill https://github.com/user/skill-repo.git ``` -------------------------------- ### Credentials File Example Source: https://github.com/conway-research/automaton/blob/main/_autodocs/identity-and-wallet.md Example JSON structure for the API credentials file, containing Conway API key and wallet address. ```json { "conwayApiKey": "key_abc123xyz789...", "provisioned": "2025-06-20T14:05:00Z", "walletAddress": "0x1234567890123456789012345678901234567890" } ``` -------------------------------- ### EVM Wallet File Example Source: https://github.com/conway-research/automaton/blob/main/_autodocs/identity-and-wallet.md Example JSON structure for an EVM wallet file, including private key and creation timestamp. ```json { "privateKey": "0xabcdef123456789...", "createdAt": "2025-06-20T14:00:00Z", "chainType": "evm" } ``` -------------------------------- ### Model Strategy Configuration Example Source: https://github.com/conway-research/automaton/blob/main/_autodocs/configuration.md An example demonstrating how to configure the model strategy, specifying primary and fallback models, token limits, and enabling model fallback. This allows for fine-tuning AI model selection and usage. ```json { "modelStrategy": { "inferenceModel": "claude-sonnet-4-6", "lowComputeModel": "gpt-5-mini", "maxTokensPerTurn": 2048, "enableModelFallback": true } } ``` -------------------------------- ### Example: Executing the 'exec' Tool Source: https://github.com/conway-research/automaton/blob/main/_autodocs/api-reference.md Shows how to execute the 'exec' tool with specific command and timeout arguments. The example logs the result, which typically includes the exit code, standard output, and standard error. ```typescript const result = await executeTool(execTool, { command: "echo hello", timeout: 10000, }, context); console.log(result); // "exit_code: 0\nstdout: hello\nstderr: " ``` -------------------------------- ### Trigger Setup Wizard Manually Source: https://github.com/conway-research/automaton/blob/main/DOCUMENTATION.md Launches the interactive configuration wizard to define wallet, API keys, and agent identity. ```bash node dist/index.js --setup ``` -------------------------------- ### installTool Source: https://github.com/conway-research/automaton/blob/main/_autodocs/api-reference.md Registers a new tool as installed, making it available for use. ```APIDOC ## installTool(tool: InstalledTool): void ### Description Register an installed tool. ### Parameters #### Request Body - **tool** (InstalledTool) - Required - The InstalledTool object to register. ``` -------------------------------- ### Solana Wallet File Example Source: https://github.com/conway-research/automaton/blob/main/_autodocs/identity-and-wallet.md Example JSON structure for a Solana wallet file, including base58-encoded secret key and creation timestamp. ```json { "secretKey": "6i6HKP9...base58-encoded-64-byte-key...", "createdAt": "2025-06-20T14:00:00Z", "chainType": "solana" } ``` -------------------------------- ### Load Installed Tools Source: https://github.com/conway-research/automaton/blob/main/_autodocs/api-reference.md Retrieves all custom tools that have been installed via the 'install_tool' function from the Automaton database. ```typescript export function loadInstalledTools(db: AutomatonDatabase): AutomatonTool[] ``` -------------------------------- ### Clone and Install Automaton Project Source: https://github.com/conway-research/automaton/blob/main/README.md Clone the Automaton repository from GitHub and install its dependencies using pnpm. ```bash git clone https://github.com/Conway-Research/automaton.git cd automaton pnpm install pnpm build ``` -------------------------------- ### Install and Load a Custom Skill Source: https://github.com/conway-research/automaton/blob/main/_autodocs/README.md This code installs a new skill by writing its markdown content to the skills directory and then reloads all skills. Ensure the skill content is correctly formatted with a header specifying its name, description, and auto-activation status. ```typescript const newSkill = `---\nname: my-skill\ndescription: Custom skill\nauto-activate: true\n---\n\nInstructions for using this skill...\n`; await conway.writeFile("/root/.automaton/skills/my-skill.md", newSkill); // Reload skills const skills = loadSkills(skillsDir, db); console.log(`Loaded ${skills.length} skills`); ``` -------------------------------- ### Example AgentTurn JSON Object Source: https://github.com/conway-research/automaton/blob/main/_autodocs/agent-loop.md Illustrates a concrete example of an AgentTurn object in JSON format. This shows typical values for agent state, reasoning, executed tool calls with their results, and token/cost usage. ```json { "id": "01ARZ3NDEKTSV4RRFFQ69G5FAV", "timestamp": "2025-06-20T14:32:15Z", "state": "running", "input": null, "thinking": "I have $50 in credits. I should check my balance and look for revenue opportunities.", "toolCalls": [ { "id": "tool_1", "name": "check_balance", "arguments": {}, "result": "Credits: $5000 cents ($50.00)\nUSDC: $500", "durationMs": 245, "error": null }, { "id": "tool_2", "name": "send_status_ping", "arguments": { "broadcast": true }, "result": "Status pinged to 4 agents", "durationMs": 1203, "error": null } ], "tokenUsage": { "promptTokens": 1247, "completionTokens": 412, "totalTokens": 1659 }, "costCents": 8 } ``` -------------------------------- ### Create Heartbeat Daemon Instance Source: https://github.com/conway-research/automaton/blob/main/_autodocs/heartbeat.md Instantiate the heartbeat daemon with necessary configurations and callbacks. The daemon can be started using its `start()` method. ```typescript export function createHeartbeatDaemon(options: HeartbeatDaemonOptions): HeartbeatDaemon ``` ```typescript const heartbeat = createHeartbeatDaemon({ identity, config, heartbeatConfig, db, rawDb: db.raw, conway, social, onWakeRequest: (reason) => { console.log(`Wake requested: ${reason}`); }, }); heartbeat.start(); // Begin background execution ``` -------------------------------- ### Install Automaton Manually Source: https://github.com/conway-research/automaton/blob/main/DOCUMENTATION.md Clones the repository and builds the project from source for local execution. ```bash git clone https://github.com/Conway-Research/automaton.git cd automaton pnpm install pnpm build node dist/index.js --run ``` -------------------------------- ### Skill Markdown File Example Source: https://github.com/conway-research/automaton/blob/main/_autodocs/skills.md An example of a skill defined in a markdown file with YAML frontmatter. This format includes metadata like name, description, and requirements, followed by usage and implementation details. ```markdown --- name: fetch-weather description: Fetch weather data for a location auto-activate: true requires: bins: - curl - jq env: - WEATHER_API_KEY --- # Fetch Weather This skill fetches current weather from OpenWeatherMap. ## Usage Call the `fetch_weather` tool with a location name. ## Implementation The skill executes the following: 1. Format OpenWeatherMap API request 2. curl the endpoint with API key 3. Parse JSON response with jq 4. Return formatted weather string ## Example ``` fetch_weather("San Francisco") → "San Francisco: 72°F, Partly Cloudy" ``` ``` -------------------------------- ### Automaton Installer Script Source: https://github.com/conway-research/automaton/blob/main/ARCHITECTURE.md Shell script for bootstrapping the automaton using curl and pipe. ```bash scripts/automaton.sh ``` -------------------------------- ### Example: Using Built-in Tools Source: https://github.com/conway-research/automaton/blob/main/_autodocs/api-reference.md Demonstrates how to obtain the built-in tools and find a specific tool, such as the 'exec' tool, by its name. It then logs the description of the found tool. ```typescript const tools = createBuiltinTools(sandboxId); const execTool = tools.find(t => t.name === "exec"); console.log(`Exec tool: ${execTool?.description}`); ``` -------------------------------- ### Spawn Child Process Example Source: https://github.com/conway-research/automaton/blob/main/_autodocs/replication.md Demonstrates spawning a child process by first defining its configuration and then executing a `spawnChildTool`. This involves validating genesis, creating a sandbox, generating a wallet, and initializing the runtime. ```typescript // Within agent turn const childConfig: GenesisConfig = { name: "task-agent-1", genesisPrompt: "You are specialized in data processing tasks...", creatorMessage: "Process customer data efficiently", creatorAddress: identity.creatorAddress, parentAddress: identity.address, chainType: "evm", }; // Use spawn_child tool const result = await executeTool( spawnChildTool, { name: childConfig.name, genesisPrompt: childConfig.genesisPrompt, fundingCents: 50000, // $500 creatorMessage: childConfig.creatorMessage, }, context ); // Result: child is created and funded const children = db.getChildren(); console.log(`${children.length} children created`); ``` -------------------------------- ### Provision API Key Source: https://github.com/conway-research/automaton/blob/main/DOCUMENTATION.md Command to run when the agent fails to start due to a missing API key. ```bash No API key found. Run: automaton --provision ``` -------------------------------- ### Load Installed Tools Source: https://github.com/conway-research/automaton/blob/main/_autodocs/INDEX.md Loads custom tools installed in the environment. This allows for extending the automaton's capabilities. ```typescript const customTools = loadInstalledTools(); ``` -------------------------------- ### Install or Update Skill in Database Source: https://github.com/conway-research/automaton/blob/main/_autodocs/skills.md Inserts a new skill or updates an existing one in the database. Requires a complete Skill object, including name, description, source, and installation details. ```typescript db.upsertSkill({ name: "fetch-weather", description: "Fetch weather data", autoActivate: true, instructions: "...", source: "git", path: "/root/.automaton/skills/fetch-weather.md", enabled: true, installedAt: new Date().toISOString(), }); ``` -------------------------------- ### Override Treasury Policy Example Source: https://github.com/conway-research/automaton/blob/main/_autodocs/configuration.md Provides an example of how to override specific treasury policy settings in the configuration. This is useful for setting custom limits on transfers and reserves. ```json { "treasuryPolicy": { "maxSingleTransferCents": 1000, "maxDailyTransferCents": 5000, "minimumReserveCents": 500 } } ``` -------------------------------- ### Example Structured Log Output Source: https://github.com/conway-research/automaton/blob/main/_autodocs/observability.md An example of a structured log entry in JSON format, illustrating the fields and their typical values for an informational log. ```json { "timestamp": "2025-06-20T14:32:15.123Z", "level": "info", "module": "loop", "message": "Turn 1247 completed", "context": { "tools": 2, "tokens": 1659, "costCents": 8 } } ``` -------------------------------- ### Automaton File Structure Source: https://github.com/conway-research/automaton/blob/main/DOCUMENTATION.md Displays the directory layout and configuration files created in the home directory after setup. ```text ~/.automaton/ wallet.json Ethereum private key (mode 0600) automaton.json Main configuration (mode 0600) heartbeat.yml Heartbeat schedule api-key Conway API key constitution.md The Three Laws (read-only, mode 0444) SOUL.md Agent self-description (evolves) state.db SQLite database (all persistent state) skills/ Installed skill files conway-compute/ conway-payments/ survival/ ``` -------------------------------- ### createConfig(params) Source: https://github.com/conway-research/automaton/blob/main/_autodocs/configuration.md Creates a new Automaton configuration object from provided setup parameters. ```APIDOC ## createConfig(params) ### Description Creates a new `AutomatonConfig` object using the provided parameters. This function applies default values and normalizes certain inputs to ensure a valid configuration is generated. ### Parameters #### Request Body - **params** (`object`) - Required - An object containing the parameters for the new configuration. - **name** (`string`) - Required - The name of the automaton. - **genesisPrompt** (`string`) - Required - The initial prompt for the automaton. - **creatorMessage** (`string`) - Optional - An initial message from the creator. - **creatorAddress** (`string`) - Required - The blockchain address of the creator. - **registeredWithConway** (`boolean`) - Required - Indicates if the automaton is registered with Conway. - **sandboxId** (`string`) - Required - The identifier for the sandbox environment. - **walletAddress** (`string`) - Required - The wallet address associated with the automaton. - **apiKey** (`string`) - Required - The API key for authentication. - **openaiApiKey** (`string`) - Optional - OpenAI API key. - **anthropicApiKey** (`string`) - Optional - Anthropic API key. - **ollamaBaseUrl** (`string`) - Optional - Base URL for Ollama. - **parentAddress** (`string`) - Optional - The address of the parent automaton. - **treasuryPolicy** (`TreasuryPolicy`) - Optional - The treasury policy configuration. - **chainType** (`ChainType`) - Optional - The type of blockchain chain. ### Returns - `AutomatonConfig`: A fully-populated configuration object ready to be saved. ### Behavior - Normalizes the sandbox ID by trimming whitespace. - Applies all default values from `DEFAULT_CONFIG`. ### Example ```typescript const config = createConfig({ name: "alice", genesisPrompt: "You are a helpful AI agent", creatorAddress: "0x1234...", registeredWithConway: true, sandboxId: "sandbox-123", walletAddress: "0xabcd...", apiKey: "key_abc123", }); saveConfig(config); ``` ``` -------------------------------- ### Example Usage of SpendTracker Source: https://github.com/conway-research/automaton/blob/main/_autodocs/policy-engine.md Demonstrates how to instantiate and use the SpendTracker to record transactions, retrieve hourly spend, and check against defined treasury limits. ```typescript const tracker = new SpendTracker(db.raw); // Record a transfer tracker.recordSpend({ toolName: "transfer_credits", amountCents: 2500, recipient: "0x...", category: "transfer", }); // Check limits const hourlySpend = tracker.getHourlySpend("transfer"); console.log(`Transferred $${(hourlySpend / 100).toFixed(2)} this hour`); // Check if new transfer is allowed const check = tracker.checkLimit(5000, "transfer", config.treasuryPolicy); if (!check.allowed) { console.log(`Would exceed limit: ${check.reason}`); } ``` -------------------------------- ### Install Weather Skill Source: https://github.com/conway-research/automaton/blob/main/_autodocs/skills.md Clones the weather skill repository and copies the skill file to the automaton skills directory. Reloads the automaton to recognize the new skill. ```bash # From git git clone https://github.com/conway-ai/skill-weather.git cp skill-weather/fetch-weather.md ~/.automaton/skills/ # Then reload automaton --status # Shows loaded skills ``` -------------------------------- ### loadInstalledTools Source: https://github.com/conway-research/automaton/blob/main/_autodocs/api-reference.md Loads all custom tools that have been installed using the `install_tool` function. This allows access to user-defined functionalities. ```APIDOC ## Function: loadInstalledTools ### Description Get all custom tools installed via `install_tool`. ### Signature ```typescript export function loadInstalledTools(db: AutomatonDatabase): AutomatonTool[] ``` ### Parameters #### Path Parameters - **db** (AutomatonDatabase) - The database instance to load tools from. ``` -------------------------------- ### Create an Automaton Instance with Clients Source: https://github.com/conway-research/automaton/blob/main/_autodocs/README.md This TypeScript code initializes the database, Conway client, and inference client, then starts the agent loop. Ensure all necessary modules are imported before execution. ```typescript import { createDatabase } from "./state/database.js"; import { createConwayClient } from "./conway/client.js"; import { createInferenceClient } from "./conway/inference.js"; import { runAgentLoop } from "./agent/loop.js"; const db = createDatabase("/root/.automaton/state.db"); const conway = createConwayClient({ apiUrl: "https://api.conway.tech", apiKey: "key_abc123", sandboxId: "sandbox-xyz", }); const inference = createInferenceClient({ apiUrl: "https://api.conway.tech", apiKey: "key_abc123", defaultModel: "gpt-5.2", maxTokens: 4096, }); await runAgentLoop({ identity, config, db, conway, inference, skills: [], policyEngine, spendTracker, }); ``` -------------------------------- ### upsertSkill Source: https://github.com/conway-research/automaton/blob/main/_autodocs/api-reference.md Installs a new skill or updates an existing one in the system. ```APIDOC ## upsertSkill(skill: Skill): void ### Description Install or update a skill. ### Parameters #### Request Body - **skill** (Skill) - Required - The Skill object to install or update. ``` -------------------------------- ### Automated Sandbox Provisioning for Automaton Source: https://github.com/conway-research/automaton/blob/main/README.md Use this command to automatically provision a sandbox environment for Automaton. This script handles the setup process, allowing for quick deployment in a testing environment. ```bash curl -fsSL https://conway.tech/automaton.sh | sh ``` -------------------------------- ### getInstalledTools Source: https://github.com/conway-research/automaton/blob/main/_autodocs/api-reference.md Retrieves a list of all tools that are currently installed and available for use. ```APIDOC ## getInstalledTools(): InstalledTool[] ### Description Get all installed tools. ### Returns - (InstalledTool[]) - An array of InstalledTool objects. ``` -------------------------------- ### Create and Install a New Skill Dynamically Source: https://github.com/conway-research/automaton/blob/main/_autodocs/skills.md This snippet demonstrates how an automaton can programmatically create a new skill definition, write it to disk, and then reload its skills to make the new skill available for use. Ensure the path for writing the skill file is correct. ```javascript // Within agent turn const newSkill = `--- name: sentiment-analysis description: Analyze sentiment of text auto-activate: true --- This skill uses a simple NLP approach to analyze sentiment. Implementation: - Count positive/negative keywords - Return score 0.0-1.0 `; // Write to disk await conway.writeFile("/root/.automaton/skills/sentiment-analysis.md", newSkill); // Reload skills skills = loadSkills(skillsDir, db); // Skill is now available const sentiment = db.getSkillByName("sentiment-analysis"); console.log(`Installed: ${sentiment.name}`); ``` -------------------------------- ### Spawn a Child Automaton Source: https://github.com/conway-research/automaton/blob/main/_autodocs/README.md This example demonstrates spawning a child automaton using the `spawn_child` tool. It requires the tool itself, parameters like name, genesis prompt, and funding, and a context object. The result includes the ID of the newly spawned child. ```typescript // Use the spawn_child tool const result = await executeTool( spawnChildTool, { name: "worker-1", genesisPrompt: "You are a task executor...", fundingCents: 50000, // $500 }, context ); console.log(`Child spawned: ${result.childId}`); ``` -------------------------------- ### Agent Usage Example for Weather Skill Source: https://github.com/conway-research/automaton/blob/main/_autodocs/skills.md Demonstrates a typical interaction where the agent requests weather information for an event planning scenario and uses the result to make a recommendation. ```text Agent: I need to know the weather to help plan an outdoor event. Tool Call: fetch_weather(location="San Francisco") Result: "San Francisco: 72°F, Partly Cloudy, Wind 8 mph" Agent: Based on this weather, I recommend an outdoor event. It's perfect conditions. ``` -------------------------------- ### Send Message with Tools Source: https://github.com/conway-research/automaton/blob/main/_autodocs/api-reference.md Send a message to an LLM and specify tools for function calling. This example demonstrates overriding the default model and setting a temperature for sampling. Handles tool calls and their arguments. ```typescript const response = await inference.chat([ { role: "user", content: "Get the weather" }, ], { model: "claude-sonnet-4-6", temperature: 0.7, tools: [{ type: "function", function: { name: "get_weather", description: "Get weather for a location", parameters: { type: "object", properties: { location: { type: "string" }, }, required: ["location"], }, }, }], }); if (response.toolCalls) { for (const call of response.toolCalls) { console.log(`Tool: ${call.function.name}`); console.log(`Args: ${call.function.arguments}`); } } ``` -------------------------------- ### Log a Config Change Source: https://github.com/conway-research/automaton/blob/main/_autodocs/observability.md Example of how to log a configuration change using the `db.insertModification` method. This snippet demonstrates creating a new modification entry with relevant details. ```typescript db.insertModification({ id: ulid(), timestamp: new Date().toISOString(), type: "config_change", description: "Updated inference model to gpt-5.2", reversible: true, }); ``` -------------------------------- ### Create Built-in Tools Source: https://github.com/conway-research/automaton/blob/main/_autodocs/api-reference.md Get the full set of built-in tools available to the agent. These tools cover various categories like VM operations, Conway management, financial transactions, self-modification, replication, skills, and memory. ```typescript export function createBuiltinTools(sandboxId: string): AutomatonTool[] ``` -------------------------------- ### Initialize Policy Engine Source: https://github.com/conway-research/automaton/blob/main/_autodocs/policy-engine.md Instantiate the PolicyEngine with database and policy rules. Use createDefaultRules for common rule sets. ```typescript import { PolicyEngine } from "./agent/policy-engine.js"; import { createDefaultRules } from "./agent/policy-rules/index.js"; const rules = createDefaultRules(config.treasuryPolicy); const policyEngine = new PolicyEngine(db.raw, rules); ``` -------------------------------- ### Build and Test Commands Source: https://github.com/conway-research/automaton/blob/main/ARCHITECTURE.md Commands for building the project, running tests, and performing type checking. ```bash pnpm build ``` ```bash pnpm test ``` ```bash pnpm typecheck ``` -------------------------------- ### PolicyEngine Source: https://github.com/conway-research/automaton/blob/main/_autodocs/api-reference.md Initializes a new PolicyEngine with a database connection and a set of policy rules. ```APIDOC ## PolicyEngine Constructor ### Description Initializes a new PolicyEngine with a database connection for logging and an array of policy rules. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Name | Type | Description | |------|------|-------------| | `db` | `Database` | SQLite database for logging decisions | | `rules` | `PolicyRule[]` | Initial rules to apply | ``` -------------------------------- ### Get All Skills from Database Source: https://github.com/conway-research/automaton/blob/main/_autodocs/skills.md Retrieves all skills stored in the database. ```typescript const allSkills = db.getSkills(); ``` -------------------------------- ### SkillSource Type Definition Source: https://github.com/conway-research/automaton/blob/main/_autodocs/types.md Defines the possible sources from which a skill can be installed. ```typescript type SkillSource = "builtin" | "git" | "url" | "self"; ``` -------------------------------- ### getSkills Source: https://github.com/conway-research/automaton/blob/main/_autodocs/api-reference.md Retrieves a list of installed skills. Optionally filters to only include enabled skills. ```APIDOC ## getSkills(enabledOnly?: boolean): Skill[] ### Description Get installed skills (optionally filtered to enabled only). ### Parameters #### Query Parameters - **enabledOnly** (boolean) - Optional - If true, only return enabled skills. ### Returns - (Skill[]) - An array of Skill objects. ``` -------------------------------- ### Build and Verify Automaton Source: https://github.com/conway-research/automaton/blob/main/DOCUMENTATION.md Commands for building the project from source and running the test suite. ```bash git clone https://github.com/Conway-Research/automaton.git cd automaton pnpm install pnpm build ``` ```bash pnpm typecheck # TypeScript type checking pnpm test # Run all 897 tests ``` -------------------------------- ### Get Only Enabled Skills from Database Source: https://github.com/conway-research/automaton/blob/main/_autodocs/skills.md Retrieves only the currently active (enabled) skills from the database. ```typescript const activeSkills = db.getSkills(true); ``` -------------------------------- ### Get Credit Balance Source: https://github.com/conway-research/automaton/blob/main/_autodocs/api-reference.md Retrieves the current credit balance in cents. The balance can be used to estimate remaining usage. ```typescript const creditsCents = await conway.getCreditsBalance(); console.log(`Balance: $${(creditsCents / 100).toFixed(2)}`); ``` -------------------------------- ### Tool Reference - Sandbox Operations (vm) Source: https://github.com/conway-research/automaton/blob/main/DOCUMENTATION.md Lists and describes the tools available for interacting with the sandbox environment. ```APIDOC ## Tool Reference - Sandbox Operations (vm) ### Description Tools for managing and interacting with the sandbox environment. | Tool | Risk | Description | |---|---|---| | `exec` | caution | Execute a shell command. Returns stdout, stderr, exit code. | | `write_file` | caution | Write content to a file. Protected paths are blocked. | | `read_file` | safe | Read a file. Sensitive files (wallet, API keys) are blocked. | | `expose_port` | caution | Expose a port to the internet. Returns public URL. | | `remove_port` | caution | Remove a previously exposed port. ``` -------------------------------- ### Define a new skill Source: https://github.com/conway-research/automaton/blob/main/DOCUMENTATION.md Create a SKILL.md file with YAML frontmatter to define agent instructions and triggers. ```markdown --- name: my-skill description: "What this skill does" auto-activate: true triggers: [keyword1, keyword2] --- # Skill Instructions Step-by-step instructions for the agent... ``` -------------------------------- ### Get Automaton Configuration Directory Source: https://github.com/conway-research/automaton/blob/main/_autodocs/identity-and-wallet.md Retrieves the absolute path to the automaton's configuration directory, typically located at `~/.automaton`. ```typescript export function getAutomatonDir(): string ``` ```typescript const dir = getAutomatonDir(); const configPath = path.join(dir, "automaton.json"); ``` -------------------------------- ### Get Credits Balance via Conway Client Source: https://github.com/conway-research/automaton/blob/main/_autodocs/INDEX.md Retrieves the current credits balance for the automaton. This is essential for financial operations. ```typescript const balance = await client.getCreditsBalance(); console.log(`Balance: ${balance}`); ``` -------------------------------- ### Get All Children Records Source: https://github.com/conway-research/automaton/blob/main/_autodocs/replication.md Retrieves all child records from the database and logs their name and status. Ensure the database connection is established before calling. ```typescript const children = db.getChildren(); for (const child of children) { console.log(`${child.name}: ${child.status}`); } ``` -------------------------------- ### Get Automaton Config Path Source: https://github.com/conway-research/automaton/blob/main/_autodocs/configuration.md Retrieves the absolute path to the automaton configuration file. Useful for direct file access or verification. ```typescript export function getConfigPath(): string ``` ```typescript const configPath = getConfigPath(); // Returns: /home/user/.automaton/automaton.json ``` -------------------------------- ### Backup Database Source: https://github.com/conway-research/automaton/blob/main/DOCUMENTATION.md Creates a timestamped backup of the state database. ```bash scripts/backup-restore.sh backup ``` -------------------------------- ### Fund Automaton via Creator CLI Source: https://github.com/conway-research/automaton/blob/main/_autodocs/README.md Fund an automaton using the creator CLI with a specified amount. This is an alternative method for topping up credits. ```bash node packages/cli/dist/index.js fund 5.00 ``` -------------------------------- ### createInferenceClient Source: https://github.com/conway-research/automaton/blob/main/_autodocs/api-reference.md Initializes a client for the Conway Inference API, supporting multiple backends like Conway, OpenAI, Anthropic, and Ollama. ```APIDOC ## Function: createInferenceClient ### Description Creates an inference client that can interface with multiple LLM backends, including Conway, OpenAI, Anthropic, and Ollama. ### Method `createInferenceClient(options: InferenceClientOptions): InferenceClient` ### Parameters #### Options - **apiUrl** (string) - Required - Conway API endpoint. - **apiKey** (string) - Required - Conway API key. - **defaultModel** (string) - Required - Default model to use (e.g., "gpt-5.2"). - **maxTokens** (number) - Required - Maximum tokens to generate per response. - **lowComputeModel** (string) - Optional - Fallback model for low-compute tier. - **openaiApiKey** (string) - Optional - API key to enable the OpenAI backend. - **anthropicApiKey** (string) - Optional - API key to enable the Anthropic backend. - **ollamaBaseUrl** (string) - Optional - Base URL to enable the Ollama backend. - **getModelProvider** (function) - Optional - A function for custom model routing. ### Returns `InferenceClient` object with a `chat()` method. ### Example ```typescript const inference = createInferenceClient({ apiUrl: "https://api.conway.tech", apiKey: "key_abc123", defaultModel: "gpt-5.2", maxTokens: 4096, openaiApiKey: "sk-...", // Optional anthropicApiKey: "sk-ant-...", // Optional }); const response = await inference.chat([ { role: "system", content: "You are helpful" }, { role: "user", content: "What is 2+2?" }, ]); console.log(response.message.content); // "4" ``` ``` -------------------------------- ### Get Survival Tier Source: https://github.com/conway-research/automaton/blob/main/_autodocs/INDEX.md Retrieves the automaton's survival tier classification based on predefined thresholds. This helps in understanding its operational status. ```typescript const tier = await client.getSurvivalTier(); console.log(`Survival Tier: ${tier}`); ``` -------------------------------- ### Get Skill by Name from Database Source: https://github.com/conway-research/automaton/blob/main/_autodocs/skills.md Retrieves a specific skill from the database by its unique name. Logs the skill's name and description if found. ```typescript const skill = db.getSkillByName("fetch-weather"); if (skill) { console.log(`${skill.name}: ${skill.description}`); } ``` -------------------------------- ### Interact with Creator CLI Source: https://github.com/conway-research/automaton/blob/main/README.md Use the Creator CLI to check status, view logs, or fund the automaton. ```bash node packages/cli/dist/index.js status node packages/cli/dist/index.js logs --tail 20 node packages/cli/dist/index.js fund 5.00 ``` -------------------------------- ### Custom Log Sink Interface and Implementation Source: https://github.com/conway-research/automaton/blob/main/_autodocs/observability.md Defines the 'LogSink' interface for custom log handlers and provides an example implementation 'MyCustomSink' that logs to the console. ```typescript interface LogSink { write(entry: LogEntry): void; } class MyCustomSink implements LogSink { write(entry: LogEntry) { // Send to external service console.log(`[${entry.level.toUpperCase()}] ${entry.message}`); } } StructuredLogger.setSink(new MyCustomSink()); ``` -------------------------------- ### Load Skills from Directory Source: https://github.com/conway-research/automaton/blob/main/_autodocs/skills.md Loads all skills from a specified directory, resolving '~' paths and scanning for various file types. It parses frontmatter, updates the database, and returns an array of Skill objects. ```typescript export function loadSkills(skillsDir: string, db: AutomatonDatabase): Skill[] ``` ```typescript const skills = loadSkills("~/.automaton/skills", db); console.log(`Loaded ${skills.length} skills`); for (const skill of skills) { console.log(`- ${skill.name}: ${skill.enabled ? "enabled" : "disabled"}`); } ``` -------------------------------- ### Create New Automaton Configuration Source: https://github.com/conway-research/automaton/blob/main/_autodocs/configuration.md Generates a new AutomatonConfig object from provided setup parameters, applying default values. This is useful for initializing a configuration before saving. ```typescript export function createConfig(params: { name: string; genesisPrompt: string; creatorMessage?: string; creatorAddress: string; registeredWithConway: boolean; sandboxId: string; walletAddress: string; apiKey: string; openaiApiKey?: string; anthropicApiKey?: string; ollamaBaseUrl?: string; parentAddress?: string; treasuryPolicy?: TreasuryPolicy; chainType?: ChainType; }): AutomatonConfig ``` ```typescript const config = createConfig({ name: "alice", genesisPrompt: "You are a helpful AI agent", creatorAddress: "0x1234...", registeredWithConway: true, sandboxId: "sandbox-123", walletAddress: "0xabcd...", apiKey: "key_abc123", }); saveConfig(config); ``` -------------------------------- ### createConwayClient Source: https://github.com/conway-research/automaton/blob/main/_autodocs/api-reference.md Creates a Conway API client instance, enabling interaction with Conway infrastructure like sandboxes, domains, and credits. It configures the client with API URL, authentication key, and sandbox ID, and includes built-in resilience features. ```APIDOC ## Function: createConwayClient ### Description Creates a Conway API client instance, enabling interaction with Conway infrastructure like sandboxes, domains, and credits. It configures the client with API URL, authentication key, and sandbox ID, and includes built-in resilience features. ### Signature ```typescript export function createConwayClient(options: ConwayClientOptions): ConwayClient ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters `options` (`ConwayClientOptions`) - Required - Client configuration - `options.apiUrl` (string) - Required - Conway API endpoint - `options.apiKey` (string) - Required - API authentication key - `options.sandboxId` (string) - Required - Sandbox ID (empty string = local execution) ### Request Example ```typescript const conway = createConwayClient({ apiUrl: "https://api.conway.tech", apiKey: "key_abc123", sandboxId: "sandbox-xyz", }); const result = await conway.exec("ls -la"); console.log(result.stdout); ``` ### Response #### Success Response (`ConwayClient`) API client with methods for sandbox control, file I/O, domain management, and credit operations. #### Response Example (No specific response example provided for the client object itself, but usage is shown in the Request Example.) ### Behavior Details - Normalizes sandbox ID (removes whitespace, handles empty/undefined) - Defaults to local execution if sandbox ID is empty - Creates resilient HTTP client with retry logic and circuit breaker - Auto-retries 404s (up to 3 times) to handle LB routing issues ``` -------------------------------- ### createHeartbeatDaemon Source: https://github.com/conway-research/automaton/blob/main/_autodocs/heartbeat.md Creates a background heartbeat daemon that runs scheduled tasks. It requires several configuration options and returns a HeartbeatDaemon object with start and stop methods. ```APIDOC ## Function: createHeartbeatDaemon ### Description Create a background heartbeat daemon that runs scheduled tasks. ### Parameters #### Path Parameters - **identity** (AutomatonIdentity) - Required - Agent identity - **config** (AutomatonConfig) - Required - Runtime config - **heartbeatConfig** (HeartbeatConfig) - Required - Scheduled tasks config - **db** (AutomatonDatabase) - Required - State database - **rawDb** (Database) - Required - SQLite instance - **conway** (ConwayClient) - Required - API client - **social** (SocialClientInterface) - Optional - Messaging relay - **onWakeRequest** (function) - Optional - Callback when task requests wake ### Request Example ```typescript const heartbeat = createHeartbeatDaemon({ identity, config, heartbeatConfig, db, rawDb: db.raw, conway, social, onWakeRequest: (reason) => { console.log(`Wake requested: ${reason}`); }, }); ``` ### Returns `HeartbeatDaemon` with `start()` and `stop()` methods. ``` -------------------------------- ### Create Database Instance Source: https://github.com/conway-research/automaton/blob/main/_autodocs/INDEX.md Initializes a new SQLite database instance. This is used for local data storage and management. ```typescript import { createDatabase } from "@conway/automaton/database"; const db = createDatabase("automaton.db"); ``` -------------------------------- ### Create Conway Client Source: https://github.com/conway-research/automaton/blob/main/_autodocs/api-reference.md Use this function to create an API client for Conway infrastructure. It requires configuration options including the API URL, an API key, and a sandbox ID. The client supports sandbox control, file I/O, domain management, and credit operations. ```typescript export function createConwayClient(options: ConwayClientOptions): ConwayClient ``` ```typescript const conway = createConwayClient({ apiUrl: "https://api.conway.tech", apiKey: "key_abc123", sandboxId: "sandbox-xyz", }); const result = await conway.exec("ls -la"); console.log(result.stdout); ``` -------------------------------- ### Get Child Record by ID Source: https://github.com/conway-research/automaton/blob/main/_autodocs/replication.md Retrieves a specific child record by its unique identifier. Checks if the child exists and if its status is 'dead' to log a specific message. ```typescript const child = db.getChildById("01ARZ3NDEKTSV4RRFFQ69G5FAV"); if (child && child.status === "dead") { console.log(`Child is out of funds`); } ``` -------------------------------- ### Manual State Backup Source: https://github.com/conway-research/automaton/blob/main/DOCUMENTATION.md Creates a compressed archive of the entire agent state directory. ```bash tar czf automaton-backup-$(date +%Y%m%d).tar.gz ~/.automaton/ ``` -------------------------------- ### Create Inference Client Source: https://github.com/conway-research/automaton/blob/main/_autodocs/INDEX.md Initializes an inference client that supports multiple backends. This allows for flexible model selection. ```typescript import { createInferenceClient } from "@conway/automaton/inference"; const inferenceClient = createInferenceClient({ backends: ["conway", "openai"], }); ``` -------------------------------- ### Resolve Path with Tilde Expansion Source: https://github.com/conway-research/automaton/blob/main/_autodocs/configuration.md Resolves paths starting with '~' to the user's home directory. Handles cases where the HOME environment variable might be unset. ```typescript export function resolvePath(p: string): string ``` ```typescript const dbPath = resolvePath("~/.automaton/state.db"); // Returns: /home/user/.automaton/state.db ``` -------------------------------- ### Skill Type Definition Source: https://github.com/conway-research/automaton/blob/main/_autodocs/skills.md Defines the structure of a Skill object, including its properties like name, description, activation status, requirements, instructions, source, path, and installation timestamp. ```typescript interface Skill { name: string; // Unique identifier description: string; // Human-readable description autoActivate: boolean; // Auto-enable on install requires?: SkillRequirements; // Binary/env dependencies instructions: string; // Full skill code/instructions source: SkillSource; // How it was installed path: string; // File path enabled: boolean; // Is this skill active installedAt: string; // ISO 8601 timestamp } interface SkillRequirements { bins?: string[]; // Executables env?: string[]; // Environment variables } type SkillSource = "builtin" | "git" | "url" | "self"; ``` -------------------------------- ### Initialize and Use Automaton Database Source: https://github.com/conway-research/automaton/blob/main/_autodocs/api-reference.md Initializes a new automaton database at the specified path and demonstrates basic usage for retrieving recent turns. Ensure the database path is correctly specified. The database connection should be closed when no longer needed. ```typescript export function createDatabase(dbPath: string): AutomatonDatabase ``` ```typescript const db = createDatabase("/root/.automaton/state.db"); const turns = db.getRecentTurns(10); console.log(`${turns.length} recent turns`); db.close(); ``` -------------------------------- ### Get or Create Automaton Wallet Source: https://github.com/conway-research/automaton/blob/main/_autodocs/identity-and-wallet.md Retrieves an existing wallet or creates a new one for the automaton. Supports EVM and Solana chain types. Wallet is stored securely in `~/.automaton/wallet.json`. ```typescript export async function getWallet( chainType?: ChainType ): Promise<{ account: PrivateKeyAccount; chainIdentity: ChainIdentity; chainType: ChainType; isNew: boolean; }> ``` ```typescript const { account, chainIdentity, chainType, isNew } = await getWallet("evm"); console.log(`Wallet: ${chainIdentity.address}`); if (isNew) { console.log("New wallet created"); } ``` -------------------------------- ### Skill Markdown File Structure Source: https://github.com/conway-research/automaton/blob/main/ARCHITECTURE.md Defines the structure for skill files, including YAML frontmatter for metadata and markdown for instructions. Skills are loaded from a specific directory and can be installed from various sources. ```yaml --- name: my-skill description: What this skill does triggers: [keyword1, keyword2] --- # Instructions Step-by-step instructions for the agent... ```