Skip to main content

acosmi/agent_runs/
types.rs

1//! Agent Runs 公开 SDK 协议类型。端口自 `agent-runs/types.ts`。
2//!
3//! 公开 API camelCase(这里以 PascalCase 类型 + snake wire 字段表达);HTTP wire 为
4//! snake_case,转换在 `client.rs`。
5//!
6//! 🔴 **`AgentRunStreamEvent` 未知 type → Error 变体注入流**(不丢;与
7//! `remote_control::parse_remote_control_event` 未知→None 静默丢弃**相反**,两套独立解析)。
8
9use crate::agent_runs::remote_control::{
10    AdapterKind, PermissionPolicy, RunnerKind, WorkspacePolicy,
11};
12use serde_json::Value;
13
14/// run 状态。对应 TS `AgentRunStatus`。
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
16pub enum AgentRunStatus {
17    /// 默认 / 未知 wire 值(对齐 TS `toStatus` 默认分支)。
18    #[default]
19    Queued,
20    Running,
21    Completed,
22    Failed,
23    Cancelled,
24}
25
26impl AgentRunStatus {
27    /// wire string → 状态(未知 → Queued,对齐 TS `toStatus` 默认分支)。
28    pub fn from_wire(s: Option<&str>) -> Self {
29        match s {
30            Some("running") => Self::Running,
31            Some("completed") => Self::Completed,
32            Some("failed") => Self::Failed,
33            Some("cancelled") => Self::Cancelled,
34            _ => Self::Queued,
35        }
36    }
37
38    pub fn as_str(&self) -> &'static str {
39        match self {
40            Self::Queued => "queued",
41            Self::Running => "running",
42            Self::Completed => "completed",
43            Self::Failed => "failed",
44            Self::Cancelled => "cancelled",
45        }
46    }
47}
48
49/// 远控运行时选择器(Phase 3 / 契约 §3)。
50pub const AGENT_RUN_RUNTIME_STANDARD: &str = "standard";
51pub const AGENT_RUN_RUNTIME_CRABCODE_REMOTE: &str = "crabcode_remote";
52
53/// run metadata 约定键(契约 §18.3 r4)。
54pub const AGENT_RUN_META_TITLE: &str = "title";
55pub const AGENT_RUN_META_WORKSPACE: &str = "workspace";
56
57/// 本地上下文策略。对应 TS `AgentRunLocalContextPolicy`。
58#[derive(Debug, Clone, Default)]
59pub struct AgentRunLocalContextPolicy {
60    pub enabled: Option<bool>,
61    pub readonly: Option<bool>,
62    pub max_bytes: Option<i64>,
63    pub allowed_tools: Option<Vec<String>>,
64}
65
66/// 产物策略。对应 TS `AgentRunArtifactPolicy`。
67#[derive(Debug, Clone, Default)]
68pub struct AgentRunArtifactPolicy {
69    pub enabled: Option<bool>,
70    pub max_files: Option<i64>,
71}
72
73/// 创建请求。对应 TS `AgentRunCreateRequest`(公开 camelCase;wire 转换在 client)。
74#[derive(Debug, Clone, Default)]
75pub struct AgentRunCreateRequest {
76    pub app_id: String,
77    pub mode: Option<String>,
78    pub session_id: Option<String>,
79    pub input: String,
80    pub messages: Option<Vec<Value>>,
81    pub model: Option<String>,
82    pub active_skill_ids: Option<Vec<String>>,
83    pub knowledge_base_ids: Option<Vec<String>>,
84    pub metadata: Option<std::collections::HashMap<String, String>>,
85    pub local_context_policy: Option<AgentRunLocalContextPolicy>,
86    pub artifact_policy: Option<AgentRunArtifactPolicy>,
87
88    // Phase 3+ remote-control 扩展(契约 §3 / ADR-2)。
89    pub runtime: Option<String>,
90    pub runner: Option<RunnerKind>,
91    pub adapter: Option<AdapterKind>,
92    pub permission_policy: Option<PermissionPolicy>,
93    pub workspace_policy: Option<WorkspacePolicy>,
94    /// BYO 模型密钥公开引用(契约 §18.2;仅远控 runtime + runner='cloud')。
95    pub byok_credential_ref: Option<String>,
96}
97
98/// agent run view(公开形态)。对应 TS `AgentRun`。
99#[derive(Debug, Clone, Default)]
100pub struct AgentRun {
101    pub run_id: String,
102    pub session_id: String,
103    pub app_id: Option<String>,
104    pub mode: Option<String>,
105    pub status: Option<AgentRunStatus>,
106    pub created_at: Option<String>,
107    pub started_at: Option<String>,
108    pub completed_at: Option<String>,
109    pub error: Option<AgentRunErrorPayload>,
110    pub metadata: Option<std::collections::HashMap<String, String>>,
111    // 远控 view 元数据(Phase 5C;标准 run 为 'standard'/缺省)。view 永不携带 token/policy/messages。
112    pub runtime: Option<String>,
113    pub runner: Option<String>,
114    pub adapter: Option<String>,
115}
116
117/// `list()` 过滤/分页参数。对应 TS `AgentRunListOptions`。
118#[derive(Debug, Clone, Default)]
119pub struct AgentRunListOptions {
120    pub runtime: Option<String>,
121    pub status: Option<String>,
122    pub page: Option<i64>,
123    pub page_size: Option<i64>,
124}
125
126/// `list()` 结果。对应 TS `AgentRunListResult`。
127#[derive(Debug, Clone)]
128pub struct AgentRunListResult {
129    pub records: Vec<AgentRun>,
130    pub total: i64,
131    pub page: i64,
132    pub page_size: i64,
133}
134
135/// 创建响应。对应 TS `AgentRunCreateResponse`。
136#[derive(Debug, Clone, Default)]
137pub struct AgentRunCreateResponse {
138    pub run_id: String,
139    pub session_id: String,
140    pub status: AgentRunStatus,
141}
142
143/// 产物。对应 TS `AgentRunArtifact`。
144#[derive(Debug, Clone, Default)]
145pub struct AgentRunArtifact {
146    pub id: String,
147    pub filename: String,
148    pub content_type: Option<String>,
149    pub size: Option<i64>,
150    pub r#type: Option<String>,
151    pub metadata: Option<std::collections::HashMap<String, String>>,
152}
153
154/// 下载结果。对应 TS `AgentRunDownload`。
155#[derive(Debug, Clone)]
156pub struct AgentRunDownload {
157    pub data: Vec<u8>,
158    pub filename: String,
159    pub content_type: Option<String>,
160}
161
162/// usage(开放形态:已知字段 + raw passthrough)。对应 TS `AgentRunUsage`。
163#[derive(Debug, Clone, Default)]
164pub struct AgentRunUsage {
165    pub input_tokens: Option<i64>,
166    pub output_tokens: Option<i64>,
167    pub total_tokens: Option<i64>,
168    pub cache_read_tokens: Option<i64>,
169    pub cache_create_tokens: Option<i64>,
170    pub exact: Option<bool>,
171    pub source: Option<String>,
172    /// 原始 wire 对象(TS `[key:string]:unknown` 扩展)。
173    pub raw: Value,
174}
175
176/// settlement(开放形态)。对应 TS `AgentRunSettlement`。
177#[derive(Debug, Clone, Default)]
178pub struct AgentRunSettlement {
179    pub request_id: Option<String>,
180    pub status: Option<String>,
181    pub consume_status: Option<String>,
182    pub input_tokens: Option<i64>,
183    pub output_tokens: Option<i64>,
184    pub total_tokens: Option<i64>,
185    pub cache_read_tokens: Option<i64>,
186    pub cache_create_tokens: Option<i64>,
187    pub token_remaining: Option<i64>,
188    pub call_remaining: Option<i64>,
189    pub retry_queued: Option<bool>,
190    pub exact: Option<bool>,
191    pub raw: Value,
192}
193
194/// 错误载荷。对应 TS `AgentRunErrorPayload`。
195#[derive(Debug, Clone, Default)]
196pub struct AgentRunErrorPayload {
197    pub code: Option<String>,
198    pub message: String,
199    pub stage: Option<String>,
200    pub retryable: Option<bool>,
201    pub raw: Option<Value>,
202}
203
204/// 本地工具回写结果。对应 TS `AgentRunLocalToolResult`。
205#[derive(Debug, Clone, Default)]
206pub struct AgentRunLocalToolResult {
207    pub request_id: String,
208    pub ok: bool,
209    pub content: Option<Value>,
210    pub error: Option<String>,
211}
212
213/// stream options。对应 TS `AgentRunStreamOptions`。
214#[derive(Debug, Clone)]
215pub struct AgentRunStreamOptions {
216    /// 默认 true:error 事件解析后转 `Error::AgentRunStream` 抛出。
217    pub throw_on_error: bool,
218}
219
220impl Default for AgentRunStreamOptions {
221    fn default() -> Self {
222        Self {
223            throw_on_error: true,
224        }
225    }
226}
227
228/// `run()` options(继承 stream options)。对应 TS `AgentRunRunOptions`。
229pub type AgentRunRunOptions = AgentRunStreamOptions;
230
231/// `run_with_local_tools()` options。对应 TS `AgentRunWithLocalToolsOptions`。
232#[derive(Debug, Clone)]
233pub struct AgentRunWithLocalToolsOptions {
234    pub throw_on_error: bool,
235    /// 本地工具回调硬超时(毫秒);缺省 30_000。
236    pub timeout_ms: u64,
237}
238
239impl Default for AgentRunWithLocalToolsOptions {
240    fn default() -> Self {
241        Self {
242            throw_on_error: true,
243            timeout_ms: 30_000,
244        }
245    }
246}
247
248/// SSE 事件 union(扁平判别符 enum,恰镜像 TS discriminated union)。对应 TS `AgentRunStreamEvent`。
249///
250/// 🔴 未知 type 在内部 SSE 流解析器中映射为 [`AgentRunStreamEvent::Error`]
251/// (`code="unknown_event"`),**注入流不丢**。
252#[derive(Debug, Clone)]
253pub enum AgentRunStreamEvent {
254    RunStarted {
255        run_id: String,
256        session_id: String,
257    },
258    Status {
259        status: String,
260        message: Option<String>,
261    },
262    TextDelta {
263        text: String,
264    },
265    ReasoningDelta {
266        text: String,
267    },
268    ToolCall {
269        id: String,
270        name: String,
271        input: Option<Value>,
272    },
273    ToolResult {
274        id: String,
275        name: Option<String>,
276        result: Option<Value>,
277        error: Option<String>,
278    },
279    LocalToolRequest {
280        request_id: String,
281        name: String,
282        input: Value,
283    },
284    Artifact {
285        artifact: AgentRunArtifact,
286    },
287    Sources {
288        sources: Value,
289    },
290    Usage {
291        usage: AgentRunUsage,
292    },
293    Settle {
294        settlement: AgentRunSettlement,
295    },
296    Error {
297        error: AgentRunErrorPayload,
298    },
299    Done {
300        run_id: String,
301        status: String,
302    },
303}
304
305impl AgentRunStreamEvent {
306    /// 事件判别符(对齐 TS `event.type`)。
307    pub fn type_str(&self) -> &'static str {
308        match self {
309            Self::RunStarted { .. } => "run_started",
310            Self::Status { .. } => "status",
311            Self::TextDelta { .. } => "text_delta",
312            Self::ReasoningDelta { .. } => "reasoning_delta",
313            Self::ToolCall { .. } => "tool_call",
314            Self::ToolResult { .. } => "tool_result",
315            Self::LocalToolRequest { .. } => "local_tool_request",
316            Self::Artifact { .. } => "artifact",
317            Self::Sources { .. } => "sources",
318            Self::Usage { .. } => "usage",
319            Self::Settle { .. } => "settle",
320            Self::Error { .. } => "error",
321            Self::Done { .. } => "done",
322        }
323    }
324}