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
132 .clone()
133 .unwrap_or_else(|| "X-API-Key".into()),
134 String::new(),
135 ),
136 _ => ("Authorization".into(), "Bearer ".into()),
137 }
138 }
139
140 /// For a stdio server, the environment variable the token is set in, if this
141 /// server uses env-based auth.
142 pub fn stdio_auth_env(&self) -> Option<String> {
143 if self.auth.as_deref() == Some("env") {
144 self.auth_header.clone()
145 } else {
146 None
147 }
148 }
149}
150
151/// Per-invocation limits and steering (`CONTEXT.md` §10 budgets).
152#[derive(Debug, Clone, Default, Serialize, Deserialize)]
153pub struct Constraints {
154 /// Hard wall-clock timeout for this invocation, if any.
155 pub timeout_secs: Option<u64>,
156 /// Optional session id to continue cheap intra-worker context where the
157 /// underlying tool supports it (`CONTEXT.md` §8).
158 pub session_id: Option<String>,
159 /// Ambient steering text captured from the user mid-run (`CONTEXT.md` §11).
160 pub steer: Option<String>,
161 /// Model the harness should run for this node, if selected. Passed to the
162 /// CLI as e.g. `--model sonnet` / `-m grok-build`.
163 pub model: Option<String>,
164 /// When true, harness workers should open a visible Stage/PTY session so the
165 /// user can watch the native agent CLI (`plan.md` Harness Stage).
166 #[serde(default)]
167 pub visible_stage: bool,
168}
169
170/// Everything a worker needs to do one unit of work (`CONTEXT.md` §8).
171#[derive(Debug, Clone)]
172pub struct ExecuteRequest {
173 pub role: Role,
174 pub instruction: String,
175 pub context: ContextPacket,
176 /// The repository / working directory the worker operates in.
177 pub workspace: PathBuf,
178 pub constraints: Constraints,
179 /// MCP tools this node may call via the host agentic loop (`MCP_SKILLS.md`
180 /// §6). Empty for nodes that attach none; only API workers act on it. Built
181 /// by the engine from `node.tools` against the run's tool catalog.
182 pub tools: Vec<ToolSpec>,
183 /// MCP servers to provision into a harness so it calls the node's tools
184 /// natively — the provision path (`MCP_SKILLS.md` §6). The harness sibling of
185 /// `tools`: both are filled from `node.tools`; an API worker reads `tools`, a
186 /// harness reads `mcp_servers`.
187 pub mcp_servers: Vec<McpServerSpec>,
188}
189
190/// How an execution ended.
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
192#[serde(rename_all = "kebab-case", tag = "status", content = "detail")]
193pub enum ExecStatus {
194 /// Completed normally.
195 Success,
196 /// The worker ran but reported failure (non-zero exit, error result).
197 Failed(String),
198 /// Exceeded its timeout.
199 TimedOut,
200 /// Cancelled via a cancellation token (`/pause`, budget kill, stuck abort).
201 Cancelled,
202}
203
204impl ExecStatus {
205 pub fn is_success(&self) -> bool {
206 matches!(self, ExecStatus::Success)
207 }
208}
209
210/// Token / time accounting for one invocation (`CONTEXT.md` §8 usage).
211#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
212pub struct Usage {
213 pub prompt_tokens: u64,
214 pub completion_tokens: u64,
215 /// Wall-clock duration of the invocation.
216 pub wall_ms: u64,
217}
218
219impl Usage {
220 pub fn total_tokens(&self) -> u64 {
221 self.prompt_tokens + self.completion_tokens
222 }
223
224 /// Rough token estimate for Latin text (~4 chars / token). Used when a
225 /// harness CLI does not report usage (e.g. Grok streaming-json has no
226 /// usage field) so the ledger and UI are not stuck at `0 tok`.
227 pub fn estimate_tokens(text: &str) -> u64 {
228 let n = text.chars().count() as u64;
229 if n == 0 {
230 0
231 } else {
232 (n / 4).max(1)
233 }
234 }
235
236 /// Fill zero token fields from approximate prompt/result sizes. Leaves
237 /// non-zero (CLI-reported) values alone.
238 pub fn fill_estimates(&mut self, prompt: &str, result: &str) {
239 if self.prompt_tokens == 0 {
240 self.prompt_tokens = Self::estimate_tokens(prompt);
241 }
242 if self.completion_tokens == 0 {
243 self.completion_tokens = Self::estimate_tokens(result);
244 }
245 }
246
247 /// Compact human form: `1.2k` / `350` / `0`.
248 pub fn format_total(&self) -> String {
249 format_token_count(self.total_tokens())
250 }
251}
252
253/// Format a token count for status lines (`0`, `350`, `1.2k`, `2.0M`).
254pub fn format_token_count(n: u64) -> String {
255 if n >= 1_000_000 {
256 format!("{:.1}M", n as f64 / 1_000_000.0)
257 } else if n >= 10_000 {
258 format!("{}k", n / 1000)
259 } else if n >= 1000 {
260 format!("{:.1}k", n as f64 / 1000.0)
261 } else {
262 n.to_string()
263 }
264}
265
266/// The normalized result every adapter returns (`CONTEXT.md` §8).
267#[derive(Debug, Clone, Serialize, Deserialize)]
268pub struct ExecuteResult {
269 /// The worker's primary textual output.
270 pub result: String,
271 /// A unified diff of file changes, if the worker edited the workspace.
272 #[serde(default)]
273 pub file_diff: Option<String>,
274 /// The raw transcript of the worker's session (for `.rinne/transcripts/`).
275 #[serde(default)]
276 pub transcript: String,
277 pub status: ExecStatus,
278 pub usage: Usage,
279 /// A session id the worker can be resumed with, if it supports continuation.
280 #[serde(default)]
281 pub session_id: Option<String>,
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287
288 #[test]
289 fn context_packet_defaults_empty_symbol_map() {
290 let p = ContextPacket::default();
291 assert!(p.symbol_map.is_empty());
292 let json = serde_json::to_string(&p).unwrap();
293 // Round-trips without requiring the field to be present.
294 let back: ContextPacket = serde_json::from_str("{}").unwrap();
295 assert!(back.symbol_map.is_empty());
296 let _ = json;
297 }
298}