Skip to main content

agentmux_srv_core/ambient/
tasks.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The background and one-shot ambient Haiku callers: pushed and per-definition
5//! activity summaries, subagent and workflow-batch names, and narration. Each is
6//! best-effort — every failure path returns `None` and the caller carries on
7//! without. They all go through `call::admit` / `Slot::run`, so admission,
8//! cancellation, concurrency caps and reply validation are the same for each.
9//!
10//! The two pull RPCs (`session:activity_summary`, `session:next_prompt_suggestion`)
11//! use the same path from `server::app_api::session`.
12
13use std::sync::Arc;
14
15use super::call::{self, CliTarget, Reply};
16use super::reply::judge_line;
17use super::limits::Class;
18use super::{digest, prompt, purpose, validate};
19use crate::agents::TokenCounts;
20use crate::backend::obj::{Block, MetaMapType};
21use crate::backend::storage::store::Store;
22
23/// What a background call produced. `None` from a task means it did not run to
24/// completion (superseded, capped out, nothing to send, CLI failed), so a caller
25/// that tracks progress should try again later. `Some` means the CLI ran: `text`
26/// is `None` when the model had nothing usable to say (the reply failed
27/// validation, or was empty), which is a finished attempt, not a failure, and
28/// `tokens` is the spend either way.
29#[derive(Debug)]
30pub struct Generated {
31    pub text: Option<String>,
32    pub tokens: Option<TokenCounts>,
33}
34
35fn finish(reply: Reply) -> Option<Generated> {
36    if reply.error.is_some() {
37        return None;
38    }
39    let text = (!reply.text.is_empty()).then_some(reply.text);
40    Some(Generated { text, tokens: reply.tokens })
41}
42
43/// Read-only CLI path lookup for `provider_id` — checks the versioned
44/// local-install dir, then falls back to system PATH. Deliberately never
45/// installs anything (unlike the `resolvecli` RPC handler / `agent_open.rs`'s
46/// launch-time resolution, which both trigger an npm install as a fallback):
47/// this is a best-effort BACKGROUND call, not a user-initiated launch —
48/// silently installing a CLI as a side effect of a picker preview summary
49/// would be a surprising, unwanted cost. Returns `None` (not an error) for
50/// an unknown provider or a CLI that isn't already available either way;
51/// the caller treats that the same as any other unresolvable case.
52pub async fn resolve_provider_cli_path_readonly(provider_id: &str) -> Option<String> {
53    super::cli_locator::locate(provider_id).await
54}
55
56/// How a recovery call ended, for the sweep that decides when to try again.
57#[derive(Debug)]
58pub(crate) enum Recovery {
59    /// Nothing ran: no conversation in the digest, no CLI path, or superseded.
60    NotRun,
61    /// The CLI could not run, exited badly or timed out.
62    Failed,
63    /// The CLI answered; `text` is `None` when the model had nothing usable to say.
64    Done(Generated),
65}
66
67/// A session title recovered from the session's recent activity, for an agent
68/// that has none — called by the background sweep in
69/// `backend::reactive::activity_watcher`, which writes an accepted result to
70/// `term:ambient_summary` itself. Goes through the same Ambient Model Call gateway
71/// (admission, cancellation-of-superseded, token accounting) under the distinct
72/// `purpose::ACTIVITY_SUMMARY_PUSHED` purpose, so it never contends with the
73/// pane's own title request. The prompt is the pane's own title prompt
74/// (`build_session_title_prompt`), given the activity instead of a message, not a
75/// "what is happening now" summary: the result is shown as the session's title.
76///
77/// `generation` only needs to strictly increase across successive calls for
78/// the *same* `block_id` — the sweep loop's tick counter is sufficient; it
79/// doesn't need to correlate with the pull path's per-turn generation.
80///
81/// [`Recovery::NotRun`] when there's nothing to summarize yet, the block/CLI path
82/// isn't resolvable or this call was superseded; [`Recovery::Failed`] when the
83/// CLI failed, so the sweep can wait before it tries this block again.
84pub(crate) async fn generate_recovered_title(
85    mstore: &Store,
86    filestore: &crate::backend::storage::filestore::FileStore,
87    block_id: &str,
88    generation: u64,
89    word_target: u32,
90) -> Recovery {
91    let word_target = word_target.max(3).min(20);
92
93    let Some(slot) = call::admit(&purpose::ACTIVITY_SUMMARY_PUSHED, block_id, generation).await else {
94        return Recovery::NotRun;
95    };
96
97    let Some(block) = mstore.get::<Block>(block_id).ok().flatten() else {
98        return Recovery::NotRun;
99    };
100    let Some(digest) = digest::read_recent_activity_digest(filestore, mstore, block_id) else {
101        slot.abandon(super::outcome::Outcome::EmptyDigest);
102        return Recovery::NotRun;
103    };
104    let Some(target) = CliTarget::from_meta(&block.meta) else {
105        return Recovery::NotRun;
106    };
107
108    let prompt = prompt::build_session_title_prompt("", None, Some(&digest), word_target);
109    let limits = validate::title_limits(word_target);
110    let reply = slot.run(&target, &prompt, |raw| judge_line(raw, |t| validate::accept_line(t, &limits))).await;
111    match reply.error.as_deref() {
112        // A newer request replaced this one: not a failure of the CLI.
113        Some(error) if error.starts_with("cancelled") => Recovery::NotRun,
114        Some(_) => Recovery::Failed,
115        None => finish(reply).map_or(Recovery::NotRun, Recovery::Done),
116    }
117}
118
119/// Generate (and persist) a short activity summary for a definition whose
120/// AgentPicker row has no structured `output.state.json` conversation
121/// snapshot to preview — legacy rows predating snapshot persistence, per
122/// `has_snapshot` in `agent_handlers::session::listrecentsessions`. Built
123/// from the instance's raw terminal capture (the `"output"` filestore file,
124/// written unconditionally by the CLI pipeline, independent of the newer
125/// structured snapshot), reusing `read_recent_activity_digest` — the same
126/// extraction `generate_recovered_title` above uses.
127///
128/// One-shot per definition, not per-turn: `generation` is always the
129/// constant `1`, mirroring `generate_subagent_name`'s cache-once posture —
130/// the caller only invokes this when `agent_activity_summary_get` found
131/// nothing persisted yet, so there is no "newer turn" to supersede an
132/// in-flight call here (unlike the `session:activity_summary` RPC, which
133/// regenerates every turn for a LIVE conversation).
134///
135/// CLI path resolution (reagent P1, PR #2786): the row shape this feature
136/// actually targets is a CLOSED pane — `DeleteBlock`
137/// (`sagas::delete_block::run`) removes the `Block` row entirely on pane
138/// close while the instance row and raw filestore output survive. For such
139/// rows there is no live block to read `cmd`/`cmd:env` meta from at all, so
140/// this prefers the block record when it still exists (richer: carries the
141/// per-block auth env the CLI needs) and falls back to
142/// `resolve_provider_cli_path_readonly` + an EMPTY auth env otherwise —
143/// best-effort: a provider that needs per-block injected credentials (no
144/// ambient/global login available) fails the Haiku call cleanly (`None`,
145/// same as any other unresolvable case here), not a wrong result.
146///
147/// Fire-and-forget by design: the caller (`listrecentsessions`) spawns this
148/// in the background and does not await it inline. The row that triggered
149/// generation still shows its existing fallback text on THIS response; on
150/// success this broadcasts `agents:changed`, which `MyAgentsList.tsx`
151/// already refetches on, picking up the now-persisted summary on the next
152/// load. Returns `None` (nothing persisted, nothing broadcast) when there's
153/// no raw output to summarize, the CLI path isn't resolvable, this call was
154/// superseded/capped, or the CLI failed — the caller treats all of these as
155/// "still nothing to show," not an error.
156pub async fn generate_definition_activity_summary(
157    mstore: &Store,
158    filestore: &crate::backend::storage::filestore::FileStore,
159    broker: &Arc<crate::backend::mps::Broker>,
160    definition_id: &str,
161    block_id: &str,
162    provider_id: &str,
163) -> Option<Generated> {
164    let slot = call::admit(&purpose::DEFINITION_SUMMARY, definition_id, 1).await?;
165
166    let digest = digest::read_recent_activity_digest(filestore, mstore, block_id)?;
167
168    let target = match mstore.get::<Block>(block_id) {
169        Ok(Some(block)) => match CliTarget::from_meta(&block.meta) {
170            Some(target) => target,
171            None => provider_fallback_target(provider_id).await?,
172        },
173        _ => provider_fallback_target(provider_id).await?,
174    };
175
176    let prompt = prompt::build_definition_summary_prompt(&digest);
177    let generated =
178        finish(slot.run(&target, &prompt, |raw| judge_line(raw, |t| validate::accept_line(t, &validate::PREVIEW))).await)?;
179    let Some(summary) = generated.text.clone() else {
180        return Some(generated);
181    };
182
183    let now = agentmux_common::time::now_ms();
184    match mstore.agent_activity_summary_set(definition_id, &summary, now) {
185        Ok(()) => {
186            broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
187        }
188        Err(e) => {
189            // reagent P2, PR #2786: the caller's definition_summary_attempted()
190            // gate already permanently claims definition_id before spawning —
191            // a persistence failure here silently and permanently discards a
192            // successfully generated (and billed) summary with no diagnostic
193            // trail otherwise, unlike every other fallible store call this PR
194            // touches (agent_activity_summary_get's error path logs).
195            tracing::warn!(
196                error = %e,
197                definition_id = %definition_id,
198                "generate_definition_activity_summary: agent_activity_summary_set \
199                 failed — a successfully generated summary was discarded"
200            );
201        }
202    }
203
204    Some(generated)
205}
206
207/// The provider's own CLI with an EMPTY auth env, for a block that no longer
208/// exists or names no CLI. `None` when the provider's CLI isn't installed.
209async fn provider_fallback_target(provider_id: &str) -> Option<CliTarget> {
210    let cli_path = resolve_provider_cli_path_readonly(provider_id).await?;
211    Some(CliTarget { cli_path, meta: MetaMapType::new() })
212}
213
214/// Generate (or return the already-cached) concise Haiku display name for a
215/// subagent. Called on-demand the first time a client expands that
216/// subagent's row in the Swarm view — see `("subagent", "GenerateName")` in
217/// `server::service::misc`. Subagents have no `Block`/meta of their own, so
218/// this borrows the parent block's CLI path + auth env, and reads the
219/// subagent's own initial task prompt directly off its JSONL (available
220/// immediately even for a still-running subagent, unlike a transcript
221/// summary which needs output to summarize).
222///
223/// Returns `None` when there's nothing to name (unknown subagent, no task
224/// prompt on the first JSONL line, parent block unresolvable, or the call
225/// was superseded/capped/failed) — callers should treat that as "leave the
226/// row showing its slug/id fallback," not an error. A cache hit (name
227/// already generated) returns the cached name with `tokens: None` — there's
228/// no new spend to report.
229pub async fn generate_subagent_name(
230    mstore: &Store,
231    subagent_watcher: &Arc<crate::backend::subagent_watcher::SubagentWatcher>,
232    agent_id: &str,
233    class: Class,
234) -> Option<Generated> {
235    let info = subagent_watcher.get_info(agent_id)?;
236    if let Some(existing) = info.display_name {
237        return Some(Generated { text: Some(existing), tokens: None });
238    }
239
240    // Interactive for a live subagent or a row the user opened, background for
241    // the backlog pass over historical ones — see each call site.
242    // Checked again once admitted: the parent's description may have named it
243    // while this call waited.
244    let still_unnamed = || subagent_watcher.get_info(agent_id).is_some_and(|i| i.display_name.is_none());
245    let generated = generate_name_from_task_prompt(
246        mstore,
247        &info,
248        (&purpose::SUBAGENT_NAME, agent_id),
249        class,
250        prompt::build_subagent_name_prompt,
251        still_unnamed,
252    )
253    .await?;
254    if let Some(name) = &generated.text {
255        subagent_watcher.set_display_name(agent_id, name);
256    }
257    Some(generated)
258}
259
260/// Generate the one Haiku display name for a Workflow-kind dispatch,
261/// eagerly, the first time its first member is observed live, or for an
262/// unnamed historical dispatch via `SubagentWatcher::resolve_unnamed_backlog`
263/// when the Swarm pane opens (never called for a Solo dispatch — a Solo
264/// dispatch's name IS its one member's `display_name`, already covered by
265/// `generate_subagent_name`; never called during cold-backfill replay — see
266/// the `live` gate on `process_jsonl_change`'s `trigger_eager_naming` call in
267/// `crates/srv-core/src/backend/subagent_watcher/jsonl.rs`).
268///
269/// A workflow has no single task prompt the way a solo call does (members
270/// can have different prompts) — this reads `first_member_agent_id`'s own
271/// task prompt via the same `read_task_prompt()` `generate_subagent_name`
272/// uses, on the resolved design basis that the first member's prompt is a
273/// reasonable stand-in for the whole batch (SPEC §3 — not a perfect
274/// representation of every member's task, an accepted v1 trade-off).
275///
276/// Otherwise runs the same `generate_name_from_task_prompt` pipeline as
277/// `generate_subagent_name` — no cache-hit short-circuit here
278/// (unlike that function): this is only ever called once per dispatch,
279/// already guarded by `naming_triggered` at the call site, so a cache check
280/// would be dead code, not a real fast path.
281pub(crate) async fn generate_dispatch_name(
282    mstore: &Store,
283    subagent_watcher: &Arc<crate::backend::subagent_watcher::SubagentWatcher>,
284    dispatch_id: &str,
285    first_member_agent_id: &str,
286    class: Class,
287) -> Option<Generated> {
288    let info = subagent_watcher.get_info(first_member_agent_id)?;
289
290    // Its class: see `generate_subagent_name`'s matching comment above.
291    let generated = generate_name_from_task_prompt(
292        mstore,
293        &info,
294        (&purpose::DISPATCH_NAME, dispatch_id),
295        class,
296        prompt::build_dispatch_name_prompt,
297        || true,
298    )
299    .await?;
300    if let Some(name) = &generated.text {
301        subagent_watcher.set_dispatch_name(dispatch_id, name);
302    }
303    Some(generated)
304}
305
306/// Admit `purpose` for `entity`, read `info`'s own task prompt off its JSONL,
307/// borrow its parent block's CLI, and run `build_prompt`'s prompt through the
308/// name check.
309async fn generate_name_from_task_prompt(
310    mstore: &Store,
311    info: &crate::backend::subagent_watcher::SubAgent,
312    (purpose, entity): (&'static purpose::Purpose, &str),
313    class: Class,
314    build_prompt: fn(&str) -> String,
315    still_needed: impl Fn() -> bool,
316) -> Option<Generated> {
317    let slot = call::admit_as(purpose, entity, 1, class).await?;
318    if !still_needed() {
319        slot.abandon(super::outcome::Outcome::Gated);
320        return None;
321    }
322
323    let task_prompt = crate::backend::subagent_watcher::read_task_prompt(&info.jsonl_path)?;
324    let block: Block = mstore.get(&info.parent_block_id).ok().flatten()?;
325    let target = CliTarget::from_meta(&block.meta)?;
326
327    let prompt = build_prompt(&prompt::clip_material(&task_prompt, TASK_HEAD_CHARS, TASK_TAIL_CHARS));
328    finish(slot.run(&target, &prompt, |raw| judge_line(raw, |t| validate::accept_line(t, &validate::NAME))).await)
329}
330
331/// How much of a subagent's task prompt a name call reads. Task prompts run to
332/// many kilobytes; what the task is comes first, and the whole prompt only made
333/// the call slower and gave the model more to mistake for its own instructions.
334const TASK_HEAD_CHARS: usize = 1200;
335const TASK_TAIL_CHARS: usize = 300;
336
337/// Generate a short user-facing line narrating an autonomous action.
338///
339/// Best-effort by construction — every failure path returns `None` and the
340/// caller simply says nothing. A UI state change must NEVER be gated on this:
341/// if Haiku is slow, capped out, or absent, the thing being narrated still
342/// happened and the UI must already reflect it.
343pub async fn generate_ambient_narration(
344    mstore: &Store,
345    block_id: &str,
346    event_id: &str,
347    generation: u64,
348    kind: &str,
349    context: &str,
350) -> Option<String> {
351    let prompt = prompt::narration_prompt(kind, context)?;
352
353    // Keyed on the EVENT, not the block. `admit()` cancels the prior in-flight
354    // call for a key as soon as a newer generation arrives — correct for the
355    // summary callers this is otherwise modelled on, where only the latest
356    // result is ever shown, and wrong here. Each narrated event is independent
357    // and all of them should arrive: two Bash calls backgrounded moments apart
358    // in one block are two separate facts, and `useAmbientNarration` retains
359    // several precisely because it expects them. Keying on the block alone let
360    // the second silently cancel the first, whose Haiku call then returned
361    // "cancelled" and was swallowed. (reagent P1 on #3169.)
362    let slot = call::admit(&purpose::NARRATION, format!("{block_id}:{event_id}"), generation).await?;
363
364    let block: Block = mstore.get(block_id).ok().flatten()?;
365    let target = CliTarget::from_meta(&block.meta)?;
366    let (text, _tokens) = slot
367        .run(&target, &prompt, |raw| judge_line(raw, |t| validate::accept_line(t, &validate::NARRATION)))
368        .await
369        .into_option()?;
370    Some(text)
371}
372
373/// reagent P1, PR #2786: `generate_definition_activity_summary` falls back
374/// to this resolver when the instance's `Block` row is gone (the closed-
375/// pane case this feature actually targets). Only the cheap, deterministic
376/// "unknown provider" early return is exercised here — the filesystem/PATH
377/// probing branches depend on this machine's actual CLI install state and
378/// aren't meaningfully unit-testable without mocking the filesystem.
379#[cfg(test)]
380mod resolve_provider_cli_path_readonly_tests {
381    use super::*;
382
383    #[tokio::test]
384    async fn unknown_provider_returns_none_without_touching_the_filesystem() {
385        assert!(resolve_provider_cli_path_readonly("not-a-real-provider-xyz").await.is_none());
386    }
387}
388
389#[cfg(test)]
390mod narration_key_tests {
391    use super::*;
392
393    #[test]
394    fn two_events_in_one_block_do_not_cancel_each_other() {
395        // The regression reagent caught on #3169. admit() cancels the prior
396        // in-flight call for a KEY, so keying narration on the block alone made
397        // a second backgrounded command in the same turn silently kill the
398        // first one's narration. Distinct event ids must be distinct keys.
399        use crate::ambient::{gateway, Admission, AmbientCallKey};
400
401        let first = AmbientCallKey::new("block-x:toolu_1", purpose::NARRATION.tag);
402        let second = AmbientCallKey::new("block-x:toolu_2", purpose::NARRATION.tag);
403        assert_ne!(first, second, "distinct events must not share a gateway key");
404
405        let g1 = match gateway().admit(first, 1) {
406            Admission::Proceed(g) => g,
407            Admission::StaleOnArrival => panic!("first should be admitted"),
408        };
409        let cancel1 = g1.cancellation();
410        let _g2 = match gateway().admit(second, 2) {
411            Admission::Proceed(g) => g,
412            Admission::StaleOnArrival => panic!("second should be admitted"),
413        };
414        // The second admission must leave the first alone.
415        assert!(!cancel1.is_cancelled(), "a sibling narration cancelled the first");
416    }
417}
418
419#[cfg(test)]
420mod finish_tests {
421    use super::*;
422
423    #[test]
424    fn a_failed_or_superseded_call_is_not_a_finished_attempt() {
425        let reply = Reply { text: String::new(), tokens: None, error: Some("cancelled".into()) };
426        assert!(finish(reply).is_none());
427    }
428
429    #[test]
430    fn a_rejected_reply_is_a_finished_attempt_that_keeps_its_spend() {
431        let tokens = Some(TokenCounts::default());
432        let reply = Reply { text: String::new(), tokens: tokens.clone(), error: None };
433        let generated = finish(reply).expect("the CLI ran");
434        assert!(generated.text.is_none());
435        assert!(generated.tokens.is_some());
436    }
437
438    #[test]
439    fn a_usable_reply_carries_its_text_and_spend() {
440        let reply = Reply { text: "Fix login".into(), tokens: Some(TokenCounts::default()), error: None };
441        let generated = finish(reply).unwrap();
442        assert_eq!(generated.text.as_deref(), Some("Fix login"));
443        assert!(generated.tokens.is_some());
444    }
445}