kiss-coding 0.0.23

Coding harness: sessions, tools, compaction, settings, skills
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
//! Settings: global `~/.kiss/agent/settings.json` deep-merged with project
//! `.kiss/settings.json` (project wins).

use kiss_ai::Transport;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum CompactionMode {
    #[default]
    Summary,
    Jev,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct CompactionSettings {
    pub enabled: bool,
    pub mode: CompactionMode,
    pub reserve_tokens: u64,
    pub keep_recent_tokens: u64,
    pub model_overrides: BTreeMap<String, CompactionModelOverride>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct CompactionModelOverride {
    pub reserve_tokens: Option<u64>,
    pub keep_recent_tokens: Option<u64>,
}

impl Default for CompactionSettings {
    fn default() -> Self {
        CompactionSettings {
            enabled: true,
            mode: CompactionMode::Summary,
            reserve_tokens: 16_384,
            keep_recent_tokens: 20_000,
            model_overrides: BTreeMap::new(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ReasoningEffortMode {
    #[default]
    Fixed,
    Jev,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct ReasoningEffortSettings {
    pub mode: ReasoningEffortMode,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct RetrySettings {
    pub enabled: bool,
    pub max_retries: u32,
    pub base_delay_ms: u64,
    pub max_agent_delay_ms: u64,
}

impl Default for RetrySettings {
    fn default() -> Self {
        RetrySettings {
            enabled: true,
            max_retries: 3,
            base_delay_ms: 2000,
            max_agent_delay_ms: 60_000,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct SubagentSettings {
    /// Subagent tools are hidden until the user enables them.
    pub enabled: bool,
}

/// How many agents to advise the model to aim for when it writes a workflow.
///
/// This is advice sent to the model, not a cap: a prompt that clearly calls for
/// a different scale still wins. The runtime limits are the real bound.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum WorkflowSize {
    Small,
    #[default]
    Medium,
    Large,
    Unrestricted,
}

impl WorkflowSize {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Small => "small",
            Self::Medium => "medium",
            Self::Large => "large",
            Self::Unrestricted => "unrestricted",
        }
    }

    /// The agent count the model is asked to stay under, if any.
    pub fn target_agents(self) -> Option<u32> {
        match self {
            Self::Small => Some(5),
            Self::Medium => Some(15),
            Self::Large => Some(50),
            Self::Unrestricted => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct WorkflowSettings {
    /// Dynamic workflows are built on subagents, so they are available only
    /// when `subagents.enabled` is also on.
    pub enabled: bool,
    /// Ask before a run starts. This is a cost gate, not a permission gate: one
    /// run can start hundreds of child agents.
    pub confirm: bool,
    /// Let a typed prompt containing `ultracode`, or asking for a workflow in
    /// plain words, start one.
    pub keyword_trigger: bool,
    pub size: WorkflowSize,
}

impl Default for WorkflowSettings {
    fn default() -> Self {
        WorkflowSettings {
            enabled: true,
            confirm: true,
            keyword_trigger: true,
            size: WorkflowSize::default(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum QueueMode {
    All,
    #[default]
    OneAtATime,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ProjectTrustDefault {
    #[default]
    Ask,
    Always,
    Never,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum CacheWarmingMode {
    Off,
    #[default]
    Streaming,
    Idle,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum MermaidRendering {
    Off,
    Final,
    #[default]
    Streaming,
}

impl MermaidRendering {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Off => "off",
            Self::Final => "final",
            Self::Streaming => "streaming",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct MarkdownSettings {
    pub code_block_indent: Option<String>,
    pub mermaid: MermaidRendering,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct WebMcpSettings {
    pub allowed_origins: Option<Vec<String>>,
    pub disallowed_origins: Vec<String>,
    pub cdp: Option<Value>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct Settings {
    pub default_provider: Option<String>,
    pub default_model: Option<String>,
    pub default_thinking_level: Option<String>,
    pub transport: Transport,
    pub hide_thinking_block: bool,
    pub theme: Option<String>,
    pub quiet_startup: bool,
    pub default_project_trust: ProjectTrustDefault,
    pub compaction: CompactionSettings,
    pub reasoning_effort: ReasoningEffortSettings,
    pub retry: RetrySettings,
    pub cache_warming: CacheWarmingMode,
    pub subagents: SubagentSettings,
    pub workflows: WorkflowSettings,
    pub steering_mode: QueueMode,
    pub follow_up_mode: QueueMode,
    pub shell_path: Option<String>,
    pub shell_command_prefix: Option<String>,
    pub session_dir: Option<String>,
    pub enabled_models: Option<Vec<String>>,
    pub default_tools: Option<Vec<String>>,
    pub external_editor: Option<String>,
    pub skills: Vec<String>,
    pub prompts: Vec<String>,
    pub themes: Vec<String>,
    pub enable_skill_commands: Option<bool>,
    /// `None` preserves the default-on behavior for existing settings files.
    pub auto_recap: Option<bool>,
    pub voice_language: Option<String>,
    pub voice_backend: Option<String>,
    pub markdown: MarkdownSettings,
    pub webmcp: WebMcpSettings,
    /// Unknown keys survive load/save.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

pub fn global_settings_path() -> Option<PathBuf> {
    dirs::home_dir().map(|h| h.join(".kiss/agent/settings.json"))
}

pub fn project_settings_path(cwd: &Path) -> PathBuf {
    cwd.join(".kiss/settings.json")
}

fn read_json(path: &Path) -> Option<Value> {
    let text = std::fs::read_to_string(path).ok()?;
    serde_json::from_str(&text).ok()
}

/// Deep-merge `overlay` onto `base` (objects merge, everything else replaces).
fn deep_merge(base: &mut Value, overlay: Value) {
    match (base, overlay) {
        (Value::Object(base_map), Value::Object(overlay_map)) => {
            for (k, v) in overlay_map {
                match base_map.get_mut(&k) {
                    Some(slot) => deep_merge(slot, v),
                    None => {
                        base_map.insert(k, v);
                    }
                }
            }
        }
        (slot, v) => *slot = v,
    }
}

fn merged_settings(mut global: Value, project: Option<Value>) -> Settings {
    let subagents_enabled = global
        .pointer("/subagents/enabled")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    let workflows_enabled = global
        .pointer("/workflows/enabled")
        .and_then(Value::as_bool)
        .unwrap_or(true);
    // A project must not opt the user's microphone in to a cloud service.
    let voice_backend = global
        .get("voiceBackend")
        .and_then(Value::as_str)
        .map(str::to_owned);
    let cache_warming = global
        .get("cacheWarming")
        .cloned()
        .and_then(|value| serde_json::from_value(value).ok())
        .unwrap_or_default();
    if let Some(mut project) = project {
        if let Some(object) = project.as_object_mut() {
            object.remove("deviceId");
        }
        if let Some(entries) = project.get("defaultTools").and_then(Value::as_array)
            && entries.iter().all(|entry| {
                entry
                    .as_str()
                    .is_some_and(|name| name.starts_with(['+', '-']))
            })
            && let Some(base) = global.get("defaultTools").and_then(Value::as_array)
        {
            let mut combined = base.clone();
            combined.extend(entries.iter().cloned());
            project["defaultTools"] = Value::Array(combined);
        }
        deep_merge(&mut global, project);
    }
    let mut settings: Settings = serde_json::from_value(global).unwrap_or_default();
    // Subagents are a user-level authority choice. A repository must not turn
    // them on through a trusted project settings file.
    settings.subagents.enabled = subagents_enabled;
    // Workflows spend the user's tokens many agents at a time, so the same rule
    // applies: only the user's own settings file decides whether they are on.
    settings.workflows.enabled = workflows_enabled;
    settings.cache_warming = cache_warming;
    settings.voice_backend = voice_backend;
    settings
}

impl Settings {
    /// Read only user settings when creating the installation ID.
    pub fn get_or_create_device_id() -> anyhow::Result<String> {
        let path = global_settings_path().ok_or_else(|| anyhow::anyhow!(
            "ChatGPT login has no user settings path. A home directory is required. Set HOME and run login again."
        ))?;
        let mut settings: Value = match std::fs::read_to_string(&path) {
            Ok(text) => serde_json::from_str(&text).map_err(|_| anyhow::anyhow!(
                "ChatGPT login cannot read {}. Settings must contain a JSON object. Correct the JSON and run login again.", path.display()
            ))?,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => serde_json::json!({}),
            Err(error) => return Err(error.into()),
        };
        if !settings.is_object() {
            anyhow::bail!(
                "ChatGPT login cannot update {}. Settings must contain a JSON object. Correct the JSON and run login again.",
                path.display()
            );
        }
        if let Some(id) = settings.get("deviceId").and_then(Value::as_str)
            && uuid::Uuid::parse_str(id).is_ok()
        {
            return Ok(id.to_string());
        }
        let id = uuid::Uuid::new_v4().to_string();
        settings["deviceId"] = Value::String(id.clone());
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(path, serde_json::to_string_pretty(&settings)?)?;
        Ok(id)
    }

    pub fn auto_recap_enabled(&self) -> bool {
        self.auto_recap.unwrap_or(true)
    }

    /// Load global settings, overlaying project settings when trusted.
    pub fn load(cwd: &Path, project_trusted: bool) -> Settings {
        let global = global_settings_path()
            .and_then(|p| read_json(&p))
            .unwrap_or_else(|| Value::Object(Default::default()));
        let project = project_trusted
            .then(|| read_json(&project_settings_path(cwd)))
            .flatten();
        merged_settings(global, project)
    }

    pub fn save_global(&self) -> anyhow::Result<()> {
        let path = global_settings_path().ok_or_else(|| anyhow::anyhow!("no home directory"))?;
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let mut value = serde_json::to_value(self)?;
        if let Some(id) = read_json(&path).and_then(|disk| disk.get("deviceId").cloned()) {
            value["deviceId"] = id;
        }
        std::fs::write(&path, serde_json::to_string_pretty(&value)?)?;
        Ok(())
    }
}

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

    #[test]
    fn project_tool_modifiers_preserve_user_selection() {
        let user = json!({"defaultTools":["read", "+grep"]});
        let settings =
            merged_settings(user.clone(), Some(json!({"defaultTools":["-read", "+ls"]})));
        assert_eq!(
            settings.default_tools.unwrap(),
            ["read", "+grep", "-read", "+ls"]
        );
        let settings = merged_settings(user.clone(), Some(json!({"defaultTools":["bash"]})));
        assert_eq!(settings.default_tools.unwrap(), ["bash"]);
        let settings = merged_settings(user, Some(json!({"defaultTools":[]})));
        assert_eq!(settings.default_tools.unwrap(), ["read", "+grep"]);
        let settings = merged_settings(
            json!({"deviceId":"user-id"}),
            Some(json!({"deviceId":"project-id"})),
        );
        assert_eq!(settings.extra["deviceId"], "user-id");
    }

    #[test]
    fn project_cannot_enable_cloud_voice() {
        let settings = merged_settings(json!({}), Some(json!({"voiceBackend":"deepgram"})));
        assert_eq!(settings.voice_backend, None);
        let settings = merged_settings(
            json!({"voiceBackend":"elevenlabs"}),
            Some(json!({"voiceBackend":"local"})),
        );
        assert_eq!(settings.voice_backend.as_deref(), Some("elevenlabs"));
    }

    #[test]
    fn deep_merge_nested() {
        let mut base =
            json!({"theme": "dark", "compaction": {"enabled": true, "reserveTokens": 16384}});
        deep_merge(&mut base, json!({"compaction": {"reserveTokens": 8192}}));
        assert_eq!(base["theme"], "dark");
        assert_eq!(base["compaction"]["enabled"], true);
        assert_eq!(base["compaction"]["reserveTokens"], 8192);
    }

    #[test]
    fn defaults_match_pi() {
        let s = Settings::default();
        assert_eq!(s.compaction.mode, CompactionMode::Summary);
        assert_eq!(s.compaction.reserve_tokens, 16_384);
        assert_eq!(s.compaction.keep_recent_tokens, 20_000);
        assert_eq!(s.reasoning_effort.mode, ReasoningEffortMode::Fixed);
        assert_eq!(s.retry.max_retries, 3);
        assert_eq!(s.retry.max_agent_delay_ms, 60_000);
        assert_eq!(s.cache_warming, CacheWarmingMode::Streaming);
        assert!(!s.subagents.enabled);
        assert_eq!(s.steering_mode, QueueMode::OneAtATime);
        assert!(s.auto_recap_enabled());
        assert_eq!(s.markdown.mermaid, MermaidRendering::Streaming);
    }

    #[test]
    fn compaction_model_overrides_use_exact_provider_model_keys() {
        let settings: Settings = serde_json::from_value(json!({
            "compaction": {
                "modelOverrides": {
                    "anthropic/claude-opus-4-8": {
                        "reserveTokens": 1000,
                        "keepRecentTokens": 2000
                    }
                }
            },
            "cacheWarming": "idle"
        }))
        .unwrap();
        let override_settings = &settings.compaction.model_overrides["anthropic/claude-opus-4-8"];
        assert_eq!(override_settings.reserve_tokens, Some(1000));
        assert_eq!(override_settings.keep_recent_tokens, Some(2000));
        assert_eq!(settings.cache_warming, CacheWarmingMode::Idle);
    }

    #[test]
    fn old_compaction_settings_default_to_summary_mode() {
        let settings: Settings = serde_json::from_value(json!({
            "compaction": {"enabled": true, "reserveTokens": 1, "keepRecentTokens": 2}
        }))
        .unwrap();
        assert_eq!(settings.compaction.mode, CompactionMode::Summary);
        assert_eq!(
            serde_json::to_value(settings).unwrap()["compaction"]["mode"],
            "summary"
        );
    }

    #[test]
    fn old_settings_default_to_fixed_reasoning_effort() {
        let settings: Settings = serde_json::from_value(json!({})).unwrap();
        assert_eq!(settings.reasoning_effort.mode, ReasoningEffortMode::Fixed);
        assert_eq!(
            serde_json::to_value(settings).unwrap()["reasoningEffort"]["mode"],
            "fixed"
        );
    }

    #[test]
    fn queue_mode_wire_format() {
        assert_eq!(
            serde_json::to_value(QueueMode::OneAtATime).unwrap(),
            "one-at-a-time"
        );
    }

    #[test]
    fn markdown_settings_use_the_pi_wire_shape() {
        let value = serde_json::to_value(Settings::default()).unwrap();
        assert_eq!(value["markdown"]["mermaid"], "streaming");
        assert!(value.get("mermaidRendering").is_none());
    }

    #[test]
    fn webmcp_settings_use_the_reference_wire_shape() {
        let loaded: Settings = serde_json::from_value(json!({
            "webmcp": {
                "allowedOrigins": ["example.com"],
                "disallowedOrigins": ["blocked.example"],
                "cdp": 9333
            }
        }))
        .unwrap();
        assert_eq!(
            loaded.webmcp.allowed_origins,
            Some(vec!["example.com".to_string()])
        );
        assert_eq!(
            loaded.webmcp.disallowed_origins,
            vec!["blocked.example".to_string()]
        );
        assert_eq!(loaded.webmcp.cdp, Some(json!(9333)));
    }

    #[test]
    fn subagents_are_opt_in_on_the_wire() {
        let value = serde_json::to_value(Settings::default()).unwrap();
        assert_eq!(value["subagents"]["enabled"], false);

        let loaded: Settings = serde_json::from_value(json!({})).unwrap();
        assert!(!loaded.subagents.enabled);
    }

    #[test]
    fn workflows_default_on_but_only_matter_with_subagents() {
        let settings = Settings::default();
        assert!(settings.workflows.enabled);
        assert!(settings.workflows.confirm);
        assert!(settings.workflows.keyword_trigger);
        assert_eq!(settings.workflows.size, WorkflowSize::Medium);
        // Subagents stay off, so workflows are unavailable until the user opts
        // in to child agents.
        assert!(!settings.subagents.enabled);
    }

    #[test]
    fn project_settings_cannot_turn_workflows_on_or_off() {
        let off = merged_settings(
            json!({"workflows": {"enabled": false}}),
            Some(json!({"workflows": {"enabled": true}})),
        );
        assert!(!off.workflows.enabled);

        let on = merged_settings(json!({}), Some(json!({"workflows": {"enabled": false}})));
        assert!(on.workflows.enabled);
    }

    #[test]
    fn project_settings_cannot_enable_paid_cache_warming() {
        let settings = merged_settings(
            json!({"cacheWarming": "off"}),
            Some(json!({"cacheWarming": "idle"})),
        );
        assert_eq!(settings.cache_warming, CacheWarmingMode::Off);
    }

    #[test]
    fn the_size_guideline_maps_to_an_agent_count() {
        assert_eq!(WorkflowSize::Small.target_agents(), Some(5));
        assert_eq!(WorkflowSize::Medium.target_agents(), Some(15));
        assert_eq!(WorkflowSize::Large.target_agents(), Some(50));
        assert_eq!(WorkflowSize::Unrestricted.target_agents(), None);
    }

    #[test]
    fn project_settings_cannot_change_subagent_authority() {
        let enabled = merged_settings(
            json!({"subagents": {"enabled": true}}),
            Some(json!({"subagents": {"enabled": false}})),
        );
        assert!(enabled.subagents.enabled);

        let disabled = merged_settings(json!({}), Some(json!({"subagents": {"enabled": true}})));
        assert!(!disabled.subagents.enabled);
    }
}