runact 1.0.0

A Rust-native actor runtime with BEAM-style processes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
# Runact Agents

## Overview

Agents in Runact are runtime entities that interact with the system through a controlled, auditable interface. An agent is NOT the LLM itself — it is a process that wraps an LLM adapter and executes operations through the standard message system.

## Architecture

```
Agent
├── Identity
├── Capabilities
├── Context
├── Task
├── State
├── Tools
├── Audit
└── ModelAdapter
```

The LLM is replaceable. Future adapters:

- Local model
- OpenAI-compatible API
- Anthropic-compatible API
- Ollama
- Custom inference
- Future models

## Agent Process

An agent is implemented as a supervised process.

```rust
pub struct AgentProcess {
    id: AgentId,
    name: String,
    adapter: Box<dyn ModelAdapter>,
    capabilities: Capabilities,
    context: AgentContext,
    state: AgentState,
    audit_log: AuditLog,
}
```

### Process Implementation

```rust
impl Process for AgentProcess {
    type Message = AgentMessage;

    async fn handle(
        &mut self,
        message: AgentMessage,
        context: &mut ProcessContext,
    ) -> Result<(), ProcessError> {
        match message {
            AgentMessage::ExecuteTask(task) => {
                self.execute_task(task, context).await
            }
            AgentMessage::ReceiveObservation(obs) => {
                self.process_observation(obs, context).await
            }
            AgentMessage::RequestApproval(tx_id) => {
                self.handle_approval(tx_id, context).await
            }
        }
    }
}
```

## Identity

```rust
pub struct AgentIdentity {
    pub id: AgentId,
    pub name: String,
    pub description: String,
    pub created_at: Timestamp,
}
```

## Capabilities

Capability-based permissions control what agents can do.

### Capability Set

```rust
pub struct Capabilities {
    pub grants: Vec<Capability>,
}
```

### Capability Types

```rust
pub enum Capability {
    ProcessExecute,
    ProcessSpawn,
    TimerCreate,
    SystemRead,
    SystemWrite,
    NetworkConnect,
}
```

### Capability Checking

```rust
impl Capabilities {
    pub fn has(&self, capability: &Capability) -> bool {
        self.grants.iter().any(|g| g.matches(capability))
    }

    pub fn require(&self, capability: &Capability) -> Result<(), CapabilityError> {
        if self.has(capability) {
            Ok(())
        } else {
            Err(CapabilityError::Missing {
                required: capability.clone(),
            })
        }
    }
}
```

## Context

Agent maintains context about its current state.

```rust
pub struct AgentContext {
    pub history: Vec<AgentAction>,
    pub observations: Vec<Observation>,
}
```

### AgentAction

```rust
pub struct AgentAction {
    pub action_id: MessageId,
    pub action_type: ActionType,
    pub timestamp: Timestamp,
    pub result: ActionResult,
}

pub enum ActionType {
    SendMessage { target: ProcessId },
    SpawnProcess { process_type: String },
    CreateTimer { duration: Duration },
    ExecuteCommand { command_name: String },
}

pub enum ActionResult {
    Success { output: String },
    Failure { error: String },
    RequiresApproval { request_id: MessageId },
}
```

### Observation

```rust
pub struct Observation {
    pub observation_id: MessageId,
    pub source: ProcessId,
    pub observation_type: ObservationType,
    pub timestamp: Timestamp,
    pub data: Vec<u8>,
}

pub enum ObservationType {
    ProcessStarted { process_id: ProcessId },
    ProcessStopped { process_id: ProcessId },
    MessageReceived { message_id: MessageId },
    TimerFired { timer_id: TimerId },
}
```

## State

```rust
pub enum AgentState {
    Idle,
    Thinking { task: Task },
    Executing { action: ActionType },
    WaitingForApproval { request_id: MessageId },
    WaitingForObservation,
    Failed { error: String },
}
```

## Model Adapter

Interface for LLM integration.

```rust
#[async_trait]
pub trait ModelAdapter: Send + Sync {
    async fn complete(
        &self,
        messages: &[Message],
        tools: &[ToolDefinition],
    ) -> Result<Completion, ModelError>;

    async fn embedding(&self, text: &str) -> Result<Vec<f32>, ModelError>;

    fn model_name(&self) -> &str;
    fn supports_tools(&self) -> bool;
}
```

### Message

```rust
pub struct Message {
    pub role: Role,
    pub content: String,
    pub tool_calls: Option<Vec<ToolCall>>,
    pub tool_call_id: Option<String>,
}

pub enum Role {
    System,
    User,
    Assistant,
    Tool,
}
```

### Tool Definition

```rust
pub struct ToolDefinition {
    pub name: String,
    pub description: String,
    pub parameters: JsonSchema,
}
```

### Completion

```rust
pub struct Completion {
    pub content: Option<String>,
    pub tool_calls: Vec<ToolCall>,
    pub finish_reason: FinishReason,
}

pub struct ToolCall {
    pub id: String,
    pub name: String,
    pub arguments: serde_json::Value,
}

pub enum FinishReason {
    Stop,
    ToolCalls,
    Length,
}
```

## Tool API

Agents interact with the system through tools.

### Built-in Tools

```rust
pub struct ToolRegistry {
    tools: HashMap<String, Box<dyn Tool>>,
}

impl ToolRegistry {
    pub fn builtin() -> Self {
        let mut registry = Self::new();
        registry.register(SendMessageTool);
        registry.register(SpawnProcessTool);
        registry.register(CreateTimerTool);
        registry.register(ListProcessesTool);
        registry.register(InspectProcessTool);
        registry
    }
}
```

### Tool Trait

```rust
#[async_trait]
pub trait Tool: Send + Sync {
    fn name(&self) -> &str;
    fn description(&self) -> &str;
    fn parameters(&self) -> JsonSchema;
    fn required_capabilities(&self) -> Vec<Capability>;

    async fn execute(
        &self,
        arguments: serde_json::Value,
        context: &ToolContext,
    ) -> Result<serde_json::Value, ToolError>;
}
```

### Tool Context

```rust
pub struct ToolContext {
    pub agent_id: AgentId,
    pub capabilities: Capabilities,
    pub runtime: RuntimeHandle,
}
```

### Tool Examples

```rust
pub struct SendMessageTool;

#[async_trait]
impl Tool for SendMessageTool {
    fn name(&self) -> &str { "process.send" }
    fn description(&self) -> &str { "Send a message to a process" }

    fn required_capabilities(&self) -> Vec<Capability> {
        vec![Capability::ProcessExecute]
    }

    fn parameters(&self) -> JsonSchema {
        json!({
            "type": "object",
            "properties": {
                "target": { "type": "string" },
                "message": { "type": "object" }
            },
            "required": ["target", "message"]
        })
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<serde_json::Value, ToolError> {
        let target: ProcessId = serde_json::from_value(args["target"])?;
        let message: serde_json::Value = args["message"].clone();

        // Check capability
        ctx.capabilities.require(&Capability::ProcessExecute)?;

        // Send message
        ctx.runtime.send(target, message).await?;

        Ok(json!({ "success": true }))
    }
}
```

## Task Execution

### Task

```rust
pub struct Task {
    pub task_id: MessageId,
    pub description: String,
    pub goal: String,
    pub constraints: Vec<String>,
    pub max_iterations: usize,
}
```

### Execution Loop

```rust
impl AgentProcess {
    async fn execute_task(&mut self, task: Task, ctx: &mut ProcessContext) -> Result<(), ProcessError> {
        self.state = AgentState::Thinking { task: task.clone() };

        let mut messages = vec![
            Message {
                role: Role::System,
                content: self.system_prompt(),
                tool_calls: None,
                tool_call_id: None,
            },
            Message {
                role: Role::User,
                content: task.description.clone(),
                tool_calls: None,
                tool_call_id: None,
            },
        ];

        for iteration in 0..task.max_iterations {
            // Get completion from model
            let completion = self.adapter.complete(&messages, &self.tool_definitions()).await?;

            // Handle tool calls
            if !completion.tool_calls.is_empty() {
                for tool_call in &completion.tool_calls {
                    // Check capabilities
                    let tool = self.tools.get(&tool_call.name)?;
                    ctx.capabilities.require(&tool.required_capabilities())?;

                    // Execute tool
                    self.state = AgentState::Executing {
                        action: ActionType::ExecuteCommand {
                            command_name: tool_call.name.clone(),
                        },
                    };

                    let result = tool.execute(tool_call.arguments.clone(), &self.tool_context(ctx)).await;

                    // Record action
                    self.context.history.push(AgentAction {
                        action_id: MessageId::new(),
                        action_type: ActionType::ExecuteCommand {
                            command_name: tool_call.name.clone(),
                        },
                        timestamp: Timestamp::now(),
                        result: match &result {
                            Ok(_) => ActionResult::Success {
                                output: serde_json::to_string(&result)?,
                            },
                            Err(e) => ActionResult::Failure {
                                error: e.to_string(),
                            },
                        },
                    });

                    // Add tool result to messages
                    messages.push(Message {
                        role: Role::Tool,
                        content: serde_json::to_string(&result)?,
                        tool_calls: None,
                        tool_call_id: Some(tool_call.id.clone()),
                    });
                }
            } else {
                // No tool calls — task complete
                if let Some(content) = completion.content {
                    // Output final response
                    ctx.send_response(content);
                }
                break;
            }
        }

        self.state = AgentState::Idle;
        Ok(())
    }
}
```

## Approval Flow

### Dangerous Operations

Some operations require explicit approval.

```rust
impl AgentProcess {
    async fn spawn_process(&mut self, config: ProcessConfig, ctx: &mut ProcessContext) -> Result<(), AgentError> {
        // Check capability
        self.capabilities.require(&Capability::ProcessSpawn)?;

        // Check if approval required
        if self.requires_approval(&config) {
            self.state = AgentState::WaitingForApproval {
                request_id: MessageId::new(),
            };

            // Request approval
            // ... wait for user decision
        } else {
            // Auto-approve
            ctx.runtime.spawn(config).await?;
        }

        Ok(())
    }

    fn requires_approval(&self, config: &ProcessConfig) -> bool {
        // Check if process type is sensitive
        config.sensitive
    }
}
```

## Audit

Every agent action is recorded.

```rust
pub struct AuditLog {
    entries: Vec<AuditEntry>,
}

pub struct AuditEntry {
    pub entry_id: MessageId,
    pub agent_id: AgentId,
    pub action: AuditAction,
    pub timestamp: Timestamp,
    pub context: AuditContext,
    pub result: AuditResult,
}

pub enum AuditAction {
    SendMessage { target: ProcessId },
    SpawnProcess { process_type: String },
    CreateTimer { duration: Duration },
    ExecuteCommand { command: String },
}

pub struct AuditContext {
    pub correlation_id: Option<CorrelationId>,
}

pub enum AuditResult {
    Success,
    Failure { error: String },
    Denied { capability: Capability },
}
```

## Observability

### Agent Metrics

```rust
pub struct AgentMetrics {
    pub tasks_completed: u64,
    pub tasks_failed: u64,
    pub tool_calls: u64,
    pub messages_sent: u64,
    pub processes_spawned: u64,
    pub approvals_requested: u64,
    pub approvals_granted: u64,
    pub approvals_denied: u64,
    pub average_task_duration: Duration,
}
```

### Tracing

```rust
#[instrument(skip(self, ctx), fields(agent_id = %self.id))]
async fn execute_task(&mut self, task: Task, ctx: &mut ProcessContext) -> Result<(), ProcessError> {
    // ...
}
```