Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions rust/contracts/application-boundary.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,18 @@ turn is suppressed, allowing a same-batch terminal result to finish Stop.
See [the native session contract](../../shared/plugins/contract/v1/README.md#native-sessions)
and [the shared fixture](../fixtures/agents/turn-interaction-v1.json).

### Agent conversation views

Core assigns stable row IDs, merges live message deltas and tool updates, and
applies previously loaded history pages to the same row index and retention
budget. A restored conversation places historical turns before live turns.
Retry names the original row and Core checks its identity and contents again
when it accepts the prompt. The desktop owns the unconfirmed input preview,
draft, scroll anchor and selection. Closing a process leaves its conversation
readable until the host releases the view. The projection lives in memory.
See the [command contract](rust-core-api.md#agent-conversation-projection)
and [mixed-session example](../fixtures/agents/session-projection-v1.json).

### Dev Container configuration and execution environment

The same explicit runtime target follows discovery, configuration lookup, build,
Expand Down
79 changes: 79 additions & 0 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,7 @@ or removing a command fails until the table changes in the same commit.
| `agents.setConfigOption` | Pick a value of a session setting the agent backend reported |
| `agents.close` | End a live agent session |
| `agents.waitEvents` | Wait, bounded, for agent session events after a sequence |
| `agents.projection` | Read a bounded conversation view or apply a loaded history page |
| `agentSessions.configure` | Open the agent session record cache |
| `agentSessions.sync` | Read one agent's changed session files through its plugin |
| `agentSessions.forget` | Drop one agent's cached session records |
Expand Down Expand Up @@ -9208,6 +9209,84 @@ may contain secrets. Public backend methods and lifecycle are specified in the

### Recorded conversation windows

#### Agent conversation projection

A desktop that requests `projection: true` in `agents.start` owns a view
identified by the returned session ID. Core applies accepted events before
publishing their sequence. Ordinary sends enter the projection before backend
delivery completes. Failed delivery retracts the corresponding row. Existing
hosts can continue to use the original event stream. Pass `compact: true` to
`agents.waitEvents` to receive change notifications and required UI events
without streaming message and tool bodies a second time. Sessions without an active projection,
including released views, deliver full event bodies even in compact mode. Recovery delivery
and acknowledgements keep their existing semantics. Hosts drain through the header's `exitSequence` before they stop waiting for final recoveries. A compact wait can include
`views`, a map of session IDs to installed revisions. Only events and recoveries for those sessions cross the boundary. Consecutive short text
suffixes for one row then arrive in `inline[session]` with the new revision,
row position, appended text and budget status in the same response.

`agents.projection` takes one application operation.

| Operation | Request | Result |
| --- | --- | --- |
| `open` | `agent?, cwd?` | An independent history viewer ID in `session`. Supply its catalog `agent` key to bind cached pages to its read grant. |
| `page` | `session, ticket, start, end, messages, before, replace?` | Applies one page from the existing record reader. An increasing ticket orders page changes. Replaying the same ticket is idempotent. `restarted` marks a full history viewer that reopened at this page. |
| `chunk` | `session, frame, offset` | Reads the next UTF-8 fragment of an oversized response. |
| `clearHistory` | `session, ticket` | Removes recorded rows, preserving live rows. |
| `read` | `session, after?, offset?, snapshot?` | A bounded update with `revision`, history `ticket`, `trimmed` rows, `outputDropped` upstream lines, their display total `dropped`, and `room` for another record page. |
| `release` | `session` | Releases rows, buffered updates and snapshot resources. Releasing twice is safe. |

A detached view can supply its session directory as `cwd` on `open`. Changed
files resolve against that directory, or against the live CLI working directory.
A tool row retains its latest supplied `diff`, including a missing versus empty
`oldText`. The per-text and aggregate retention limits also cover these diffs.
When `agents.start` resumes a session with `projection: true`, it can pass
`previousView` to keep the same agent's retained rows and their serials.
The resumed view keeps the upstream dropped-line count. Assistant replies and thoughts
with the same message ID remain distinct. Earlier live turns then occupy historical turn numbers. Only rows read from disk carry
`recorded: true`. Clearing history or losing the read grant preserves earlier live turns and invalidates
recorded data held by snapshots and response frames, even after row eviction. The old view remains
owned by the caller until the new process starts successfully.

On a first read or an expired cursor, `reset` is true. Replace rows starting
at `start`. Request `nextOffset` with the returned revision in `snapshot`
until the snapshot ends. In ordinary reads, apply `edits` in order. Each edit
specifies a zero-based position `at` and a row to insert at the end or replace,
a text suffix to append, or a row to remove. Apply any `cut` to the front
after that edit. `more` asks the reader to continue after the delivered
revision. A header or file list in the response replaces its previous value.
Absent optional row fields have their empty or false value. Row kinds 0 through 4 mean user input, assistant text, thought, tool and notice.
`serial` identifies a retained row across index changes. The original input
identified by `opening` is eligible for retry when the row's `retryable` and the
header's `canPrompt` are true. Pass its `retrySerial` to `agents.prompt` in
`send` mode. Other modes return `agents.invalidInputMode`. An unavailable opening
prompt or a mismatch in its serial, text or attachments returns `agents.retryUnavailable`.
A prompt whose original UTF-8 text exceeds the retention limit is ineligible for retry.
On process exit, `header.exit.stderrTail` carries the bounded CLI diagnostic tail.
Draft text, pending paste operations and native request progress remain local.

Read responses fit a 512 KiB payload budget. If a header, file list or row
would exceed it, the response carries `frame`, `chunk` and `nextByte`. Join
the chunks and decode the resulting page when `nextByte` is zero. A discarded
frame returns `agentSessions.invalidPage`. Retry from the last installed
revision. Ordinary file reads can pass `projection: {session,ticket}` to
`agentSessions.page` to merge the authorized page directly and return its byte
range. A detached viewer restarts at the requested page if the combined rows
would exceed its capacity. Its cursor advances over complete source lines that
fit after folding mirrors and partial tool updates. If one line alone normalizes beyond that capacity, it returns `tooLong`
with both offsets at the original cursor. Use the separate `page` operation for a page captured before resuming
a CLI that may immediately append to the source.

Files preserve their first-occurrence order within the retained session, a
turn, or a visible reply segment keyed by its first row serial. Empty paths
and non-mutating tools contribute no files. The retained view keeps up to
2,000 rows and a 4 MiB estimated row budget, including tool paths and their
changed-file index entries. Each tool row retains whole locations within a
1 MiB location budget. Reply text keeps a 256 KiB
prefix and tool output a 16 KiB tail on UTF-8 boundaries. A transport replay
gap, row eviction and dropped upstream output keep their respective meanings.

#### Recorded session pages

`agentSessions.page` takes `{agent, path, size, generation, cursor, direction}` for a
readable agent. `size` is a listed session's nonzero `readBytes` snapshot and
`generation` the same listing's `generation`; empty sessions need no page request. `direction` is `before`
Expand Down
80 changes: 79 additions & 1 deletion rust/crates/agent-runtime/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -803,6 +803,8 @@ pub(crate) struct HostEvent {
pub sequence: u64,
pub session: String,
pub event: Box<serde_json::value::RawValue>,
#[serde(skip)]
kind: String,
}

impl HostEvent {
Expand Down Expand Up @@ -834,10 +836,19 @@ struct QueueState {
#[derive(Default)]
pub(crate) struct EventQueue {
state: Mutex<QueueState>,
pub(crate) views: crate::projection::command::Views,
ready: Condvar,
}

impl EventQueue {
pub(crate) fn project_input(&self, id: &str, event: impl FnOnce() -> Value) {
if let Some(p) = self.views.get(id) {
p.lock()
.unwrap_or_else(PoisonError::into_inner)
.event(&event())
}
}

/// Reserves a recovery before sending an input. The fixed headroom covers
/// Core's bounded failure code and envelope; recovery omits backend prose.
pub fn reserve_input(&self, session: &str, input: &crate::interaction::Input) -> bool {
Expand Down Expand Up @@ -886,13 +897,28 @@ impl EventQueue {
/// Stores compact encoded payloads. Superseded interaction snapshots are
/// replaced; only replay eviction marks a gap, not snapshot compaction.
pub fn push(&self, session: &str, event: Value) {
let kind = event["kind"].as_str().unwrap_or_default().to_owned();
let snapshot = event["kind"] == "interactionState";
let exited = event["kind"] == "exited";
let resolved = event["kind"] == "inputResolved";
let encoded = serde_json::value::to_raw_value(&event).expect("session event serializes");
// Serialize a session's projection and replay order without holding the
// shared queue lock while merging rows or evicting old content.
let view = self.views.get(session);
let mut projection = view
.as_ref()
.map(|v| v.lock().unwrap_or_else(PoisonError::into_inner));
if let Some(p) = projection.as_mut() {
p.event(&event)
}
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
state.next_sequence += 1;
let sequence = state.next_sequence;
if exited {
if let Some(p) = projection.as_mut() {
p.set_exit_sequence(sequence);
}
}
if resolved {
let key = (
session.to_string(),
Expand All @@ -911,6 +937,7 @@ impl EventQueue {
.expect("input resolution is an object")
.remove("message");
let recovery = HostEvent {
kind: kind.clone(),
sequence,
session: session.into(),
event: serde_json::value::to_raw_value(&recovery).expect("recovery serializes"),
Expand All @@ -920,6 +947,7 @@ impl EventQueue {
}
}
let entry = HostEvent {
kind,
sequence,
session: session.into(),
event: encoded,
Expand All @@ -946,7 +974,19 @@ impl EventQueue {
/// Reads ordered replay and current snapshots after `after`. Recoveries
/// also travel outside the cursor until acknowledged, including after an
/// output gap or a lost response. A future cursor only probes the latest ID.
#[cfg(test)]
pub fn wait(&self, after: u64, timeout: Duration, limit: usize) -> Value {
self.wait_mode(after, timeout, limit, false, None)
}

pub fn wait_mode(
&self,
after: u64,
timeout: Duration,
limit: usize,
compact: bool,
views: Option<&BTreeMap<String, u64>>,
) -> Value {
let deadline = Instant::now() + timeout.min(MAX_WAIT);
let limit = limit.clamp(1, MAX_EVENTS_PER_WAIT);
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
Expand All @@ -961,6 +1001,16 @@ impl EventQueue {
.unwrap_or_else(PoisonError::into_inner)
.0;
}
// A session may have released its view while the wait was asleep. Full event
// bodies remain its only way to receive an actionable permission or question.
let projected = if compact {
drop(state);
let ids = self.views.session_ids();
state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
Some(ids)
} else {
None
};
let missed = after < state.dropped_through;
let mut events: Vec<&HostEvent> = state
.events
Expand All @@ -978,14 +1028,42 @@ impl EventQueue {
events.dedup_by_key(|event| event.sequence);
events.truncate(limit);
let next = events.last().map_or(state.next_sequence, |e| e.sequence);
// Advance the shared cursor over every event, then deliver only this
// window's sessions and rejected drafts across the application boundary.
let visible = |session: &str| !compact || views.is_none_or(|ids| ids.contains_key(session));
events.retain(|e| visible(&e.session));
let recoveries: Vec<_> = state
.recoveries
.values()
.filter_map(|slot| slot.event.as_ref())
.filter(|event| after <= state.next_sequence && event.sequence <= next)
.filter(|event| {
after <= state.next_sequence && event.sequence <= next && visible(&event.session)
})
.collect();
let mut recoveries = recoveries;
recoveries.sort_by_key(|event| event.sequence);
if let Some(projected) = projected {
let events: Vec<_> = events
.iter()
.map(|e| {
if !projected.contains(&e.session)
|| matches!(
e.kind.as_str(),
"inputResolved"
| "interactionFailed"
| "questionAnswered"
| "turnStarted"
| "turnEnded"
)
{
json!(e)
} else {
json!({"session":e.session,"sequence":e.sequence,"event":{"kind":e.kind}})
Comment thread
WhiteZeek marked this conversation as resolved.
Resolved
}
})
.collect();
return json!({"events":events,"next":next,"missed":missed,"recoveries":recoveries});
}
json!({"events":events,"next":next,"missed":missed,"recoveries":recoveries})
}
}
6 changes: 6 additions & 0 deletions rust/crates/agent-runtime/src/interaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,12 @@ pub(crate) fn worker(
runtime.live.queue.push(&session.id, json!({"kind":"inputResolved", "turn":params["turn"], "input":params["input"], "accepted":false, "content":input}));
}
} else if state.active_turn == params["turn"].as_u64() {
if input.as_ref().is_some_and(|i| i.id.is_empty()) {
runtime.live.queue.project_input(
&session.id,
|| json!({"kind":"promptRetracted","input":"","turn":params["turn"]}),
);
}
let event = json!({"kind":"turnEnded", "turn":params["turn"], "reason":"failed"});
state.active_turn = None;
state.interaction.stopping = false;
Expand Down
8 changes: 8 additions & 0 deletions rust/crates/agent-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ mod events;
mod interaction;
mod library;
mod live;
mod projection;
mod records;

#[cfg(test)]
Expand Down Expand Up @@ -76,6 +77,7 @@ pub const AGENT_COMMANDS: &[&str] = &[
"agents.setConfigOption",
"agents.close",
"agents.waitEvents",
"agents.projection",
];

/// The commands of the `agentSessions.*` family.
Expand Down Expand Up @@ -137,6 +139,7 @@ impl Runtime {
match command {
"agents.configure" => {
let answer = self.catalog.configure(payload)?;
self.live.queue.views.purge_unreadable(&self.catalog);
// A session whose agent is gone or no longer granted ends.
self.live.end_where(|plugin_id, agent_id| {
self.catalog
Expand All @@ -156,6 +159,11 @@ impl Runtime {
"agents.setConfigOption" => live::set_config_option(self, payload),
"agents.close" => live::close(self, payload),
"agents.waitEvents" => live::wait_events(self, payload),
"agents.projection" => self
.live
.queue
.views
.execute(&self.catalog, crate::decode(payload)?),
"agentSessions.configure" => self.records.configure(payload),
"agentSessions.sync" => self.records.sync(self, payload),
"agentSessions.forget" => self.records.forget(payload),
Expand Down
Loading
Loading