yolop 0.12.1

Yolop — a terminal coding agent built on everruns-runtime
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
// The `background` capability — a thin surface over everruns session tasks.
//
// Detached background work (e.g. `gh pr checks --watch` waiting on CI) runs
// through everruns' `spawn_background`, which wraps the background-capable
// `bash` tool: it streams to a session-file log, tracks a `background_tool`
// session task, and on completion signals the session. yolop delivers that
// signal to the host as a proactive wake turn via the platform-store wake seam
// (see `crate::runtime::background_wake`).
//
// This capability adds only the `/background` command, which lists the
// session's everruns tasks. The model inspects and controls them with the
// everruns `list_tasks` / `get_task` / `cancel_task` tools (the `session_tasks`
// capability). See knowledge/specs/background.md.
//
// `NarratedBackgroundExecutionCapability` wraps upstream
// `BackgroundExecutionCapability` so `spawn_background` gets human narration
// instead of the generic "Running Spawn Background" fallback.

use crate::capabilities::narration::narrate_spawn_background;
use crate::tui::session_tasks_view::{load_task_tree, render_task_tree};
use async_trait::async_trait;
use everruns_core::capabilities::{
    BackgroundExecutionCapability, Capability, CapabilityLocalization, CapabilityStatus,
    SystemPromptContext,
};
use everruns_core::command::{
    CommandDescriptor, CommandExecutionContext, CommandResult, CommandSource, ExecuteCommandRequest,
};
use everruns_core::session_task::SessionTaskRegistry;
use everruns_core::session_task::TASK_KIND_MONITOR;
use everruns_core::tool_narration::ToolNarrationPhase;
use everruns_core::tool_types::{ToolCall, ToolDefinition};
use everruns_core::tools::Tool;
use everruns_core::traits::SessionStore;
use everruns_core::typed_id::SessionId;
use std::sync::Arc;

pub(crate) const BACKGROUND_CAPABILITY_ID: &str = "background";

// Prompt-side half of the poll-proofing seam (the runtime-enforced half is
// `progress_guard`'s Waiting class): waiting on an external event must cost
// zero turns, so steer the model to detach the wait and rely on the
// completion wake instead of foreground watches or poll-sleep turns.
const BACKGROUND_SYSTEM_PROMPT: &str = "<capability id=\"background\">\n\
    Waiting on an external event — a CI run, a PR review window, a deploy, a long \
    build — must not consume turns. Do not run watch commands in the foreground and \
    do not poll status across turns. Start one blocking watch detached via \
    `spawn_background` (e.g. `gh pr checks --watch`, `gh run watch --exit-status`, \
    or `until <check>; do sleep 30; done`), say what you are waiting for, and end \
    the turn: completion wakes you with the result. You can keep working on other \
    steps while it runs. In one-shot (`-p`) runs there is no wake — block on the \
    spawned task with `wait_task` instead of ending the turn. To inspect background \
    state, call `list_tasks` once without kind or state filters; scheduled work is a \
    `monitor`, not a `background_tool`. Scheduled monitors are obligations you own: \
    before finishing work, cancel any monitor whose purpose is satisfied, superseded, \
    or no longer needed; keep it armed only when its future wake is still required. \
    Treat `disarmed: true` or a terminal task state from `cancel_task` as completed \
    cancellation; `cancellation_pending: true` means cooperative shutdown is still in \
    progress.\n\
    </capability>";

pub(crate) struct BackgroundCapability {
    pub(crate) session_id: SessionId,
    pub(crate) task_registry: Arc<dyn SessionTaskRegistry>,
    pub(crate) session_store: Arc<dyn SessionStore>,
}

#[async_trait]
impl Capability for BackgroundCapability {
    fn id(&self) -> &str {
        BACKGROUND_CAPABILITY_ID
    }
    fn name(&self) -> &str {
        "Background execution"
    }
    fn description(&self) -> &str {
        "List detached background tasks (started with `spawn_background`, e.g. waiting for CI) and \
         their status. Completions wake the agent automatically; inspect results with \
         `get_task`/`list_tasks`."
    }
    fn status(&self) -> CapabilityStatus {
        CapabilityStatus::Available
    }
    fn category(&self) -> Option<&str> {
        Some("Execution")
    }

    async fn system_prompt_contribution(&self, _ctx: &SystemPromptContext) -> Option<String> {
        let active_monitors = self
            .task_registry
            .list(self.session_id, None)
            .await
            .unwrap_or_default()
            .into_iter()
            .filter(|task| task.kind == TASK_KIND_MONITOR && !task.state.is_terminal())
            .map(|task| task.id)
            .collect::<Vec<_>>();
        let mut prompt = BACKGROUND_SYSTEM_PROMPT
            .strip_suffix("</capability>")
            .unwrap_or(BACKGROUND_SYSTEM_PROMPT)
            .to_string();
        if !active_monitors.is_empty() {
            prompt.push_str(&format!(
                "Active scheduled monitor obligations in this session: {}. Reconcile each before reporting its parent work complete.\n",
                active_monitors.join(", ")
            ));
        }
        prompt.push_str("</capability>");
        Some(prompt)
    }

    fn system_prompt_preview(&self) -> Option<String> {
        Some(
            "<capability id=\"background\">\nDetach waits on external events via `spawn_background`; completion wakes the agent.\n</capability>"
                .to_string(),
        )
    }

    fn commands(&self) -> Vec<CommandDescriptor> {
        vec![CommandDescriptor {
            name: "background".to_string(),
            description: "show the session task tree and branch usage".to_string(),
            source: CommandSource::System,
            args: Vec::new(),
        }]
    }

    async fn execute_command(
        &self,
        request: &ExecuteCommandRequest,
        _ctx: &CommandExecutionContext,
    ) -> everruns_core::Result<CommandResult> {
        if request.name != "background" {
            return Err(everruns_core::AgentLoopError::config(format!(
                "{} cannot execute /{}",
                self.id(),
                request.name
            )));
        }
        let tree = load_task_tree(
            self.session_id,
            self.task_registry.as_ref(),
            self.session_store.as_ref(),
        )
        .await;
        Ok(CommandResult {
            success: true,
            message: render_task_tree(&tree, None),
            error_code: None,
            error_fields: None,
        })
    }
}

/// Upstream `spawn_background` without argument-aware narration. Yolop wraps it
/// so transcript / ACP titles read "Spawn background: …" instead of
/// "Running Spawn Background".
pub(crate) struct NarratedBackgroundExecutionCapability {
    inner: BackgroundExecutionCapability,
}

impl NarratedBackgroundExecutionCapability {
    pub(crate) fn new() -> Self {
        Self {
            inner: BackgroundExecutionCapability,
        }
    }
}

#[async_trait]
impl Capability for NarratedBackgroundExecutionCapability {
    fn id(&self) -> &str {
        self.inner.id()
    }

    fn name(&self) -> &str {
        self.inner.name()
    }

    fn description(&self) -> &str {
        self.inner.description()
    }

    fn localizations(&self) -> Vec<CapabilityLocalization> {
        self.inner.localizations()
    }

    fn status(&self) -> CapabilityStatus {
        self.inner.status()
    }

    fn icon(&self) -> Option<&str> {
        self.inner.icon()
    }

    fn category(&self) -> Option<&str> {
        self.inner.category()
    }

    fn tools(&self) -> Vec<Box<dyn Tool>> {
        self.inner.tools()
    }

    fn narrate(
        &self,
        _tool_def: Option<&ToolDefinition>,
        tool_call: &ToolCall,
        phase: ToolNarrationPhase,
        _locale: Option<&str>,
        _ctx: everruns_core::tool_narration::ToolNarrationContext<'_>,
    ) -> Option<String> {
        if tool_call.name == "spawn_background" {
            Some(narrate_spawn_background(tool_call, phase))
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use everruns_core::session_task::{
        CreateSessionTask, NewTaskMessage, SessionTask, SessionTaskFilter, SessionTaskUpdate,
        TaskMessage,
    };
    use serde_json::json;

    /// The prompt contribution tolerates an empty registry.
    struct StubRegistry {
        tasks: Vec<SessionTask>,
    }

    #[async_trait]
    impl SessionTaskRegistry for StubRegistry {
        async fn create(&self, _input: CreateSessionTask) -> everruns_core::Result<SessionTask> {
            unimplemented!("stub")
        }
        async fn update(
            &self,
            _session_id: SessionId,
            _task_id: &str,
            _update: SessionTaskUpdate,
        ) -> everruns_core::Result<Option<SessionTask>> {
            unimplemented!("stub")
        }
        async fn get(
            &self,
            _session_id: SessionId,
            _task_id: &str,
        ) -> everruns_core::Result<Option<SessionTask>> {
            unimplemented!("stub")
        }
        async fn list(
            &self,
            _session_id: SessionId,
            _filter: Option<&SessionTaskFilter>,
        ) -> everruns_core::Result<Vec<SessionTask>> {
            Ok(self.tasks.clone())
        }
        async fn request_cancel(
            &self,
            _session_id: SessionId,
            _task_id: &str,
        ) -> everruns_core::Result<Option<SessionTask>> {
            unimplemented!("stub")
        }
        async fn record_message(
            &self,
            _session_id: SessionId,
            _task_id: &str,
            _message: NewTaskMessage,
        ) -> everruns_core::Result<TaskMessage> {
            unimplemented!("stub")
        }
        async fn list_messages(
            &self,
            _session_id: SessionId,
            _task_id: &str,
            _limit: Option<u32>,
            _after_id: Option<&str>,
        ) -> everruns_core::Result<Vec<TaskMessage>> {
            unimplemented!("stub")
        }
    }

    #[async_trait]
    impl everruns_core::traits::SessionStore for StubRegistry {
        async fn get_session(
            &self,
            _session_id: SessionId,
        ) -> everruns_core::Result<Option<everruns_core::Session>> {
            Ok(None)
        }
    }

    #[tokio::test]
    async fn system_prompt_teaches_detached_waits_per_host() {
        let store = Arc::new(StubRegistry { tasks: vec![] });
        let capability = BackgroundCapability {
            session_id: SessionId::new(),
            task_registry: store.clone(),
            session_store: store,
        };
        let ctx = SystemPromptContext::without_file_store(SessionId::new());

        let prompt = capability
            .system_prompt_contribution(&ctx)
            .await
            .expect("background capability contributes a prompt");
        // Interactive hosts detach and get woken; one-shot runs must block
        // instead because `-p` exits before any wake can be delivered.
        assert!(prompt.contains("spawn_background"));
        assert!(prompt.contains("end the turn"));
        assert!(prompt.contains("wait_task"));
        assert!(prompt.contains("cancel any monitor whose purpose is satisfied"));
        assert!(prompt.contains("disarmed: true"));
    }

    #[tokio::test]
    async fn system_prompt_surfaces_active_monitor_obligations() {
        let session_id = SessionId::from_seed(42);
        let task = everruns_core::session_task::new_session_task(
            CreateSessionTask {
                session_id,
                id: Some("task_scheduled_check".into()),
                kind: TASK_KIND_MONITOR.into(),
                display_name: "scheduled check".into(),
                spec: serde_json::json!({}),
                state: everruns_core::session_task::SessionTaskState::Running,
                links: Default::default(),
                wake_policy: everruns_core::session_task::TaskWakePolicy::Silent,
            },
            chrono::Utc::now(),
        );
        let store = Arc::new(StubRegistry { tasks: vec![task] });
        let capability = BackgroundCapability {
            session_id,
            task_registry: store.clone(),
            session_store: store,
        };
        let ctx = SystemPromptContext::without_file_store(session_id);

        let prompt = capability
            .system_prompt_contribution(&ctx)
            .await
            .expect("background capability contributes a prompt");

        assert!(prompt.contains("Active scheduled monitor obligations"));
        assert!(prompt.contains("task_scheduled_check"));
        assert!(prompt.contains("Reconcile each"));
    }

    #[tokio::test]
    async fn background_command_renders_the_session_task_tree() {
        let session_id = SessionId::from_seed(43);
        let task = everruns_core::session_task::new_session_task(
            CreateSessionTask {
                session_id,
                id: Some("task_command".into()),
                kind: everruns_core::session_task::TASK_KIND_BACKGROUND_TOOL.into(),
                display_name: "compile workspace".into(),
                spec: serde_json::json!({}),
                state: everruns_core::session_task::SessionTaskState::Running,
                links: Default::default(),
                wake_policy: everruns_core::session_task::TaskWakePolicy::Silent,
            },
            chrono::Utc::now(),
        );
        let store = Arc::new(StubRegistry { tasks: vec![task] });
        let capability = BackgroundCapability {
            session_id,
            task_registry: store.clone(),
            session_store: store,
        };

        let result = capability
            .execute_command(
                &ExecuteCommandRequest {
                    name: "background".into(),
                    arguments: None,
                    controls: None,
                },
                &CommandExecutionContext::without_host(session_id),
            )
            .await
            .expect("background command");

        assert!(result.success);
        assert!(
            result
                .message
                .contains("[task_command] background_tool running: compile workspace")
        );
    }

    #[test]
    fn spawn_background_capability_narrates_with_title() {
        let capability = NarratedBackgroundExecutionCapability::new();
        let call = ToolCall {
            id: "call-1".to_owned(),
            name: "spawn_background".to_owned(),
            arguments: json!({
                "tool": "bash",
                "title": "Wait for CI",
                "args": { "command": "gh pr checks --watch" }
            }),
        };
        let narration = capability.narrate(
            None,
            &call,
            ToolNarrationPhase::Started,
            None,
            everruns_core::tool_narration::ToolNarrationContext::default(),
        );
        assert_eq!(narration.as_deref(), Some("Spawn background: Wait for CI"));
    }
}