rinne_types/worker/exec.rs
1//! The execution contract: what goes into a worker and what comes back
2//! (`CONTEXT.md` §8).
3
4use std::path::PathBuf;
5
6use serde::{Deserialize, Serialize};
7
8/// The role a node plays in the DAG (`CONTEXT.md` §10). Defined here because
9/// `execute` takes a role; the DAG types in Phase 3 reuse it.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
11#[serde(rename_all = "lowercase")]
12pub enum Role {
13 Planner,
14 Generator,
15 Evaluator,
16 Synthesizer,
17 Fixer,
18}
19
20/// The assembled context for one node, shaped per worker family by the context
21/// assembler (`CONTEXT.md` §12).
22///
23/// For a harness worker the assembler writes a thin packet and **pins file
24/// paths** (the worker reads the repo itself). For an API worker it **inlines
25/// file contents** (the model sees only what is sent). Both forms are carried
26/// here; an adapter consumes whichever fits its family.
27#[derive(Debug, Clone, Default, Serialize, Deserialize)]
28pub struct ContextPacket {
29 /// Pinned file paths for harness workers to read themselves.
30 #[serde(default)]
31 pub pinned_paths: Vec<PathBuf>,
32 /// Inlined `(path, contents)` for API workers.
33 #[serde(default)]
34 pub inlined_files: Vec<InlinedFile>,
35 /// Prior node outputs / blackboard digest text relevant to this node.
36 #[serde(default)]
37 pub prior_context: String,
38 /// A critique artifact from a failed evaluator, fed back on loop-back
39 /// (`CONTEXT.md` §10, §11).
40 #[serde(default)]
41 pub critique: Option<String>,
42 /// Instruction text from any skills attached to this node (`MCP_SKILLS.md`
43 /// §11). Injected verbatim into the worker's prompt, both families.
44 #[serde(default)]
45 pub skill_text: String,
46 /// Graph-derived neighborhoods (definition + callers/callees/imports with
47 /// file:line coordinates) for symbols this node is expected to touch, so a
48 /// harness finds the right code without re-scanning. Empty when the graph
49 /// resolved nothing; never removes the pinned paths.
50 #[serde(default)]
51 pub symbol_map: Vec<crate::graph::Neighborhood>,
52}
53
54/// A file inlined into an API worker's context.
55#[derive(Debug, Clone, Serialize, Deserialize)]
56pub struct InlinedFile {
57 pub path: PathBuf,
58 pub contents: String,
59}
60
61/// An MCP tool offered to a worker for the host agentic loop (`MCP_SKILLS.md`
62/// §6). Carries the full argument schema; the cheap catalog layer the planner
63/// plans over is only id+description.
64#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct ToolSpec {
66 /// Qualified id `server.tool` — also the function name sent to the model.
67 pub id: String,
68 pub description: String,
69 /// JSON Schema for the tool's arguments (the MCP `inputSchema`).
70 pub schema: serde_json::Value,
71}
72
73/// How an MCP server is reached. Mirrors the config transport but lives here so
74/// the worker adapters need no dependency on `rinne-config`.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "lowercase")]
77pub enum McpTransportKind {
78 Stdio,
79 Http,
80}
81
82/// Everything a harness needs to launch/connect an MCP server itself — the
83/// provision path (`MCP_SKILLS.md` §6). A harness with a node's `mcp_servers`
84/// runs the tools natively rather than Rinne driving the host loop.
85///
86/// The `token` is the resolved secret, held in memory only: a provisioner must
87/// reference it via environment expansion in the config it writes, never inline
88/// it on disk (§9, §12).
89#[derive(Debug, Clone, Serialize, Deserialize)]
90pub struct McpServerSpec {
91 pub name: String,
92 pub transport: McpTransportKind,
93 #[serde(default)]
94 pub command: Option<String>,
95 #[serde(default)]
96 pub args: Vec<String>,
97 /// Non-secret environment passed to a stdio server.
98 #[serde(default)]
99 pub env: Vec<(String, String)>,
100 #[serde(default)]
101 pub url: Option<String>,
102 /// Non-secret headers for an http server.
103 #[serde(default)]
104 pub headers: Vec<(String, String)>,
105 /// The environment variable the server's token is referenced through (the
106 /// var a stdio server reads, or the one an http `Authorization` header
107 /// expands). `None` when the server needs no token.
108 #[serde(default)]
109 pub token_env: Option<String>,
110 /// The resolved token value. In memory only — never serialized to a config
111 /// file by a provisioner; injected into the harness subprocess environment
112 /// and referenced via `token_env`.
113 #[serde(default, skip_serializing)]
114 pub token: Option<String>,
115 /// How the token is presented (`MCP_SKILLS.md` §10): `bearer` (default HTTP
116 /// `Authorization: Bearer`), `apikey` (a custom HTTP header named by
117 /// `auth_header`), or `env` (a stdio env var named by `auth_header`).
118 #[serde(default)]
119 pub auth: Option<String>,
120 /// The header/env-var name for `apikey`/`env` auth.
121 #[serde(default)]
122 pub auth_header: Option<String>,
123}
124
125impl McpServerSpec {
126 /// For an HTTP server, the `(header_name, value_prefix)` the token is sent as
127 /// (bearer by default).
128 pub fn http_auth(&self) -> (String, String) {
129 match self.auth.as_deref() {
130 Some("apikey") => (
131 self.auth_header.clone().unwrap_or_else(|| "X-API-Key".into()),
132 String::new(),
133 ),
134 _ => ("Authorization".into(), "Bearer ".into()),
135 }
136 }
137
138 /// For a stdio server, the environment variable the token is set in, if this
139 /// server uses env-based auth.
140 pub fn stdio_auth_env(&self) -> Option<String> {
141 if self.auth.as_deref() == Some("env") {
142 self.auth_header.clone()
143 } else {
144 None
145 }
146 }
147}
148
149/// Per-invocation limits and steering (`CONTEXT.md` §10 budgets).
150#[derive(Debug, Clone, Default, Serialize, Deserialize)]
151pub struct Constraints {
152 /// Hard wall-clock timeout for this invocation, if any.
153 pub timeout_secs: Option<u64>,
154 /// Optional session id to continue cheap intra-worker context where the
155 /// underlying tool supports it (`CONTEXT.md` §8).
156 pub session_id: Option<String>,
157 /// Ambient steering text captured from the user mid-run (`CONTEXT.md` §11).
158 pub steer: Option<String>,
159 /// Model the harness should run for this node, if selected. Passed to the
160 /// CLI as e.g. `--model sonnet` / `-m grok-build`.
161 pub model: Option<String>,
162}
163
164/// Everything a worker needs to do one unit of work (`CONTEXT.md` §8).
165#[derive(Debug, Clone)]
166pub struct ExecuteRequest {
167 pub role: Role,
168 pub instruction: String,
169 pub context: ContextPacket,
170 /// The repository / working directory the worker operates in.
171 pub workspace: PathBuf,
172 pub constraints: Constraints,
173 /// MCP tools this node may call via the host agentic loop (`MCP_SKILLS.md`
174 /// §6). Empty for nodes that attach none; only API workers act on it. Built
175 /// by the engine from `node.tools` against the run's tool catalog.
176 pub tools: Vec<ToolSpec>,
177 /// MCP servers to provision into a harness so it calls the node's tools
178 /// natively — the provision path (`MCP_SKILLS.md` §6). The harness sibling of
179 /// `tools`: both are filled from `node.tools`; an API worker reads `tools`, a
180 /// harness reads `mcp_servers`.
181 pub mcp_servers: Vec<McpServerSpec>,
182}
183
184/// How an execution ended.
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186#[serde(rename_all = "kebab-case", tag = "status", content = "detail")]
187pub enum ExecStatus {
188 /// Completed normally.
189 Success,
190 /// The worker ran but reported failure (non-zero exit, error result).
191 Failed(String),
192 /// Exceeded its timeout.
193 TimedOut,
194 /// Cancelled via a cancellation token (`/pause`, budget kill, stuck abort).
195 Cancelled,
196}
197
198impl ExecStatus {
199 pub fn is_success(&self) -> bool {
200 matches!(self, ExecStatus::Success)
201 }
202}
203
204/// Token / time accounting for one invocation (`CONTEXT.md` §8 usage).
205#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
206pub struct Usage {
207 pub prompt_tokens: u64,
208 pub completion_tokens: u64,
209 /// Wall-clock duration of the invocation.
210 pub wall_ms: u64,
211}
212
213impl Usage {
214 pub fn total_tokens(&self) -> u64 {
215 self.prompt_tokens + self.completion_tokens
216 }
217
218 /// Rough token estimate for Latin text (~4 chars / token). Used when a
219 /// harness CLI does not report usage (e.g. Grok streaming-json has no
220 /// usage field) so the ledger and UI are not stuck at `0 tok`.
221 pub fn estimate_tokens(text: &str) -> u64 {
222 let n = text.chars().count() as u64;
223 if n == 0 {
224 0
225 } else {
226 (n / 4).max(1)
227 }
228 }
229
230 /// Fill zero token fields from approximate prompt/result sizes. Leaves
231 /// non-zero (CLI-reported) values alone.
232 pub fn fill_estimates(&mut self, prompt: &str, result: &str) {
233 if self.prompt_tokens == 0 {
234 self.prompt_tokens = Self::estimate_tokens(prompt);
235 }
236 if self.completion_tokens == 0 {
237 self.completion_tokens = Self::estimate_tokens(result);
238 }
239 }
240
241 /// Compact human form: `1.2k` / `350` / `0`.
242 pub fn format_total(&self) -> String {
243 format_token_count(self.total_tokens())
244 }
245}
246
247/// Format a token count for status lines (`0`, `350`, `1.2k`, `2.0M`).
248pub fn format_token_count(n: u64) -> String {
249 if n >= 1_000_000 {
250 format!("{:.1}M", n as f64 / 1_000_000.0)
251 } else if n >= 10_000 {
252 format!("{}k", n / 1000)
253 } else if n >= 1000 {
254 format!("{:.1}k", n as f64 / 1000.0)
255 } else {
256 n.to_string()
257 }
258}
259
260/// The normalized result every adapter returns (`CONTEXT.md` §8).
261#[derive(Debug, Clone, Serialize, Deserialize)]
262pub struct ExecuteResult {
263 /// The worker's primary textual output.
264 pub result: String,
265 /// A unified diff of file changes, if the worker edited the workspace.
266 #[serde(default)]
267 pub file_diff: Option<String>,
268 /// The raw transcript of the worker's session (for `.rinne/transcripts/`).
269 #[serde(default)]
270 pub transcript: String,
271 pub status: ExecStatus,
272 pub usage: Usage,
273 /// A session id the worker can be resumed with, if it supports continuation.
274 #[serde(default)]
275 pub session_id: Option<String>,
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281
282 #[test]
283 fn context_packet_defaults_empty_symbol_map() {
284 let p = ContextPacket::default();
285 assert!(p.symbol_map.is_empty());
286 let json = serde_json::to_string(&p).unwrap();
287 // Round-trips without requiring the field to be present.
288 let back: ContextPacket = serde_json::from_str("{}").unwrap();
289 assert!(back.symbol_map.is_empty());
290 let _ = json;
291 }
292}