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
51 changes: 46 additions & 5 deletions core/src/opencode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
//! `tool.execute.after`, with the tool's name, call id and input, and at the end its `status`,
//! error and a shell's `exit`), and from its event stream `permission.asked` and a turn's end
//! (`session.execution.succeeded`, `.failed` or `.interrupted`; `.started` only for a turn that
//! starts with no prompt, as when a background subagent's result wakes its parent), which carries
//! the model the turn's steps named, the turn's last text and, on a top-level turn's, its latest
//! step's input tokens (`context_tokens`: `session.step.ended`'s `input + cache.read +
//! cache.write`, #719). OpenCode reports no session start or end. A subagent is a
//! starts with no prompt, as when a background subagent's result wakes its parent, with the subagent
//! results its turn took, `reported`), which carries the model the turn's steps named, the turn's
//! last text and, on a top-level turn's, its latest step's input tokens (`context_tokens`:
//! `session.step.ended`'s `input + cache.read + cache.write`, #719); a subagent's result delivered
//! into a running turn comes as `session.inbox.delivered` (#779). OpenCode reports no session start
//! or end. A subagent is a
//! child session that always runs in the background (#718): its `subagent` call's end names it
//! (`spawned_session_id`), and the plugin puts its calls, asks and the end of each of its runs
//! under the session that spawned it, with its own id (`subagent_session_id`). The tool names
Expand Down Expand Up @@ -86,6 +88,10 @@ struct Raw {
subagent_session_id: Option<String>,
/// The child session a `subagent` call started, on its end.
spawned_session_id: Option<String>,
/// The subagent results a turn took (#779): on a wake-up, those it took before its first step,
/// empty when none was a subagent's, as a shell job's; on `session.inbox.delivered`, one that
/// joined a running turn. A log from the plugin before #779 has none.
reported: Option<Vec<Reported>>,
/// When the plugin sent the line (#717); a log from the plugin before it has none.
sent_ms: Option<u64>,
#[serde(default)]
Expand All @@ -102,9 +108,44 @@ struct Raw {
studio_touched_roots: Option<Vec<String>>,
}

/// A subagent's result, from OpenCode's `session.inbox.enqueued` item (`metadata.childID` and
/// `metadata.state`).
#[derive(Deserialize)]
struct Reported {
subagent_session_id: String,
/// `completed`, `error` or `cancelled`
/// (`docs/studio/research/opencode-background-results.md`, section 1).
state: String,
}

impl Reported {
/// The child and the status it ends with, in the studio's words: an `error` failed, and
/// `cancelled` is `interrupted`, as a Claude subagent's are.
fn task(&self) -> (String, String) {
let status = match self.state.as_str() {
"error" => "failed",
"cancelled" => "interrupted",
other => other,
};
(self.subagent_session_id.clone(), status.into())
}
}

/// The tasks a line reports on, each with how it ended.
fn reported(results: Option<&[Reported]>) -> Option<Happened> {
let tasks = results?.iter().map(Reported::task);
Some(Happened::TasksReported(tasks.collect()))
}

/// The event of OpenCode plugin line `line`; an error when it has no such line's shape.
pub(crate) fn parse(line: &str) -> Result<Event, serde_json::Error> {
serde_json::from_str::<Raw>(line).map(adapt)
let raw = serde_json::from_str::<Raw>(line)?;
let tasks = reported(raw.reported.as_deref());
let mut event = adapt(raw);
// The subagent results a wake-up took, or one a running turn took on a line of its own,
// `session.inbox.delivered` (#779).
event.happened.extend(tasks);
Ok(event)
}

/// What a call of tool `name` is.
Expand Down
2 changes: 1 addition & 1 deletion core/src/saved.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::{cell::Cell, collections::BTreeMap, fmt};
/// The saved state's format. Bump it when a saved field changes meaning or a field the pane's JSON
/// leaves out is added, so an older file is not read as the new shape: a field the old file lacks
/// makes it unreadable anyway, unless it has a default.
const FORMAT: u32 = 9;
const FORMAT: u32 = 10;

thread_local! {
static SAVING: Cell<bool> = const { Cell::new(false) };
Expand Down
30 changes: 30 additions & 0 deletions core/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,10 @@ pub struct Turn {
/// by", never as Daniel's. A turn stored before it reads as his.
#[serde(default)]
pub wake_up: bool,
/// The tasks a wake-up's turn took the results of, in order, for an agent that says which
/// (OpenCode, #779); empty for any other turn.
#[serde(skip_serializing_if = "crate::saved::unsaved", default)]
pub(crate) results_of: Vec<String>,
/// The id its `Stop` gives a card or a summary on it (`Stopped::card`); `None` until it stopped.
pub id: Option<String>,
/// The first line of its final reply, from its `Stop`.
Expand Down Expand Up @@ -1078,6 +1082,32 @@ impl Session {
last.map(|a| a.agent.id.clone()).unwrap_or_default()
}

/// Names the latest turn, a wake-up's, after `tasks` too, whose results it took (#779): "worker
/// A returned", "workers A and B returned", or "background job returned" when it took none of a
/// subagent's. A turn Daniel prompted keeps its prompt.
pub(crate) fn wake_up_took(&mut self, tasks: &[String]) {
let Some(turn) = self.turns.last_mut().filter(|t| t.wake_up) else {
return;
};
for task in tasks {
if !turn.results_of.contains(task) {
turn.results_of.push(task.clone());
}
}
let results_of = turn.results_of.clone();
let names: Vec<&str> = results_of.iter().map(|id| self.agent_name(id)).collect();
let label = match names.as_slice() {
[] => "background job returned".into(),
[name] => format!("worker {name} returned"),
[first @ .., last] => format!("workers {} and {last} returned", first.join(", ")),
};
let turn = self.turns.last_mut().expect("found above");
turn.prompt.clone_from(&label);
if self.returned.is_some() {
self.returned = Some(label);
}
}

/// Who sent `prompt`. A wake-up names a known task id of the session in markup the studio
/// knows: `<agent-message from="…">` or `<task-id>…</task-id>`. A known id in other markup is
/// drift, and one in plain text is Daniel's.
Expand Down
40 changes: 37 additions & 3 deletions core/src/studio/take.rs
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,15 @@ impl Take<'_> {
self.blocked_answered(tool, id, answer);
}
Happened::TurnStart { prompt, origin } => self.turn_start(prompt, origin.as_ref()),
// A result that joins a running turn names its task on a wake-up's (#779); one the hook
// took late, or that lands after its turn's end, is of a turn already past.
Happened::TasksReported(_)
if self.session.in_turn()
&& !event.has(|h| matches!(h, Happened::TurnStart { .. } | Happened::Late)) =>
{
let tasks = self.reported_tasks();
self.session.wake_up_took(&tasks);
}
// A reply in an event of its own waits for its turn's end (#362). Only the main agent's: a
// subagent's reply (Claude Code's `SubagentStop`) is never its parent turn's.
Happened::Reply(reply)
Expand Down Expand Up @@ -670,27 +679,39 @@ impl Take<'_> {

/// A prompt opens a wait, also after an interrupt, which fires no `Stop`.
fn turn_start(&mut self, prompt: &str, origin: Option<&Origin>) {
let reported = self.reported_tasks();
// An adapter's wake-up that says which tasks it took names them all, the first as its sender
// (#779).
// A wake-up the hook took late is of a turn already past, and names none.
let late = self.event.has(|h| matches!(h, Happened::Late));
let told = origin == Some(&Origin::WakeUp)
&& self.event.has(|h| matches!(h, Happened::TasksReported(_)))
&& !late;
let session = &mut *self.session;
session.reply.clear();
let sender = match origin {
Some(Origin::Daniel) => Sender::Daniel,
Some(Origin::WakeUp) if told => {
Sender::WakeUp(reported.first().cloned().unwrap_or_default())
}
Some(Origin::WakeUp) => Sender::WakeUp(session.woken_by()),
None => session.sender(prompt),
};
let wake_up = !sender.is_daniels();
self.background_retries_reported(prompt);
let session = &mut *self.session;
match &sender {
// The row says which worker returned until the session's next step.
Sender::WakeUp(task_id) => {
// The row says which worker returned until the session's next step; a late wake-up
// leaves the running turn's.
Sender::WakeUp(task_id) if !late => {
let returned = format!("worker {} returned", session.agent_name(task_id));
session.returned = Some(returned);
}
Sender::Unrecognised(task_id) => self.outputs.push(Output::Unrecognised {
session_id: self.event.session_id.clone(),
task_id: task_id.clone(),
}),
Sender::Daniel => {}
Sender::WakeUp(_) | Sender::Daniel => {}
}
if sender.is_daniels() {
self.ask_name(prompt);
Expand All @@ -716,9 +737,22 @@ impl Take<'_> {
session.unblock();
}
session.reopen_turn();
// Named after every task it took; Claude Code's wake-ups keep the name their markup gives.
if told {
session.wake_up_took(&reported);
}
}
}

/// The ids of the tasks the event reports on.
fn reported_tasks(&self) -> Vec<String> {
self.event
.reported()
.iter()
.map(|(id, _)| id.clone())
.collect()
}

/// A background retry ends at the notification that names its task, one of perhaps several in
/// the wake-up.
fn background_retries_reported(&mut self, prompt: &str) {
Expand Down
135 changes: 135 additions & 0 deletions core/tests/opencode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -423,3 +423,138 @@ fn an_opencode_sessions_context_size_is_its_last_top_level_steps_input_tokens()
assert_eq!(session.agents.len(), 1);
assert_eq!(session.state, State::YourTurn);
}

/// A line of `HELLO`'s, sent and received at `at`.
fn hello(name: &str, at: u64, fields: Value) -> String {
let mut line = json!({
"session_id": HELLO, "cwd": "/Users/me/work/hello", "hook_event_name": name, "sent_ms": at,
"studio_agent": "opencode", "studio_received_ms": at,
});
line.as_object_mut()
.unwrap()
.extend(fields.as_object().unwrap().clone());
line.to_string()
}

/// The `reported` of a line of the plugin since #779: each child with OpenCode's `state`.
fn reported(pairs: &[(&str, &str)]) -> Value {
let each = pairs
.iter()
.map(|(child, state)| json!({ "subagent_session_id": child, "state": state }));
json!({ "reported": Value::Array(each.collect()) })
}

/// The end of `HELLO`'s turn, or of subagent `child`'s run, at `at`.
fn run_end(at: u64, child: Option<&str>) -> String {
let mut fields = json!({ "last_assistant_message": "Done." });
if let Some(child) = child {
fields["subagent_session_id"] = child.into();
}
hello("session.execution.succeeded", at, fields)
}

/// A turn of `HELLO`'s that spawns two background subagents, A (`ses_aaaaa`) and B (`ses_bbbbb`),
/// each of which then reads a file, A last.
fn two_children() -> Vec<String> {
let spawn = |at: u64, call: &str, child: &str, description: &str| {
let input = json!({ "description": description, "prompt": "Go.", "agent": "general" });
let call = json!({ "tool_name": "subagent", "tool_use_id": call, "tool_input": input });
let mut ended = call.clone();
ended["status"] = "completed".into();
ended["spawned_session_id"] = child.into();
[
hello("tool.execute.before", at, call),
hello("tool.execute.after", at + 5, ended),
]
};
let read = |at: u64, child: &str| {
let fields = json!({ "tool_name": "read", "tool_use_id": format!("read-{child}"), "tool_input": { "path": "f" }, "subagent_session_id": child });
hello("tool.execute.before", at, fields)
};
let prompt = json!({ "prompt_id": "msg_0", "prompt": "Spawn two." });
let mut lines = vec![hello("session.prompt", 100, prompt)];
lines.extend(spawn(110, "call_a", "ses_aaaaa", "A"));
lines.extend(spawn(130, "call_b", "ses_bbbbb", "B"));
lines.extend([
run_end(150, None),
read(200, "ses_bbbbb"),
read(300, "ses_aaaaa"),
]);
lines
}

/// What a wake-up's turn took (#779): the plugin sends with a wake-up the subagent results its turn
/// took before its first step (`reported`, each child with OpenCode's `state`), and a result
/// delivered into a running turn on a line of its own (`session.inbox.delivered`). Two children,
/// A and B, run in the background; A has the latest event, and both children's end lines land
/// after the wake-up. A turn names, in delivery order, every child whose result it took, and each
/// such child ends with its result's status, whatever its status-less end says.
#[test]
fn a_wake_up_names_the_subagents_whose_results_its_turn_took_and_each_ends_with_its_status() {
let (a, b) = ("ses_aaaaa", "ses_bbbbb");
let wake = |pairs: Option<&[(&str, &str)]>| {
let fields = pairs.map_or(json!({}), reported);
hello("session.execution.started", 900, fields)
};
let prompt = hello(
"session.prompt",
900,
json!({ "prompt_id": "msg_1", "prompt": "And now?" }),
);
let delivered = |pairs: &[(&str, &str)]| hello("session.inbox.delivered", 950, reported(pairs));
let late_wake = |pairs: &[(&str, &str)]| {
let mut fields = reported(pairs);
fields["studio_late"] = true.into();
hello("session.execution.started", 850, fields)
};
let completed = Status::Completed;
let failed = Status::Ended("failed".into());
let interrupted = Status::Ended("interrupted".into());
// Each case: the lines after the two children's, its turn's label and whether it is a
// wake-up's, and how A and B end.
#[rustfmt::skip]
let cases = [
("B's result alone names B, though A has the latest event",
vec![wake(Some(&[(b, "completed")]))], "worker B returned", true, [completed.clone(), completed.clone()]),
("two results name both, each child ending with its own status",
vec![wake(Some(&[(a, "error"), (b, "cancelled")]))], "workers A and B returned", true, [failed.clone(), interrupted.clone()]),
("a result that joins the running wake-up names its child after the first",
vec![wake(Some(&[(b, "completed")])), delivered(&[(a, "error")])], "workers B and A returned", true, [failed.clone(), completed.clone()]),
("a wake-up whose turn took no subagent's result, as a shell job's, names none",
vec![wake(Some(&[]))], "background job returned", true, [completed.clone(), completed.clone()]),
("a log from before #779 names the child with the latest event, and its children end completed",
vec![wake(None)], "worker A returned", true, [completed.clone(), completed.clone()]),
("a result delivered into a turn Daniel prompted ends its child and leaves his prompt",
vec![prompt, delivered(&[(a, "cancelled")])], "And now?", false, [interrupted.clone(), completed.clone()]),
("a result after its child's end, OpenCode's own order, still ends it with its status",
vec![run_end(800, Some(b)), wake(Some(&[(b, "error")]))], "worker B returned", true, [completed.clone(), failed.clone()]),
("a wake-up the hook took late ends its child but leaves the running wake-up's name",
vec![wake(Some(&[(b, "completed")])), late_wake(&[(a, "error")])], "worker B returned", true, [failed.clone(), completed.clone()]),
];
for (case, after, label, wake_up, statuses) in cases {
let mut lines = two_children();
lines.extend(after);
lines.extend([
run_end(1000, Some(b)),
run_end(1010, Some(a)),
run_end(1100, None),
]);
let studio = Studio::replayed(&lines);
let session = studio.session(HELLO).unwrap();

let turn = &session.turns[1];
assert_eq!(
(turn.prompt.as_str(), turn.wake_up),
(label, wake_up),
"{case}"
);
let status = |id: &str| {
let agent = session.agents.iter().find(|s| s.agent.id == id).unwrap();
agent.status.clone()
};
assert_eq!([status(a), status(b)], statuses, "{case}");
assert_eq!(session.turns.len(), 2, "{case}");
let row = wake_up.then(|| label.to_owned());
assert_eq!(session.returned, row, "{case}: the row's name");
}
}
23 changes: 14 additions & 9 deletions core/tests/wake_ups.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,21 @@ fn prompt(prompt: &str) -> String {

#[test]
fn a_wake_up_from_a_task_with_no_subagent_names_it_by_its_short_id() {
let mut studio = replay(DAY);
// `brh86k1fz` is the day's background command, which no subagent record names. A Claude Code
// wake-up that reports two tasks still names the first its markup knows, as OpenCode's names
// all it took (#779) only from its own lines.
let notification = common::task_notification("brh86k1fz", "completed");
let two = notification.clone() + &common::task_notification("zzzzzzzzz", "completed");
for (case, text) in [("one task", notification), ("two tasks", two)] {
let mut studio = replay(DAY);
studio.apply(&prompt(&text));

// `brh86k1fz` is the day's background command, which no subagent record names.
studio.apply(&prompt(&common::task_notification(
"brh86k1fz",
"completed",
)));

let session = studio.session(IMPLEMENT_SPEC).unwrap();
assert_eq!(session.returned.as_deref(), Some("worker brh86 returned"));
let session = studio.session(IMPLEMENT_SPEC).unwrap();
let returned = Some("worker brh86 returned");
assert_eq!(session.returned.as_deref(), returned, "{case}");
let turn = session.turns.last().unwrap();
assert_eq!(Some(turn.prompt.as_str()), returned, "{case}");
}
}

/// The senders of the prompts after the day's 18.
Expand Down
Loading
Loading