Skip to main content

aios_spec/
intent.rs

1//! 意图与动作 — "what the LLM tells us to do"
2//!
3//! Cloud LLM 返回的结构化决策, 从 agent 流向 core。
4
5use serde::{Deserialize, Serialize};
6
7use crate::event::ExtensionCategory;
8
9/// 云端 LLM 返回的结构化决策
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct IntentBatch {
12    /// 请求对应的窗口 ID
13    pub window_id: String,
14    /// 候选意图列表 (按置信度降序)
15    pub intents: Vec<Intent>,
16    /// 生成时间 (epoch ms)
17    pub generated_at_ms: i64,
18    /// 模型标识
19    pub model: String,
20}
21
22/// 推理路由选择。
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24pub enum DecisionRoute {
25    RuleBased,
26    LocalEvaluator,
27    CloudLlm,
28    FallbackNoOp,
29    Mock,
30}
31
32/// 单个推理后端的统一输出。
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct DecisionBackendResult {
35    pub route: DecisionRoute,
36    pub intent_batch: IntentBatch,
37    pub rationale_tags: Vec<String>,
38    pub latency_us: u64,
39    pub error: Option<String>,
40}
41
42/// 单条意图
43#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct Intent {
45    /// 意图唯一 ID
46    pub intent_id: String,
47    /// 意图类型
48    pub intent_type: IntentType,
49    /// 置信度 (0.0 ~ 1.0)
50    pub confidence: f32,
51    /// 风险等级
52    pub risk_level: RiskLevel,
53    /// 该意图的推荐动作列表
54    pub suggested_actions: Vec<SuggestedAction>,
55    /// LLM 给出的理由标签 (简短, 不用自然语言)
56    pub rationale_tags: Vec<String>,
57}
58
59/// 意图类型
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61pub enum IntentType {
62    /// 用户将打开某个 app
63    OpenApp(String),
64    /// 用户将切换到某个 app
65    SwitchToApp(String),
66    /// 用户将查看某条通知
67    CheckNotification(String),
68    /// 用户将处理某类文件
69    HandleFile(ExtensionCategory),
70    /// 用户即将进入某个物理场景
71    EnterContext(String),
72    /// 无明确意图, 保持观察
73    Idle,
74}
75
76/// 风险等级
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
78pub enum RiskLevel {
79    /// 可自动执行
80    Low,
81    /// 需要策略引擎二次确认后执行
82    Medium,
83    /// 仅建议, 不自动执行
84    High,
85}
86
87/// 推荐动作
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct SuggestedAction {
90    pub action_type: ActionType,
91    /// 目标标识 (app package 或其他)
92    pub target: Option<String>,
93    /// 紧迫度
94    pub urgency: ActionUrgency,
95}
96
97/// 动作类型
98#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
99pub enum ActionType {
100    /// 预热应用进程
101    PreWarmProcess,
102    /// 预加载热点文件到页缓存
103    PrefetchFile,
104    /// 保活当前前台进程
105    KeepAlive,
106    /// 释放指定进程的非关键内存
107    ReleaseMemory,
108    /// 不执行任何操作
109    NoOp,
110}
111
112/// 动作紧迫度
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
114pub enum ActionUrgency {
115    /// 立即执行
116    Immediate,
117    /// 空闲时执行
118    IdleTime,
119    /// 延迟执行
120    Deferred,
121}
122
123// ============================================================
124// CapabilityLevel — 后端能力上限
125// ============================================================
126
127/// 推理后端的能力上限。
128///
129/// 每个 `DecisionRoute` 变体绑定一个 `CapabilityLevel`,
130/// 声明该后端能产出的最大风险等级和允许的动作类型。
131/// `PolicyEngine` 在审查时据此拒绝越权意图。
132#[derive(Debug, Clone)]
133pub struct CapabilityLevel {
134    pub max_risk: RiskLevel,
135    pub allowed_actions: Vec<ActionType>,
136}
137
138/// Structured rejection reason emitted by `PolicyEngine`.
139///
140/// Replaces the previous `Option<String>` channel so downstream consumers
141/// (replay summary, golden tests, observability) can count denials per
142/// reason without parsing free-form strings. `BTreeMap` keying requires
143/// `Ord`; `Hash` keeps the door open for `HashMap` callers.
144#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
145pub enum DenialReason {
146    /// Intent risk exceeds the engine's configured `max_auto_risk`.
147    RiskExceedsConfig,
148    /// Intent risk exceeds the decision backend's `CapabilityLevel.max_risk`.
149    RiskExceedsCapability,
150    /// Intent confidence is below the engine's floor.
151    ConfidenceTooLow,
152    /// Action type matches the engine's blocked-action substring list.
153    ActionTypeBlocked,
154    /// Action urgency is `Deferred` — not in scope for this batch.
155    ActionUrgencyDeferred,
156    /// Action type is not in the backend `CapabilityLevel.allowed_actions`.
157    ActionCapabilityDenied,
158    /// Action targets a package or path that was not observed in the
159    /// `StructuredContext` that produced this batch.
160    TargetNotInContext,
161    /// Per-intent action count is above the engine's `max_actions_per_batch`.
162    BatchActionCapExceeded,
163}
164
165impl CapabilityLevel {
166    /// 根据路由选择返回对应的能力等级。
167    pub fn for_route(route: DecisionRoute) -> Self {
168        use ActionType::*;
169        match route {
170            DecisionRoute::RuleBased => Self {
171                max_risk: RiskLevel::Low,
172                allowed_actions: vec![NoOp, ReleaseMemory, KeepAlive],
173            },
174            DecisionRoute::LocalEvaluator => Self {
175                max_risk: RiskLevel::Low,
176                allowed_actions: vec![NoOp, PreWarmProcess, PrefetchFile, ReleaseMemory, KeepAlive],
177            },
178            DecisionRoute::CloudLlm => Self {
179                max_risk: RiskLevel::Medium,
180                allowed_actions: vec![NoOp, PreWarmProcess, PrefetchFile, KeepAlive, ReleaseMemory],
181            },
182            DecisionRoute::FallbackNoOp => Self {
183                max_risk: RiskLevel::Low,
184                allowed_actions: vec![NoOp],
185            },
186            DecisionRoute::Mock => Self {
187                max_risk: RiskLevel::Medium,
188                allowed_actions: vec![NoOp, PreWarmProcess, PrefetchFile, KeepAlive, ReleaseMemory],
189            },
190        }
191    }
192
193    /// 检查给定意图的风险等级是否在后端能力范围内。
194    pub fn allows_risk(&self, risk: RiskLevel) -> bool {
195        risk as u8 <= self.max_risk as u8
196    }
197
198    /// 检查给定动作类型是否在后端允许的白名单内。
199    pub fn allows_action(&self, action: &ActionType) -> bool {
200        self.allowed_actions.contains(action)
201    }
202}