Skip to main content

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}
47
48/// A file inlined into an API worker's context.
49#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct InlinedFile {
51    pub path: PathBuf,
52    pub contents: String,
53}
54
55/// An MCP tool offered to a worker for the host agentic loop (`MCP_SKILLS.md`
56/// §6). Carries the full argument schema; the cheap catalog layer the planner
57/// plans over is only id+description.
58#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct ToolSpec {
60    /// Qualified id `server.tool` — also the function name sent to the model.
61    pub id: String,
62    pub description: String,
63    /// JSON Schema for the tool's arguments (the MCP `inputSchema`).
64    pub schema: serde_json::Value,
65}
66
67/// How an MCP server is reached. Mirrors the config transport but lives here so
68/// the worker adapters need no dependency on `rinne-config`.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(rename_all = "lowercase")]
71pub enum McpTransportKind {
72    Stdio,
73    Http,
74}
75
76/// Everything a harness needs to launch/connect an MCP server itself — the
77/// provision path (`MCP_SKILLS.md` §6). A harness with a node's `mcp_servers`
78/// runs the tools natively rather than Rinne driving the host loop.
79///
80/// The `token` is the resolved secret, held in memory only: a provisioner must
81/// reference it via environment expansion in the config it writes, never inline
82/// it on disk (§9, §12).
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct McpServerSpec {
85    pub name: String,
86    pub transport: McpTransportKind,
87    #[serde(default)]
88    pub command: Option<String>,
89    #[serde(default)]
90    pub args: Vec<String>,
91    /// Non-secret environment passed to a stdio server.
92    #[serde(default)]
93    pub env: Vec<(String, String)>,
94    #[serde(default)]
95    pub url: Option<String>,
96    /// Non-secret headers for an http server.
97    #[serde(default)]
98    pub headers: Vec<(String, String)>,
99    /// The environment variable the server's token is referenced through (the
100    /// var a stdio server reads, or the one an http `Authorization` header
101    /// expands). `None` when the server needs no token.
102    #[serde(default)]
103    pub token_env: Option<String>,
104    /// The resolved token value. In memory only — never serialized to a config
105    /// file by a provisioner; injected into the harness subprocess environment
106    /// and referenced via `token_env`.
107    #[serde(default, skip_serializing)]
108    pub token: Option<String>,
109    /// How the token is presented (`MCP_SKILLS.md` §10): `bearer` (default HTTP
110    /// `Authorization: Bearer`), `apikey` (a custom HTTP header named by
111    /// `auth_header`), or `env` (a stdio env var named by `auth_header`).
112    #[serde(default)]
113    pub auth: Option<String>,
114    /// The header/env-var name for `apikey`/`env` auth.
115    #[serde(default)]
116    pub auth_header: Option<String>,
117}
118
119impl McpServerSpec {
120    /// For an HTTP server, the `(header_name, value_prefix)` the token is sent as
121    /// (bearer by default).
122    pub fn http_auth(&self) -> (String, String) {
123        match self.auth.as_deref() {
124            Some("apikey") => (
125                self.auth_header.clone().unwrap_or_else(|| "X-API-Key".into()),
126                String::new(),
127            ),
128            _ => ("Authorization".into(), "Bearer ".into()),
129        }
130    }
131
132    /// For a stdio server, the environment variable the token is set in, if this
133    /// server uses env-based auth.
134    pub fn stdio_auth_env(&self) -> Option<String> {
135        if self.auth.as_deref() == Some("env") {
136            self.auth_header.clone()
137        } else {
138            None
139        }
140    }
141}
142
143/// Per-invocation limits and steering (`CONTEXT.md` §10 budgets).
144#[derive(Debug, Clone, Default, Serialize, Deserialize)]
145pub struct Constraints {
146    /// Hard wall-clock timeout for this invocation, if any.
147    pub timeout_secs: Option<u64>,
148    /// Optional session id to continue cheap intra-worker context where the
149    /// underlying tool supports it (`CONTEXT.md` §8).
150    pub session_id: Option<String>,
151    /// Ambient steering text captured from the user mid-run (`CONTEXT.md` §11).
152    pub steer: Option<String>,
153    /// Model the harness should run for this node, if selected. Passed to the
154    /// CLI as e.g. `--model sonnet` / `-m grok-build`.
155    pub model: Option<String>,
156}
157
158/// Everything a worker needs to do one unit of work (`CONTEXT.md` §8).
159#[derive(Debug, Clone)]
160pub struct ExecuteRequest {
161    pub role: Role,
162    pub instruction: String,
163    pub context: ContextPacket,
164    /// The repository / working directory the worker operates in.
165    pub workspace: PathBuf,
166    pub constraints: Constraints,
167    /// MCP tools this node may call via the host agentic loop (`MCP_SKILLS.md`
168    /// §6). Empty for nodes that attach none; only API workers act on it. Built
169    /// by the engine from `node.tools` against the run's tool catalog.
170    pub tools: Vec<ToolSpec>,
171    /// MCP servers to provision into a harness so it calls the node's tools
172    /// natively — the provision path (`MCP_SKILLS.md` §6). The harness sibling of
173    /// `tools`: both are filled from `node.tools`; an API worker reads `tools`, a
174    /// harness reads `mcp_servers`.
175    pub mcp_servers: Vec<McpServerSpec>,
176}
177
178/// How an execution ended.
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
180#[serde(rename_all = "kebab-case", tag = "status", content = "detail")]
181pub enum ExecStatus {
182    /// Completed normally.
183    Success,
184    /// The worker ran but reported failure (non-zero exit, error result).
185    Failed(String),
186    /// Exceeded its timeout.
187    TimedOut,
188    /// Cancelled via a cancellation token (`/pause`, budget kill, stuck abort).
189    Cancelled,
190}
191
192impl ExecStatus {
193    pub fn is_success(&self) -> bool {
194        matches!(self, ExecStatus::Success)
195    }
196}
197
198/// Token / time accounting for one invocation (`CONTEXT.md` §8 usage).
199#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
200pub struct Usage {
201    pub prompt_tokens: u64,
202    pub completion_tokens: u64,
203    /// Wall-clock duration of the invocation.
204    pub wall_ms: u64,
205}
206
207impl Usage {
208    pub fn total_tokens(&self) -> u64 {
209        self.prompt_tokens + self.completion_tokens
210    }
211}
212
213/// The normalized result every adapter returns (`CONTEXT.md` §8).
214#[derive(Debug, Clone, Serialize, Deserialize)]
215pub struct ExecuteResult {
216    /// The worker's primary textual output.
217    pub result: String,
218    /// A unified diff of file changes, if the worker edited the workspace.
219    #[serde(default)]
220    pub file_diff: Option<String>,
221    /// The raw transcript of the worker's session (for `.rinne/transcripts/`).
222    #[serde(default)]
223    pub transcript: String,
224    pub status: ExecStatus,
225    pub usage: Usage,
226    /// A session id the worker can be resumed with, if it supports continuation.
227    #[serde(default)]
228    pub session_id: Option<String>,
229}