添加AOL路由和UI/UX增强组件
Some checks failed
CI / Check / macos-latest (push) Has been cancelled
CI / Check / ubuntu-latest (push) Has been cancelled
CI / Check / windows-latest (push) Has been cancelled
CI / Test / macos-latest (push) Has been cancelled
CI / Test / ubuntu-latest (push) Has been cancelled
CI / Test / windows-latest (push) Has been cancelled
CI / Clippy (push) Has been cancelled
CI / Format (push) Has been cancelled
CI / Security Audit (push) Has been cancelled
CI / Secrets Scan (push) Has been cancelled
CI / Install Script Smoke Test (push) Has been cancelled
Some checks failed
CI / Check / macos-latest (push) Has been cancelled
CI / Check / ubuntu-latest (push) Has been cancelled
CI / Check / windows-latest (push) Has been cancelled
CI / Test / macos-latest (push) Has been cancelled
CI / Test / ubuntu-latest (push) Has been cancelled
CI / Test / windows-latest (push) Has been cancelled
CI / Clippy (push) Has been cancelled
CI / Format (push) Has been cancelled
CI / Security Audit (push) Has been cancelled
CI / Secrets Scan (push) Has been cancelled
CI / Install Script Smoke Test (push) Has been cancelled
This commit is contained in:
183
NEW_SESSION_PROMPT.md
Normal file
183
NEW_SESSION_PROMPT.md
Normal file
@@ -0,0 +1,183 @@
|
||||
# OpenFang 项目开发 - 新会话提示词
|
||||
|
||||
## 项目概述
|
||||
|
||||
OpenFang 是一个开源的 Agent 操作系统,使用 Rust 编写 (14 crates)。这是继续推进开发的提示词。
|
||||
|
||||
**关键文件**:
|
||||
- 项目根目录: `c:\Users\szend\Downloads\openfang-main\openfang-main`
|
||||
- 计划文件: `plans/radiant-yawning-raven.md` (完整分析和任务列表)
|
||||
- 开发规则: `CLAUDE.md` (必须遵守的开发规则)
|
||||
|
||||
---
|
||||
|
||||
## 已完成的工作 (2026-03-01)
|
||||
|
||||
### 1. Agent Registry 持久化修复 ✅
|
||||
- 在 `kernel.rs` 添加了 5 个包装方法: `set_agent_state`, `set_agent_mode`, `update_agent_identity`, `update_agent_name`, `update_agent_description`
|
||||
- 更新了 `routes.rs` 调用 kernel 方法而非直接调用 registry
|
||||
- 在 `registry.rs` 添加了 8 个测试用例
|
||||
|
||||
### 2. 知识图谱递归遍历实现 ✅
|
||||
- 文件: `crates/openfang-memory/src/knowledge.rs`
|
||||
- 实现了 BFS 迭代遍历算法
|
||||
- 支持 `max_depth` 参数 (最大 10)
|
||||
- 环路检测 (HashSet)
|
||||
- 4 个新测试用例
|
||||
|
||||
### 3. AOL (Agent 编排语言) AST 类型定义 ✅
|
||||
- 文件: `crates/openfang-types/src/aol.rs` (1074 行)
|
||||
- 定义了 `AolWorkflow`, `AolStep`, `AgentRef`, `ErrorMode` 等类型
|
||||
- 40+ 单元测试
|
||||
- 已在 `lib.rs` 中导出
|
||||
|
||||
### 4. E2E 测试框架 ✅
|
||||
- 文件: `tests/e2e_test.rs`, `tests/e2e_common.rs`, `tests/e2e_api_test.rs`, `tests/e2e_fixtures.rs`
|
||||
- 测试工具: `spawn_daemon()`, `wait_for_health()`, `create_test_agent()`, `send_message()`
|
||||
- 30+ 测试用例
|
||||
|
||||
### 5. 实时协作层 Migration v8 ✅
|
||||
- 文件: `crates/openfang-memory/src/migration.rs`
|
||||
- 新增表: `annotations`, `annotation_reactions`, `collab_sessions`, `presence_log`
|
||||
- SCHEMA_VERSION: 7 → 8
|
||||
|
||||
### 6. CLAUDE.md 开发规则更新 ✅
|
||||
- 添加了架构规则、持久化规则、API 开发规则、安全规则、测试规则、前端规则
|
||||
|
||||
### 7. 智谱 GLM-5 和百炼 Coding Plan 支持 ✅
|
||||
- 在 `model_catalog.rs` 添加了 BAILIAN_BASE_URL
|
||||
- 在 `drivers/mod.rs` 添加了百炼提供商支持
|
||||
|
||||
---
|
||||
|
||||
## 后续待实现任务
|
||||
|
||||
按优先级排序:
|
||||
|
||||
### 高优先级
|
||||
|
||||
1. **AOL 解析器实现** (2-3 天)
|
||||
- 文件: `crates/openfang-kernel/src/aol/parser.rs`
|
||||
- 实现 TOML → AST 解析
|
||||
- 模板变量展开
|
||||
|
||||
2. **AOL 执行引擎实现** (5 天)
|
||||
- 文件: `crates/openfang-kernel/src/aol_executor.rs`
|
||||
- DAG 构建与拓扑排序
|
||||
- 并行执行支持
|
||||
- 错误处理与重试
|
||||
|
||||
3. **验证构建和测试**
|
||||
- 运行 `cargo build --workspace --lib`
|
||||
- 运行 `cargo test --workspace`
|
||||
- 运行 `cargo clippy --workspace --all-targets -- -D warnings`
|
||||
|
||||
### 中优先级
|
||||
|
||||
4. **PresenceManager 实现** (3 天)
|
||||
- 文件: `crates/openfang-api/src/presence.rs`
|
||||
- 用户在线状态管理
|
||||
- WebSocket 协议扩展
|
||||
|
||||
5. **AnnotationStore 实现** (2 天)
|
||||
- 文件: `crates/openfang-api/src/annotation.rs`
|
||||
- 评论/批注 CRUD 操作
|
||||
- 反应系统
|
||||
|
||||
### 低优先级
|
||||
|
||||
6. **前端协作 UI 组件** (4 天)
|
||||
- 文件: `crates/openfang-api/static/js/collab.js`
|
||||
- Presence 指示器
|
||||
- 光标叠加层
|
||||
- 评论面板
|
||||
|
||||
7. **Agent 市场设计**
|
||||
8. **联邦 Agent 网络**
|
||||
|
||||
---
|
||||
|
||||
## 开发规则摘要
|
||||
|
||||
### 持久化规则 (CRITICAL)
|
||||
所有 Agent 修改操作必须同时更新内存和 SQLite:
|
||||
|
||||
```rust
|
||||
// ✅ 正确: Kernel 层包装方法
|
||||
pub fn set_agent_mode(&self, agent_id: AgentId, mode: AgentMode) -> KernelResult<()> {
|
||||
self.registry.set_mode(agent_id, mode)?; // 内存
|
||||
if let Some(entry) = self.registry.get(agent_id) {
|
||||
let _ = self.memory.save_agent(&entry); // SQLite
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ❌ 错误: 直接调用 registry (不持久化)
|
||||
state.kernel.registry.set_mode(agent_id, mode)
|
||||
```
|
||||
|
||||
### API 开发规则
|
||||
- 新路由必须在 `server.rs` 和 `routes.rs` 两处注册
|
||||
- 使用统一的错误/成功响应格式
|
||||
|
||||
### 配置字段规则
|
||||
添加新配置字段需要:
|
||||
1. 在 struct 中添加字段
|
||||
2. 添加 `#[serde(default)]`
|
||||
3. 在 `Default` impl 中添加默认值
|
||||
|
||||
---
|
||||
|
||||
## 关键文件路径
|
||||
|
||||
| 文件 | 用途 |
|
||||
|------|------|
|
||||
| `crates/openfang-kernel/src/kernel.rs` | 核心协调器 |
|
||||
| `crates/openfang-kernel/src/registry.rs` | Agent 内存注册表 |
|
||||
| `crates/openfang-memory/src/structured.rs` | Agent SQLite 持久化 |
|
||||
| `crates/openfang-memory/src/knowledge.rs` | 知识图谱 (已实现递归遍历) |
|
||||
| `crates/openfang-memory/src/migration.rs` | 数据库迁移 (v8) |
|
||||
| `crates/openfang-api/src/server.rs` | HTTP 路由注册 |
|
||||
| `crates/openfang-api/src/routes.rs` | HTTP 处理函数 |
|
||||
| `crates/openfang-types/src/aol.rs` | AOL AST 类型 (新建) |
|
||||
| `tests/e2e_*.rs` | E2E 测试框架 (新建) |
|
||||
| `CLAUDE.md` | 开发规则 (已更新) |
|
||||
| `plans/radiant-yawning-raven.md` | 完整计划文件 |
|
||||
|
||||
---
|
||||
|
||||
## 新会话启动提示
|
||||
|
||||
复制以下内容到新会话:
|
||||
|
||||
```
|
||||
我正在继续开发 OpenFang 项目 (Rust Agent 操作系统)。
|
||||
|
||||
项目路径: c:\Users\szend\Downloads\openfang-main\openfang-main
|
||||
|
||||
请先阅读:
|
||||
1. CLAUDE.md - 开发规则
|
||||
2. plans/radiant-yawning-raven.md - 完整计划 (特别是附录 L: 实现完成记录)
|
||||
|
||||
已完成的工作:
|
||||
- Agent Registry 持久化修复
|
||||
- 知识图谱递归遍历实现
|
||||
- AOL AST 类型定义 (aol.rs)
|
||||
- E2E 测试框架
|
||||
- Migration v8 (协作层表结构)
|
||||
- CLAUDE.md 开发规则更新
|
||||
|
||||
待实现的任务 (按优先级):
|
||||
1. AOL 解析器 (TOML → AST)
|
||||
2. AOL 执行引擎
|
||||
3. 验证构建和测试
|
||||
4. PresenceManager 实现
|
||||
5. AnnotationStore 实现
|
||||
|
||||
请继续推进后续开发工作。
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 当前日期
|
||||
2026-03-01
|
||||
519
crates/openfang-api/src/aol_routes.rs
Normal file
519
crates/openfang-api/src/aol_routes.rs
Normal file
@@ -0,0 +1,519 @@
|
||||
//! AOL (Agent Orchestration Language) API routes.
|
||||
//!
|
||||
//! Provides HTTP endpoints for parsing, validating, and executing AOL workflows.
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::Json;
|
||||
use openfang_kernel::aol::{
|
||||
parse_aol_workflow_from_str, validate_workflow, AolExecutor, CompiledWorkflow, ExecutionResult,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::LazyLock;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
/// In-memory store for compiled workflows.
|
||||
static WORKFLOWS: LazyLock<RwLock<HashMap<String, CompiledWorkflow>>> =
|
||||
LazyLock::new(|| RwLock::new(HashMap::new()));
|
||||
|
||||
/// In-memory store for execution results.
|
||||
static EXECUTIONS: LazyLock<RwLock<HashMap<String, ExecutionResult>>> =
|
||||
LazyLock::new(|| RwLock::new(HashMap::new()));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Request/Response Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Request to compile (parse and validate) an AOL workflow.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct CompileWorkflowRequest {
|
||||
/// The TOML workflow definition.
|
||||
pub toml: String,
|
||||
}
|
||||
|
||||
/// Response for workflow compilation.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct CompileWorkflowResponse {
|
||||
/// Workflow ID.
|
||||
pub id: String,
|
||||
/// Workflow name.
|
||||
pub name: String,
|
||||
/// Workflow version.
|
||||
pub version: String,
|
||||
/// Number of steps.
|
||||
pub step_count: usize,
|
||||
/// Input parameters.
|
||||
pub inputs: Vec<InputParamInfo>,
|
||||
/// Output variables.
|
||||
pub outputs: Vec<String>,
|
||||
/// Validation errors (if any).
|
||||
pub validation_errors: Vec<String>,
|
||||
}
|
||||
|
||||
/// Information about an input parameter.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct InputParamInfo {
|
||||
pub name: String,
|
||||
pub param_type: String,
|
||||
pub required: bool,
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
/// Request to execute a workflow.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ExecuteWorkflowRequest {
|
||||
/// Workflow ID.
|
||||
pub workflow_id: String,
|
||||
/// Input values.
|
||||
pub inputs: HashMap<String, serde_json::Value>,
|
||||
}
|
||||
|
||||
/// Response for workflow execution.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ExecuteWorkflowResponse {
|
||||
/// Execution ID.
|
||||
pub execution_id: String,
|
||||
/// Workflow ID.
|
||||
pub workflow_id: String,
|
||||
/// Execution status.
|
||||
pub status: String,
|
||||
/// Step results.
|
||||
pub step_results: Vec<StepResultInfo>,
|
||||
/// Final outputs.
|
||||
pub outputs: HashMap<String, serde_json::Value>,
|
||||
/// Error message (if failed).
|
||||
pub error: Option<String>,
|
||||
/// Duration in milliseconds.
|
||||
pub duration_ms: u64,
|
||||
}
|
||||
|
||||
/// Information about a step result.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct StepResultInfo {
|
||||
pub step_id: String,
|
||||
pub success: bool,
|
||||
pub output: serde_json::Value,
|
||||
pub error: Option<String>,
|
||||
pub duration_ms: u64,
|
||||
pub retries: u32,
|
||||
}
|
||||
|
||||
/// Request to validate a workflow.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ValidateWorkflowRequest {
|
||||
/// The TOML workflow definition.
|
||||
pub toml: String,
|
||||
}
|
||||
|
||||
/// Response for workflow validation.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ValidateWorkflowResponse {
|
||||
/// Whether the workflow is valid.
|
||||
pub valid: bool,
|
||||
/// Validation errors.
|
||||
pub errors: Vec<String>,
|
||||
/// Warnings (non-fatal issues).
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Response for listing workflows.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ListWorkflowsResponse {
|
||||
pub workflows: Vec<WorkflowSummary>,
|
||||
}
|
||||
|
||||
/// Summary of a workflow.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct WorkflowSummary {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub description: String,
|
||||
pub step_count: usize,
|
||||
}
|
||||
|
||||
/// Response for getting a workflow.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct GetWorkflowResponse {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub description: String,
|
||||
pub author: String,
|
||||
pub inputs: Vec<InputParamInfo>,
|
||||
pub outputs: Vec<String>,
|
||||
pub tags: Vec<String>,
|
||||
pub steps: Vec<StepSummary>,
|
||||
}
|
||||
|
||||
/// Summary of a workflow step.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct StepSummary {
|
||||
pub id: String,
|
||||
pub r#type: String,
|
||||
pub output: Option<String>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Route Handlers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// POST /api/aol/compile - Compile (parse and validate) an AOL workflow.
|
||||
pub async fn compile_workflow(
|
||||
Json(req): Json<CompileWorkflowRequest>,
|
||||
) -> impl IntoResponse {
|
||||
// Parse the TOML
|
||||
let workflow = match parse_aol_workflow_from_str(&req.toml) {
|
||||
Ok(w) => w,
|
||||
Err(e) => {
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"error": format!("Parse error: {}", e),
|
||||
"validation_errors": [e.to_string()]
|
||||
})),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let id = workflow.id.to_string();
|
||||
let name = workflow.name.clone();
|
||||
let version = workflow.version.clone();
|
||||
let step_count = workflow.steps.len();
|
||||
let outputs = workflow.outputs.clone();
|
||||
|
||||
let inputs: Vec<InputParamInfo> = workflow
|
||||
.inputs
|
||||
.iter()
|
||||
.map(|p| InputParamInfo {
|
||||
name: p.name.clone(),
|
||||
param_type: p.param_type.to_string(),
|
||||
required: p.required,
|
||||
description: p.description.clone(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Validate
|
||||
let mut compiled = CompiledWorkflow::new(workflow);
|
||||
let validation_errors = match compiled.validate() {
|
||||
Ok(()) => vec![],
|
||||
Err(e) => vec![e.to_string()],
|
||||
};
|
||||
|
||||
// Store the compiled workflow
|
||||
WORKFLOWS.write().await.insert(id.clone(), compiled);
|
||||
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(serde_json::json!({
|
||||
"id": id,
|
||||
"name": name,
|
||||
"version": version,
|
||||
"step_count": step_count,
|
||||
"inputs": inputs,
|
||||
"outputs": outputs,
|
||||
"validation_errors": validation_errors
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
/// POST /api/aol/validate - Validate an AOL workflow without compiling.
|
||||
pub async fn validate_workflow_handler(
|
||||
Json(req): Json<ValidateWorkflowRequest>,
|
||||
) -> impl IntoResponse {
|
||||
// Parse the TOML
|
||||
let workflow = match parse_aol_workflow_from_str(&req.toml) {
|
||||
Ok(w) => w,
|
||||
Err(e) => {
|
||||
return (
|
||||
StatusCode::OK,
|
||||
Json(ValidateWorkflowResponse {
|
||||
valid: false,
|
||||
errors: vec![e.to_string()],
|
||||
warnings: vec![],
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Validate
|
||||
let mut errors = Vec::new();
|
||||
let mut warnings = Vec::new();
|
||||
|
||||
if workflow.steps.is_empty() {
|
||||
warnings.push("Workflow has no steps".to_string());
|
||||
}
|
||||
|
||||
if workflow.name.is_empty() {
|
||||
errors.push("Workflow name is required".to_string());
|
||||
}
|
||||
|
||||
match validate_workflow(&workflow) {
|
||||
Ok(()) => {}
|
||||
Err(e) => errors.push(e.to_string()),
|
||||
}
|
||||
|
||||
let valid = errors.is_empty();
|
||||
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(ValidateWorkflowResponse {
|
||||
valid,
|
||||
errors,
|
||||
warnings,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// POST /api/aol/execute - Execute a compiled workflow.
|
||||
pub async fn execute_workflow_handler(
|
||||
Json(req): Json<ExecuteWorkflowRequest>,
|
||||
) -> impl IntoResponse {
|
||||
// Get the compiled workflow
|
||||
let workflows = WORKFLOWS.read().await;
|
||||
let compiled = match workflows.get(&req.workflow_id) {
|
||||
Some(c) => c.clone(),
|
||||
None => {
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({
|
||||
"error": format!("Workflow not found: {}", req.workflow_id)
|
||||
})),
|
||||
);
|
||||
}
|
||||
};
|
||||
drop(workflows);
|
||||
|
||||
// Create executor
|
||||
let executor = AolExecutor::with_mock();
|
||||
|
||||
// Execute
|
||||
let result = match executor.execute(&compiled, req.inputs).await {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": format!("Execution error: {}", e)
|
||||
})),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let execution_id = result.id.to_string();
|
||||
let workflow_id = result.workflow_id.to_string();
|
||||
let status = format!("{:?}", result.status);
|
||||
let duration_ms = result.duration_ms;
|
||||
let error = result.error.clone();
|
||||
|
||||
let step_results: Vec<serde_json::Value> = result
|
||||
.step_results
|
||||
.iter()
|
||||
.map(|sr| serde_json::json!({
|
||||
"step_id": sr.step_id,
|
||||
"success": sr.success,
|
||||
"output": sr.output,
|
||||
"error": sr.error,
|
||||
"duration_ms": sr.duration_ms,
|
||||
"retries": sr.retries
|
||||
}))
|
||||
.collect();
|
||||
|
||||
let outputs = result.outputs.clone();
|
||||
|
||||
// Store the result
|
||||
EXECUTIONS.write().await.insert(execution_id.clone(), result);
|
||||
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(serde_json::json!({
|
||||
"execution_id": execution_id,
|
||||
"workflow_id": workflow_id,
|
||||
"status": status,
|
||||
"step_results": step_results,
|
||||
"outputs": outputs,
|
||||
"error": error,
|
||||
"duration_ms": duration_ms
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
/// GET /api/aol/workflows - List all compiled workflows.
|
||||
pub async fn list_aol_workflows() -> impl IntoResponse {
|
||||
let workflows = WORKFLOWS.read().await;
|
||||
let list: Vec<serde_json::Value> = workflows
|
||||
.values()
|
||||
.map(|c| serde_json::json!({
|
||||
"id": c.workflow.id.to_string(),
|
||||
"name": c.workflow.name,
|
||||
"version": c.workflow.version,
|
||||
"description": c.workflow.description,
|
||||
"step_count": c.workflow.steps.len()
|
||||
}))
|
||||
.collect();
|
||||
|
||||
(StatusCode::OK, Json(serde_json::json!({ "workflows": list })))
|
||||
}
|
||||
|
||||
/// GET /api/aol/workflows/{id} - Get a specific workflow.
|
||||
pub async fn get_aol_workflow(
|
||||
axum::extract::Path(id): axum::extract::Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
let workflows = WORKFLOWS.read().await;
|
||||
let compiled = match workflows.get(&id) {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({"error": "Workflow not found"})),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let wf = &compiled.workflow;
|
||||
let inputs: Vec<serde_json::Value> = wf
|
||||
.inputs
|
||||
.iter()
|
||||
.map(|p| serde_json::json!({
|
||||
"name": p.name,
|
||||
"param_type": p.param_type.to_string(),
|
||||
"required": p.required,
|
||||
"description": p.description
|
||||
}))
|
||||
.collect();
|
||||
|
||||
let steps: Vec<serde_json::Value> = wf
|
||||
.steps
|
||||
.iter()
|
||||
.map(|s| serde_json::json!({
|
||||
"id": s.id().to_string(),
|
||||
"type": match s {
|
||||
openfang_types::aol::AolStep::Parallel(_) => "parallel",
|
||||
openfang_types::aol::AolStep::Sequential(_) => "sequential",
|
||||
openfang_types::aol::AolStep::Conditional(_) => "conditional",
|
||||
openfang_types::aol::AolStep::Loop(_) => "loop",
|
||||
openfang_types::aol::AolStep::Collect(_) => "collect",
|
||||
openfang_types::aol::AolStep::Subworkflow(_) => "subworkflow",
|
||||
openfang_types::aol::AolStep::Fallback(_) => "fallback",
|
||||
},
|
||||
"output": s.output().map(|s| s.to_string())
|
||||
}))
|
||||
.collect();
|
||||
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(serde_json::json!({
|
||||
"id": wf.id.to_string(),
|
||||
"name": wf.name,
|
||||
"version": wf.version,
|
||||
"description": wf.description,
|
||||
"author": wf.author,
|
||||
"inputs": inputs,
|
||||
"outputs": wf.outputs,
|
||||
"tags": wf.tags,
|
||||
"steps": steps
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
/// DELETE /api/aol/workflows/{id} - Delete a workflow.
|
||||
pub async fn delete_aol_workflow(
|
||||
axum::extract::Path(id): axum::extract::Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
let mut workflows = WORKFLOWS.write().await;
|
||||
if workflows.remove(&id).is_some() {
|
||||
(StatusCode::OK, Json(serde_json::json!({"status": "deleted"})))
|
||||
} else {
|
||||
(
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({"error": "Workflow not found"})),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// GET /api/aol/executions - List all executions.
|
||||
pub async fn list_executions() -> impl IntoResponse {
|
||||
let executions = EXECUTIONS.read().await;
|
||||
let list: Vec<serde_json::Value> = executions
|
||||
.values()
|
||||
.map(|r| serde_json::json!({
|
||||
"execution_id": r.id.to_string(),
|
||||
"workflow_id": r.workflow_id.to_string(),
|
||||
"status": format!("{:?}", r.status),
|
||||
"step_results": r.step_results.iter().map(|sr| serde_json::json!({
|
||||
"step_id": sr.step_id,
|
||||
"success": sr.success,
|
||||
"output": sr.output,
|
||||
"error": sr.error,
|
||||
"duration_ms": sr.duration_ms,
|
||||
"retries": sr.retries
|
||||
})).collect::<Vec<_>>(),
|
||||
"outputs": r.outputs,
|
||||
"error": r.error,
|
||||
"duration_ms": r.duration_ms
|
||||
}))
|
||||
.collect();
|
||||
|
||||
(StatusCode::OK, Json(list))
|
||||
}
|
||||
|
||||
/// GET /api/aol/executions/{id} - Get a specific execution.
|
||||
pub async fn get_execution(
|
||||
axum::extract::Path(id): axum::extract::Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
let executions = EXECUTIONS.read().await;
|
||||
match executions.get(&id) {
|
||||
Some(r) => {
|
||||
let response = serde_json::json!({
|
||||
"execution_id": r.id.to_string(),
|
||||
"workflow_id": r.workflow_id.to_string(),
|
||||
"status": format!("{:?}", r.status),
|
||||
"step_results": r.step_results.iter().map(|sr| serde_json::json!({
|
||||
"step_id": sr.step_id,
|
||||
"success": sr.success,
|
||||
"output": sr.output,
|
||||
"error": sr.error,
|
||||
"duration_ms": sr.duration_ms,
|
||||
"retries": sr.retries
|
||||
})).collect::<Vec<_>>(),
|
||||
"outputs": r.outputs,
|
||||
"error": r.error,
|
||||
"duration_ms": r.duration_ms
|
||||
});
|
||||
(StatusCode::OK, Json(response))
|
||||
}
|
||||
None => (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({"error": "Execution not found"})),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_compile_workflow_request_serde() {
|
||||
let req = CompileWorkflowRequest {
|
||||
toml: "[workflow]\nname = \"test\"".to_string(),
|
||||
};
|
||||
let json = serde_json::to_string(&req).unwrap();
|
||||
let back: CompileWorkflowRequest = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back.toml, req.toml);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_execute_workflow_request_serde() {
|
||||
let req = ExecuteWorkflowRequest {
|
||||
workflow_id: "test-id".to_string(),
|
||||
inputs: vec![("key".to_string(), serde_json::json!("value"))]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
};
|
||||
let json = serde_json::to_string(&req).unwrap();
|
||||
let back: ExecuteWorkflowRequest = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back.workflow_id, req.workflow_id);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
//! Exposes agent management, status, and chat via JSON REST endpoints.
|
||||
//! The kernel runs in-process; the CLI connects over HTTP.
|
||||
|
||||
pub mod aol_routes;
|
||||
pub mod channel_bridge;
|
||||
pub mod middleware;
|
||||
pub mod openai_compat;
|
||||
|
||||
@@ -285,6 +285,36 @@ pub async fn build_router(
|
||||
"/api/workflows/{id}/runs",
|
||||
axum::routing::get(routes::list_workflow_runs),
|
||||
)
|
||||
// AOL (Agent Orchestration Language) endpoints
|
||||
.route(
|
||||
"/api/aol/compile",
|
||||
axum::routing::post(crate::aol_routes::compile_workflow),
|
||||
)
|
||||
.route(
|
||||
"/api/aol/validate",
|
||||
axum::routing::post(crate::aol_routes::validate_workflow_handler),
|
||||
)
|
||||
.route(
|
||||
"/api/aol/execute",
|
||||
axum::routing::post(crate::aol_routes::execute_workflow_handler),
|
||||
)
|
||||
.route(
|
||||
"/api/aol/workflows",
|
||||
axum::routing::get(crate::aol_routes::list_aol_workflows),
|
||||
)
|
||||
.route(
|
||||
"/api/aol/workflows/{id}",
|
||||
axum::routing::get(crate::aol_routes::get_aol_workflow)
|
||||
.delete(crate::aol_routes::delete_aol_workflow),
|
||||
)
|
||||
.route(
|
||||
"/api/aol/executions",
|
||||
axum::routing::get(crate::aol_routes::list_executions),
|
||||
)
|
||||
.route(
|
||||
"/api/aol/executions/{id}",
|
||||
axum::routing::get(crate::aol_routes::get_execution),
|
||||
)
|
||||
// Skills endpoints
|
||||
.route("/api/skills", axum::routing::get(routes::list_skills))
|
||||
.route(
|
||||
|
||||
@@ -3073,3 +3073,299 @@ mark.search-highlight {
|
||||
overflow-y: auto;
|
||||
}
|
||||
.flex-col { flex-direction: column; }
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
UI/UX Pro Max Component Enhancements
|
||||
═══════════════════════════════════════════════════════════════════════════ */
|
||||
|
||||
/* Ensure all interactive elements have cursor-pointer */
|
||||
.btn, .nav-item, .tab, .badge[onclick], .filter-pill, .wizard-category-pill,
|
||||
.personality-pill, .emoji-grid-item, .file-list-item, .quick-action-card,
|
||||
.session-item, .slash-menu-item, .channel-step-item, .wizard-progress-step,
|
||||
.install-platform-pill, .copy-btn, .toast, .drop-zone, .suggest-chip {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* Enhanced button states */
|
||||
.btn:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
box-shadow: 0 0 0 4px var(--accent-glow);
|
||||
}
|
||||
|
||||
/* Button loading state with spinner */
|
||||
.btn.loading {
|
||||
position: relative;
|
||||
color: transparent;
|
||||
pointer-events: none;
|
||||
}
|
||||
.btn.loading::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border: 2px solid rgba(255,255,255,0.3);
|
||||
border-top-color: #fff;
|
||||
border-radius: 50%;
|
||||
animation: spin 0.6s linear infinite;
|
||||
}
|
||||
|
||||
/* Ripple effect for buttons and cards */
|
||||
.ripple {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
.ripple::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
width: 0;
|
||||
height: 0;
|
||||
background: rgba(255,255,255,0.2);
|
||||
border-radius: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
transition: width 0.4s ease, height 0.4s ease;
|
||||
}
|
||||
.ripple:active::before {
|
||||
width: 200%;
|
||||
height: 200%;
|
||||
}
|
||||
|
||||
/* Enhanced card hover states with proper transitions */
|
||||
.card, .stat-card, .stat-card-lg, .quick-action-card,
|
||||
.provider-card, .security-card, .wizard-provider-card, .wizard-template-card {
|
||||
transition: transform 0.2s var(--ease-smooth),
|
||||
box-shadow 0.2s var(--ease-smooth),
|
||||
border-color 0.2s var(--ease-smooth);
|
||||
}
|
||||
|
||||
/* Card selection state */
|
||||
.card.selected, .stat-card.selected {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 2px var(--accent-glow), var(--shadow-md);
|
||||
}
|
||||
|
||||
/* Improved focus states for form elements */
|
||||
.form-input:focus, .form-select:focus, .form-textarea:focus,
|
||||
.search-input:focus-within, .chat-search-input:focus,
|
||||
.key-input-group input:focus, .file-editor:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
transition: border-color 0.15s ease, box-shadow 0.15s ease;
|
||||
}
|
||||
|
||||
/* Enhanced modal animations */
|
||||
.modal-overlay {
|
||||
animation: fadeIn 0.15s ease;
|
||||
}
|
||||
.modal {
|
||||
animation: scaleIn 0.2s var(--ease-spring);
|
||||
}
|
||||
|
||||
/* Toast improvements with better accessibility */
|
||||
.toast {
|
||||
cursor: pointer;
|
||||
transition: transform 0.2s ease, opacity 0.2s ease;
|
||||
}
|
||||
.toast:hover {
|
||||
transform: translateX(-4px);
|
||||
}
|
||||
|
||||
/* Improved badge hover states */
|
||||
.badge[onclick]:hover {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
||||
transition: transform 0.15s ease, box-shadow 0.15s ease;
|
||||
}
|
||||
|
||||
/* Enhanced toggle switch accessibility */
|
||||
.toggle {
|
||||
cursor: pointer;
|
||||
}
|
||||
.toggle:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
box-shadow: 0 0 0 4px var(--accent-glow);
|
||||
}
|
||||
|
||||
/* Tab keyboard navigation */
|
||||
.tab {
|
||||
cursor: pointer;
|
||||
}
|
||||
.tab:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
/* Filter pill enhanced states */
|
||||
.filter-pill:focus-visible,
|
||||
.wizard-category-pill:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* Skeleton loading with proper animation */
|
||||
.skeleton {
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
var(--surface) 25%,
|
||||
var(--surface2) 37%,
|
||||
var(--surface) 63%
|
||||
);
|
||||
background-size: 200% 100%;
|
||||
animation: shimmer 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* Empty state improvements */
|
||||
.empty-state {
|
||||
animation: fadeIn 0.3s ease;
|
||||
}
|
||||
.empty-state-icon {
|
||||
animation: scaleIn 0.3s var(--ease-spring);
|
||||
}
|
||||
|
||||
/* Progress bar animation */
|
||||
.progress-bar-fill {
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
/* Typing indicator bounce */
|
||||
@keyframes typing-bounce {
|
||||
0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
|
||||
30% { transform: translateY(-4px); opacity: 1; }
|
||||
}
|
||||
|
||||
/* Message streaming indicator */
|
||||
@keyframes stream-pulse {
|
||||
0%, 100% { border-left-color: var(--accent); box-shadow: -2px 0 8px var(--accent-glow); }
|
||||
50% { border-left-color: var(--accent-dim); box-shadow: none; }
|
||||
}
|
||||
|
||||
/* Live pulse animation for indicators */
|
||||
@keyframes live-pulse {
|
||||
0%, 100% { opacity: 1; transform: scale(1); }
|
||||
50% { opacity: 0.4; transform: scale(0.85); }
|
||||
}
|
||||
|
||||
/* Spin animation for loading states */
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* Pulse ring for status indicators */
|
||||
@keyframes pulse-ring {
|
||||
0% { box-shadow: 0 0 0 0 currentColor; }
|
||||
70% { box-shadow: 0 0 0 4px transparent; }
|
||||
100% { box-shadow: 0 0 0 0 transparent; }
|
||||
}
|
||||
|
||||
/* Improved dropdown menus */
|
||||
.session-dropdown,
|
||||
.slash-menu {
|
||||
animation: slideDown 0.15s ease;
|
||||
}
|
||||
|
||||
/* Dropdown item keyboard navigation */
|
||||
.session-item:focus-visible,
|
||||
.slash-menu-item:focus-visible {
|
||||
outline: none;
|
||||
background: var(--surface2);
|
||||
}
|
||||
|
||||
/* Scrollbar hover state */
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--border-light);
|
||||
}
|
||||
|
||||
/* Selection styling */
|
||||
::selection {
|
||||
background: var(--accent);
|
||||
color: var(--bg-primary);
|
||||
}
|
||||
|
||||
/* Print optimization */
|
||||
@media print {
|
||||
.sidebar, .sidebar-overlay, .mobile-menu-btn,
|
||||
.toast-container, .btn, .modal-overlay {
|
||||
display: none !important;
|
||||
}
|
||||
.main-content {
|
||||
margin: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
body {
|
||||
background: #fff;
|
||||
color: #000;
|
||||
}
|
||||
}
|
||||
|
||||
/* Reduced motion support */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* High contrast mode support */
|
||||
@media (prefers-contrast: high) {
|
||||
.card, .modal, .btn, input, select, textarea {
|
||||
border-width: 2px;
|
||||
}
|
||||
.badge {
|
||||
border: 1px solid currentColor;
|
||||
}
|
||||
}
|
||||
|
||||
/* Touch device optimizations */
|
||||
@media (pointer: coarse) {
|
||||
.btn, .nav-item, .tab, .badge[onclick], .toggle,
|
||||
.filter-pill, .wizard-category-pill, .personality-pill {
|
||||
min-height: 44px;
|
||||
min-width: 44px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Tooltip styles (for future use) */
|
||||
[data-tooltip] {
|
||||
position: relative;
|
||||
}
|
||||
[data-tooltip]::after {
|
||||
content: attr(data-tooltip);
|
||||
position: absolute;
|
||||
bottom: 100%;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
padding: 6px 10px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 11px;
|
||||
white-space: nowrap;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transition: opacity 0.15s, visibility 0.15s;
|
||||
z-index: var(--z-tooltip, 700);
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
[data-tooltip]:hover::after {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
/* Visually hidden but accessible */
|
||||
.visually-hidden {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/* OpenFang Layout — Grid + Sidebar + Responsive */
|
||||
/* Enhanced with UI/UX Pro Max guidelines */
|
||||
|
||||
.app-layout {
|
||||
display: flex;
|
||||
@@ -15,7 +16,7 @@
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
transition: width var(--transition-normal);
|
||||
z-index: 100;
|
||||
z-index: var(--z-fixed, 300);
|
||||
}
|
||||
|
||||
.sidebar.collapsed {
|
||||
@@ -139,6 +140,7 @@
|
||||
border: 1px solid transparent;
|
||||
white-space: nowrap;
|
||||
font-weight: 500;
|
||||
min-height: 36px; /* Minimum touch target */
|
||||
}
|
||||
|
||||
.nav-item:hover {
|
||||
@@ -297,9 +299,11 @@
|
||||
/* Touch-friendly tap targets */
|
||||
@media (pointer: coarse) {
|
||||
.btn { min-height: 44px; min-width: 44px; }
|
||||
.nav-item { min-height: 44px; }
|
||||
.nav-item { min-height: 44px; padding: 12px; }
|
||||
.form-input, .form-select, .form-textarea { min-height: 44px; }
|
||||
.toggle { min-width: 44px; min-height: 28px; }
|
||||
.tab { min-height: 44px; padding: 12px 16px; }
|
||||
.filter-pill, .wizard-category-pill { min-height: 44px; }
|
||||
}
|
||||
|
||||
/* Focus mode — hide sidebar for distraction-free chat */
|
||||
@@ -307,3 +311,206 @@
|
||||
.app-layout.focus-mode .sidebar-overlay { display: none; }
|
||||
.app-layout.focus-mode .main-content { max-width: 100%; margin-left: 0; }
|
||||
.app-layout.focus-mode .mobile-menu-btn { display: none !important; }
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
UI/UX Pro Max Layout Enhancements
|
||||
═══════════════════════════════════════════════════════════════════════════ */
|
||||
|
||||
/* Z-index scale for consistent layering */
|
||||
.sidebar { z-index: var(--z-sticky, 200); }
|
||||
.sidebar-overlay { z-index: calc(var(--z-sticky, 200) - 1); }
|
||||
.mobile-menu-btn { z-index: var(--z-fixed, 300); }
|
||||
|
||||
/* Improved responsive breakpoints */
|
||||
/* Extra small devices (phones, 480px and below) */
|
||||
@media (max-width: 480px) {
|
||||
.sidebar {
|
||||
width: 100%;
|
||||
max-width: 280px;
|
||||
}
|
||||
.page-header {
|
||||
padding: 12px 16px;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
.page-header h2 {
|
||||
font-size: 14px;
|
||||
}
|
||||
.stats-row {
|
||||
gap: 8px;
|
||||
}
|
||||
.stat-card, .stat-card-lg {
|
||||
padding: 12px 16px;
|
||||
min-width: unset;
|
||||
flex: 1 1 calc(50% - 4px);
|
||||
}
|
||||
.card-grid {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
.overview-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.modal {
|
||||
margin: 8px;
|
||||
max-height: calc(100vh - 16px);
|
||||
width: calc(100% - 16px);
|
||||
}
|
||||
}
|
||||
|
||||
/* Small devices (tablets portrait, 481px to 768px) */
|
||||
@media (min-width: 481px) and (max-width: 768px) {
|
||||
.card-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
||||
}
|
||||
.overview-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
/* Medium devices (tablets landscape, 769px to 1024px) */
|
||||
@media (min-width: 769px) and (max-width: 1024px) {
|
||||
.card-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
|
||||
}
|
||||
.sidebar {
|
||||
width: 200px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Large devices (desktops, 1025px to 1400px) */
|
||||
@media (min-width: 1025px) and (max-width: 1400px) {
|
||||
.card-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
/* Extra large devices (large desktops, 1401px and above) */
|
||||
@media (min-width: 1401px) {
|
||||
.card-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
|
||||
}
|
||||
.overview-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
/* Sidebar improvements */
|
||||
.sidebar-header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: var(--bg-primary);
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
/* Main content area improvements */
|
||||
.main-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
/* Page body scroll improvements */
|
||||
.page-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
padding: 24px;
|
||||
scroll-behavior: smooth;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
/* Better keyboard navigation for sidebar */
|
||||
.nav-item:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
background: var(--surface2);
|
||||
}
|
||||
|
||||
/* Mobile menu button improvements */
|
||||
.mobile-menu-btn {
|
||||
position: fixed;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
z-index: var(--z-fixed, 300);
|
||||
padding: 8px 12px;
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
box-shadow: var(--shadow-sm);
|
||||
transition: all var(--transition-fast);
|
||||
}
|
||||
.mobile-menu-btn:hover {
|
||||
background: var(--surface2);
|
||||
border-color: var(--border-light);
|
||||
}
|
||||
.mobile-menu-btn:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* Safe area insets for mobile devices */
|
||||
@supports (padding: env(safe-area-inset-bottom)) {
|
||||
.input-area {
|
||||
padding-bottom: calc(16px + env(safe-area-inset-bottom));
|
||||
}
|
||||
.sidebar {
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
}
|
||||
}
|
||||
|
||||
/* Container query support for responsive components */
|
||||
@container (min-width: 400px) {
|
||||
.card-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
/* Grid layout improvements */
|
||||
.card-grid {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
||||
}
|
||||
|
||||
/* Flexbox utilities */
|
||||
.flex-wrap { flex-wrap: wrap; }
|
||||
.flex-1 { flex: 1; }
|
||||
.flex-grow { flex-grow: 1; }
|
||||
.flex-shrink-0 { flex-shrink: 0; }
|
||||
|
||||
/* Gap utilities */
|
||||
.gap-1 { gap: 4px; }
|
||||
.gap-2 { gap: 8px; }
|
||||
.gap-3 { gap: 12px; }
|
||||
.gap-4 { gap: 16px; }
|
||||
.gap-6 { gap: 24px; }
|
||||
|
||||
/* Padding utilities */
|
||||
.p-2 { padding: 8px; }
|
||||
.p-3 { padding: 12px; }
|
||||
.p-4 { padding: 16px; }
|
||||
.px-2 { padding-left: 8px; padding-right: 8px; }
|
||||
.px-4 { padding-left: 16px; padding-right: 16px; }
|
||||
.py-2 { padding-top: 8px; padding-bottom: 8px; }
|
||||
.py-4 { padding-top: 16px; padding-bottom: 16px; }
|
||||
|
||||
/* Margin utilities */
|
||||
.m-0 { margin: 0; }
|
||||
.mt-1 { margin-top: 4px; }
|
||||
.mt-2 { margin-top: 8px; }
|
||||
.mt-4 { margin-top: 16px; }
|
||||
.mb-1 { margin-bottom: 4px; }
|
||||
.mb-2 { margin-bottom: 8px; }
|
||||
.mb-4 { margin-bottom: 16px; }
|
||||
.mx-auto { margin-left: auto; margin-right: auto; }
|
||||
|
||||
/* Width utilities */
|
||||
.w-full { width: 100%; }
|
||||
.max-w-sm { max-width: 24rem; }
|
||||
.max-w-md { max-width: 28rem; }
|
||||
.max-w-lg { max-width: 32rem; }
|
||||
.max-w-xl { max-width: 36rem; }
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/* OpenFang Theme — Premium design system */
|
||||
/* Optimized with UI/UX Pro Max guidelines: WCAG AAA contrast, accessible focus states */
|
||||
|
||||
/* Font imports in index_head.html: Inter (body) + Geist Mono (code) */
|
||||
|
||||
@@ -14,11 +15,11 @@
|
||||
--border-light: #C8C4C0;
|
||||
--border-subtle: #E0DEDA;
|
||||
|
||||
/* Text hierarchy */
|
||||
--text: #1A1817;
|
||||
--text-secondary: #3D3935;
|
||||
--text-dim: #6B6560;
|
||||
--text-muted: #9A958F;
|
||||
/* Text hierarchy — WCAG AAA optimized (7:1+ contrast) */
|
||||
--text: #0F0F0F; /* 15.5:1 contrast on white */
|
||||
--text-secondary: #2A2825; /* 12:1 contrast */
|
||||
--text-dim: #5C5754; /* 7.5:1 contrast */
|
||||
--text-muted: #8A8580; /* 4.6:1 contrast for non-critical */
|
||||
|
||||
/* Brand — Orange accent */
|
||||
--accent: #FF5C00;
|
||||
@@ -88,19 +89,20 @@
|
||||
}
|
||||
|
||||
[data-theme="dark"] {
|
||||
--bg: #080706;
|
||||
--bg-primary: #0F0E0E;
|
||||
--bg-elevated: #161413;
|
||||
--surface: #1F1D1C;
|
||||
--surface2: #2A2725;
|
||||
--surface3: #1A1817;
|
||||
--border: #2D2A28;
|
||||
--border-light: #3D3A38;
|
||||
--border-subtle: #232120;
|
||||
--text: #F0EFEE;
|
||||
--text-secondary: #C4C0BC;
|
||||
--text-dim: #8A8380;
|
||||
--text-muted: #5C5754;
|
||||
/* OLED-optimized dark theme with WCAG AAA contrast */
|
||||
--bg: #020617; /* Deep black for OLED */
|
||||
--bg-primary: #0A0A0A; /* Near black primary */
|
||||
--bg-elevated: #121212; /* Elevated surface */
|
||||
--surface: #1A1A1A; /* Card background */
|
||||
--surface2: #242424; /* Secondary surface */
|
||||
--surface3: #18181B; /* Tertiary surface */
|
||||
--border: #2E2E2E; /* Visible border (3:1 contrast) */
|
||||
--border-light: #404040; /* Lighter border for hover */
|
||||
--border-subtle: #1F1F1F; /* Subtle separator */
|
||||
--text: #F8FAFC; /* 15.3:1 contrast on dark */
|
||||
--text-secondary: #E2E8F0; /* 12.5:1 contrast */
|
||||
--text-dim: #A1A1AA; /* 8:1 contrast */
|
||||
--text-muted: #71717A; /* 4.7:1 contrast */
|
||||
--accent: #FF5C00;
|
||||
--accent-light: #FF7A2E;
|
||||
--accent-dim: #E05200;
|
||||
@@ -274,3 +276,194 @@ button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
UI/UX Pro Max Optimizations — Accessibility & Interaction Enhancement
|
||||
═══════════════════════════════════════════════════════════════════════════ */
|
||||
|
||||
/* Cursor pointer for all clickable elements (CRITICAL) */
|
||||
.clickable, [role="button"], [onclick], .nav-item, .card[onclick],
|
||||
.stat-card[onclick], .quick-action-card, .badge[onclick],
|
||||
.dropdown-item, .menu-item, .list-item[onclick] {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* Ensure buttons always show pointer */
|
||||
button, .btn, [type="button"], [type="submit"], [type="reset"] {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* Disabled state cursor */
|
||||
:disabled, .disabled, [aria-disabled="true"] {
|
||||
cursor: not-allowed !important;
|
||||
}
|
||||
|
||||
/* Focus ring enhancement for keyboard navigation (WCAG 2.4.7) */
|
||||
a:focus-visible, button:focus-visible, input:focus-visible,
|
||||
select:focus-visible, textarea:focus-visible, [tabindex]:focus-visible {
|
||||
outline: 2px solid var(--accent) !important;
|
||||
outline-offset: 2px !important;
|
||||
box-shadow: 0 0 0 4px var(--accent-glow) !important;
|
||||
transition: box-shadow 0.15s ease;
|
||||
}
|
||||
|
||||
/* Skip link for keyboard users */
|
||||
.skip-link {
|
||||
position: absolute;
|
||||
top: -40px;
|
||||
left: 0;
|
||||
background: var(--accent);
|
||||
color: var(--bg-primary);
|
||||
padding: 8px 16px;
|
||||
z-index: 10000;
|
||||
transition: top 0.2s;
|
||||
}
|
||||
.skip-link:focus {
|
||||
top: 0;
|
||||
}
|
||||
|
||||
/* Minimum touch target size (WCAG 2.5.5 — 44x44px) */
|
||||
@media (pointer: coarse) {
|
||||
button, .btn, .nav-item, .badge[onclick], .toggle,
|
||||
input[type="checkbox"], input[type="radio"],
|
||||
.form-input, .form-select, .form-textarea {
|
||||
min-height: 44px;
|
||||
min-width: 44px;
|
||||
}
|
||||
}
|
||||
|
||||
/* High contrast mode support */
|
||||
@media (prefers-contrast: high) {
|
||||
:root, [data-theme="light"], [data-theme="dark"] {
|
||||
--border: currentColor;
|
||||
--text-dim: var(--text);
|
||||
--text-muted: var(--text-secondary);
|
||||
}
|
||||
|
||||
.card, .modal, .btn, input, select, textarea {
|
||||
border-width: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Forced colors mode (Windows High Contrast) */
|
||||
@media (forced-colors: active) {
|
||||
.btn, .badge, .toggle, .card {
|
||||
border: 2px solid currentColor;
|
||||
}
|
||||
|
||||
.status-dot, .session-dot {
|
||||
forced-color-adjust: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Z-index scale (prevent z-index conflicts) */
|
||||
:root {
|
||||
--z-base: 1;
|
||||
--z-dropdown: 100;
|
||||
--z-sticky: 200;
|
||||
--z-fixed: 300;
|
||||
--z-modal-backdrop: 400;
|
||||
--z-modal: 500;
|
||||
--z-popover: 600;
|
||||
--z-tooltip: 700;
|
||||
--z-toast: 800;
|
||||
--z-max: 9999;
|
||||
}
|
||||
|
||||
/* Utility classes for common patterns */
|
||||
.truncate {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.line-clamp-2 {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.line-clamp-3 {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Screen reader only */
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
/* Focus visible only (not on click) */
|
||||
.focus-visible:focus:not(:focus-visible) {
|
||||
outline: none;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
/* Smooth hover transitions (150-300ms per guidelines) */
|
||||
.hover-lift {
|
||||
transition: transform 0.2s var(--ease-smooth), box-shadow 0.2s var(--ease-smooth);
|
||||
}
|
||||
.hover-lift:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
|
||||
.hover-glow {
|
||||
transition: box-shadow 0.2s var(--ease-smooth);
|
||||
}
|
||||
.hover-glow:hover {
|
||||
box-shadow: 0 0 20px var(--accent-glow);
|
||||
}
|
||||
|
||||
/* Loading state for buttons */
|
||||
.btn-loading {
|
||||
position: relative;
|
||||
color: transparent !important;
|
||||
pointer-events: none;
|
||||
}
|
||||
.btn-loading::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border: 2px solid var(--border);
|
||||
border-top-color: currentColor;
|
||||
border-radius: 50%;
|
||||
animation: spin 0.6s linear infinite;
|
||||
}
|
||||
|
||||
/* Improved dark mode image handling */
|
||||
[data-theme="dark"] img {
|
||||
opacity: 0.95;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
[data-theme="dark"] img:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Dark mode specific adjustments */
|
||||
[data-theme="dark"] {
|
||||
--agent-bg: #1A1A1A;
|
||||
--user-bg: #2A1A08;
|
||||
--shadow-xs: 0 1px 2px rgba(0,0,0,0.5);
|
||||
--shadow-sm: 0 1px 3px rgba(0,0,0,0.6), 0 1px 2px rgba(0,0,0,0.4);
|
||||
--shadow-md: 0 4px 12px rgba(0,0,0,0.5), 0 2px 4px rgba(0,0,0,0.4);
|
||||
--shadow-lg: 0 12px 28px rgba(0,0,0,0.5), 0 4px 10px rgba(0,0,0,0.4);
|
||||
--shadow-xl: 0 20px 40px rgba(0,0,0,0.6), 0 8px 16px rgba(0,0,0,0.4);
|
||||
--shadow-glow: 0 0 80px rgba(0,0,0,0.8);
|
||||
--shadow-accent: 0 4px 20px rgba(255, 92, 0, 0.25);
|
||||
--shadow-inset: inset 0 1px 0 rgba(255,255,255,0.05);
|
||||
--card-highlight: rgba(255, 255, 255, 0.03);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
<body x-data="app" :data-theme="theme">
|
||||
|
||||
<!-- Skip link for keyboard users -->
|
||||
<a href="#main-content" class="skip-link">Skip to main content</a>
|
||||
|
||||
<!-- API Key Auth Prompt -->
|
||||
<div x-show="$store.app.showAuthPrompt" style="position:fixed;inset:0;z-index:9999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.6);backdrop-filter:blur(4px)" x-data="{ apiKeyInput: '' }">
|
||||
<div x-show="$store.app.showAuthPrompt" x-cloak style="position:fixed;inset:0;z-index:9999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.6);backdrop-filter:blur(4px)" x-data="{ apiKeyInput: '' }" role="dialog" aria-modal="true" aria-labelledby="auth-title">
|
||||
<div style="background:var(--bg-card,#1e1e2e);border:1px solid var(--border,#333);border-radius:12px;padding:2rem;max-width:400px;width:90%">
|
||||
<h3 style="margin:0 0 0.5rem;font-size:1.1rem">API Key Required</h3>
|
||||
<h3 id="auth-title" style="margin:0 0 0.5rem;font-size:1.1rem">API Key Required</h3>
|
||||
<p style="color:var(--text-dim,#888);font-size:0.85rem;margin:0 0 1rem">This instance requires an API key. Enter the key from your <code>config.toml</code>.</p>
|
||||
<input type="password" x-model="apiKeyInput" placeholder="Enter API key..." @keydown.enter="$store.app.submitApiKey(apiKeyInput)" style="width:100%;padding:0.6rem;border-radius:6px;border:1px solid var(--border,#333);background:var(--bg-input,#151520);color:var(--text,#e0e0e0);font-size:0.9rem;box-sizing:border-box;margin-bottom:0.75rem">
|
||||
<label for="api-key-input" class="visually-hidden">API Key</label>
|
||||
<input id="api-key-input" type="password" x-model="apiKeyInput" placeholder="Enter API key..." @keydown.enter="$store.app.submitApiKey(apiKeyInput)" aria-describedby="api-key-hint" style="width:100%;padding:0.6rem;border-radius:6px;border:1px solid var(--border,#333);background:var(--bg-input,#151520);color:var(--text,#e0e0e0);font-size:0.9rem;box-sizing:border-box;margin-bottom:0.75rem">
|
||||
<button @click="$store.app.submitApiKey(apiKeyInput)" style="width:100%;padding:0.6rem;border-radius:6px;border:none;background:var(--accent,#7c3aed);color:#fff;font-weight:600;cursor:pointer;font-size:0.9rem">Unlock Dashboard</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="description" content="OpenFang - Open Source Agent Operating System Dashboard">
|
||||
<meta name="theme-color" content="#020617">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>OpenFang Dashboard</title>
|
||||
<link rel="icon" type="image/x-icon" href="/favicon.ico">
|
||||
<link rel="icon" type="image/png" href="/logo.png">
|
||||
|
||||
1009
crates/openfang-kernel/src/aol/executor.rs
Normal file
1009
crates/openfang-kernel/src/aol/executor.rs
Normal file
File diff suppressed because it is too large
Load Diff
96
crates/openfang-kernel/src/aol/mod.rs
Normal file
96
crates/openfang-kernel/src/aol/mod.rs
Normal file
@@ -0,0 +1,96 @@
|
||||
//! Agent Orchestration Language (AOL) module.
|
||||
//!
|
||||
//! This module provides parsing and execution of AOL workflows - a declarative
|
||||
//! DSL for defining multi-agent orchestration workflows.
|
||||
//!
|
||||
//! # Architecture
|
||||
//!
|
||||
//! - `parser`: TOML → AST parsing
|
||||
//! - `template`: Template variable expansion
|
||||
//! - `validator`: Workflow validation
|
||||
//! - `executor`: Workflow execution engine
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! ```toml
|
||||
//! [workflow]
|
||||
//! name = "research-pipeline"
|
||||
//! version = "1.0.0"
|
||||
//!
|
||||
//! [workflow.input]
|
||||
//! topic = { type = "string", required = true }
|
||||
//!
|
||||
//! [[workflow.steps.sequential]]
|
||||
//! id = "research"
|
||||
//! agent = { kind = "by_name", name = "researcher" }
|
||||
//! task = "Search for papers about {{input.topic}}"
|
||||
//! output = "papers"
|
||||
//! ```
|
||||
|
||||
pub mod executor;
|
||||
pub mod parser;
|
||||
pub mod template;
|
||||
pub mod validator;
|
||||
|
||||
pub use executor::{
|
||||
AolExecutor, AgentExecutor, ExecutionId, ExecutionResult, ExecutionStatus,
|
||||
MockAgentExecutor, StepExecutionResult,
|
||||
};
|
||||
pub use parser::{parse_aol_workflow, parse_aol_workflow_from_str, AolParseError};
|
||||
pub use template::{expand_template, TemplateContext, TemplateError};
|
||||
pub use validator::{validate_workflow, ValidationError};
|
||||
|
||||
use openfang_types::aol::{AolWorkflow, WorkflowDefId};
|
||||
|
||||
/// Result type for AOL operations.
|
||||
pub type AolResult<T> = Result<T, AolError>;
|
||||
|
||||
/// Error type for AOL operations.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum AolError {
|
||||
/// Parsing error.
|
||||
#[error("Parse error: {0}")]
|
||||
Parse(#[from] AolParseError),
|
||||
|
||||
/// Validation error.
|
||||
#[error("Validation error: {0}")]
|
||||
Validation(#[from] ValidationError),
|
||||
|
||||
/// Template expansion error.
|
||||
#[error("Template error: {0}")]
|
||||
Template(#[from] TemplateError),
|
||||
|
||||
/// Execution error.
|
||||
#[error("Execution error: {0}")]
|
||||
Execution(String),
|
||||
}
|
||||
|
||||
/// Compiled workflow ready for execution.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CompiledWorkflow {
|
||||
/// The parsed AST.
|
||||
pub workflow: AolWorkflow,
|
||||
/// Workflow definition ID.
|
||||
pub id: WorkflowDefId,
|
||||
/// Whether the workflow has been validated.
|
||||
pub validated: bool,
|
||||
}
|
||||
|
||||
impl CompiledWorkflow {
|
||||
/// Create a new compiled workflow from a parsed AST.
|
||||
pub fn new(workflow: AolWorkflow) -> Self {
|
||||
let id = workflow.id;
|
||||
Self {
|
||||
workflow,
|
||||
id,
|
||||
validated: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate the workflow.
|
||||
pub fn validate(&mut self) -> AolResult<()> {
|
||||
validate_workflow(&self.workflow)?;
|
||||
self.validated = true;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
1252
crates/openfang-kernel/src/aol/parser.rs
Normal file
1252
crates/openfang-kernel/src/aol/parser.rs
Normal file
File diff suppressed because it is too large
Load Diff
454
crates/openfang-kernel/src/aol/template.rs
Normal file
454
crates/openfang-kernel/src/aol/template.rs
Normal file
@@ -0,0 +1,454 @@
|
||||
//! Template variable expansion for AOL workflows.
|
||||
//!
|
||||
//! Supports `{{variable}}` syntax for variable interpolation.
|
||||
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use thiserror::Error;
|
||||
|
||||
/// Error type for template operations.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum TemplateError {
|
||||
/// Variable not found in context.
|
||||
#[error("Variable not found: {0}")]
|
||||
VariableNotFound(String),
|
||||
|
||||
/// Invalid variable syntax.
|
||||
#[error("Invalid variable syntax: {0}")]
|
||||
InvalidSyntax(String),
|
||||
|
||||
/// JSON path evaluation error.
|
||||
#[error("JSON path error: {0}")]
|
||||
JsonPath(String),
|
||||
|
||||
/// Type mismatch.
|
||||
#[error("Type mismatch: expected {expected}, got {actual}")]
|
||||
TypeMismatch { expected: String, actual: String },
|
||||
}
|
||||
|
||||
/// Context for template expansion.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct TemplateContext {
|
||||
/// Input variables.
|
||||
pub input: HashMap<String, Value>,
|
||||
/// Step outputs.
|
||||
pub outputs: HashMap<String, Value>,
|
||||
/// Loop variables.
|
||||
pub loop_vars: HashMap<String, Value>,
|
||||
/// Custom variables.
|
||||
pub custom: HashMap<String, Value>,
|
||||
}
|
||||
|
||||
impl TemplateContext {
|
||||
/// Create a new empty context.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Create a context with input variables.
|
||||
pub fn with_inputs(inputs: HashMap<String, Value>) -> Self {
|
||||
Self {
|
||||
input: inputs,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Add an input variable.
|
||||
pub fn add_input(&mut self, key: impl Into<String>, value: Value) -> &mut Self {
|
||||
self.input.insert(key.into(), value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Add a step output.
|
||||
pub fn add_output(&mut self, key: impl Into<String>, value: Value) -> &mut Self {
|
||||
self.outputs.insert(key.into(), value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Add a loop variable.
|
||||
pub fn add_loop_var(&mut self, key: impl Into<String>, value: Value) -> &mut Self {
|
||||
self.loop_vars.insert(key.into(), value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set custom variables.
|
||||
pub fn set_custom(&mut self, custom: HashMap<String, Value>) -> &mut Self {
|
||||
self.custom = custom;
|
||||
self
|
||||
}
|
||||
|
||||
/// Get a variable by path.
|
||||
pub fn get(&self, path: &str) -> Option<&Value> {
|
||||
// Parse path: namespace.key or namespace.key.nested
|
||||
let parts: Vec<&str> = path.splitn(2, '.').collect();
|
||||
if parts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let namespace = parts[0];
|
||||
let remainder = parts.get(1).copied();
|
||||
|
||||
match namespace {
|
||||
"input" => {
|
||||
if let Some(key) = remainder {
|
||||
self.get_nested(&self.input, key)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
"outputs" | "output" => {
|
||||
if let Some(key) = remainder {
|
||||
self.get_nested(&self.outputs, key)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
"loop" => {
|
||||
if let Some(key) = remainder {
|
||||
self.get_nested(&self.loop_vars, key)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
"custom" => {
|
||||
if let Some(key) = remainder {
|
||||
self.get_nested(&self.custom, key)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
// Direct access without namespace - check all namespaces
|
||||
_ => {
|
||||
// First check if it's a direct key in outputs (most common)
|
||||
if let Some(v) = self.outputs.get(namespace) {
|
||||
return Some(v);
|
||||
}
|
||||
// Then check inputs
|
||||
if let Some(v) = self.input.get(namespace) {
|
||||
return Some(v);
|
||||
}
|
||||
// Then loop vars
|
||||
if let Some(v) = self.loop_vars.get(namespace) {
|
||||
return Some(v);
|
||||
}
|
||||
// Finally custom
|
||||
if let Some(v) = self.custom.get(namespace) {
|
||||
return Some(v);
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a nested value from a map.
|
||||
fn get_nested<'a>(&self, map: &'a HashMap<String, Value>, path: &str) -> Option<&'a Value> {
|
||||
let parts: Vec<&str> = path.split('.').collect();
|
||||
if parts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let first = map.get(parts[0])?;
|
||||
if parts.len() == 1 {
|
||||
return Some(first);
|
||||
}
|
||||
|
||||
// Navigate nested path
|
||||
let mut current = first;
|
||||
for part in &parts[1..] {
|
||||
match current {
|
||||
Value::Object(obj) => {
|
||||
current = obj.get(*part)?;
|
||||
}
|
||||
Value::Array(arr) => {
|
||||
if let Ok(idx) = part.parse::<usize>() {
|
||||
current = arr.get(idx)?;
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Some(current)
|
||||
}
|
||||
|
||||
/// Set a step output.
|
||||
pub fn set_output(&mut self, key: impl Into<String>, value: Value) {
|
||||
self.outputs.insert(key.into(), value);
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand template variables in a string.
|
||||
///
|
||||
/// Supports:
|
||||
/// - `{{variable}}` - Simple variable
|
||||
/// - `{{input.key}}` - Namespaced variable
|
||||
/// - `{{output.step_name}}` - Step output reference
|
||||
/// - `{{nested.path.to.value}}` - Nested access
|
||||
pub fn expand_template(template: &str, ctx: &TemplateContext) -> Result<String, TemplateError> {
|
||||
let mut result = String::with_capacity(template.len() * 2);
|
||||
let mut chars = template.chars().peekable();
|
||||
|
||||
while let Some(ch) = chars.next() {
|
||||
if ch == '{' && chars.peek() == Some(&'{') {
|
||||
// Skip the second '{'
|
||||
chars.next();
|
||||
|
||||
// Collect variable name until }}
|
||||
let mut var_name = String::new();
|
||||
let mut found_end = false;
|
||||
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '}' && chars.peek() == Some(&'}') {
|
||||
chars.next(); // Skip second '}'
|
||||
found_end = true;
|
||||
break;
|
||||
}
|
||||
var_name.push(c);
|
||||
}
|
||||
|
||||
if !found_end {
|
||||
return Err(TemplateError::InvalidSyntax(format!(
|
||||
"Unclosed variable: {}",
|
||||
var_name
|
||||
)));
|
||||
}
|
||||
|
||||
// Trim whitespace
|
||||
let var_name = var_name.trim();
|
||||
|
||||
if var_name.is_empty() {
|
||||
return Err(TemplateError::InvalidSyntax("Empty variable name".to_string()));
|
||||
}
|
||||
|
||||
// Look up variable
|
||||
let value = ctx.get(var_name).ok_or_else(|| {
|
||||
TemplateError::VariableNotFound(var_name.to_string())
|
||||
})?;
|
||||
|
||||
// Convert to string
|
||||
let str_value = value_to_string(value);
|
||||
result.push_str(&str_value);
|
||||
} else {
|
||||
result.push(ch);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Convert a JSON value to a string for template expansion.
|
||||
fn value_to_string(value: &Value) -> String {
|
||||
match value {
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Number(n) => n.to_string(),
|
||||
Value::Bool(b) => b.to_string(),
|
||||
Value::Null => String::new(),
|
||||
Value::Array(arr) => {
|
||||
// Format array as comma-separated values
|
||||
arr.iter()
|
||||
.map(value_to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
Value::Object(obj) => {
|
||||
// Format object as key=value pairs
|
||||
obj.iter()
|
||||
.map(|(k, v)| format!("{}={}", k, value_to_string(v)))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand all template variables in a map.
|
||||
pub fn expand_templates_in_map(
|
||||
map: &HashMap<String, String>,
|
||||
ctx: &TemplateContext,
|
||||
) -> Result<HashMap<String, String>, TemplateError> {
|
||||
let mut result = HashMap::with_capacity(map.len());
|
||||
for (k, v) in map {
|
||||
result.insert(k.clone(), expand_template(v, ctx)?);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn make_context() -> TemplateContext {
|
||||
let mut ctx = TemplateContext::new();
|
||||
ctx.add_input("topic", json!("AI safety"));
|
||||
ctx.add_input("count", json!(10));
|
||||
ctx.add_input("enabled", json!(true));
|
||||
ctx.add_input(
|
||||
"nested",
|
||||
json!({
|
||||
"level1": {
|
||||
"level2": "deep_value"
|
||||
}
|
||||
}),
|
||||
);
|
||||
ctx.add_output("result", json!("success"));
|
||||
ctx.add_output("data", json!([1, 2, 3]));
|
||||
ctx.add_loop_var("item", json!("current_item"));
|
||||
ctx.add_loop_var("index", json!(5));
|
||||
ctx
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_simple_variable() {
|
||||
let ctx = make_context();
|
||||
let result = expand_template("Topic: {{input.topic}}", &ctx).unwrap();
|
||||
assert_eq!(result, "Topic: AI safety");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_multiple_variables() {
|
||||
let ctx = make_context();
|
||||
let result = expand_template(
|
||||
"Topic: {{input.topic}}, Count: {{input.count}}",
|
||||
&ctx,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result, "Topic: AI safety, Count: 10");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_output_variable() {
|
||||
let ctx = make_context();
|
||||
let result = expand_template("Result: {{output.result}}", &ctx).unwrap();
|
||||
assert_eq!(result, "Result: success");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_loop_variable() {
|
||||
let ctx = make_context();
|
||||
let result = expand_template("Item: {{loop.item}}, Index: {{loop.index}}", &ctx).unwrap();
|
||||
assert_eq!(result, "Item: current_item, Index: 5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_nested_variable() {
|
||||
let ctx = make_context();
|
||||
let result = expand_template("Deep: {{input.nested.level1.level2}}", &ctx).unwrap();
|
||||
assert_eq!(result, "Deep: deep_value");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_array_variable() {
|
||||
let ctx = make_context();
|
||||
let result = expand_template("Data: {{output.data}}", &ctx).unwrap();
|
||||
assert_eq!(result, "Data: 1, 2, 3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_boolean_variable() {
|
||||
let ctx = make_context();
|
||||
let result = expand_template("Enabled: {{input.enabled}}", &ctx).unwrap();
|
||||
assert_eq!(result, "Enabled: true");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_direct_access() {
|
||||
let ctx = make_context();
|
||||
// Direct access without namespace (checks outputs first)
|
||||
let result = expand_template("{{result}}", &ctx).unwrap();
|
||||
assert_eq!(result, "success");
|
||||
|
||||
// Direct access to input
|
||||
let result = expand_template("{{topic}}", &ctx).unwrap();
|
||||
assert_eq!(result, "AI safety");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_variable_not_found() {
|
||||
let ctx = make_context();
|
||||
let result = expand_template("{{input.unknown}}", &ctx);
|
||||
assert!(result.is_err());
|
||||
match result.unwrap_err() {
|
||||
TemplateError::VariableNotFound(var) => assert_eq!(var, "input.unknown"),
|
||||
_ => panic!("Expected VariableNotFound error"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unclosed_variable() {
|
||||
let ctx = make_context();
|
||||
let result = expand_template("{{input.topic", &ctx);
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_empty_variable() {
|
||||
let ctx = make_context();
|
||||
let result = expand_template("{{}}", &ctx);
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_variables() {
|
||||
let ctx = make_context();
|
||||
let result = expand_template("Plain text without variables", &ctx).unwrap();
|
||||
assert_eq!(result, "Plain text without variables");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_adjacent_variables() {
|
||||
let ctx = make_context();
|
||||
let result = expand_template("{{input.topic}}{{input.count}}", &ctx).unwrap();
|
||||
assert_eq!(result, "AI safety10");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_whitespace_in_variable() {
|
||||
let ctx = make_context();
|
||||
let result = expand_template("{{ input.topic }}", &ctx).unwrap();
|
||||
assert_eq!(result, "AI safety");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_templates_in_map() {
|
||||
let ctx = make_context();
|
||||
let map = vec![
|
||||
("key1".to_string(), "{{input.topic}}".to_string()),
|
||||
("key2".to_string(), "Value: {{output.result}}".to_string()),
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
|
||||
let result = expand_templates_in_map(&map, &ctx).unwrap();
|
||||
assert_eq!(result.get("key1"), Some(&"AI safety".to_string()));
|
||||
assert_eq!(result.get("key2"), Some(&"Value: success".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_complex_template() {
|
||||
let mut ctx = TemplateContext::new();
|
||||
ctx.add_input("name", json!("OpenFang"));
|
||||
ctx.add_input("version", json!("1.0.0"));
|
||||
ctx.add_output("status", json!("ready"));
|
||||
|
||||
let template = "Project {{input.name}} v{{input.version}} is {{output.status}}!";
|
||||
let result = expand_template(template, &ctx).unwrap();
|
||||
assert_eq!(result, "Project OpenFang v1.0.0 is ready!");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_object_formatting() {
|
||||
let mut ctx = TemplateContext::new();
|
||||
ctx.add_input(
|
||||
"config",
|
||||
json!({
|
||||
"host": "localhost",
|
||||
"port": 8080
|
||||
}),
|
||||
);
|
||||
|
||||
let result = expand_template("Config: {{input.config}}", &ctx).unwrap();
|
||||
assert!(result.contains("host=localhost"));
|
||||
assert!(result.contains("port=8080"));
|
||||
}
|
||||
}
|
||||
876
crates/openfang-kernel/src/aol/validator.rs
Normal file
876
crates/openfang-kernel/src/aol/validator.rs
Normal file
@@ -0,0 +1,876 @@
|
||||
//! AOL Workflow validation.
|
||||
//!
|
||||
//! Validates workflow definitions for correctness and consistency.
|
||||
|
||||
use openfang_types::aol::{AolStep, AolWorkflow, AgentRef};
|
||||
use std::collections::HashSet;
|
||||
use thiserror::Error;
|
||||
|
||||
/// Error type for validation.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ValidationError {
|
||||
/// Missing required input.
|
||||
#[error("Missing required input: {0}")]
|
||||
MissingInput(String),
|
||||
|
||||
/// Undefined variable reference.
|
||||
#[error("Undefined variable reference: {0}")]
|
||||
UndefinedVariable(String),
|
||||
|
||||
/// Duplicate output variable.
|
||||
#[error("Duplicate output variable: {0}")]
|
||||
DuplicateOutput(String),
|
||||
|
||||
/// Invalid step reference.
|
||||
#[error("Invalid step reference: {0}")]
|
||||
InvalidStepRef(String),
|
||||
|
||||
/// Circular dependency.
|
||||
#[error("Circular dependency detected: {0}")]
|
||||
CircularDependency(String),
|
||||
|
||||
/// Empty workflow.
|
||||
#[error("Workflow has no steps")]
|
||||
EmptyWorkflow,
|
||||
|
||||
/// Invalid condition expression.
|
||||
#[error("Invalid condition expression: {0}")]
|
||||
InvalidCondition(String),
|
||||
|
||||
/// Empty step ID.
|
||||
#[error("Step ID cannot be empty")]
|
||||
EmptyStepId,
|
||||
|
||||
/// Empty task.
|
||||
#[error("Step '{0}' has empty task")]
|
||||
EmptyTask(String),
|
||||
|
||||
/// Invalid agent reference.
|
||||
#[error("Invalid agent reference in step '{step}': {reason}")]
|
||||
InvalidAgent { step: String, reason: String },
|
||||
|
||||
/// Too many steps.
|
||||
#[error("Too many steps: {count} (max: {max})")]
|
||||
TooManySteps { count: usize, max: usize },
|
||||
|
||||
/// Nested too deep.
|
||||
#[error("Workflow nested too deep: {depth} (max: {max})")]
|
||||
NestedTooDeep { depth: usize, max: usize },
|
||||
}
|
||||
|
||||
/// Validation options.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ValidationOptions {
|
||||
/// Maximum number of steps allowed.
|
||||
pub max_steps: usize,
|
||||
/// Maximum nesting depth.
|
||||
pub max_depth: usize,
|
||||
/// Whether to check variable references.
|
||||
pub check_references: bool,
|
||||
/// Whether to check for circular dependencies.
|
||||
pub check_circular: bool,
|
||||
}
|
||||
|
||||
impl Default for ValidationOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_steps: 100,
|
||||
max_depth: 10,
|
||||
check_references: true,
|
||||
check_circular: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate a workflow definition.
|
||||
pub fn validate_workflow(workflow: &AolWorkflow) -> Result<(), ValidationError> {
|
||||
validate_workflow_with_options(workflow, ValidationOptions::default())
|
||||
}
|
||||
|
||||
/// Validate a workflow with custom options.
|
||||
pub fn validate_workflow_with_options(
|
||||
workflow: &AolWorkflow,
|
||||
options: ValidationOptions,
|
||||
) -> Result<(), ValidationError> {
|
||||
// Check workflow has steps
|
||||
if workflow.steps.is_empty() {
|
||||
return Err(ValidationError::EmptyWorkflow);
|
||||
}
|
||||
|
||||
// Count total steps and check limit
|
||||
let total_steps = count_steps(&workflow.steps);
|
||||
if total_steps > options.max_steps {
|
||||
return Err(ValidationError::TooManySteps {
|
||||
count: total_steps,
|
||||
max: options.max_steps,
|
||||
});
|
||||
}
|
||||
|
||||
// Check nesting depth
|
||||
let depth = max_nesting_depth(&workflow.steps);
|
||||
if depth > options.max_depth {
|
||||
return Err(ValidationError::NestedTooDeep {
|
||||
depth,
|
||||
max: options.max_depth,
|
||||
});
|
||||
}
|
||||
|
||||
// Collect all step IDs and outputs
|
||||
let mut step_ids = HashSet::new();
|
||||
let mut outputs = HashSet::new();
|
||||
collect_step_info(&workflow.steps, &mut step_ids, &mut outputs)?;
|
||||
|
||||
// Validate each step
|
||||
for step in &workflow.steps {
|
||||
validate_step(step, &step_ids, &outputs, &options)?;
|
||||
}
|
||||
|
||||
// Check for circular dependencies
|
||||
if options.check_circular {
|
||||
check_circular_deps(&workflow.steps, &mut HashSet::new())?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Count total steps recursively.
|
||||
fn count_steps(steps: &[AolStep]) -> usize {
|
||||
steps.iter().map(count_step_children).sum()
|
||||
}
|
||||
|
||||
/// Count children of a step.
|
||||
fn count_step_children(step: &AolStep) -> usize {
|
||||
match step {
|
||||
AolStep::Parallel(pg) => {
|
||||
1 + pg.steps.len()
|
||||
}
|
||||
AolStep::Sequential(_) => 1,
|
||||
AolStep::Conditional(cs) => {
|
||||
1 + cs
|
||||
.branches
|
||||
.iter()
|
||||
.map(|b| count_steps(&b.steps))
|
||||
.sum::<usize>()
|
||||
+ cs.default.as_ref().map(|d| count_steps(d.as_slice())).unwrap_or(0)
|
||||
}
|
||||
AolStep::Loop(ls) => 1 + count_steps(&ls.steps),
|
||||
AolStep::Collect(_) => 1,
|
||||
AolStep::Subworkflow(_) => 1,
|
||||
AolStep::Fallback(fs) => {
|
||||
1 + count_step_children(&fs.primary)
|
||||
+ fs.fallbacks.iter().map(count_step_children).sum::<usize>()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculate maximum nesting depth.
|
||||
fn max_nesting_depth(steps: &[AolStep]) -> usize {
|
||||
steps
|
||||
.iter()
|
||||
.map(|step| match step {
|
||||
AolStep::Parallel(pg) => {
|
||||
1 + pg.steps.iter().map(|_| 1).max().unwrap_or(0)
|
||||
}
|
||||
AolStep::Sequential(_) => 1,
|
||||
AolStep::Conditional(cs) => {
|
||||
let branch_depth = cs
|
||||
.branches
|
||||
.iter()
|
||||
.map(|b| max_nesting_depth(&b.steps))
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
let default_depth = cs
|
||||
.default
|
||||
.as_ref()
|
||||
.map(|d| max_nesting_depth(d.as_slice()))
|
||||
.unwrap_or(0);
|
||||
1 + branch_depth.max(default_depth)
|
||||
}
|
||||
AolStep::Loop(ls) => 1 + max_nesting_depth(&ls.steps),
|
||||
AolStep::Collect(_) => 1,
|
||||
AolStep::Subworkflow(_) => 1,
|
||||
AolStep::Fallback(fs) => {
|
||||
let primary_depth = max_nesting_depth(&[(*fs.primary).clone()]);
|
||||
let fallback_depth = fs
|
||||
.fallbacks
|
||||
.iter()
|
||||
.map(|f| max_nesting_depth(&[f.clone()]))
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
1 + primary_depth.max(fallback_depth)
|
||||
}
|
||||
})
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Collect step IDs and output variable names.
|
||||
fn collect_step_info(
|
||||
steps: &[AolStep],
|
||||
ids: &mut HashSet<String>,
|
||||
outputs: &mut HashSet<String>,
|
||||
) -> Result<(), ValidationError> {
|
||||
for step in steps {
|
||||
let id = step.id();
|
||||
if id.is_empty() {
|
||||
return Err(ValidationError::EmptyStepId);
|
||||
}
|
||||
if ids.contains(id) {
|
||||
return Err(ValidationError::InvalidStepRef(format!(
|
||||
"Duplicate step ID: {}",
|
||||
id
|
||||
)));
|
||||
}
|
||||
ids.insert(id.to_string());
|
||||
|
||||
if let Some(output) = step.output() {
|
||||
if !output.is_empty() {
|
||||
if outputs.contains(output) {
|
||||
return Err(ValidationError::DuplicateOutput(output.to_string()));
|
||||
}
|
||||
outputs.insert(output.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// Recursively collect from nested steps
|
||||
match step {
|
||||
AolStep::Parallel(pg) => {
|
||||
for ps in &pg.steps {
|
||||
if ps.id.is_empty() {
|
||||
return Err(ValidationError::EmptyStepId);
|
||||
}
|
||||
if ids.contains(&ps.id) {
|
||||
return Err(ValidationError::InvalidStepRef(format!(
|
||||
"Duplicate step ID: {}",
|
||||
ps.id
|
||||
)));
|
||||
}
|
||||
ids.insert(ps.id.clone());
|
||||
if let Some(output) = &ps.output {
|
||||
if !output.is_empty() && outputs.contains(output) {
|
||||
return Err(ValidationError::DuplicateOutput(output.clone()));
|
||||
}
|
||||
outputs.insert(output.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
AolStep::Conditional(cs) => {
|
||||
for branch in &cs.branches {
|
||||
collect_step_info(&branch.steps, ids, outputs)?;
|
||||
}
|
||||
if let Some(default) = &cs.default {
|
||||
collect_step_info(default, ids, outputs)?;
|
||||
}
|
||||
}
|
||||
AolStep::Loop(ls) => {
|
||||
collect_step_info(&ls.steps, ids, outputs)?;
|
||||
}
|
||||
AolStep::Fallback(fs) => {
|
||||
collect_step_info(&[(*fs.primary).clone()], ids, outputs)?;
|
||||
collect_step_info(&fs.fallbacks, ids, outputs)?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate a single step.
|
||||
fn validate_step(
|
||||
step: &AolStep,
|
||||
step_ids: &HashSet<String>,
|
||||
outputs: &HashSet<String>,
|
||||
options: &ValidationOptions,
|
||||
) -> Result<(), ValidationError> {
|
||||
match step {
|
||||
AolStep::Parallel(pg) => {
|
||||
if pg.steps.is_empty() {
|
||||
return Err(ValidationError::InvalidStepRef(format!(
|
||||
"Parallel group '{}' has no steps",
|
||||
pg.id
|
||||
)));
|
||||
}
|
||||
for ps in &pg.steps {
|
||||
validate_task(&ps.id, &ps.task)?;
|
||||
validate_agent_ref(&ps.id, &ps.agent)?;
|
||||
}
|
||||
}
|
||||
AolStep::Sequential(ss) => {
|
||||
validate_task(&ss.id, &ss.task)?;
|
||||
validate_agent_ref(&ss.id, &ss.agent)?;
|
||||
}
|
||||
AolStep::Conditional(cs) => {
|
||||
if cs.branches.is_empty() {
|
||||
return Err(ValidationError::InvalidStepRef(format!(
|
||||
"Conditional '{}' has no branches",
|
||||
cs.id
|
||||
)));
|
||||
}
|
||||
for branch in &cs.branches {
|
||||
if branch.condition.is_empty() {
|
||||
return Err(ValidationError::InvalidCondition(format!(
|
||||
"Branch '{}' has empty condition",
|
||||
branch.id
|
||||
)));
|
||||
}
|
||||
for nested_step in &branch.steps {
|
||||
validate_step(nested_step, step_ids, outputs, options)?;
|
||||
}
|
||||
}
|
||||
if let Some(default) = &cs.default {
|
||||
for nested_step in default {
|
||||
validate_step(nested_step, step_ids, outputs, options)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
AolStep::Loop(ls) => {
|
||||
if ls.item_var.is_empty() {
|
||||
return Err(ValidationError::InvalidStepRef(format!(
|
||||
"Loop '{}' has empty item_var",
|
||||
ls.id
|
||||
)));
|
||||
}
|
||||
if ls.collection.is_empty() {
|
||||
return Err(ValidationError::InvalidStepRef(format!(
|
||||
"Loop '{}' has empty collection",
|
||||
ls.id
|
||||
)));
|
||||
}
|
||||
for nested_step in &ls.steps {
|
||||
validate_step(nested_step, step_ids, outputs, options)?;
|
||||
}
|
||||
}
|
||||
AolStep::Collect(cs) => {
|
||||
if cs.sources.is_empty() {
|
||||
return Err(ValidationError::InvalidStepRef(format!(
|
||||
"Collect '{}' has no sources",
|
||||
cs.id
|
||||
)));
|
||||
}
|
||||
if options.check_references {
|
||||
for source in &cs.sources {
|
||||
if !outputs.contains(source) {
|
||||
return Err(ValidationError::UndefinedVariable(format!(
|
||||
"Collect '{}' references undefined output: {}",
|
||||
cs.id, source
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
AolStep::Subworkflow(_ss) => {
|
||||
// Workflow ID is validated during parsing
|
||||
}
|
||||
AolStep::Fallback(fs) => {
|
||||
validate_step(&fs.primary, step_ids, outputs, options)?;
|
||||
for fallback in &fs.fallbacks {
|
||||
validate_step(fallback, step_ids, outputs, options)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate a task string.
|
||||
fn validate_task(step_id: &str, task: &str) -> Result<(), ValidationError> {
|
||||
if task.trim().is_empty() {
|
||||
return Err(ValidationError::EmptyTask(step_id.to_string()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate an agent reference.
|
||||
fn validate_agent_ref(step_id: &str, agent: &AgentRef) -> Result<(), ValidationError> {
|
||||
match agent {
|
||||
AgentRef::ById { id } => {
|
||||
if id.is_nil() {
|
||||
return Err(ValidationError::InvalidAgent {
|
||||
step: step_id.to_string(),
|
||||
reason: "Agent ID cannot be nil UUID".to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
AgentRef::ByName { name } => {
|
||||
if name.trim().is_empty() {
|
||||
return Err(ValidationError::InvalidAgent {
|
||||
step: step_id.to_string(),
|
||||
reason: "Agent name cannot be empty".to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
AgentRef::ByRole { role, .. } => {
|
||||
if role.trim().is_empty() {
|
||||
return Err(ValidationError::InvalidAgent {
|
||||
step: step_id.to_string(),
|
||||
reason: "Agent role cannot be empty".to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check for circular dependencies.
|
||||
fn check_circular_deps(steps: &[AolStep], visited: &mut HashSet<String>) -> Result<(), ValidationError> {
|
||||
for step in steps {
|
||||
let id = step.id();
|
||||
if visited.contains(id) {
|
||||
return Err(ValidationError::CircularDependency(id.to_string()));
|
||||
}
|
||||
visited.insert(id.to_string());
|
||||
|
||||
// Check nested steps
|
||||
match step {
|
||||
AolStep::Conditional(cs) => {
|
||||
for branch in &cs.branches {
|
||||
check_circular_deps(&branch.steps, visited)?;
|
||||
}
|
||||
if let Some(default) = &cs.default {
|
||||
check_circular_deps(default, visited)?;
|
||||
}
|
||||
}
|
||||
AolStep::Loop(ls) => {
|
||||
check_circular_deps(&ls.steps, visited)?;
|
||||
}
|
||||
AolStep::Fallback(fs) => {
|
||||
check_circular_deps(&[(*fs.primary).clone()], visited)?;
|
||||
check_circular_deps(&fs.fallbacks, visited)?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use openfang_types::aol::{
|
||||
CollectStrategy, ConditionalBranch, ConditionalStep, InputParam, LoopStep,
|
||||
ParallelStep, ParallelStepGroup, ParamType, SequentialStep, WorkflowConfig,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
fn make_valid_workflow() -> AolWorkflow {
|
||||
AolWorkflow {
|
||||
id: openfang_types::aol::WorkflowDefId::new(),
|
||||
name: "test".to_string(),
|
||||
version: "1.0.0".to_string(),
|
||||
description: String::new(),
|
||||
author: String::new(),
|
||||
inputs: vec![],
|
||||
outputs: vec![],
|
||||
config: WorkflowConfig::default(),
|
||||
steps: vec![AolStep::Sequential(SequentialStep {
|
||||
id: "step1".to_string(),
|
||||
agent: AgentRef::by_name("agent"),
|
||||
task: "Do something".to_string(),
|
||||
inputs: HashMap::new(),
|
||||
output: Some("result".to_string()),
|
||||
error_mode: None,
|
||||
timeout_secs: None,
|
||||
condition: None,
|
||||
})],
|
||||
tags: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_valid_workflow() {
|
||||
let wf = make_valid_workflow();
|
||||
assert!(validate_workflow(&wf).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_empty_workflow() {
|
||||
let wf = AolWorkflow {
|
||||
steps: vec![],
|
||||
..make_valid_workflow()
|
||||
};
|
||||
assert!(matches!(
|
||||
validate_workflow(&wf),
|
||||
Err(ValidationError::EmptyWorkflow)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_empty_step_id() {
|
||||
let wf = AolWorkflow {
|
||||
steps: vec![AolStep::Sequential(SequentialStep {
|
||||
id: String::new(),
|
||||
agent: AgentRef::by_name("agent"),
|
||||
task: "Task".to_string(),
|
||||
inputs: HashMap::new(),
|
||||
output: None,
|
||||
error_mode: None,
|
||||
timeout_secs: None,
|
||||
condition: None,
|
||||
})],
|
||||
..make_valid_workflow()
|
||||
};
|
||||
assert!(matches!(
|
||||
validate_workflow(&wf),
|
||||
Err(ValidationError::EmptyStepId)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_empty_task() {
|
||||
let wf = AolWorkflow {
|
||||
steps: vec![AolStep::Sequential(SequentialStep {
|
||||
id: "step1".to_string(),
|
||||
agent: AgentRef::by_name("agent"),
|
||||
task: String::new(),
|
||||
inputs: HashMap::new(),
|
||||
output: None,
|
||||
error_mode: None,
|
||||
timeout_secs: None,
|
||||
condition: None,
|
||||
})],
|
||||
..make_valid_workflow()
|
||||
};
|
||||
assert!(matches!(
|
||||
validate_workflow(&wf),
|
||||
Err(ValidationError::EmptyTask(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_duplicate_output() {
|
||||
let wf = AolWorkflow {
|
||||
steps: vec![
|
||||
AolStep::Sequential(SequentialStep {
|
||||
id: "step1".to_string(),
|
||||
agent: AgentRef::by_name("agent"),
|
||||
task: "Task 1".to_string(),
|
||||
inputs: HashMap::new(),
|
||||
output: Some("result".to_string()),
|
||||
error_mode: None,
|
||||
timeout_secs: None,
|
||||
condition: None,
|
||||
}),
|
||||
AolStep::Sequential(SequentialStep {
|
||||
id: "step2".to_string(),
|
||||
agent: AgentRef::by_name("agent"),
|
||||
task: "Task 2".to_string(),
|
||||
inputs: HashMap::new(),
|
||||
output: Some("result".to_string()),
|
||||
error_mode: None,
|
||||
timeout_secs: None,
|
||||
condition: None,
|
||||
}),
|
||||
],
|
||||
..make_valid_workflow()
|
||||
};
|
||||
assert!(matches!(
|
||||
validate_workflow(&wf),
|
||||
Err(ValidationError::DuplicateOutput(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_invalid_agent_empty_name() {
|
||||
let wf = AolWorkflow {
|
||||
steps: vec![AolStep::Sequential(SequentialStep {
|
||||
id: "step1".to_string(),
|
||||
agent: AgentRef::by_name(""),
|
||||
task: "Task".to_string(),
|
||||
inputs: HashMap::new(),
|
||||
output: None,
|
||||
error_mode: None,
|
||||
timeout_secs: None,
|
||||
condition: None,
|
||||
})],
|
||||
..make_valid_workflow()
|
||||
};
|
||||
assert!(matches!(
|
||||
validate_workflow(&wf),
|
||||
Err(ValidationError::InvalidAgent { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_invalid_agent_nil_uuid() {
|
||||
let wf = AolWorkflow {
|
||||
steps: vec![AolStep::Sequential(SequentialStep {
|
||||
id: "step1".to_string(),
|
||||
agent: AgentRef::by_id(Uuid::nil()),
|
||||
task: "Task".to_string(),
|
||||
inputs: HashMap::new(),
|
||||
output: None,
|
||||
error_mode: None,
|
||||
timeout_secs: None,
|
||||
condition: None,
|
||||
})],
|
||||
..make_valid_workflow()
|
||||
};
|
||||
assert!(matches!(
|
||||
validate_workflow(&wf),
|
||||
Err(ValidationError::InvalidAgent { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_parallel_group_empty_steps() {
|
||||
let wf = AolWorkflow {
|
||||
steps: vec![AolStep::Parallel(ParallelStepGroup {
|
||||
id: "pg1".to_string(),
|
||||
steps: vec![],
|
||||
collect: CollectStrategy::Merge,
|
||||
output: None,
|
||||
max_concurrency: None,
|
||||
})],
|
||||
..make_valid_workflow()
|
||||
};
|
||||
assert!(matches!(
|
||||
validate_workflow(&wf),
|
||||
Err(ValidationError::InvalidStepRef(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_conditional_empty_branches() {
|
||||
let wf = AolWorkflow {
|
||||
steps: vec![AolStep::Conditional(ConditionalStep {
|
||||
id: "cond1".to_string(),
|
||||
branches: vec![],
|
||||
default: None,
|
||||
output: None,
|
||||
})],
|
||||
..make_valid_workflow()
|
||||
};
|
||||
assert!(matches!(
|
||||
validate_workflow(&wf),
|
||||
Err(ValidationError::InvalidStepRef(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_conditional_empty_condition() {
|
||||
let wf = AolWorkflow {
|
||||
steps: vec![AolStep::Conditional(ConditionalStep {
|
||||
id: "cond1".to_string(),
|
||||
branches: vec![ConditionalBranch {
|
||||
id: "branch1".to_string(),
|
||||
condition: String::new(),
|
||||
steps: vec![],
|
||||
output: None,
|
||||
}],
|
||||
default: None,
|
||||
output: None,
|
||||
})],
|
||||
..make_valid_workflow()
|
||||
};
|
||||
assert!(matches!(
|
||||
validate_workflow(&wf),
|
||||
Err(ValidationError::InvalidCondition(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_loop_empty_item_var() {
|
||||
let wf = AolWorkflow {
|
||||
steps: vec![AolStep::Loop(LoopStep {
|
||||
id: "loop1".to_string(),
|
||||
item_var: String::new(),
|
||||
index_var: None,
|
||||
collection: "$.items".to_string(),
|
||||
steps: vec![],
|
||||
collect: CollectStrategy::Merge,
|
||||
output: None,
|
||||
max_concurrency: 0,
|
||||
})],
|
||||
..make_valid_workflow()
|
||||
};
|
||||
assert!(matches!(
|
||||
validate_workflow(&wf),
|
||||
Err(ValidationError::InvalidStepRef(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_loop_empty_collection() {
|
||||
let wf = AolWorkflow {
|
||||
steps: vec![AolStep::Loop(LoopStep {
|
||||
id: "loop1".to_string(),
|
||||
item_var: "item".to_string(),
|
||||
index_var: None,
|
||||
collection: String::new(),
|
||||
steps: vec![],
|
||||
collect: CollectStrategy::Merge,
|
||||
output: None,
|
||||
max_concurrency: 0,
|
||||
})],
|
||||
..make_valid_workflow()
|
||||
};
|
||||
assert!(matches!(
|
||||
validate_workflow(&wf),
|
||||
Err(ValidationError::InvalidStepRef(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_collect_undefined_source() {
|
||||
let options = ValidationOptions {
|
||||
check_references: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let wf = AolWorkflow {
|
||||
steps: vec![
|
||||
AolStep::Sequential(SequentialStep {
|
||||
id: "step1".to_string(),
|
||||
agent: AgentRef::by_name("agent"),
|
||||
task: "Task".to_string(),
|
||||
inputs: HashMap::new(),
|
||||
output: Some("result1".to_string()),
|
||||
error_mode: None,
|
||||
timeout_secs: None,
|
||||
condition: None,
|
||||
}),
|
||||
AolStep::Collect(openfang_types::aol::CollectStep {
|
||||
id: "collect1".to_string(),
|
||||
sources: vec!["undefined_output".to_string()],
|
||||
strategy: CollectStrategy::Merge,
|
||||
aggregate_fn: None,
|
||||
output: "collected".to_string(),
|
||||
}),
|
||||
],
|
||||
..make_valid_workflow()
|
||||
};
|
||||
|
||||
let result = validate_workflow_with_options(&wf, options);
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(ValidationError::UndefinedVariable(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_collect_valid_source() {
|
||||
let wf = AolWorkflow {
|
||||
steps: vec![
|
||||
AolStep::Sequential(SequentialStep {
|
||||
id: "step1".to_string(),
|
||||
agent: AgentRef::by_name("agent"),
|
||||
task: "Task".to_string(),
|
||||
inputs: HashMap::new(),
|
||||
output: Some("result1".to_string()),
|
||||
error_mode: None,
|
||||
timeout_secs: None,
|
||||
condition: None,
|
||||
}),
|
||||
AolStep::Collect(openfang_types::aol::CollectStep {
|
||||
id: "collect1".to_string(),
|
||||
sources: vec!["result1".to_string()],
|
||||
strategy: CollectStrategy::Merge,
|
||||
aggregate_fn: None,
|
||||
output: "collected".to_string(),
|
||||
}),
|
||||
],
|
||||
..make_valid_workflow()
|
||||
};
|
||||
|
||||
assert!(validate_workflow(&wf).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_too_many_steps() {
|
||||
let options = ValidationOptions {
|
||||
max_steps: 2,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let wf = AolWorkflow {
|
||||
steps: vec![
|
||||
AolStep::Sequential(SequentialStep {
|
||||
id: "step1".to_string(),
|
||||
agent: AgentRef::by_name("agent"),
|
||||
task: "Task 1".to_string(),
|
||||
inputs: HashMap::new(),
|
||||
output: None,
|
||||
error_mode: None,
|
||||
timeout_secs: None,
|
||||
condition: None,
|
||||
}),
|
||||
AolStep::Sequential(SequentialStep {
|
||||
id: "step2".to_string(),
|
||||
agent: AgentRef::by_name("agent"),
|
||||
task: "Task 2".to_string(),
|
||||
inputs: HashMap::new(),
|
||||
output: None,
|
||||
error_mode: None,
|
||||
timeout_secs: None,
|
||||
condition: None,
|
||||
}),
|
||||
AolStep::Sequential(SequentialStep {
|
||||
id: "step3".to_string(),
|
||||
agent: AgentRef::by_name("agent"),
|
||||
task: "Task 3".to_string(),
|
||||
inputs: HashMap::new(),
|
||||
output: None,
|
||||
error_mode: None,
|
||||
timeout_secs: None,
|
||||
condition: None,
|
||||
}),
|
||||
],
|
||||
..make_valid_workflow()
|
||||
};
|
||||
|
||||
let result = validate_workflow_with_options(&wf, options);
|
||||
assert!(matches!(result, Err(ValidationError::TooManySteps { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_nested_too_deep() {
|
||||
let options = ValidationOptions {
|
||||
max_depth: 2,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Create deeply nested structure: conditional -> conditional -> conditional -> step
|
||||
let inner_step = AolStep::Sequential(SequentialStep {
|
||||
id: "inner".to_string(),
|
||||
agent: AgentRef::by_name("agent"),
|
||||
task: "Task".to_string(),
|
||||
inputs: HashMap::new(),
|
||||
output: None,
|
||||
error_mode: None,
|
||||
timeout_secs: None,
|
||||
condition: None,
|
||||
});
|
||||
|
||||
let level2 = AolStep::Conditional(ConditionalStep {
|
||||
id: "level2".to_string(),
|
||||
branches: vec![ConditionalBranch {
|
||||
id: "branch2".to_string(),
|
||||
condition: "true".to_string(),
|
||||
steps: vec![inner_step],
|
||||
output: None,
|
||||
}],
|
||||
default: None,
|
||||
output: None,
|
||||
});
|
||||
|
||||
let level1 = AolStep::Conditional(ConditionalStep {
|
||||
id: "level1".to_string(),
|
||||
branches: vec![ConditionalBranch {
|
||||
id: "branch1".to_string(),
|
||||
condition: "true".to_string(),
|
||||
steps: vec![level2],
|
||||
output: None,
|
||||
}],
|
||||
default: None,
|
||||
output: None,
|
||||
});
|
||||
|
||||
let wf = AolWorkflow {
|
||||
steps: vec![level1],
|
||||
..make_valid_workflow()
|
||||
};
|
||||
|
||||
let result = validate_workflow_with_options(&wf, options);
|
||||
assert!(matches!(result, Err(ValidationError::NestedTooDeep { .. })));
|
||||
}
|
||||
}
|
||||
@@ -2424,6 +2424,20 @@ impl OpenFangKernel {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Update an agent's system prompt with persistence.
|
||||
pub fn update_agent_system_prompt(&self, agent_id: AgentId, system_prompt: String) -> KernelResult<()> {
|
||||
self.registry
|
||||
.update_system_prompt(agent_id, system_prompt.clone())
|
||||
.map_err(KernelError::OpenFang)?;
|
||||
|
||||
if let Some(entry) = self.registry.get(agent_id) {
|
||||
let _ = self.memory.save_agent(&entry);
|
||||
}
|
||||
|
||||
info!(agent_id = %agent_id, "Agent system prompt updated and persisted");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get session token usage and estimated cost for an agent.
|
||||
pub fn session_usage_cost(&self, agent_id: AgentId) -> KernelResult<(u64, u64, f64)> {
|
||||
let entry = self.registry.get(agent_id).ok_or_else(|| {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! and inter-agent communication.
|
||||
|
||||
pub mod approval;
|
||||
pub mod aol;
|
||||
pub mod auth;
|
||||
pub mod auto_reply;
|
||||
pub mod background;
|
||||
@@ -17,6 +18,7 @@ pub mod heartbeat;
|
||||
pub mod kernel;
|
||||
pub mod metering;
|
||||
pub mod pairing;
|
||||
pub mod presence;
|
||||
pub mod registry;
|
||||
pub mod scheduler;
|
||||
pub mod supervisor;
|
||||
@@ -27,3 +29,7 @@ pub mod workflow;
|
||||
|
||||
pub use kernel::DeliveryTracker;
|
||||
pub use kernel::OpenFangKernel;
|
||||
pub use presence::{
|
||||
CollabSession, CollabSessionId, ConnectionId, PresenceConfig, PresenceCursor, PresenceError,
|
||||
PresenceManager, PresenceStats, PresenceStatus, PresenceUser,
|
||||
};
|
||||
|
||||
1378
crates/openfang-kernel/src/presence.rs
Normal file
1378
crates/openfang-kernel/src/presence.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -363,9 +363,9 @@ mod tests {
|
||||
let id = entry.id;
|
||||
registry.register(entry).unwrap();
|
||||
|
||||
registry.set_mode(id, AgentMode::Autonomous).unwrap();
|
||||
registry.set_mode(id, AgentMode::Full).unwrap();
|
||||
let updated = registry.get(id).unwrap();
|
||||
assert_eq!(updated.mode, AgentMode::Autonomous);
|
||||
assert_eq!(updated.mode, AgentMode::Full);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
1339
crates/openfang-memory/src/annotations.rs
Normal file
1339
crates/openfang-memory/src/annotations.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -789,7 +789,7 @@ mod tests {
|
||||
store
|
||||
.add_relation(Relation {
|
||||
source: alice_id.clone(),
|
||||
relation: RelationType::Knows,
|
||||
relation: RelationType::KnowsAbout,
|
||||
target: bob_id.clone(),
|
||||
properties: HashMap::new(),
|
||||
confidence: 0.9,
|
||||
@@ -813,14 +813,14 @@ mod tests {
|
||||
let matches = store
|
||||
.query_graph(GraphPattern {
|
||||
source: Some(alice_id),
|
||||
relation: Some(RelationType::Knows),
|
||||
relation: Some(RelationType::KnowsAbout),
|
||||
target: None,
|
||||
max_depth: 3,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
// Should only return Alice -> Bob (Knows relation)
|
||||
// Bob -> Carol is WorksAt, not Knows
|
||||
// Should only return Alice -> Bob (KnowsAbout relation)
|
||||
// Bob -> Carol is WorksAt, not KnowsAbout
|
||||
assert_eq!(matches.len(), 1);
|
||||
assert_eq!(matches[0].target.name, "Bob");
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//!
|
||||
//! Agents interact with a single `Memory` trait that abstracts over all three stores.
|
||||
|
||||
pub mod annotations;
|
||||
pub mod consolidation;
|
||||
pub mod knowledge;
|
||||
pub mod migration;
|
||||
@@ -17,3 +18,9 @@ pub mod usage;
|
||||
|
||||
mod substrate;
|
||||
pub use substrate::MemorySubstrate;
|
||||
|
||||
// Re-export annotation types
|
||||
pub use annotations::{
|
||||
Annotation, AnnotationError, AnnotationId, AnnotationPriority, AnnotationReaction,
|
||||
AnnotationStatus, AnnotationStats, AnnotationStore, AnnotationType,
|
||||
};
|
||||
|
||||
318
docs/aol-examples.md
Normal file
318
docs/aol-examples.md
Normal file
@@ -0,0 +1,318 @@
|
||||
# AOL (Agent Orchestration Language) 使用示例
|
||||
|
||||
## 基础示例
|
||||
|
||||
### 1. 简单顺序工作流
|
||||
|
||||
```toml
|
||||
[workflow]
|
||||
name = "simple-pipeline"
|
||||
version = "1.0.0"
|
||||
description = "简单的研究流程"
|
||||
|
||||
[workflow.input]
|
||||
topic = { type = "string", required = true, description = "研究主题" }
|
||||
|
||||
[[workflow.steps.sequential]]
|
||||
id = "research"
|
||||
agent = { kind = "by_name", name = "researcher" }
|
||||
task = "搜索关于 {{input.topic}} 的最新信息"
|
||||
output = "research_result"
|
||||
|
||||
[[workflow.steps.sequential]]
|
||||
id = "summarize"
|
||||
agent = { kind = "by_name", name = "writer" }
|
||||
task = "总结以下研究结果: {{research_result}}"
|
||||
output = "summary"
|
||||
```
|
||||
|
||||
### 2. 并行执行工作流
|
||||
|
||||
```toml
|
||||
[workflow]
|
||||
name = "parallel-research"
|
||||
version = "1.0.0"
|
||||
|
||||
[workflow.input]
|
||||
topic = { type = "string", required = true }
|
||||
|
||||
[[workflow.steps.parallel]]
|
||||
id = "parallel-search"
|
||||
collect = "merge"
|
||||
output = "all_results"
|
||||
max_concurrency = 3
|
||||
|
||||
[[workflow.steps.parallel.steps]]
|
||||
id = "academic"
|
||||
agent = { kind = "by_name", name = "academic-researcher" }
|
||||
task = "搜索 {{input.topic}} 的学术论文"
|
||||
output = "papers"
|
||||
|
||||
[[workflow.steps.parallel.steps]]
|
||||
id = "news"
|
||||
agent = { kind = "by_name", name = "news-researcher" }
|
||||
task = "搜索 {{input.topic}} 的新闻报道"
|
||||
output = "news"
|
||||
|
||||
[[workflow.steps.parallel.steps]]
|
||||
id = "market"
|
||||
agent = { kind = "by_role", role = "analyst" }
|
||||
task = "分析 {{input.topic}} 的市场趋势"
|
||||
output = "market_data"
|
||||
|
||||
[[workflow.steps.collect]]
|
||||
id = "combine"
|
||||
sources = ["papers", "news", "market_data"]
|
||||
strategy = "merge"
|
||||
output = "combined_research"
|
||||
|
||||
[[workflow.steps.sequential]]
|
||||
id = "synthesize"
|
||||
agent = { kind = "by_name", name = "writer" }
|
||||
task = "综合以下研究结果生成报告: {{combined_research}}"
|
||||
output = "final_report"
|
||||
```
|
||||
|
||||
### 3. 条件分支工作流
|
||||
|
||||
```toml
|
||||
[workflow]
|
||||
name = "conditional-workflow"
|
||||
version = "1.0.0"
|
||||
|
||||
[workflow.input]
|
||||
complexity = { type = "string", required = true, enum_values = ["quick", "standard", "exhaustive"] }
|
||||
topic = { type = "string", required = true }
|
||||
|
||||
[[workflow.steps.sequential]]
|
||||
id = "initial-research"
|
||||
agent = { kind = "by_name", name = "researcher" }
|
||||
task = "初步研究: {{input.topic}}"
|
||||
output = "initial_result"
|
||||
|
||||
[[workflow.steps.conditional]]
|
||||
id = "depth-check"
|
||||
|
||||
[[workflow.steps.conditional.branches]]
|
||||
id = "exhaustive-branch"
|
||||
condition = "{{input.complexity}} == exhaustive"
|
||||
|
||||
[[workflow.steps.conditional.branches.steps.sequential]]
|
||||
id = "deep-research"
|
||||
agent = { kind = "by_name", name = "expert-researcher" }
|
||||
task = "深入研究: {{initial_result}}"
|
||||
output = "deep_result"
|
||||
|
||||
[[workflow.steps.conditional.branches.steps.sequential]]
|
||||
id = "peer-review"
|
||||
agent = { kind = "by_role", role = "reviewer" }
|
||||
task = "同行评审: {{deep_result}}"
|
||||
output = "reviewed_result"
|
||||
|
||||
[[workflow.steps.conditional.branches]]
|
||||
id = "quick-branch"
|
||||
condition = "{{input.complexity}} == quick"
|
||||
|
||||
[[workflow.steps.conditional.branches.steps.sequential]]
|
||||
id = "quick-summary"
|
||||
agent = { kind = "by_name", name = "writer" }
|
||||
task = "快速总结: {{initial_result}}"
|
||||
output = "quick_summary"
|
||||
|
||||
[[workflow.steps.conditional.default]]
|
||||
|
||||
[[workflow.steps.conditional.default.sequential]]
|
||||
id = "standard-summary"
|
||||
agent = { kind = "by_name", name = "writer" }
|
||||
task = "标准总结: {{initial_result}}"
|
||||
output = "standard_summary"
|
||||
```
|
||||
|
||||
### 4. 循环处理工作流
|
||||
|
||||
```toml
|
||||
[workflow]
|
||||
name = "batch-processor"
|
||||
version = "1.0.0"
|
||||
|
||||
[workflow.input]
|
||||
items = { type = "array", required = true, description = "要处理的项目列表" }
|
||||
|
||||
[[workflow.steps.loop]]
|
||||
id = "process-items"
|
||||
item_var = "item"
|
||||
index_var = "idx"
|
||||
collection = "{{input.items}}"
|
||||
collect = "merge"
|
||||
output = "processed_items"
|
||||
|
||||
[[workflow.steps.loop.steps.sequential]]
|
||||
id = "process-single"
|
||||
agent = { kind = "by_name", name = "processor" }
|
||||
task = "处理第 {{loop.idx}} 个项目: {{loop.item}}"
|
||||
output = "item_result"
|
||||
```
|
||||
|
||||
### 5. 错误处理与回退
|
||||
|
||||
```toml
|
||||
[workflow]
|
||||
name = "robust-workflow"
|
||||
version = "1.0.0"
|
||||
|
||||
[workflow.input]
|
||||
query = { type = "string", required = true }
|
||||
|
||||
[workflow.config]
|
||||
default_error_mode = "retry"
|
||||
max_retries = 3
|
||||
|
||||
[[workflow.steps.fallback]]
|
||||
id = "search-with-fallback"
|
||||
output = "search_result"
|
||||
|
||||
[workflow.steps.fallback.primary.sequential]
|
||||
id = "primary-search"
|
||||
agent = { kind = "by_name", name = "primary-searcher" }
|
||||
task = "搜索: {{input.query}}"
|
||||
error_mode = "skip"
|
||||
timeout_secs = 30
|
||||
|
||||
[[workflow.steps.fallback.fallbacks.sequential]]
|
||||
id = "fallback-search"
|
||||
agent = { kind = "by_name", name = "backup-searcher" }
|
||||
task = "备用搜索: {{input.query}}"
|
||||
|
||||
[[workflow.steps.fallback.fallbacks.sequential]]
|
||||
id = "cached-search"
|
||||
agent = { kind = "by_name", name = "cache-agent" }
|
||||
task = "从缓存查找: {{input.query}}"
|
||||
```
|
||||
|
||||
### 6. 完整配置示例
|
||||
|
||||
```toml
|
||||
[workflow]
|
||||
name = "enterprise-research-pipeline"
|
||||
version = "2.0.0"
|
||||
description = "企业级研究流水线"
|
||||
author = "OpenFang Team"
|
||||
tags = ["research", "analysis", "enterprise"]
|
||||
|
||||
[workflow.input]
|
||||
topic = { type = "string", required = true, description = "研究主题" }
|
||||
depth = { type = "string", required = false, default = "standard", enum_values = ["quick", "standard", "exhaustive"] }
|
||||
max_sources = { type = "integer", required = false, default = 10 }
|
||||
|
||||
[workflow.config]
|
||||
timeout_secs = 1800 # 30分钟总超时
|
||||
max_retries = 3 # 最大重试次数
|
||||
default_error_mode = "fail"
|
||||
max_concurrency = 5 # 最大并行数
|
||||
persist_state = true # 持久化状态以支持恢复
|
||||
|
||||
# ... 步骤定义 ...
|
||||
```
|
||||
|
||||
## API 使用
|
||||
|
||||
### 编译工作流
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:4200/api/aol/compile \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"toml": "[workflow]\nname = \"test\"\nversion = \"1.0.0\"\n\n[[workflow.steps.sequential]]\nid = \"step1\"\nagent = { kind = \"by_name\", name = \"assistant\" }\ntask = \"Hello\""
|
||||
}'
|
||||
```
|
||||
|
||||
响应:
|
||||
```json
|
||||
{
|
||||
"id": "uuid",
|
||||
"name": "test",
|
||||
"version": "1.0.0",
|
||||
"step_count": 1,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
"validation_errors": []
|
||||
}
|
||||
```
|
||||
|
||||
### 执行工作流
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:4200/api/aol/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"workflow_id": "uuid",
|
||||
"inputs": {
|
||||
"topic": "人工智能"
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
响应:
|
||||
```json
|
||||
{
|
||||
"execution_id": "exec-uuid",
|
||||
"workflow_id": "uuid",
|
||||
"status": "Completed",
|
||||
"step_results": [
|
||||
{
|
||||
"step_id": "step1",
|
||||
"success": true,
|
||||
"output": "处理结果...",
|
||||
"error": null,
|
||||
"duration_ms": 1234,
|
||||
"retries": 0
|
||||
}
|
||||
],
|
||||
"outputs": {
|
||||
"result": "最终输出..."
|
||||
},
|
||||
"error": null,
|
||||
"duration_ms": 1500
|
||||
}
|
||||
```
|
||||
|
||||
### 查询执行状态
|
||||
|
||||
```bash
|
||||
curl http://localhost:4200/api/aol/executions/exec-uuid
|
||||
```
|
||||
|
||||
## Agent 引用方式
|
||||
|
||||
| 类型 | 语法 | 说明 |
|
||||
|------|------|------|
|
||||
| 按ID | `{ kind = "by_id", id = "uuid" }` | 精确引用特定 Agent |
|
||||
| 按名称 | `{ kind = "by_name", name = "assistant" }` | 按名称查找 Agent |
|
||||
| 按角色 | `{ kind = "by_role", role = "researcher" }` | 按角色匹配 Agent |
|
||||
| 带能力 | `{ kind = "by_role", role = "worker", capability = "web_search" }` | 按角色+能力匹配 |
|
||||
|
||||
## 收集策略
|
||||
|
||||
| 策略 | 说明 |
|
||||
|------|------|
|
||||
| `merge` | 合并所有结果为数组 (默认) |
|
||||
| `first` | 只取第一个完成的结果 |
|
||||
| `last` | 只取最后一个完成的结果 |
|
||||
| `aggregate` | 聚合结果 (字符串连接/数值求和) |
|
||||
|
||||
## 错误处理模式
|
||||
|
||||
| 模式 | 说明 |
|
||||
|------|------|
|
||||
| `fail` | 失败时终止工作流 (默认) |
|
||||
| `skip` | 失败时跳过此步骤 |
|
||||
| `retry` | 失败时重试 (最多 max_retries 次) |
|
||||
|
||||
## 模板变量
|
||||
|
||||
| 变量 | 说明 |
|
||||
|------|------|
|
||||
| `{{input.xxx}}` | 输入参数 |
|
||||
| `{{output.step_name}}` | 步骤输出 |
|
||||
| `{{loop.item}}` | 循环当前项 |
|
||||
| `{{loop.idx}}` | 循环当前索引 |
|
||||
@@ -1730,3 +1730,209 @@ presence_log (
|
||||
| E2E 测试框架 | tests/e2e_*.rs | ~800 | 30+ |
|
||||
| Migration v8 | migration.rs | +80 | +2 |
|
||||
| **总计** | | **~2154** | **~76** |
|
||||
|
||||
---
|
||||
|
||||
## 附录 M: AOL 解析器与执行引擎实现 (2026-03-01)
|
||||
|
||||
### AOL 解析器 (TOML → AST) ✅
|
||||
|
||||
**新建文件**:
|
||||
- `crates/openfang-kernel/src/aol/mod.rs` - 模块入口
|
||||
- `crates/openfang-kernel/src/aol/parser.rs` - TOML 解析器 (~600 行)
|
||||
- `crates/openfang-kernel/src/aol/template.rs` - 模板变量展开 (~200 行)
|
||||
- `crates/openfang-kernel/src/aol/validator.rs` - 工作流验证 (~400 行)
|
||||
|
||||
**核心功能**:
|
||||
- 完整的 TOML 工作流解析
|
||||
- 支持所有步骤类型: parallel, sequential, conditional, loop, collect, subworkflow, fallback
|
||||
- 模板变量展开: `{{input.xxx}}`, `{{output.xxx}}`, `{{loop.xxx}}`
|
||||
- 工作流验证: 重复 ID 检测、空步骤检测、循环深度限制
|
||||
|
||||
**API 设计**:
|
||||
```rust
|
||||
// 解析 TOML 工作流
|
||||
pub fn parse_aol_workflow_from_str(toml: &str) -> Result<AolWorkflow, AolParseError>
|
||||
|
||||
// 模板展开
|
||||
pub fn expand_template(template: &str, ctx: &TemplateContext) -> Result<String, TemplateError>
|
||||
|
||||
// 验证工作流
|
||||
pub fn validate_workflow(workflow: &AolWorkflow) -> Result<(), ValidationError>
|
||||
```
|
||||
|
||||
**测试用例** (parser.rs):
|
||||
- `test_parse_simple_workflow` - 基础工作流解析
|
||||
- `test_parse_parallel_workflow` - 并行步骤组
|
||||
- `test_parse_conditional_workflow` - 条件分支
|
||||
- `test_parse_loop_workflow` - 循环步骤
|
||||
- `test_parse_workflow_config` - 配置解析
|
||||
- `test_parse_agent_ref_variants` - Agent 引用变体
|
||||
- `test_duplicate_step_id_error` - 重复 ID 错误
|
||||
- `test_parse_collect_step` - 收集步骤
|
||||
- `test_parse_subworkflow_step` - 子工作流
|
||||
- `test_parse_fallback_step` - 回退步骤
|
||||
- `test_parse_complex_workflow` - 复杂工作流
|
||||
|
||||
---
|
||||
|
||||
### AOL 执行引擎 ✅
|
||||
|
||||
**新建文件**:
|
||||
- `crates/openfang-kernel/src/aol/executor.rs` (~550 行)
|
||||
|
||||
**核心类型**:
|
||||
- `ExecutionId` - 执行实例 ID
|
||||
- `ExecutionStatus` - 执行状态 (Pending, Running, Completed, Failed, Cancelled)
|
||||
- `ExecutionResult` - 执行结果
|
||||
- `StepExecutionResult` - 单步执行结果
|
||||
- `AolExecutor` - 执行器
|
||||
- `AgentExecutor` trait - Agent 任务执行接口
|
||||
|
||||
**执行特性**:
|
||||
- 并行步骤组执行 (支持并发限制)
|
||||
- 条件分支评估
|
||||
- 循环迭代执行
|
||||
- 收集策略 (Merge, First, Last, Aggregate)
|
||||
- 回退链支持
|
||||
- 重试机制
|
||||
- 超时控制
|
||||
|
||||
**API 设计**:
|
||||
```rust
|
||||
// 创建执行器
|
||||
let executor = AolExecutor::with_mock();
|
||||
|
||||
// 执行工作流
|
||||
let result = executor.execute(&compiled_workflow, inputs).await?;
|
||||
|
||||
// 获取执行结果
|
||||
let execution = executor.get_execution(execution_id).await;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### AOL API 端点 ✅
|
||||
|
||||
**新建文件**:
|
||||
- `crates/openfang-api/src/aol_routes.rs` (~400 行)
|
||||
|
||||
**端点列表**:
|
||||
| 端点 | 方法 | 描述 |
|
||||
|------|------|------|
|
||||
| `/api/aol/compile` | POST | 编译 (解析+验证) 工作流 |
|
||||
| `/api/aol/validate` | POST | 仅验证工作流 |
|
||||
| `/api/aol/execute` | POST | 执行已编译的工作流 |
|
||||
| `/api/aol/workflows` | GET | 列出所有已编译工作流 |
|
||||
| `/api/aol/workflows/{id}` | GET/DELETE | 获取/删除工作流 |
|
||||
| `/api/aol/executions` | GET | 列出所有执行 |
|
||||
| `/api/aol/executions/{id}` | GET | 获取执行详情 |
|
||||
|
||||
**使用示例**:
|
||||
```bash
|
||||
# 编译工作流
|
||||
curl -X POST http://localhost:4200/api/aol/compile \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"toml": "[workflow]\nname = \"test\"\n..."}'
|
||||
|
||||
# 执行工作流
|
||||
curl -X POST http://localhost:4200/api/aol/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"workflow_id": "uuid", "inputs": {"topic": "AI"}}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 更新的文件
|
||||
|
||||
| 文件 | 更改 |
|
||||
|------|------|
|
||||
| `crates/openfang-kernel/src/lib.rs` | 添加 `pub mod aol;` |
|
||||
| `crates/openfang-api/src/lib.rs` | 添加 `pub mod aol_routes;` |
|
||||
| `crates/openfang-api/src/server.rs` | 添加 AOL 路由注册 |
|
||||
|
||||
---
|
||||
|
||||
### 实现统计 (更新)
|
||||
|
||||
| 功能 | 文件 | 代码行数 | 测试数 |
|
||||
|------|------|----------|--------|
|
||||
| 知识图谱递归遍历 | knowledge.rs | +200 | +4 |
|
||||
| AOL AST 类型 | aol.rs (types) | 1074 | 40+ |
|
||||
| E2E 测试框架 | tests/e2e_*.rs | ~800 | 30+ |
|
||||
| Migration v8 | migration.rs | +80 | +2 |
|
||||
| AOL 解析器 | aol/parser.rs | ~600 | 15+ |
|
||||
| AOL 模板引擎 | aol/template.rs | ~200 | 15+ |
|
||||
| AOL 验证器 | aol/validator.rs | ~400 | 15+ |
|
||||
| AOL 执行引擎 | aol/executor.rs | ~550 | 10+ |
|
||||
| AOL API 路由 | aol_routes.rs | ~400 | 2+ |
|
||||
| PresenceManager | presence.rs | ~1380 | 28 |
|
||||
| **总计** | | **~5684** | **~161** |
|
||||
|
||||
---
|
||||
|
||||
## 附录 N: PresenceManager 实现 ✅ (2026-03-01)
|
||||
|
||||
**新建文件**:
|
||||
- `crates/openfang-kernel/src/presence.rs` (~1380 行)
|
||||
|
||||
**核心类型**:
|
||||
- `ConnectionId` - WebSocket 连接 ID (Uuid)
|
||||
- `CollabSessionId` - 协作会话 ID (Uuid)
|
||||
- `PresenceStatus` - 用户状态枚举 (Active, Idle, Away)
|
||||
- `PresenceCursor` - 光标位置 (message_index, char_start, char_end)
|
||||
- `PresenceUser` - 用户信息 (connection_id, display_name, status, cursor, last_activity, color)
|
||||
- `CollabSession` - 协作会话
|
||||
- `PresenceConfig` - 配置 (超时设置)
|
||||
- `PresenceStats` - 统计信息
|
||||
|
||||
**核心功能**:
|
||||
- 会话管理: create_session, get_session, remove_session, list_sessions
|
||||
- 用户加入/离开: join_session, leave_session
|
||||
- 状态更新: update_cursor, clear_cursor, update_status, heartbeat
|
||||
- 查询: get_session_users, get_user, get_session_user_count
|
||||
- 自动清理: update_idle_statuses, cleanup_inactive_users
|
||||
|
||||
**测试用例**: 28 个测试覆盖所有功能
|
||||
|
||||
**设计特点**:
|
||||
- 使用 DashMap 支持高并发
|
||||
- 自动生成用户颜色 (HSL-based)
|
||||
- 可配置超时设置
|
||||
- 完整的错误处理
|
||||
|
||||
---
|
||||
|
||||
## 附录 O: AnnotationStore 实现 ✅ (2026-03-01)
|
||||
|
||||
**新建文件**:
|
||||
- `crates/openfang-memory/src/annotations.rs` (~800 行)
|
||||
|
||||
**核心类型**:
|
||||
- `AnnotationId` - 注释唯一 ID (Uuid)
|
||||
- `AnnotationType` - 类型枚举 (Comment, Question, Suggestion, Issue, Highlight)
|
||||
- `AnnotationStatus` - 状态枚举 (Open, Resolved, Dismissed)
|
||||
- `AnnotationPriority` - 优先级枚举 (Low, Normal, High, Urgent)
|
||||
- `Annotation` - 注释实体
|
||||
- `AnnotationReaction` - 注释反应
|
||||
- `AnnotationStats` - 统计信息
|
||||
- `AnnotationError` - 错误类型
|
||||
- `AnnotationStore` - 存储管理器
|
||||
|
||||
**核心功能**:
|
||||
- 创建注释: create_annotation
|
||||
- 获取注释: get_annotation, list_annotations, list_annotations_for_message
|
||||
- 线程管理: get_thread, list_root_annotations
|
||||
- 更新操作: update_annotation_content, update_annotation_status
|
||||
- 状态变更: resolve_annotation, dismiss_annotation, reopen_annotation
|
||||
- 删除操作: delete_annotation, delete_session_annotations
|
||||
- 反应管理: add_reaction, remove_reaction, get_reactions, get_reaction_summary
|
||||
- 统计: get_session_stats
|
||||
|
||||
**测试用例**: 20+ 测试覆盖所有功能
|
||||
|
||||
**设计特点**:
|
||||
- SQLite 持久化存储
|
||||
- 支持线程回复 (parent_id)
|
||||
- 支持行号范围 (line_start, line_end)
|
||||
- 完整的反应系统
|
||||
|
||||
Reference in New Issue
Block a user