codewhale-tui 0.9.1

Terminal UI for open-source and open-weight coding models
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
//! Turn authority and mode/posture policy projections.
//!
//! Keep mode, approval, shell, sandbox, trust, and input provenance decisions
//! in one place so prompt metadata, tool catalogs, and runtime gates cannot
//! drift independently.

use std::path::Path;

use crate::sandbox::SandboxPolicy;
use crate::tools::spec::ApprovalRequirement;
use crate::tui::app::AppMode;
use crate::tui::approval::ApprovalMode;
use crate::worker_profile::ShellPolicy;

use super::ops::UserInputProvenance;

/// Durable Agent-era permission baseline that Plan/YOLO restore to (#3386).
///
/// Mode cycling used to be tangled with permission policy: each mode mutated
/// `allow_shell`/`trust_mode`/`approval_mode` directly and ad-hoc snapshots
/// tried to put things back on exit. Instead, keep one canonical baseline: the
/// permission surface the user has chosen for Agent mode.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ModeSessionPrefs {
    pub(crate) agent_allow_shell: bool,
    pub(crate) agent_trust_mode: bool,
    pub(crate) agent_approval_mode: ApprovalMode,
}

/// The permission policy a given [`AppMode`] resolves to (#3386).
#[derive(Debug, Clone, Copy)]
pub(crate) struct EffectiveModePolicy {
    #[allow(dead_code)]
    pub(crate) mode: AppMode,
    pub(crate) allow_shell: bool,
    pub(crate) trust_mode: bool,
    pub(crate) approval_mode: ApprovalMode,
}

/// Resolve a mode's effective permission policy from the durable Agent baseline.
///
/// This is the single source of truth for the mode/permission table:
/// - `Plan`   -> read-only: no shell, no trust, `Suggest` approvals.
/// - `Agent`  -> the user's durable baseline (`prefs`).
/// - `Auto`   -> compatibility alias for Agent; not a separate behavior.
/// - `Operate` -> Agent baseline plus orchestration posture in prompts.
/// - `Yolo`   -> legacy compat; full authority: shell + trust + `Bypass` approvals.
#[must_use]
pub(crate) fn base_policy_for_mode(mode: AppMode, prefs: &ModeSessionPrefs) -> EffectiveModePolicy {
    match mode {
        AppMode::Plan => EffectiveModePolicy {
            mode,
            allow_shell: false,
            trust_mode: false,
            approval_mode: ApprovalMode::Suggest,
        },
        AppMode::Agent | AppMode::Auto | AppMode::Operate => EffectiveModePolicy {
            mode,
            allow_shell: prefs.agent_allow_shell,
            trust_mode: prefs.agent_trust_mode,
            approval_mode: prefs.agent_approval_mode,
        },
        AppMode::Yolo => EffectiveModePolicy {
            mode,
            allow_shell: true,
            trust_mode: true,
            approval_mode: ApprovalMode::Bypass,
        },
    }
}

/// Effective authority for one engine turn after provenance narrowing.
#[derive(Debug, Clone)]
pub(crate) struct TurnAuthority {
    pub(crate) mode: AppMode,
    pub(crate) allow_shell: bool,
    pub(crate) trust_mode: bool,
    pub(crate) auto_approve: bool,
    pub(crate) approval_mode: ApprovalMode,
    pub(crate) dynamic_active_tools: Vec<&'static str>,
    pub(crate) status: Option<String>,
}

impl TurnAuthority {
    #[must_use]
    pub(crate) fn from_effective_fields(
        mode: AppMode,
        allow_shell: bool,
        trust_mode: bool,
        auto_approve: bool,
        approval_mode: ApprovalMode,
    ) -> Self {
        Self {
            mode,
            allow_shell,
            trust_mode,
            auto_approve,
            approval_mode,
            dynamic_active_tools: Vec::new(),
            status: None,
        }
    }

    #[must_use]
    pub(crate) fn approval_mode_for_session(&self) -> ApprovalMode {
        agent_approval_mode_for_turn(self.auto_approve, self.approval_mode)
    }

    /// Authority for the per-tool approval gate, folded from the legacy
    /// session `auto_approve` bit so [`resolve_tool_permission`] observes the
    /// same effective posture the old boolean helpers encoded: a set bit is
    /// Full Access (Yolo/Bypass-shaped), a cleared bit is an ordinary Ask
    /// turn. The engine's `Never` denial deliberately stays at the UI layer,
    /// so this constructor never produces a `Never` posture.
    #[must_use]
    pub(crate) fn for_tool_approval_decision(auto_approve: bool) -> Self {
        Self::from_effective_fields(
            if auto_approve {
                AppMode::Yolo
            } else {
                AppMode::Agent
            },
            true,
            false,
            auto_approve,
            if auto_approve {
                ApprovalMode::Bypass
            } else {
                ApprovalMode::Suggest
            },
        )
    }

    #[must_use]
    pub(crate) fn shell_policy(&self) -> ShellPolicy {
        shell_policy_for_mode(self.mode, self.allow_shell)
    }

    #[must_use]
    pub(crate) fn sandbox_policy(&self, workspace: &Path) -> SandboxPolicy {
        sandbox_policy_for_mode(self.mode, workspace)
    }
}

#[must_use]
pub(crate) fn effective_input_policy(
    provenance: UserInputProvenance,
    requested_mode: AppMode,
    _content: &str,
    allow_shell: bool,
    trust_mode: bool,
    auto_approve: bool,
    approval_mode: ApprovalMode,
) -> TurnAuthority {
    let mut mode = requested_mode;
    let mut trust_mode = trust_mode;
    let mut auto_approve = auto_approve;
    let mut approval_mode = approval_mode;
    let mut status = None;

    if !provenance_can_inherit_standing_auto_authority(provenance) {
        let had_auto_authority = matches!(mode, AppMode::Yolo)
            || trust_mode
            || auto_approve
            || matches!(approval_mode, ApprovalMode::Bypass);
        if matches!(mode, AppMode::Yolo) {
            mode = AppMode::Agent;
        }
        trust_mode = false;
        auto_approve = false;
        if matches!(approval_mode, ApprovalMode::Auto | ApprovalMode::Bypass) {
            approval_mode = ApprovalMode::Suggest;
        }
        if had_auto_authority {
            status = Some(format!(
                "Input provenance '{}' cannot inherit standing auto-approval authority; continuing with approvals required.",
                provenance.as_str()
            ));
        }
    }

    // The named permission posture is authoritative. Normalize legacy or
    // host inputs that carry `Bypass` with a stale false auto-approve bit so
    // every engine surface observes the same Full Access contract.
    if approval_mode == ApprovalMode::Bypass {
        auto_approve = true;
    }

    TurnAuthority {
        mode,
        allow_shell,
        trust_mode,
        auto_approve,
        approval_mode,
        dynamic_active_tools: Vec::new(),
        status,
    }
}

#[must_use]
pub(crate) fn provenance_can_inherit_standing_auto_authority(
    provenance: UserInputProvenance,
) -> bool {
    matches!(
        provenance,
        UserInputProvenance::ExternalUser
            | UserInputProvenance::Runtime
            | UserInputProvenance::SubAgentHandoff
    )
}

/// Whether the active permission posture may pause the turn for a user
/// decision. Auto-Review is the fully autonomous posture: it must decide from
/// available context and keep moving. Tool approval and user-question policy
/// stay deliberately separate in every other posture.
#[must_use]
pub(crate) fn permission_posture_allows_questions(approval_mode: ApprovalMode) -> bool {
    approval_mode != ApprovalMode::Auto
}

#[must_use]
pub(crate) fn agent_approval_mode_for_turn(
    auto_approve: bool,
    approval_mode: ApprovalMode,
) -> ApprovalMode {
    if auto_approve {
        ApprovalMode::Bypass
    } else {
        approval_mode
    }
}

/// Pick the sandbox policy that gates shell commands for a given UI mode.
#[must_use]
pub(crate) fn sandbox_policy_for_mode(mode: AppMode, workspace: &Path) -> SandboxPolicy {
    match mode {
        AppMode::Plan => SandboxPolicy::ReadOnly,
        AppMode::Agent | AppMode::Auto | AppMode::Operate => SandboxPolicy::WorkspaceWrite {
            writable_roots: vec![workspace.to_path_buf()],
            network_access: true,
            exclude_tmpdir: false,
            exclude_slash_tmp: false,
        },
        AppMode::Yolo => SandboxPolicy::DangerFullAccess,
    }
}

/// Resolve the effective shell policy for a turn from legacy shell opt-in plus mode.
#[must_use]
pub(crate) fn shell_policy_for_mode(mode: AppMode, allow_shell: bool) -> ShellPolicy {
    if !allow_shell {
        return ShellPolicy::None;
    }
    match mode {
        AppMode::Plan => ShellPolicy::None,
        AppMode::Agent | AppMode::Auto | AppMode::Operate | AppMode::Yolo => ShellPolicy::Full,
    }
}

/// Per-tool permission decision from the unified resolver (#4412).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ToolPermission {
    /// Tool executes without any approval prompt.
    Allow,
    /// Tool requires user approval before execution.
    Prompt,
    /// Tool is denied without a prompt (approval_mode=Never).
    Deny,
}

/// Unified per-tool permission resolver (#4412).
///
/// Consolidates the approval decision that was previously scattered across
/// `registered_tool_approval_required` (turn_loop), `app_auto_approve_enabled`
/// (ui.rs), and the `Never` short-circuit. One call site, one answer.
///
/// The truth table mirrors the legacy helpers exactly:
/// - `Auto` tools always run — even under `Never`, which stays read-only
///   rather than dead.
/// - `Never` denies any tool that would otherwise prompt, but only when the
///   authority is not full-access shaped: a Yolo/Bypass authority carrying a
///   stale `Never` enum still auto-approves, matching the legacy UI order in
///   which the full-access shortcut ran before the `Never` check.
/// - `Suggest` and `Required` are both bypassable by auto-approve authority
///   unless the tool is on the typed non-bypassable hold list
///   (`is_non_bypassable`), which always prompts. A generic `Required` tool
///   remains auto-approved in Full Access (#3866).
#[must_use]
pub(crate) fn resolve_tool_permission(
    authority: &TurnAuthority,
    requirement: ApprovalRequirement,
    is_non_bypassable: bool,
) -> ToolPermission {
    if authority.approval_mode == ApprovalMode::Never
        && requirement != ApprovalRequirement::Auto
        && !authority.auto_approve
        && authority.mode != AppMode::Yolo
    {
        return ToolPermission::Deny;
    }
    match requirement {
        ApprovalRequirement::Auto => ToolPermission::Allow,
        ApprovalRequirement::Suggest | ApprovalRequirement::Required => {
            if is_non_bypassable {
                return ToolPermission::Prompt;
            }
            if authority.auto_approve
                || authority.approval_mode == ApprovalMode::Bypass
                || authority.mode == AppMode::Yolo
            {
                ToolPermission::Allow
            } else {
                ToolPermission::Prompt
            }
        }
    }
}

/// Disposition for an approval request that reached the UI (#4412).
///
/// The engine emits `ApprovalRequired` whenever its resolver answer was
/// `Prompt`; the UI then disposes of that request — honoring session caches
/// and posture races — through this single decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ApprovalRequestDisposition {
    /// Session grant or full-access posture: approve without a modal.
    AutoApprove,
    /// The user already denied this approval key this session (#360).
    AutoDenySessionDenied,
    /// A forced (non-bypassable) policy hold arrived under a full-access
    /// posture that opens no modal: fail closed.
    AutoDenyFullAccessPolicyHold,
    /// approval_mode=Never: deny without a modal.
    AutoDenyNeverPosture,
    /// Open the approval modal.
    Prompt,
}

/// Resolve how the UI disposes of one incoming approval request.
///
/// `session_approved` / `session_denied` are the caller's lookups into the
/// session approval caches (grouping key or tool name / exact approval key).
/// The branch order is the legacy handler's order: session denial, then the
/// full-access forced-hold denial, then auto-approval (full access or a
/// session grant), then the `Never` denial, and only finally a modal.
#[must_use]
pub(crate) fn resolve_approval_request_disposition(
    authority: &TurnAuthority,
    session_approved: bool,
    session_denied: bool,
    approval_force_prompt: bool,
) -> ApprovalRequestDisposition {
    if session_denied {
        return ApprovalRequestDisposition::AutoDenySessionDenied;
    }
    // The request exists, so the engine already resolved Prompt for the tool
    // itself. What remains is the posture question: how does this authority
    // treat an ordinary promptable tool?
    let posture = resolve_tool_permission(authority, ApprovalRequirement::Suggest, false);
    if approval_force_prompt && posture == ToolPermission::Allow {
        return ApprovalRequestDisposition::AutoDenyFullAccessPolicyHold;
    }
    if !approval_force_prompt && (posture == ToolPermission::Allow || session_approved) {
        return ApprovalRequestDisposition::AutoApprove;
    }
    if posture == ToolPermission::Deny {
        return ApprovalRequestDisposition::AutoDenyNeverPosture;
    }
    ApprovalRequestDisposition::Prompt
}

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

    fn authority(mode: AppMode, auto_approve: bool, approval_mode: ApprovalMode) -> TurnAuthority {
        TurnAuthority::from_effective_fields(mode, true, false, auto_approve, approval_mode)
    }

    #[test]
    fn auto_requirement_always_allows() {
        for (mode, auto_approve, approval_mode) in [
            (AppMode::Agent, false, ApprovalMode::Suggest),
            (AppMode::Agent, false, ApprovalMode::Auto),
            (AppMode::Agent, false, ApprovalMode::Never),
            (AppMode::Agent, true, ApprovalMode::Bypass),
            (AppMode::Yolo, true, ApprovalMode::Bypass),
            (AppMode::Plan, false, ApprovalMode::Suggest),
        ] {
            let auth = authority(mode, auto_approve, approval_mode);
            for non_bypassable in [false, true] {
                assert_eq!(
                    resolve_tool_permission(&auth, ApprovalRequirement::Auto, non_bypassable),
                    ToolPermission::Allow,
                    "{mode:?}/{auto_approve}/{approval_mode:?}/nb={non_bypassable}"
                );
            }
        }
    }

    #[test]
    fn ask_posture_prompts_for_non_auto_tools() {
        let auth = authority(AppMode::Agent, false, ApprovalMode::Suggest);
        for requirement in [ApprovalRequirement::Suggest, ApprovalRequirement::Required] {
            assert_eq!(
                resolve_tool_permission(&auth, requirement, false),
                ToolPermission::Prompt
            );
            assert_eq!(
                resolve_tool_permission(&auth, requirement, true),
                ToolPermission::Prompt
            );
        }
    }

    #[test]
    fn full_access_allows_bypassable_but_prompts_for_non_bypassable() {
        for auth in [
            authority(AppMode::Agent, true, ApprovalMode::Bypass),
            authority(AppMode::Yolo, true, ApprovalMode::Bypass),
            TurnAuthority::for_tool_approval_decision(true),
        ] {
            for requirement in [ApprovalRequirement::Suggest, ApprovalRequirement::Required] {
                assert_eq!(
                    resolve_tool_permission(&auth, requirement, false),
                    ToolPermission::Allow,
                    "generic {requirement:?} tool stays auto-approved in Full Access"
                );
                assert_eq!(
                    resolve_tool_permission(&auth, requirement, true),
                    ToolPermission::Prompt,
                    "non-bypassable {requirement:?} tool forces a prompt in Full Access"
                );
            }
        }
    }

    #[test]
    fn never_denies_promptable_tools_but_not_reads_or_full_access_shapes() {
        let never = authority(AppMode::Agent, false, ApprovalMode::Never);
        assert_eq!(
            resolve_tool_permission(&never, ApprovalRequirement::Suggest, false),
            ToolPermission::Deny
        );
        assert_eq!(
            resolve_tool_permission(&never, ApprovalRequirement::Required, true),
            ToolPermission::Deny
        );
        assert_eq!(
            resolve_tool_permission(&never, ApprovalRequirement::Auto, false),
            ToolPermission::Allow,
            "Never remains read-only rather than dead"
        );

        // Legacy host shape: full-access bit/Yolo mode with a stale Never enum
        // still auto-approves — the UI's full-access shortcut ran before its
        // Never check.
        let stale = authority(AppMode::Agent, true, ApprovalMode::Never);
        assert_eq!(
            resolve_tool_permission(&stale, ApprovalRequirement::Suggest, false),
            ToolPermission::Allow
        );
        let yolo_never = authority(AppMode::Yolo, false, ApprovalMode::Never);
        assert_eq!(
            resolve_tool_permission(&yolo_never, ApprovalRequirement::Suggest, false),
            ToolPermission::Allow
        );
    }

    #[test]
    fn approval_request_disposition_preserves_legacy_branch_order() {
        let ask = authority(AppMode::Agent, false, ApprovalMode::Suggest);
        let full_access = authority(AppMode::Agent, true, ApprovalMode::Bypass);
        let never = authority(AppMode::Agent, false, ApprovalMode::Never);

        // Session denial wins over everything, including full access.
        assert_eq!(
            resolve_approval_request_disposition(&full_access, true, true, false),
            ApprovalRequestDisposition::AutoDenySessionDenied
        );
        // Forced hold under full access fails closed instead of auto-approving.
        assert_eq!(
            resolve_approval_request_disposition(&full_access, true, false, true),
            ApprovalRequestDisposition::AutoDenyFullAccessPolicyHold
        );
        // Full access and session grants auto-approve ordinary requests.
        assert_eq!(
            resolve_approval_request_disposition(&full_access, false, false, false),
            ApprovalRequestDisposition::AutoApprove
        );
        assert_eq!(
            resolve_approval_request_disposition(&ask, true, false, false),
            ApprovalRequestDisposition::AutoApprove
        );
        // A session grant still auto-approves under Never (legacy order), and
        // Never denies everything else promptable.
        assert_eq!(
            resolve_approval_request_disposition(&never, true, false, false),
            ApprovalRequestDisposition::AutoApprove
        );
        assert_eq!(
            resolve_approval_request_disposition(&never, false, false, false),
            ApprovalRequestDisposition::AutoDenyNeverPosture
        );
        // Ask posture with no grant opens the modal.
        assert_eq!(
            resolve_approval_request_disposition(&ask, false, false, false),
            ApprovalRequestDisposition::Prompt
        );
    }
}