rpi-cli 0.34.0

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates
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
//! Bounded independent runs owned by plugin invocations.
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use futures::FutureExt;
use rpi_agent::{AgentEmitter, AgentEvent};
use rpi_ai::types::AssistantMessageEvent;
use rpi_harness::agent_harness::{AgentHarness, ChildHarness};
use rpi_harness::session::memory::{InMemorySessionStorage, SystemClock};
use rpi_harness::session::session::DefaultIdGenerator;
use rpi_harness::session::types::SessionMetadata;
use rpi_harness::session::Session;
use serde_json::{json, Value};
use tokio_util::sync::CancellationToken;

const MAX_JOBS: usize = 16;
const MAX_OUTPUT: usize = 4 * 1024 * 1024;
const MAX_EVENTS: usize = 8192;

fn now_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

#[derive(Default)]
pub(super) struct IndependentRuns {
    jobs: Arc<Mutex<HashMap<String, Arc<Job>>>>,
    revoked: Arc<Mutex<HashSet<u64>>>,
    active: Arc<AtomicUsize>,
    tasks: crate::host::cli_tasks::CliTaskScope,
}

// Owned preparation holds the shared registry state and its own admission.
struct RunPreparation {
    jobs: Arc<Mutex<HashMap<String, Arc<Job>>>>,
    revoked: Arc<Mutex<HashSet<u64>>>,
    active: Arc<AtomicUsize>,
    admission: crate::host::cli_tasks::CliTaskAdmission,
    signal: CancellationToken,
}

struct Permit(Arc<AtomicUsize>);
impl Drop for Permit {
    fn drop(&mut self) {
        self.0.fetch_sub(1, Ordering::AcqRel);
    }
}

struct Job {
    owner: u64,
    cancel: CancellationToken,
    invocation_signal: Option<CancellationToken>,
    state: Mutex<State>,
}

#[derive(Default)]
struct State {
    deltas: VecDeque<String>,
    bytes: usize,
    events: usize,
    turns: u32,
    result: Option<Value>,
    error: Option<String>,
    /// Supervisory metadata (host UI roster): when the child started/finished
    /// (unix ms). The finish timestamp is recorded when the run settles.
    ///
    /// `u64` (not `u128`): the roster serializes these into JSON and reads them
    /// back with `as_u64`, so the type must not be able to exceed that range.
    started_ms: u64,
    finished_ms: Option<u64>,
}

struct Start {
    input: String,
    turns: u32,
    timeout: u64,
    tools: Option<Vec<String>>,
}

impl State {
    fn is_finished(&self) -> bool {
        self.result.is_some() || self.error.is_some()
    }

    fn mark_finished(&mut self) {
        self.finished_ms.get_or_insert_with(now_ms);
    }
}

impl Job {
    /// Returns whether this call won the transition to a terminal state.
    fn fail(&self, error: impl Into<String>) -> bool {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        let transitioned = !state.is_finished();
        if transitioned {
            state.error = Some(error.into());
            state.mark_finished();
        }
        drop(state);
        self.cancel.cancel();
        transitioned
    }

    fn complete(&self, mut outcome: Value, turns: u32) {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        if state.is_finished() {
            return;
        }
        let bytes = outcome
            .get("text")
            .and_then(Value::as_str)
            .map_or(0, str::len);
        if state.bytes.saturating_add(bytes) > MAX_OUTPUT {
            state.error = Some("child output limit exceeded".into());
        } else {
            outcome["turns"] = json!(state.turns);
            outcome["turnLimited"] = json!(turns != 0 && state.turns >= turns);
            state.result = Some(outcome);
        }
        state.mark_finished();
    }

    fn observe(&self, event: AgentEvent) {
        let mut limit_hit = false;
        {
            let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
            if state.is_finished() {
                return;
            }
            match event {
                AgentEvent::TurnEnd { .. } => state.turns += 1,
                AgentEvent::MessageUpdate {
                    assistant_message_event,
                    ..
                } => {
                    let AssistantMessageEvent::TextDelta { delta, .. } = *assistant_message_event
                    else {
                        return;
                    };
                    if state.bytes.saturating_add(delta.len()) > MAX_OUTPUT
                        || state.events >= MAX_EVENTS
                    {
                        state.error = Some("child output limit exceeded".into());
                        state.mark_finished();
                        limit_hit = true;
                    } else {
                        state.bytes += delta.len();
                        state.events += 1;
                        state.deltas.push_back(delta);
                    }
                }
                _ => {}
            }
        }
        if limit_hit {
            self.cancel.cancel();
        }
    }
}

struct Emitter(Arc<Job>);
impl AgentEmitter for Emitter {
    fn emit(&self, event: AgentEvent) -> futures::future::BoxFuture<'static, ()> {
        self.0.observe(event);
        Box::pin(async {})
    }
    fn try_emit(&self, event: AgentEvent) {
        self.0.observe(event);
    }
}

impl Drop for IndependentRuns {
    fn drop(&mut self) {
        self.begin_shutdown();
    }
}

impl IndependentRuns {
    pub(crate) fn begin_shutdown(&self) {
        self.tasks.seal();
        self.cancel_all();
    }

    #[allow(dead_code)] // Staged until the CLI's complete resource owner is wired.
    pub(crate) async fn wait_shutdown(&self) -> Result<(), String> {
        self.tasks.wait().await
    }

    pub(crate) fn cancel_owner(&self, owner: u64) {
        self.revoked
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .insert(owner);
        self.jobs
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .retain(|_, job| {
                if job.owner == owner {
                    job.fail("owning plugin unloaded");
                    false
                } else {
                    true
                }
            });
    }

    pub(crate) fn cancel_all(&self) {
        for job in self.jobs.lock().unwrap_or_else(|e| e.into_inner()).values() {
            job.fail("parent session closed or changed");
        }
    }

    /// Supervisory roster for the host UI: every child this host still holds
    /// (running **and** terminated-but-not-disposed), newest first. Each row is
    /// self-contained — `childId`/`status`/`turns`/`startedMs`/`finishedMs`/
    /// `error` — so a panel can render without polling each run.
    ///
    /// Status vocabulary matches `poll`: `running` / `done` / `failed`.
    pub(crate) fn roster(&self) -> Vec<Value> {
        let jobs = self.jobs.lock().unwrap_or_else(|e| e.into_inner());
        let mut rows: Vec<Value> = jobs
            .iter()
            .map(|(id, job)| {
                let state = job.state.lock().unwrap_or_else(|e| e.into_inner());
                let status = if state.error.is_some() {
                    "failed"
                } else if state.result.is_some() {
                    "done"
                } else {
                    "running"
                };
                json!({
                    "childId": id,
                    "status": status,
                    "turns": state.turns,
                    "startedMs": state.started_ms,
                    "finishedMs": state.finished_ms,
                    "error": state.error,
                })
            })
            .collect();
        rows.sort_by_key(|row| std::cmp::Reverse(row["startedMs"].as_u64()));
        rows
    }

    /// Host-initiated stop of one child by id (the panel's Stop button).
    ///
    /// Unlike `handle_existing` this is **not** owner-scoped: the caller is the
    /// host itself (one registry per host), not a plugin. Unknown id = `Err`
    /// (never a silent success).
    pub(crate) fn stop(&self, child_id: &str) -> Result<Value, String> {
        let job = {
            let jobs = self.jobs.lock().unwrap_or_else(|e| e.into_inner());
            jobs.get(child_id).cloned()
        };
        let job = job.ok_or_else(|| format!("unknown childId `{child_id}`"))?;
        let cancelled = job.fail("child cancelled by user");
        Ok(json!({
            "childId": child_id,
            "status": if cancelled { "cancelled" } else { "already-finished" },
        }))
    }

    pub(super) async fn start_run(
        &self,
        parent: &AgentHarness,
        owner: u64,
        args: &Value,
    ) -> Result<Value, String> {
        let input = args
            .get("input")
            .and_then(Value::as_str)
            .filter(|text| !text.trim().is_empty() && text.len() <= 24_000)
            .ok_or("run input must contain 1-24000 bytes")?;
        self.start(
            parent,
            owner,
            Start {
                input: input.into(),
                turns: bounded_number(args, "maxTurns", 0, 32)? as u32,
                timeout: bounded_number(args, "timeoutSeconds", 10, 1800)?,
                tools: parse_tools(args)?,
            },
        )
        .await
    }

    pub(super) fn handle_run(&self, owner: u64, args: &Value) -> Result<Value, String> {
        let op = args
            .get("op")
            .and_then(Value::as_str)
            .ok_or("missing run op")?;
        let id = args
            .get("runId")
            .and_then(Value::as_str)
            .ok_or("missing runId")?;
        self.handle_existing(owner, op, id)
    }

    fn handle_existing(&self, owner: u64, op: &str, id: &str) -> Result<Value, String> {
        let job = {
            let jobs = self.jobs.lock().unwrap_or_else(|e| e.into_inner());
            jobs.get(id)
                .filter(|job| job.owner == owner)
                .cloned()
                .ok_or("unknown runId for this plugin")?
        };
        match op {
            "poll" => {
                let mut state = job.state.lock().unwrap_or_else(|e| e.into_inner());
                let status = if state.error.is_some() {
                    "failed"
                } else if state.result.is_some() {
                    "done"
                } else {
                    "running"
                };
                // Bound each ABI response as well as the lifetime output budget.
                let mut deltas = Vec::new();
                let mut bytes = 0;
                while let Some(delta) = state.deltas.front() {
                    if !deltas.is_empty() && bytes + delta.len() > 64 * 1024 {
                        break;
                    }
                    bytes += delta.len();
                    deltas.push(state.deltas.pop_front().expect("front exists"));
                }
                // Terminal result is delivered only after queued deltas drain.
                let drained = state.deltas.is_empty();
                Ok(
                    json!({"runId":id, "status":if drained {status} else {"running"}, "deltas":deltas,
                    "turns":state.turns, "result":if drained {state.result.clone()} else {None},
                    "error":if drained {state.error.clone()} else {None}}),
                )
            }
            "cancel" | "dispose" => {
                job.fail("child cancelled");
                if op == "dispose" {
                    self.jobs
                        .lock()
                        .unwrap_or_else(|e| e.into_inner())
                        .remove(id);
                }
                Ok(json!({"runId":id,"status":if op == "dispose" {"disposed"} else {"cancelled"}}))
            }
            _ => Err(format!("unknown run op `{op}`")),
        }
    }

    async fn start(
        &self,
        parent: &AgentHarness,
        owner: u64,
        request: Start,
    ) -> Result<Value, String> {
        let preparation = RunPreparation {
            jobs: self.jobs.clone(),
            revoked: self.revoked.clone(),
            active: self.active.clone(),
            admission: self.tasks.admit()?,
            signal: self.tasks.signal(),
        };
        self.tasks
            .call(Self::prepare_start(
                preparation,
                parent.clone(),
                owner,
                request,
            ))
            .await?
    }

    async fn prepare_start(
        preparation: RunPreparation,
        parent: AgentHarness,
        owner: u64,
        request: Start,
    ) -> Result<Value, String> {
        if preparation.signal.is_cancelled() {
            return Err("native auxiliary resources are retiring".into());
        }
        let invocation_signal = rpi_agent::tool_execution_scope::invocation_signal();
        if invocation_signal
            .as_ref()
            .is_some_and(CancellationToken::is_cancelled)
        {
            return Err("parent tool invocation cancelled".into());
        }
        let Start {
            input,
            turns,
            timeout,
            tools,
        } = request;
        let id = parent.session().id_generator().next();
        let job = Arc::new(Job {
            owner,
            cancel: preparation.signal.child_token(),
            invocation_signal,
            state: Mutex::new(State {
                started_ms: now_ms(),
                ..State::default()
            }),
        });
        // Reserve before awaiting construction so concurrent starts cannot exceed the cap.
        let permit;
        {
            let revoked = preparation
                .revoked
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            if revoked.contains(&owner) {
                return Err("owning plugin unloaded".into());
            }
            let mut jobs = preparation.jobs.lock().unwrap_or_else(|e| e.into_inner());
            // Serialize publication with shutdown's cancellation sweep.
            if preparation.signal.is_cancelled() {
                return Err("native auxiliary resources are retiring".into());
            }
            if jobs.len() >= MAX_JOBS {
                return Err("child capacity reached; dispose finished children".into());
            }
            let mut active = preparation.active.load(Ordering::Acquire);
            loop {
                if active >= MAX_JOBS {
                    return Err("child cleanup still in progress; retry later".into());
                }
                match preparation.active.compare_exchange_weak(
                    active,
                    active + 1,
                    Ordering::AcqRel,
                    Ordering::Acquire,
                ) {
                    Ok(_) => break,
                    Err(current) => active = current,
                }
            }
            permit = Permit(preparation.active.clone());
            jobs.insert(id.clone(), job.clone());
        }
        let session = Session::new(
            Arc::new(InMemorySessionStorage::new(
                SessionMetadata {
                    id: id.clone(),
                    created_at: 0,
                    parent_session_id: Some(parent.session().storage().metadata().id.clone()),
                },
                Arc::new(SystemClock),
                Arc::new(DefaultIdGenerator::new()),
            )),
            None,
        );
        let emitter = Arc::new(Emitter(job.clone()));
        let child = match parent
            .create_independent_run(session, emitter, turns, tools)
            .await
        {
            Ok(child) => child,
            Err(error) => {
                preparation
                    .jobs
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .remove(&id);
                return Err(error.to_string());
            }
        };
        let worker = job.clone();
        let execution_scope = child.execution_scope.clone();
        let cleanup_harness = child.harness.clone();
        let settlement = preparation.admission.clone();
        preparation
            .admission
            .spawn(&tokio::runtime::Handle::current(), async move {
                let _permit = permit;
                match std::panic::AssertUnwindSafe(run_child(
                    child,
                    worker.clone(),
                    input,
                    turns,
                    timeout,
                ))
                .catch_unwind()
                .await
                {
                    Ok(Ok(())) => {}
                    Ok(Err(_)) => settlement.mark_unknown(),
                    Err(_) => {
                        worker.fail("child runner panicked");
                        if cleanup_harness.close().await.is_err() {
                            settlement.mark_unknown();
                        }
                    }
                }
                // Keep the permit until any background driver has exited.
                execution_scope.wait_idle().await;
            });
        Ok(json!({"runId":id,"sessionId":id,"status":"running"}))
    }
}

fn bounded_number(args: &Value, key: &str, min: u64, max: u64) -> Result<u64, String> {
    let value = args
        .get(key)
        .ok_or_else(|| format!("missing {key}"))?
        .as_u64()
        .ok_or_else(|| format!("{key} must be an integer"))?;
    if !(min..=max).contains(&value) {
        return Err(format!("{key} must be between {min} and {max}"));
    }
    Ok(value)
}

fn parse_tools(args: &Value) -> Result<Option<Vec<String>>, String> {
    args.get("tools")
        .map(|value| {
            value
                .as_array()
                .ok_or("tools must be a string array")?
                .iter()
                .map(|tool| {
                    tool.as_str()
                        .map(str::to_owned)
                        .ok_or("tools must be a string array")
                })
                .collect()
        })
        .transpose()
        .map_err(str::to_owned)
}

async fn run_child(
    child: ChildHarness,
    job: Arc<Job>,
    prompt: String,
    turns: u32,
    timeout: u64,
) -> Result<(), String> {
    let lane = child.harness.lane("main");
    let run = lane.prompt_text(&prompt, Vec::new());
    tokio::pin!(run);
    let parent_abort = async {
        match &child.parent_signal {
            Some(signal) => signal.cancelled().await,
            None => std::future::pending::<()>().await,
        }
    };
    let invocation_abort = async {
        match &job.invocation_signal {
            Some(signal) => signal.cancelled().await,
            None => std::future::pending::<()>().await,
        }
    };
    let result = tokio::select! {
        biased;
        _ = job.cancel.cancelled() => None,
        _ = invocation_abort => {job.fail("parent tool invocation cancelled"); None},
        _ = child.scope.cancelled() => {job.fail("parent run ended"); None},
        _ = parent_abort => {job.fail("parent run cancelled"); None},
        _ = tokio::time::sleep(Duration::from_secs(timeout)) => {job.fail(format!("child timed out after {timeout} seconds")); None},
        result = &mut run => Some(result),
    };
    if let Some(result) = result {
        match result {
            Ok(result) => job.complete(
                crate::extensions_actions::run_outcome_json(result.outcome),
                turns,
            ),
            Err(error) => {
                job.fail(format!("child run failed: {error}"));
            }
        }
    } else {
        // Abort even if cancellation raced ahead of the run's first poll. A closed
        // harness rejects admission; an admitted run gets its cancellation signal.
        let _ = lane.abort().await;
        let _ = child.harness.close().await;
        let _ = tokio::time::timeout(Duration::from_secs(2), &mut run).await;
    }
    child
        .harness
        .close()
        .await
        .map_err(|error| error.to_string())
}

#[cfg(test)]
mod tests;