ultron-harness 1.0.2

Durable task runtime: the Pi Durable scheduler and conversation runtime (submissions, generation, durable REPL cells, children, swarm state), the RLM task journal, the lane snapshot reducer and the effect gate
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
//! Host operations the REPL reaches through `rlm.host_request` for durable delegation: `rlm.spawn`, `rlm.collect`,
//! `rlm.results`, `rlm.list_subagents`, `rlm.cancel` / `rlm.delete_subagent`, and `rlm.ask` for persistent children.
//! Each request is served for one cell ([`CellCall`]): children it spawns are owned by that cell's task.
//!
//! Waits run in the host (on the request's thread, bounded by the cell's signal), never as a busy cell loop.

use std::sync::Arc;
use std::time::{Duration, Instant};

use durable::{SubmissionStatus, TaskId, TaskQuery, TaskRecord, TaskStatus};
use kernel::{HostHandler, Signal};
use serde_json::{Map, Value, json};

use super::children::{CHILD_KIND, ChildCheckpoint, ChildInput, child_done, child_report, spawn_child};
use super::{CellCall, ChatHarness, ModelRef, SubmissionDraft, WhenBusy};
use crate::scheduler::{Cancel, Ctx, HarnessError};

/// How often a wait rechecks children that are not terminal tasks (persistent children going idle).
const POLL: Duration = Duration::from_millis(20);

/// How long `rlm.ask` waits for an answer when the call gives no `timeout_ms`: a kept child that stops making
/// progress must not hold the caller's cell forever (a DeepSWE run sat 67 minutes in one ask).
pub(crate) const ASK_TIMEOUT: Duration = Duration::from_secs(20 * 60);

type OpResult = Result<Value, String>;

fn error(error: HarnessError) -> String {
    error.message()
}

/// The durable delegation operations over one ChatHarness.
#[derive(Clone)]
pub struct HostOps {
    chat: ChatHarness,
}

/// A child ID as the REPL sees it (`SpawnHandle.rlm_child_id`).
pub fn child_id(task: TaskId) -> String {
    task.0.to_string()
}

fn parse_child(selector: &Value) -> Result<TaskId, String> {
    let text = match selector {
        Value::String(text) => text.clone(),
        Value::Number(number) => number.to_string(),
        other => return Err(format!("Unknown subagent selector {other}")),
    };
    text.parse::<u64>()
        .map(TaskId)
        .map_err(|_| format!("Unknown subagent {text}"))
}

fn parse_model(value: Option<&Value>) -> Result<Option<ModelRef>, String> {
    match value {
        None | Some(Value::Null) => Ok(None),
        Some(Value::String(text)) => match text.split_once('/') {
            Some((provider, model)) if model_scope::is_model_ref(text) => Ok(Some(ModelRef::new(provider, model))),
            _ => Err(format!("rlm.spawn model must be provider/model, got {text}")),
        },
        Some(other) => Err(format!("rlm.spawn model must be a string, got {other}")),
    }
}

/// The swarm, board and notes requests: served for a conversation whichever children exist.
pub const SWARM_KINDS: [&str; 12] = [
    "swarm.register",
    "swarm.agents",
    "swarm.route",
    "swarm.send",
    "swarm.inbox",
    "board.add",
    "board.claim",
    "board.update",
    "board.list",
    "notes.read",
    "notes.append",
    "notes.write",
];

/// A request [`HostOps`] serves: one about persistent children, or one of [`SWARM_KINDS`].
#[derive(Clone, Copy)]
enum Op {
    Spawn,
    Collect,
    Results,
    List,
    Cancel,
    Ask,
    Swarm,
}

impl Op {
    fn of(kind: &str) -> Option<Op> {
        Some(match kind {
            "rlm.spawn" => Op::Spawn,
            "rlm.collect" => Op::Collect,
            "rlm.results" => Op::Results,
            "rlm.list_subagents" => Op::List,
            "rlm.cancel" | "rlm.delete_subagent" => Op::Cancel,
            "rlm.ask" => Op::Ask,
            kind if SWARM_KINDS.contains(&kind) => Op::Swarm,
            _ => return None,
        })
    }
}

impl HostOps {
    pub fn new(chat: ChatHarness) -> HostOps {
        HostOps { chat }
    }

    /// Serve `kind` for the cell `call`; `None` when the request is not a delegation operation.
    pub fn handle(
        &self,
        kind: &str,
        payload: &Map<String, Value>,
        call: &CellCall,
        signal: &Cancel,
    ) -> Option<OpResult> {
        Some(match Op::of(kind)? {
            Op::Spawn => self.spawn(payload, call),
            Op::Collect => self.collect(payload, call, signal),
            Op::Results => self.results(payload, call),
            Op::List => self.list(call),
            Op::Cancel => self.cancel(payload, signal),
            Op::Ask => self.ask(payload, signal),
            Op::Swarm => self.swarm(kind, payload, call),
        })
    }

    /// A [`HostHandler`] for one cell: delegation operations here, everything else to `fallback`.
    pub fn handler(&self, call: CellCall, fallback: Option<Arc<dyn HostHandler>>) -> Arc<dyn HostHandler> {
        Arc::new(CellOps {
            ops: self.clone(),
            call,
            fallback,
        })
    }

    fn spawn(&self, payload: &Map<String, Value>, call: &CellCall) -> OpResult {
        let prompt = payload
            .get("prompt")
            .and_then(Value::as_str)
            .filter(|prompt| !prompt.trim().is_empty())
            .ok_or("rlm.spawn prompt must be a non-empty string")?;
        let empty = Map::new();
        let options = payload.get("kwargs").and_then(Value::as_object).unwrap_or(&empty);
        let name = options
            .get("name")
            .and_then(Value::as_str)
            .filter(|name| !name.trim().is_empty())
            .ok_or("rlm.spawn name must be a non-empty string")?;
        // A persistent child runs in the session's directory as a child conversation of its own: no worktree, no
        // nested delegation, no forked history. An option it would drop is refused rather than ignored.
        for (key, unset) in [
            ("worktree", &[Value::Null, Value::Bool(false)][..]),
            ("worktree_setup", &[Value::Null][..]),
            ("depth", &[Value::Null, json!(0)][..]),
            ("fork", &[Value::Null, Value::Bool(false)][..]),
        ] {
            if let Some(value) = options.get(key)
                && !unset.contains(value)
            {
                return Err(format!(
                    "rlm.spawn(keep=True) does not support {key}=: a persistent child works in the session's directory without a worktree, nested subagents or a forked conversation; drop {key}= or spawn without keep=True"
                ));
            }
        }
        let input = ChildInput {
            name: name.to_owned(),
            prompt: prompt.to_owned(),
            model: parse_model(options.get("model"))?,
            timeout_ms: options
                .get("timeout_ms")
                .and_then(Value::as_f64)
                .map(|ms| ms.ceil() as u64),
            keep: options.get("keep").and_then(Value::as_bool).unwrap_or(false)
                || payload.get("keep").and_then(Value::as_bool).unwrap_or(false),
            thinking: options.get("thinking").and_then(Value::as_str).map(str::to_owned),
            ..ChildInput::default()
        };
        let conversation = call.conversation_id;
        let cell = call.task_id;
        let task = self
            .chat
            .commit(|tx| spawn_child(tx, conversation, Some(cell), &input))
            .map_err(error)?;
        let _ = self.chat.resume();
        Ok(json!({
            "rlm_child_id": child_id(task),
            "name": input.name,
            "session_dir": "",
            "model": input.model.map(|model| format!("{}/{}", model.provider, model.model_id)).unwrap_or_default(),
            "timeout_ms": input.timeout_ms.unwrap_or(0),
            "parent_branch_anchor": "",
            "worktree": Value::Null,
        }))
    }

    /// The children of the calling conversation, oldest first.
    fn children_of(&self, call: &CellCall) -> Result<Vec<TaskRecord>, String> {
        let conversation = call.conversation_id;
        self.chat
            .commit(|tx| {
                let query = TaskQuery {
                    conversation_id: Some(conversation),
                    kind: Some(CHILD_KIND.into()),
                    ..TaskQuery::default()
                };
                let mut records = Vec::new();
                let mut cursor = None;
                loop {
                    let page = tx.committed(|storage| storage.scan_tasks(&query, 256, cursor.as_ref()))?;
                    records.extend(page.items);
                    match page.next {
                        Some(next) => cursor = Some(next),
                        None => break,
                    }
                }
                records.sort_by_key(|record| record.id);
                Ok(records)
            })
            .map_err(error)
    }

    /// The selected children (all of the calling conversation's when none are named).
    fn selected(&self, payload: &Map<String, Value>, call: &CellCall) -> Result<Vec<TaskId>, String> {
        let selectors = payload
            .get("selectors")
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default();
        if selectors.is_empty() {
            return Ok(self.children_of(call)?.iter().map(|record| record.id).collect());
        }
        selectors.iter().map(parse_child).collect()
    }

    fn record(&self, id: TaskId) -> Result<TaskRecord, String> {
        match self.chat.get_task(id).map_err(error)? {
            Some(record) if record.kind == CHILD_KIND => Ok(record),
            _ => Err(format!("Unknown subagent {}", child_id(id))),
        }
    }

    /// Wait for every selected child to have an answer, then return the results.
    fn collect(&self, payload: &Map<String, Value>, call: &CellCall, signal: &Cancel) -> OpResult {
        let ids = self.selected(payload, call)?;
        let timeout = payload
            .get("timeout_ms")
            .and_then(Value::as_f64)
            .filter(|ms| *ms > 0.0)
            .map(|ms| Instant::now() + Duration::from_millis(ms as u64));
        let mut results = Vec::new();
        for id in ids {
            loop {
                let record = self.record(id)?;
                if child_done(&record) {
                    results.extend(child_report(&record));
                    break;
                }
                if record.state.status() != TaskStatus::Terminal && !is_keep(&record) {
                    // An ordinary child becomes terminal: wait for its record, bounded by the cell and the timeout.
                    let (done, expired) = (Cancel::new(), Cancel::new());
                    let limit = timeout.map(|deadline| deadline.saturating_duration_since(Instant::now()));
                    let timer = limit.map(|limit| {
                        let (done, expired) = (done.clone(), expired.clone());
                        std::thread::spawn(move || {
                            if done.wait_timeout(limit).is_none() {
                                expired.cancel(HarnessError::msg("timeout"));
                            }
                        })
                    });
                    let linked = Cancel::any(&[signal, &expired]);
                    let waited = self.chat.wait_for_task(id, &Ctx::with_signal(linked.signal()));
                    done.abort();
                    if let Some(timer) = timer {
                        let _ = timer.join();
                    }
                    if waited.is_ok() {
                        continue;
                    }
                }
                if let Some(reason) = signal.reason() {
                    return Err(reason.message());
                }
                if timeout.is_some_and(|deadline| Instant::now() >= deadline) {
                    return Err(format!("Timed out waiting for subagent {}", child_id(id)));
                }
                signal.wait_timeout(POLL);
            }
        }
        Ok(json!({ "results": results }))
    }

    /// Never waits: the results of children with an answer and the IDs of those still running.
    fn results(&self, payload: &Map<String, Value>, call: &CellCall) -> OpResult {
        let mut results = Vec::new();
        let mut running = Vec::new();
        for id in self.selected(payload, call)? {
            let record = self.record(id)?;
            match child_report(&record) {
                Some(report) => results.push(report),
                None => running.push(json!(child_id(id))),
            }
        }
        Ok(json!({ "results": results, "running": running }))
    }

    fn list(&self, call: &CellCall) -> OpResult {
        let children: Vec<Value> = self
            .children_of(call)?
            .iter()
            .map(|record| {
                let status = match record.state.status() {
                    TaskStatus::Terminal => "ended",
                    _ if is_keep(record) => "kept",
                    _ => "running",
                };
                json!({
                    "id": child_id(record.id),
                    "name": record.input["name"],
                    "keep": is_keep(record),
                    "status": status,
                })
            })
            .collect();
        Ok(json!({ "subagents": children }))
    }

    fn cancel(&self, payload: &Map<String, Value>, signal: &Cancel) -> OpResult {
        let selector = payload
            .get("selector")
            .or_else(|| payload.get("id"))
            .ok_or("rlm.cancel needs a subagent id")?;
        let id = parse_child(selector)?;
        self.record(id)?;
        let result = self.chat.abort_task(id, &Ctx::with_signal(signal)).map_err(error)?;
        Ok(json!({ "cancelled": result == crate::scheduler::AbortResult::Marked }))
    }

    /// Ask a persistent child a follow-up question: an input submission to its conversation, answered there; the
    /// caller's context grows only by the question and the answer. The wait is bounded by `timeout_ms` (default
    /// [`ASK_TIMEOUT`]); when it runs out the answer is `status: "timeout"` and the question stays queued in the
    /// child, which keeps working on it.
    fn ask(&self, payload: &Map<String, Value>, signal: &Cancel) -> OpResult {
        let id = parse_child(payload.get("child").ok_or("rlm.ask needs a child")?)?;
        let question = payload
            .get("question")
            .and_then(Value::as_str)
            .filter(|question| !question.trim().is_empty())
            .ok_or("rlm.ask question must be a non-empty string")?;
        let record = self.record(id)?;
        if !is_keep(&record) {
            return Err(format!(
                "Subagent {} is not persistent; spawn it with keep=True to ask it follow-ups",
                child_id(id)
            ));
        }
        let conversation = loop {
            let record = self.record(id)?;
            if record.state.status() == TaskStatus::Terminal {
                return Err(format!("Subagent {} has ended", child_id(id)));
            }
            if let Some(conversation) = child_conversation(&record) {
                break conversation;
            }
            if let Some(reason) = signal.reason() {
                return Err(reason.message());
            }
            signal.wait_timeout(POLL);
        };
        let request = payload.get("request_id").and_then(Value::as_str);
        let mut draft = SubmissionDraft::input(question).when_busy(WhenBusy::FollowUp);
        if let Some(request) = request {
            draft = draft.request_id(request);
        }
        let handle = self
            .chat
            .conversation(conversation)
            .map_err(error)?
            .ok_or_else(|| format!("Subagent {} has no conversation", child_id(id)))?;
        let limit = payload
            .get("timeout_ms")
            .and_then(Value::as_f64)
            .filter(|ms| *ms > 0.0)
            .map_or(ASK_TIMEOUT, |ms| Duration::from_millis(ms as u64));
        let submission = handle.submit(draft).map_err(error)?;
        let (done, expired) = (Cancel::new(), Cancel::new());
        let timer = {
            let (done, expired) = (done.clone(), expired.clone());
            std::thread::spawn(move || {
                if done.wait_timeout(limit).is_none() {
                    expired.cancel(HarnessError::msg("timeout"));
                }
            })
        };
        let linked = Cancel::any(&[signal, &expired]);
        let waited = submission.wait(&Ctx::with_signal(linked.signal()));
        done.abort();
        let _ = timer.join();
        if waited.is_err() && signal.reason().is_none() && expired.reason().is_some() {
            return Ok(json!({
                "id": child_id(id),
                "status": "timeout",
                "error": format!(
                    "No answer from subagent {} within {} s; it is still working on the question. Carry on and \
                     rlm.ask it again later (a new question queues behind this one), or stop it with \
                     `await rlm.delete_subagent(\"{}\")`.",
                    child_id(id),
                    limit.as_secs_f64().round(),
                    child_id(id)
                ),
            }));
        }
        let settled = waited.map_err(error)?;
        match (settled.status, settled.answer) {
            (SubmissionStatus::Done, Some(answer)) => {
                let text = self
                    .chat
                    .commit(|tx| {
                        let entry = tx.entry(answer)?;
                        Ok(entry
                            .and_then(|entry| entry.model)
                            .and_then(|model| model.into_iter().next()))
                    })
                    .map_err(error)?
                    .map(|message| {
                        message["content"]
                            .as_array()
                            .into_iter()
                            .flatten()
                            .filter_map(|block| block["text"].as_str().map(str::to_owned))
                            .collect::<Vec<_>>()
                            .join("\n")
                    })
                    .unwrap_or_default();
                Ok(json!({ "id": child_id(id), "status": "succeeded", "value": text }))
            }
            _ => Ok(json!({
                "id": child_id(id),
                "status": "failed",
                "error": settled.detail.or(settled.reason.map(Value::String)).unwrap_or(Value::Null),
            })),
        }
    }
}

impl HostOps {
    /// The calling agent's name: what it registered, else `root` for the root conversation.
    fn agent_name(&self, call: &CellCall) -> Result<String, String> {
        let conversation = call.conversation_id;
        let named = self
            .chat
            .commit(|tx| super::swarm::name_of(tx, conversation))
            .map_err(error)?;
        Ok(named.unwrap_or_else(|| {
            if conversation == durable::ROOT_CONVERSATION_ID {
                "root".into()
            } else {
                format!("conversation-{}", conversation.0)
            }
        }))
    }

    fn swarm(&self, kind: &str, payload: &Map<String, Value>, call: &CellCall) -> OpResult {
        let caller = super::swarm::Caller {
            name: self.agent_name(call)?,
            conversation: Some(call.conversation_id),
            root_inbox: None,
        };
        super::swarm::serve(&self.chat, kind, payload, &caller)
    }
}

fn is_keep(record: &TaskRecord) -> bool {
    record.input["keep"] == true
}

fn child_conversation(record: &TaskRecord) -> Option<durable::ConversationId> {
    let checkpoint = match &record.state {
        durable::TaskState::Pending { checkpoint }
        | durable::TaskState::Running { checkpoint }
        | durable::TaskState::Waiting { checkpoint, .. } => checkpoint.clone(),
        _ => return None,
    };
    match serde_json::from_value::<ChildCheckpoint>(checkpoint).ok()? {
        ChildCheckpoint::Wait { conversation, .. } | ChildCheckpoint::Idle { conversation, .. } => Some(conversation),
        ChildCheckpoint::Start => None,
    }
}

struct CellOps {
    ops: HostOps,
    call: CellCall,
    fallback: Option<Arc<dyn HostHandler>>,
}

impl HostHandler for CellOps {
    fn handle(&self, kind: &str, payload: Map<String, Value>, signal: &Signal) -> Result<Value, String> {
        if Op::of(kind).is_none() {
            return match &self.fallback {
                Some(fallback) => fallback.handle(kind, payload, signal),
                None => Err(format!("Unknown host request {kind}")),
            };
        }
        // The kernel's signal ends with the cell; mirror it for host-side waits.
        let cancel = Cancel::new();
        let watcher = {
            let (cancel, signal) = (cancel.clone(), signal.clone());
            std::thread::spawn(move || {
                while !signal.wait(Duration::from_millis(50)) {
                    if cancel.is_cancelled() {
                        return;
                    }
                }
                cancel.cancel(HarnessError::msg(
                    signal.reason().unwrap_or_else(|| "cell ended".into()),
                ));
            })
        };
        let result = match self.ops.handle(kind, &payload, &self.call, &cancel) {
            Some(result) => result,
            None => match &self.fallback {
                Some(fallback) => fallback.handle(kind, payload, signal),
                None => Err(format!("Unknown host request {kind}")),
            },
        };
        // The watcher sees the cancellation within one poll and exits; nothing waits for it.
        cancel.abort();
        drop(watcher);
        result
    }
}