eclipse-core 0.14.0

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! The standing instructions that ride after the configured system prompt (`#244`).
//!
//! `[agent] system_prompt` is one sentence, and the context files are the user's own words. Neither
//! tells a model *how* to behave with tools, and the failures that cost a turn — prose instead of a
//! call, a claim of success with no read-back, three identifiers "repaired" into one — are properties
//! of a model family rather than of the project. So a small library of blocks lives here, each with a
//! gate over the model name, and `[agent] prompt_blocks` decides which of them are sent: `auto` (the
//! default) takes every block whose gate matches, a list of names takes exactly those, and `off` sends
//! none.
//!
//! The gate is a substring match on the model name, which is all a request knows about the model
//! before it asks anything. It is deliberately narrow: a block that does not match costs nothing,
//! while one that matches a model it was not written for spends the user's context on advice that
//! cannot apply. These blocks ship in the *cached prefix* of every request, so the whole set is held
//! under [`MAX_CHARS`] by a test.

use std::fmt;

/// One block of standing instructions.
pub struct Block {
    /// What `[agent] prompt_blocks` names it by.
    pub name: &'static str,
    /// The text, sent verbatim under its own heading.
    pub body: &'static str,
    /// Model-name fragments this block is for. Empty means every model.
    ///
    /// Matched case-insensitively as a substring, the way a backend names a model in practice
    /// (`gpt-oss:120b`, `mmnuc/gemma-4-12b-it-qat`, `deepseek-v4.1-flash`).
    pub families: &'static [&'static str],
}

/// `auto`: every block whose gate matches the model in force.
pub const AUTO: &str = "auto";
/// `off`: no block at all — the configured prompt and the context files, nothing more.
pub const OFF: &str = "off";

/// The ceiling on the whole set, in characters. It ships in every session's cached prefix, so it is
/// paid for once per session — and a prefix that changes between sessions is a prefix no cache helps.
pub const MAX_CHARS: usize = 4_000;

/// The two blocks every model gets: they cost a few dozen tokens and they are the ones that transfer.
const UNIVERSAL_TASK: &str = "task-completion";
const UNIVERSAL_BATCH: &str = "parallel-tool-calls";

/// The library, in the order the blocks appear in the prompt.
pub const BLOCKS: &[Block] = &[
    Block {
        name: UNIVERSAL_TASK,
        families: &[],
        body: "Finish the job. A plan, a stub or a described change is not a result: keep working \
until the artifact exists and has been exercised, then report what the tool actually returned. \
Never invent tool output, a file's contents or a test result. When a call fails, say what failed and \
try another way — a different tool, a different command — before giving up; if nothing works, say \
exactly what is blocked and why.",
    },
    Block {
        name: UNIVERSAL_BATCH,
        families: &[],
        body: "Batch independent tool calls into one reply: calls made together are executed \
together, while every extra turn resends the whole conversation. Read two files at once; run \
commands one at a time only when a later call needs an earlier result.",
    },
    Block {
        name: "tool-use-enforcement",
        families: &[
            "gpt", "codex", "gemini", "gemma", "grok", "glm", "qwen", "deepseek", "muse",
        ],
        body: "Facts about this machine, this repository or this conversation come from a tool, not \
from memory: counts, arithmetic, dates, file contents, whether a port is open, what a command \
prints. Do not state a number you did not compute with a tool, and do not describe what a file says \
without reading it. When the user asks for a change, the tool call is the answer.",
    },
    Block {
        name: "execution-guidance",
        families: &["gpt", "codex", "grok", "glm", "qwen", "deepseek", "muse"],
        body: "After a write, read the file back with `read_file` (or read the command's own output) \
before saying it worked. Keep identifiers, paths and numbers exactly as given: never \"repair\" a \
token, a case or a spelling that looks wrong — report it instead. Before saying \"all N done\", count \
what you actually changed and make the number in the sentence match. Prefer `patch` over rewriting a \
file.",
    },
    Block {
        name: "google-operational",
        families: &["gemini", "gemma"],
        body: "One tool call per step: read its result before the next, and keep prose short — state \
the action, call the tool, report what came back. Do not restate a file you just wrote; cite the \
path and the lines you changed.",
    },
];

/// Whether `name` is a block this build ships.
pub fn is_block(name: &str) -> bool {
    BLOCKS.iter().any(|block| block.name == name.trim())
}

/// Every name this build ships, for a refusal a reader can act on.
pub fn names() -> Vec<&'static str> {
    BLOCKS.iter().map(|block| block.name).collect()
}

/// The block `name`, if this build ships it.
pub fn block(name: &str) -> Option<&'static Block> {
    BLOCKS.iter().find(|b| b.name == name.trim())
}

/// Whether `block` was written for `model`.
///
/// An empty gate is every model. Otherwise the match is a case-insensitive substring of the model
/// name — the one thing available before the backend is asked anything. `contains` is safe here
/// because a model name is not a URL: the trap `#245` hit (`contains("ollama")` matching
/// `ollama.com`) was a host, and a host is what a vendor name must not be matched against.
pub fn fits(block: &Block, model: &str) -> bool {
    if block.families.is_empty() {
        return true;
    }
    let model = model.trim().to_lowercase();
    block
        .families
        .iter()
        .any(|family| model.contains(&family.to_lowercase()))
}

/// The text for a set of names, in library order, each under its own heading.
pub fn text(names: &[&str]) -> String {
    let mut out = String::new();
    for block in BLOCKS.iter().filter(|b| names.contains(&b.name)) {
        if !out.is_empty() {
            out.push_str("\n\n");
        }
        out.push_str(&format!("## {}\n\n{}", block.name, block.body));
    }
    out
}

/// Which blocks ride in the prompt: `[agent] prompt_blocks`.
///
/// Three answers and no fourth: a mode that decides per model (`auto`), a list that decides per name,
/// and nothing at all. It is one key rather than a boolean per block because the interesting
/// question is "what is my model being told", and a list of booleans answers it badly.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum Choice {
    /// Every block whose gate matches the model in force.
    #[default]
    Auto,
    /// No block at all.
    Off,
    /// Exactly these, whatever the model.
    List(Vec<String>),
}

impl Choice {
    /// The names in force for `model`, in library order.
    pub fn names_for(&self, model: &str) -> Vec<&'static str> {
        match self {
            Choice::Auto => BLOCKS
                .iter()
                .filter(|block| fits(block, model))
                .map(|block| block.name)
                .collect(),
            Choice::Off => Vec::new(),
            Choice::List(names) => BLOCKS
                .iter()
                .filter(|block| names.iter().any(|n| n == block.name))
                .map(|block| block.name)
                .collect(),
        }
    }

    /// The text to put in the system prompt — empty when nothing is in force, which is what `off`
    /// means and what an `auto` set that matched nothing means too.
    pub fn guidance(&self, model: &str) -> String {
        text(&self.names_for(model))
    }

    /// One line for `config check`: what this model is being told, and why.
    pub fn summary(&self, model: &str) -> String {
        let names = self.names_for(model);
        let why = match self {
            Choice::Auto => "auto".to_string(),
            Choice::Off => "off".to_string(),
            Choice::List(_) => "listed".to_string(),
        };
        if names.is_empty() {
            return format!("{why}: no block (the prompt and the context files only)");
        }
        format!("{why} for `{model}`: {}", names.join(" · "))
    }
}

impl fmt::Display for Choice {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Choice::Auto => write!(f, "{AUTO}"),
            Choice::Off => write!(f, "{OFF}"),
            Choice::List(names) => write!(f, "{}", names.join(" · ")),
        }
    }
}

/// `prompt_blocks = "auto"`, `"off"`, or `["task-completion", "parallel-tool-calls"]`.
///
/// A name this build does not ship is a parse error rather than a silently ignored entry: a typo in
/// a list would otherwise delete a block while the file looks like it asked for it.
impl<'de> serde::Deserialize<'de> for Choice {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        use serde::de::Error as _;
        let value = toml::Value::deserialize(d)?;
        match value {
            toml::Value::String(word) => match word.trim().to_lowercase().as_str() {
                AUTO => Ok(Choice::Auto),
                OFF => Ok(Choice::Off),
                other => Err(D::Error::custom(format!(
                    "`prompt_blocks` takes `{AUTO}`, `{OFF}`, or a list of block names, not `{other}`"
                ))),
            },
            toml::Value::Array(items) => {
                let mut picked = Vec::with_capacity(items.len());
                for item in items {
                    let toml::Value::String(name) = item else {
                        return Err(D::Error::custom(
                            "a `prompt_blocks` list holds block names as strings",
                        ));
                    };
                    let name = name.trim().to_string();
                    if name == AUTO || name == OFF {
                        return Err(D::Error::custom(format!(
                            "`{name}` is a mode, not a block name; use it alone rather than in a list"
                        )));
                    }
                    if !is_block(&name) {
                        return Err(D::Error::custom(format!(
                            "`{name}` is not a prompt block; this build ships {}",
                            names().join(", ")
                        )));
                    }
                    picked.push(name);
                }
                Ok(Choice::List(picked))
            }
            _ => Err(D::Error::custom(format!(
                "`prompt_blocks` takes `{AUTO}`, `{OFF}`, or a list of block names"
            ))),
        }
    }
}

impl serde::Serialize for Choice {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        match self {
            Choice::Auto => s.serialize_str(AUTO),
            Choice::Off => s.serialize_str(OFF),
            Choice::List(names) => names.serialize(s),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn chosen(toml_text: &str) -> Choice {
        toml::from_str::<std::collections::BTreeMap<String, Choice>>(toml_text)
            .expect("parses")
            .remove("prompt_blocks")
            .expect("the key")
    }

    /// The matrix, asserted rather than claimed: a `gpt`-shaped name, a `gemma` one, and one nothing
    /// in the library claims.
    #[test]
    fn the_matrix_is_a_fact_for_three_shapes_of_model() {
        let auto = Choice::Auto;
        assert_eq!(
            auto.names_for("gpt-oss:120b"),
            vec![
                "task-completion",
                "parallel-tool-calls",
                "tool-use-enforcement",
                "execution-guidance"
            ]
        );
        assert_eq!(
            auto.names_for("mmnuc/gemma-4-12b-it-qat"),
            vec![
                "task-completion",
                "parallel-tool-calls",
                "tool-use-enforcement",
                "google-operational"
            ],
            "Gemma gets the operational block instead of the execution one"
        );
        assert_eq!(
            auto.names_for("inkling-2-mini"),
            vec!["task-completion", "parallel-tool-calls"],
            "a family nothing claims gets only what every model gets"
        );
        assert_eq!(
            auto.names_for("DeepSeek-V4.1-Flash"),
            auto.names_for("deepseek-v4.1-flash"),
            "the gate is case-insensitive"
        );
    }

    /// The gate must be able to fail: an unknown name gets neither family block, in either
    /// direction.
    #[test]
    fn a_family_block_is_not_sent_to_a_model_it_was_not_written_for() {
        let auto = Choice::Auto;
        for family in [
            "tool-use-enforcement",
            "execution-guidance",
            "google-operational",
        ] {
            assert!(!auto.names_for("llama-3-70b").contains(&family), "{family}");
        }
        assert!(!auto.names_for("gemma-4").contains(&"execution-guidance"));
        assert!(!auto.names_for("gpt-5").contains(&"google-operational"));
    }

    /// A block is never sent twice, and no name is claimed by two blocks.
    #[test]
    fn no_block_is_sent_twice_and_no_name_is_claimed_twice() {
        let auto = Choice::Auto;
        for model in ["gpt-4", "gemma-2", "deepseek-x", "nothing-known"] {
            let names = auto.names_for(model);
            let mut sorted = names.clone();
            sorted.sort_unstable();
            sorted.dedup();
            assert_eq!(sorted.len(), names.len(), "{model}: {names:?}");
            let text = auto.guidance(model);
            for name in names {
                assert_eq!(
                    text.matches(&format!("## {name}")).count(),
                    1,
                    "{name} once in {model}"
                );
            }
        }
        let mut all = names();
        all.sort_unstable();
        let unique = all.len();
        all.dedup();
        assert_eq!(all.len(), unique, "every block name is unique");
    }

    /// It ships in the cached prefix of every request, so the whole library has a ceiling.
    #[test]
    fn the_whole_library_stays_under_its_budget() {
        let whole = text(&names());
        assert!(
            whole.chars().count() <= MAX_CHARS,
            "{}",
            whole.chars().count()
        );
        // The unversals are the part every session pays for; they must stay cheap.
        let universal = text(&[UNIVERSAL_TASK, UNIVERSAL_BATCH]);
        assert!(
            universal.chars().count() <= 900,
            "the universal pair is {} chars",
            universal.chars().count()
        );
    }

    /// `off` is nothing at all, a list is exactly what it names, and both survive a round trip
    /// through the config file.
    #[test]
    fn off_and_a_list_are_what_they_say() {
        assert!(chosen("prompt_blocks = \"off\"")
            .names_for("gpt-4")
            .is_empty());
        assert_eq!(chosen("prompt_blocks = \"off\"").guidance("gpt-4"), "");
        let listed = chosen("prompt_blocks = [\"task-completion\"]");
        assert_eq!(listed.names_for("gpt-4"), vec!["task-completion"]);
        assert_eq!(
            listed.names_for("gemma-2"),
            vec!["task-completion"],
            "a listed block is not gated: the list is the whole answer"
        );
        // A list is written back as the same list, so `config set` and the starter file agree.
        let round = toml::Value::try_from(&listed).unwrap();
        assert_eq!(
            round,
            toml::Value::Array(vec![toml::Value::String("task-completion".into())]),
            "a list is written back as a list"
        );
        assert_eq!(
            toml::Value::try_from(&Choice::Auto).unwrap(),
            toml::Value::String("auto".into())
        );
    }

    /// A typo in a list deletes a block while the file looks like it asked for it, so it is a parse
    /// error that names what exists.
    #[test]
    fn a_name_this_build_does_not_ship_is_refused() {
        let why = toml::from_str::<std::collections::BTreeMap<String, Choice>>(
            "prompt_blocks = [\"task-completions\"]",
        )
        .unwrap_err()
        .to_string();
        assert!(why.contains("task-completions"), "{why}");
        assert!(why.contains("task-completion"), "the list of names: {why}");

        let why = toml::from_str::<std::collections::BTreeMap<String, Choice>>(
            "prompt_blocks = \"sometimes\"",
        )
        .unwrap_err()
        .to_string();
        assert!(why.contains("sometimes"), "{why}");
        assert!(why.contains("auto"), "{why}");
    }

    /// The summary is what `config check` prints, so it names the model and the blocks in one line.
    #[test]
    fn the_summary_says_what_this_model_is_being_told() {
        let auto = Choice::Auto;
        let line = auto.summary("gpt-oss:120b");
        assert!(line.contains("auto"), "{line}");
        assert!(line.contains("execution-guidance"), "{line}");
        // An unknown model is not "no block": the universal pair is for every model. What the
        // summary must not claim is a family block it did not get.
        let unknown = auto.summary("nothing-known");
        assert!(unknown.contains("task-completion"), "{unknown}");
        assert!(!unknown.contains("execution-guidance"), "{unknown}");
        let off = Choice::Off.summary("gpt-4");
        assert!(off.contains("off"), "{off}");
        assert!(off.contains("no block"), "{off}");
    }
}