zeph 0.22.3

Lightweight AI agent with hybrid inference, skills-first architecture, and multi-channel I/O
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::path::PathBuf;

use dialoguer::{Confirm, Input, Select};
use zeph_subagent::def::{MemoryScope, PermissionMode};

use super::WizardState;
use super::validate::parse_optional_nonzero;

pub(super) fn step_orchestration(state: &mut WizardState) -> anyhow::Result<()> {
    println!("== Orchestration (/plan command) ==\n");

    state.orchestration_enabled = Confirm::new()
        .with_prompt("Enable task orchestration? (enables the /plan command)")
        .default(false)
        .interact()?;

    if state.orchestration_enabled {
        state.orchestration_max_tasks = Input::new()
            .with_prompt("Maximum tasks per plan")
            .default(20u32)
            .interact_text()?;

        state.orchestration_max_parallel = Input::new()
            .with_prompt("Maximum parallel tasks")
            .default(4u32)
            .interact_text()?;

        // MF6: warn if max_parallel > max_tasks.
        if state.orchestration_max_parallel > state.orchestration_max_tasks {
            println!(
                "Warning: max_parallel ({}) is greater than max_tasks ({}). \
                 Setting max_parallel = max_tasks.",
                state.orchestration_max_parallel, state.orchestration_max_tasks
            );
            state.orchestration_max_parallel = state.orchestration_max_tasks;
        }

        state.orchestration_confirm_before_execute = Confirm::new()
            .with_prompt("Require confirmation before executing plans?")
            .default(true)
            .interact()?;

        let strategies = ["abort", "retry", "skip", "ask"];
        let strategy_idx = Select::new()
            .with_prompt("Default failure strategy")
            .items(strategies)
            .default(0)
            .interact()?;
        state.orchestration_failure_strategy = strategies[strategy_idx].into();

        let provider: String = Input::new()
            .with_prompt("Provider name for planning LLM calls (empty = primary provider)")
            .default(String::new())
            .interact_text()?;
        // Validate provider name: alphanumeric + `-_`, max 64 chars.
        state.orchestration_planner_provider = if provider.is_empty() {
            None
        } else if provider.len() > 64
            || !provider
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
        {
            println!(
                "Warning: provider name contains invalid characters or exceeds 64 chars. \
                 Ignoring and using the primary provider."
            );
            None
        } else {
            Some(provider)
        };

        state.orchestration_persistence_enabled = Confirm::new()
            .with_prompt(
                "Persist task graphs to SQLite after each scheduler tick? \
                 (enables `/plan resume <id>` across restarts)",
            )
            .default(true)
            .interact()?;

        let idle_timeout_raw: String = Input::new()
            .with_prompt(
                "Default idle/no-progress timeout in seconds — kills a task if it emits no \
                 progress for this long; leave blank to disable. IMPORTANT: set this above \
                 the longest expected single-turn (single LLM call + its tool calls) \
                 duration, or a healthy long-running task may be killed spuriously",
            )
            .allow_empty(true)
            .validate_with(|s: &String| -> Result<(), String> {
                parse_optional_nonzero::<u64>(s).map(|_| ())
            })
            .interact_text()?;
        state.orchestration_default_idle_timeout_secs =
            parse_optional_nonzero(&idle_timeout_raw).map_err(|e| anyhow::anyhow!(e))?;

        step_ensemble_verify(state)?;
        step_command_handoff(state)?;
    }

    println!();
    Ok(())
}

/// Prompt for Command-style dynamic task handoff (spec-080, #6363), opt-in and nested under
/// orchestration. `LangGraph` `Command(update, goto)` parity: lets a node's agent route
/// execution to another already-planned node at runtime, using the cross-thread store
/// (`[memory.store]`) as the shared-state channel.
fn step_command_handoff(state: &mut WizardState) -> anyhow::Result<()> {
    state.command_enabled = Confirm::new()
        .with_prompt(
            "Enable Command-style dynamic task handoff? (opt-in; lets a completing node's \
             agent route execution to another already-planned node at runtime via a trailing \
             `zeph-command` output block — requires the cross-thread store enabled too, see \
             the Memory step)",
        )
        .default(false)
        .interact()?;

    if state.command_enabled {
        state.command_max_handoffs = Input::new()
            .with_prompt(
                "Maximum Command handoffs per graph run (livelock budget backstop; each hop \
                 also structurally consumes one not-yet-terminal node, so this is a backstop, \
                 not the primary bound)",
            )
            .default(16u32)
            .validate_with(|v: &u32| if *v > 0 { Ok(()) } else { Err("must be > 0") })
            .interact_text()?;
    }

    Ok(())
}

/// Prompt for ORCH-style deterministic verifier ensemble-merge (spec
/// `073-orch-ensemble-merge`), opt-in and nested under orchestration.
fn step_ensemble_verify(state: &mut WizardState) -> anyhow::Result<()> {
    state.ensemble_enabled = Confirm::new()
        .with_prompt(
            "Enable ensemble-verified plan verification? (opt-in, multiplies verify \
             cost by member count — runs the same completeness check through N \
             providers in parallel and merges by deterministic majority vote)",
        )
        .default(false)
        .interact()?;

    if !state.ensemble_enabled {
        return Ok(());
    }

    loop {
        let members_raw: String = Input::new()
            .with_prompt(
                "Ensemble member provider names (comma-separated, from \
                 [[llm.providers]]; must be odd count and >= 3, no duplicates)",
            )
            .interact_text()?;
        let members: Vec<String> = members_raw
            .split(',')
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(str::to_owned)
            .collect();
        let unique: std::collections::HashSet<&str> = members.iter().map(String::as_str).collect();
        if !members.len().is_multiple_of(2) && members.len() >= 3 && unique.len() == members.len() {
            state.ensemble_members = members;
            return Ok(());
        }
        println!(
            "Invalid: need an odd count of >= 3 unique provider names, got {} \
             (duplicates: {}). Try again.",
            members.len(),
            members.len() != unique.len()
        );
    }
}

pub(super) fn step_agents(state: &mut WizardState) -> anyhow::Result<()> {
    println!("== Step 9/10: Sub-Agent Defaults ==\n");

    state.agents_enabled = Confirm::new()
        .with_prompt("Enable the sub-agent subsystem? (required for /agent commands and multi-agent workflows)")
        .default(true)
        .interact()?;

    if state.agents_enabled {
        let delegation_items = [
            "proactive (main agent may decide on its own to delegate to a sub-agent)",
            "explicit_request_only (only /agent spawn — the main agent may never decide on its own)",
            "disabled (no spawn from any code path; definitions remain listable)",
        ];
        let delegation_sel = Select::new()
            .with_prompt(
                "Delegation mode — who may trigger a sub-agent spawn? (see spec \
                 042-subagent-delegation-mode-parity; useful to restrict in \
                 semi-trusted channels such as Telegram/Discord/webhook ingestion)",
            )
            .items(delegation_items)
            // Default to explicit_request_only (index 1), not proactive: a brand-new
            // interactive wizard run has no prior deployment behavior to preserve, so the
            // suggested answer for a first-time operator should be the more conservative
            // option. `DelegationMode::default() = Proactive` remains correct for the
            // struct-level default (FR-008, preserves existing `enabled=true` deployments) —
            // this only changes the wizard's suggested answer.
            .default(1)
            .interact()?;
        state.agents_delegation_mode = match delegation_sel {
            1 => zeph_config::DelegationMode::ExplicitRequestOnly,
            2 => zeph_config::DelegationMode::Disabled,
            _ => zeph_config::DelegationMode::Proactive,
        };
    }

    let modes = ["default", "accept_edits", "dont_ask"];
    let sel = Select::new()
        .with_prompt("Default permission mode for sub-agents")
        .items(modes)
        .default(0)
        .interact()?;
    state.agents_default_permission_mode = match sel {
        1 => Some(PermissionMode::AcceptEdits),
        2 => Some(PermissionMode::DontAsk),
        _ => None,
    };

    let tools_raw: String = Input::new()
        .with_prompt("Globally disallowed tools (comma-separated, leave empty for none)")
        .default(String::new())
        .interact_text()?;
    state.agents_default_disallowed_tools = tools_raw
        .split(',')
        .map(|s| s.trim().to_owned())
        .filter(|s| !s.is_empty())
        .collect();

    state.agents_allow_bypass_permissions = Confirm::new()
        .with_prompt("Allow sub-agents to use bypass_permissions mode?")
        .default(false)
        .interact()?;

    let user_dir_raw: String = Input::new()
        .with_prompt(
            "User-level agents directory (absolute path, leave empty for platform default)",
        )
        .default(String::new())
        .interact_text()?;
    state.agents_user_dir = if user_dir_raw.trim().is_empty() {
        None
    } else {
        Some(PathBuf::from(user_dir_raw.trim()))
    };

    let memory_scopes = ["none", "local", "project", "user"];
    let memory_sel = Select::new()
        .with_prompt("Default memory scope for sub-agents (none = no memory by default)")
        .items(memory_scopes)
        .default(0)
        .interact()?;
    state.agents_default_memory_scope = match memory_sel {
        1 => Some(MemoryScope::Local),
        2 => Some(MemoryScope::Project),
        3 => Some(MemoryScope::User),
        _ => None,
    };

    state.agents_forward_transcript = Confirm::new()
        .with_prompt(
            "Forward each running sub-agent's full per-turn text/thinking output to the TUI \
             runtime detail view and/or --bare stdout as it is produced? (opt-in; see \
             --forward-subagent-text / ZEPH_AGENTS_FORWARD_TRANSCRIPT to override per session)",
        )
        .default(false)
        .interact()?;

    println!();
    Ok(())
}

pub(super) fn step_router(state: &mut WizardState) -> anyhow::Result<()> {
    println!("== Step 10/12: Provider Router ==\n");
    println!("Configure adaptive routing when using multiple LLM providers.");
    println!("Note: routing only takes effect when [llm.router].chain has 2+ providers.");
    println!("Skip this step if you use a single provider.\n");

    let strategy_items = &[
        "None (single provider, no routing)",
        "EMA (latency-aware exponential moving average)",
        "Thompson (probabilistic exploration/exploitation)",
        "Cascade (try cheapest provider first, escalate on degenerate output)",
    ];
    let sel = Select::new()
        .with_prompt("Router strategy")
        .items(strategy_items)
        .default(0)
        .interact()?;

    match sel {
        0 => {
            state.router_strategy = None;
        }
        1 => {
            state.router_strategy = Some("ema".into());
        }
        2 => {
            state.router_strategy = Some("thompson".into());
            let custom_path: String = Input::new()
                .with_prompt(
                    "Thompson state file path (leave empty for default ~/.zeph/router_thompson_state.json)",
                )
                .default(String::new())
                .interact_text()?;
            if !custom_path.is_empty() {
                state.router_thompson_state_path = Some(custom_path);
            }
        }
        3 => {
            state.router_strategy = Some("cascade".into());
            let threshold: f64 = Input::new()
                .with_prompt(
                    "Quality threshold [0.0–1.0] — responses below this score trigger escalation",
                )
                .default(0.5_f64)
                .interact_text()?;
            state.router_cascade_quality_threshold = Some(threshold.clamp(0.0, 1.0));
            let max_esc: u8 = Input::new()
                .with_prompt("Max escalations per request (0 = no escalation)")
                .default(2_u8)
                .interact_text()?;
            state.router_cascade_max_escalations = Some(max_esc);
            let cost_tiers_input: String = Input::new()
                .with_prompt(
                    "Cost tiers: comma-separated provider names cheapest first \
                     (empty = use chain order)",
                )
                .default(String::new())
                .interact_text()?;
            let tiers: Vec<String> = cost_tiers_input
                .split(',')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(str::to_owned)
                .collect();
            if !tiers.is_empty() {
                state.router_cascade_cost_tiers = Some(tiers);
            }
        }
        _ => unreachable!(),
    }

    println!();
    Ok(())
}

pub(super) fn step_learning(state: &mut WizardState) -> anyhow::Result<()> {
    println!("== Step 11/12: Feedback Detector ==\n");

    let detector_items = &[
        "regex (default — pattern matching, no LLM)",
        "judge (LLM-based verification)",
        "model (ML classifier via classifiers feature)",
    ];
    let sel = Select::new()
        .with_prompt("Feedback detector mode")
        .items(detector_items)
        .default(0)
        .interact()?;

    match sel {
        1 => {
            state.detector_mode = Some("judge".into());
            let judge_model: String = Input::new()
                .with_prompt(
                    "Judge model name (e.g. claude-sonnet-5; leave empty to use primary provider)",
                )
                .default(String::new())
                .interact_text()?;
            if !judge_model.is_empty() {
                state.judge_model = Some(judge_model);
            }
        }
        2 => {
            state.detector_mode = Some("model".into());
            let feedback_provider: String = Input::new()
                .with_prompt(
                    "Provider name from [[llm.providers]] for feedback detection (leave empty to use primary provider)",
                )
                .default(String::new())
                .interact_text()?;
            if !feedback_provider.is_empty() {
                state.feedback_provider = Some(feedback_provider);
            }
        }
        _ => {
            state.detector_mode = Some("regex".into());
        }
    }

    state.skill_cross_session_rollout = Confirm::new()
        .with_prompt(
            "Require cross-session validation before skill promotion? (prevents promotion from a single long session)",
        )
        .default(false)
        .interact()?;
    if state.skill_cross_session_rollout {
        state.skill_min_sessions_before_promote = Input::new()
            .with_prompt("Minimum distinct sessions required for promotion")
            .default(2u32)
            .interact_text()?;
    }

    println!("\n-- Skill Evolution (ARISE / STEM / ERL) --\n");
    state.arise_enabled = Confirm::new()
        .with_prompt(
            "Enable ARISE? (trace-based skill improvement — refines skill bodies from successful tool sequences)",
        )
        .default(false)
        .interact()?;
    state.stem_enabled = Confirm::new()
        .with_prompt(
            "Enable STEM? (pattern-to-skill conversion — detects recurring tool sequences and generates skill candidates)",
        )
        .default(false)
        .interact()?;
    state.erl_enabled = Confirm::new()
        .with_prompt(
            "Enable ERL? (experiential reflective learning — extracts and injects heuristics from successful tasks)",
        )
        .default(false)
        .interact()?;

    state.d2skill_enabled = Confirm::new()
        .with_prompt(
            "Enable D2Skill? (step-level error correction hints injected into reflection prompts from past ARISE traces)",
        )
        .default(false)
        .interact()?;

    println!("\n-- SkillOrchestra: RL Routing Head --\n");
    state.rl_routing_enabled = Confirm::new()
        .with_prompt(
            "Enable RL routing head? (REINFORCE-trained MLP re-ranks skill candidates; starts blending after 50 updates)",
        )
        .default(false)
        .interact()?;

    println!();
    Ok(())
}