interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-cli / src / tool_spill.rs

298 lines · 10739 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! sovereign-core #666: oversized tool results spill to files.
17//!
18//! Mechanism after Hermes Agent (Nous Research, MIT, commit 5480918),
19//! re-implemented; no code copied.
20//!
21//! A tool can return far more text than the model can use (a 1 MB command
22//! output, a huge search). Such a result is written whole to a file in the
23//! session's spill folder, and the conversation gets a short preview (the first
24//! 40 percent and the last 60 percent of a fixed size, with one marker line)
25//! plus the file's path, so the model can page the rest instead of running the
26//! tool again. Three budgets decide what spills:
27//!
28//! - **per result:** any single result larger than this spills;
29//! - **per turn:** if the results of one model reply together are still
30//! larger, the largest remaining ones spill first until they fit;
31//! - **window-scaled:** both budgets are a share of the model's context window
32//! (15 and 30 percent at 4 characters a token), with floors and caps.
33//!
34//! Reading a file (`view_file`) never spills: a spilled read would be read
35//! back and spilled again in a loop. The pure part ([`SpillBudget`],
36//! [`choose`], [`preview`], [`render_full`], [`stub`]) does no I/O;
37//! [`write_spill`] is the only edge.
38
39use serde_json::{json, Value};
40use sha2::{Digest, Sha256};
41use std::path::{Path, PathBuf};
42
43pub const DEFAULT_PER_RESULT_CHARS: usize = 100_000;
44pub const DEFAULT_PER_TURN_CHARS: usize = 200_000;
45pub const PREVIEW_CHARS: usize = 1_500;
46const FLOOR_PER_RESULT_CHARS: usize = 8_000;
47const FLOOR_PER_TURN_CHARS: usize = 16_000;
48/// Room the stub takes besides its preview (path, counts, field names).
49const STUB_OVERHEAD_CHARS: usize = 400;
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct SpillBudget {
53 pub per_result: usize,
54 pub per_turn: usize,
55 pub preview: usize,
56}
57
58impl SpillBudget {
59 /// Budgets for a model window of `window_tokens`.
60 pub fn for_window(window_tokens: usize) -> Self {
61 let chars = window_tokens.saturating_mul(4);
62 Self {
63 per_result: (chars * 15 / 100).clamp(FLOOR_PER_RESULT_CHARS, DEFAULT_PER_RESULT_CHARS),
64 per_turn: (chars * 30 / 100).clamp(FLOOR_PER_TURN_CHARS, DEFAULT_PER_TURN_CHARS),
65 preview: PREVIEW_CHARS,
66 }
67 }
68
69 fn stub_chars(&self) -> usize {
70 self.preview + STUB_OVERHEAD_CHARS
71 }
72}
73
74/// Tools whose results never spill.
75pub fn exempt(tool: &str) -> bool {
76 matches!(tool, "view_file")
77}
78
79/// Which results spill. `sizes[i]` is result `i`'s size in characters as it
80/// would enter the conversation; `exempt[i]` marks results that never spill;
81/// `turn_room` is what is left of the per-turn budget. Pure.
82pub fn choose(
83 sizes: &[usize],
84 exempt: &[bool],
85 budget: &SpillBudget,
86 turn_room: usize,
87) -> Vec<bool> {
88 let shrinks = |i: usize| !exempt[i] && sizes[i] > budget.stub_chars();
89 let mut spill: Vec<bool> = (0..sizes.len())
90 .map(|i| shrinks(i) && sizes[i] > budget.per_result)
91 .collect();
92 let kept = |spill: &[bool]| -> usize {
93 (0..sizes.len())
94 .map(|i| {
95 if spill[i] {
96 budget.stub_chars()
97 } else {
98 sizes[i]
99 }
100 })
101 .sum()
102 };
103 let mut order: Vec<usize> = (0..sizes.len()).filter(|&i| shrinks(i)).collect();
104 order.sort_by(|&a, &b| sizes[b].cmp(&sizes[a]).then(a.cmp(&b)));
105 for i in order {
106 if kept(&spill) <= turn_room {
107 break;
108 }
109 spill[i] = true;
110 }
111 spill
112}
113
114/// The first 40 percent and the last 60 percent of `keep` characters, with
115/// one marker line between them. Text that already fits is returned as is.
116pub fn preview(full: &str, keep: usize) -> String {
117 let total = full.chars().count();
118 if total <= keep {
119 return full.to_string();
120 }
121 let head_n = keep * 40 / 100;
122 let tail_n = keep - head_n;
123 let head: String = full.chars().take(head_n).collect();
124 let tail: String = full.chars().skip(total - tail_n).collect();
125 format!(
126 "{head}\n... [TOOL OUTPUT TRUNCATED - {} chars omitted out of {total} total] ...\n{tail}",
127 total - head_n - tail_n
128 )
129}
130
131/// The whole result as a file a person or `view_file` can page: string
132/// fields with their real line breaks, one heading each; other fields as JSON.
133pub fn render_full(tool: &str, call_id: &str, result: &Value) -> String {
134 let mut out =
135 format!("# Full result of {tool} ({call_id}). The conversation holds only a preview.\n");
136 match result {
137 Value::Object(map) => {
138 for (k, v) in map {
139 match v {
140 Value::String(s) => {
141 out.push_str(&format!("## {k}\n{s}\n"));
142 }
143 other => out.push_str(&format!("## {k}: {other}\n")),
144 }
145 }
146 }
147 other => {
148 out.push_str(&serde_json::to_string_pretty(other).unwrap_or_default());
149 out.push('\n');
150 }
151 }
152 out
153}
154
155/// What the conversation gets instead of a spilled result. A top-level
156/// `status` is carried over so readers of the status still see it.
157pub fn stub(result: &Value, full_chars: usize, path: Option<&Path>, budget: &SpillBudget) -> Value {
158 let text = serde_json::to_string(result).unwrap_or_default();
159 let mut v = json!({
160 "spilled": path.is_some(),
161 "original_chars": full_chars,
162 "preview": preview(&text, budget.preview),
163 });
164 match path {
165 Some(p) => {
166 v["path"] = json!(p.display().to_string());
167 v["read_with"] = json!("view_file with start_line and end_line, a page at a time; do not run the tool again");
168 }
169 None => {
170 v["note"] =
171 json!("the full result could not be saved to a file; only this preview is left");
172 }
173 }
174 if let Some(status) = result.get("status") {
175 v["status"] = status.clone();
176 }
177 v
178}
179
180/// Writes `text` into `dir` under a name taken from its digest, so the same
181/// output twice is one file. Whole or not at all; owner-only permissions.
182pub fn write_spill(dir: &Path, text: &str) -> std::io::Result<PathBuf> {
183 std::fs::create_dir_all(dir)?;
184 #[cfg(unix)]
185 {
186 use std::os::unix::fs::PermissionsExt;
187 let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
188 }
189 let digest = hex::encode(Sha256::digest(text.as_bytes()));
190 let path = dir.join(format!("{}.txt", &digest[..16]));
191 if path.is_file() {
192 return Ok(path);
193 }
194 let tmp = dir.join(format!("{}.txt.tmp", &digest[..16]));
195 {
196 let mut opts = std::fs::OpenOptions::new();
197 opts.write(true).create(true).truncate(true);
198 #[cfg(unix)]
199 {
200 use std::os::unix::fs::OpenOptionsExt;
201 opts.mode(0o600);
202 }
203 use std::io::Write;
204 let mut f = opts.open(&tmp)?;
205 f.write_all(text.as_bytes())?;
206 f.sync_all()?;
207 }
208 std::fs::rename(&tmp, &path)?;
209 Ok(path)
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215
216 #[test]
217 fn budgets_scale_with_the_window_inside_floors_and_caps() {
218 let small = SpillBudget::for_window(8_000);
219 assert_eq!((small.per_result, small.per_turn), (8_000, 16_000));
220 let mid = SpillBudget::for_window(24_000);
221 assert_eq!((mid.per_result, mid.per_turn), (14_400, 28_800));
222 let big = SpillBudget::for_window(1_000_000);
223 assert_eq!((big.per_result, big.per_turn), (100_000, 200_000));
224 }
225
226 #[test]
227 fn a_result_over_the_per_result_budget_spills() {
228 let b = SpillBudget::for_window(24_000);
229 assert_eq!(
230 choose(&[20_000, 100], &[false, false], &b, b.per_turn),
231 vec![true, false]
232 );
233 }
234
235 #[test]
236 fn the_turn_budget_spills_the_largest_first() {
237 let b = SpillBudget {
238 per_result: 50_000,
239 per_turn: 15_000,
240 preview: 1_500,
241 };
242 // 10k + 9k + 2k = 21k > 15k: spilling the 10k alone brings it to ~12.9k.
243 assert_eq!(
244 choose(
245 &[9_000, 10_000, 2_000],
246 &[false, false, false],
247 &b,
248 b.per_turn
249 ),
250 vec![false, true, false]
251 );
252 }
253
254 #[test]
255 fn file_reads_never_spill() {
256 let b = SpillBudget::for_window(24_000);
257 assert_eq!(choose(&[1_000_000], &[true], &b, b.per_turn), vec![false]);
258 assert!(exempt("view_file") && !exempt("run_command"));
259 }
260
261 #[test]
262 fn preview_keeps_40_percent_head_and_60_percent_tail() {
263 let text: String = (0..1000)
264 .map(|i| char::from(b'a' + (i % 26) as u8))
265 .collect();
266 let p = preview(&text, 100);
267 let (head, rest) = p.split_once('\n').unwrap();
268 let (marker, tail) = rest.split_once('\n').unwrap();
269 assert_eq!(head, &text[..40]);
270 assert_eq!(tail, &text[940..]);
271 assert!(
272 marker.contains("900 chars omitted out of 1000 total"),
273 "{marker}"
274 );
275 assert_eq!(preview("short", 100), "short");
276 // Multibyte text is cut on character boundaries.
277 assert!(preview(&"\u{1F30A}".repeat(500), 10)
278 .starts_with("\u{1F30A}\u{1F30A}\u{1F30A}\u{1F30A}\n"));
279 }
280
281 #[test]
282 fn the_same_output_twice_is_one_file() {
283 let d = tempfile::tempdir().unwrap();
284 let a = write_spill(d.path(), "same").unwrap();
285 let b = write_spill(d.path(), "same").unwrap();
286 assert_eq!(a, b);
287 assert_eq!(std::fs::read_to_string(&a).unwrap(), "same");
288 assert_eq!(std::fs::read_dir(d.path()).unwrap().count(), 1);
289 }
290
291 #[test]
292 fn the_full_file_keeps_real_line_breaks() {
293 let r = json!({"stdout": "one\ntwo\n", "exit_code": 0});
294 let f = render_full("run_command", "call-3", &r);
295 assert!(f.contains("## stdout\none\ntwo\n"), "{f}");
296 assert!(f.contains("## exit_code: 0"), "{f}");
297 }
298}