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
10 changes: 10 additions & 0 deletions core/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ pub(crate) enum Happened {
SubagentEnd,
/// The model the session runs at, as the agent last said.
Model(String),
/// How full the session's context is, in tokens, where its agent's hooks say (OpenCode's, #719);
/// Claude Code's comes from its transcript.
Context(u64),
/// The git branch of the session's workspace.
Branch(String),

Expand Down Expand Up @@ -452,6 +455,13 @@ impl Event {
})
}

pub(crate) fn context(&self) -> Option<u64> {
self.find(|h| match h {
Happened::Context(tokens) => Some(*tokens),
_ => None,
})
}

pub(crate) fn branch(&self) -> Option<&str> {
self.find(|h| match h {
Happened::Branch(branch) => Some(branch.as_str()),
Expand Down
58 changes: 35 additions & 23 deletions core/src/opencode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
//! 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 and the turn's last text. OpenCode reports no session start or end. A subagent is a
//! 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
//! 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 All @@ -29,10 +31,10 @@ use std::collections::BTreeMap;
/// The name OpenCode's plugin passes (`--agent opencode`), which its lines carry.
pub(crate) const OPENCODE: &str = "opencode";

/// What OpenCode reports: a permission that waits on Daniel, the model a turn ran at, a
/// subagent's reply, and the trees the hook records of each turn (#717). Its transcript has no
/// reader here, so no version or context size; no background task ids, no permission mode and no
/// durations.
/// What OpenCode reports: a permission that waits on Daniel, the model a turn ran at, the context
/// size its latest step ended at (#719), a subagent's reply, and the trees the hook records of each
/// turn (#717). Its transcript has no reader here, so no version; no background task ids, no
/// permission mode and no durations.
pub const CAPABILITIES: Capabilities = Capabilities {
agent: OPENCODE,
asks: true,
Expand All @@ -42,7 +44,7 @@ pub const CAPABILITIES: Capabilities = Capabilities {
durations: false,
transcript_version: false,
transcript_model: false,
context: false,
context: true,
turn_trees: true,
empty_window_starts: false,
transcript_format: TranscriptFormat::Unread,
Expand Down Expand Up @@ -75,6 +77,9 @@ struct Raw {
permission: Value,
/// On a turn's end.
model: Option<String>,
/// On a top-level turn's end, its latest step's input tokens (#719); none before the plugin of
/// #719, or when the turn ended before any step did.
context_tokens: Option<u64>,
#[serde(default)]
last_assistant_message: String,
/// The subagent's own session, on a line of a subagent's.
Expand Down Expand Up @@ -137,11 +142,33 @@ fn tool(name: &str, input: &Value, cwd: &str) -> Tool {
}
}

/// What a turn's end, or a subagent's run's end, reports: its reply, and a turn's model and context
/// size; a subagent's names neither. The end of a turn already past when the hook took it would end
/// the turn running now, so it ends none, and its reply, of a turn the next start ended, is not this
/// one's, nor its count, which may be older than the one the turn after it ended with.
fn ended(raw: &Raw) -> Vec<Happened> {
let mut happened = Vec::new();
let subagent = raw.subagent_session_id.is_some();
if subagent {
happened.push(Happened::SubagentEnd);
} else if !raw.studio_late {
happened.push(Happened::TurnEnd);
}
if !raw.studio_late {
happened.push(Happened::Reply(raw.last_assistant_message.clone()));
}
happened.extend(raw.model.clone().map(Happened::Model));
if !subagent && !raw.studio_late {
happened.extend(raw.context_tokens.map(Happened::Context));
}
happened
}

fn adapt(raw: Raw) -> Event {
let id = raw.tool_use_id.clone();
let call = || tool(&raw.tool_name, &raw.tool_input, &raw.cwd);
let mut happened = Vec::new();
let mut prompt_id = raw.prompt_id;
let mut prompt_id = raw.prompt_id.clone();
match raw.hook_event_name.as_str() {
"session.prompt" => happened.push(Happened::TurnStart {
prompt: raw.prompt.clone(),
Expand All @@ -158,24 +185,9 @@ fn adapt(raw: Raw) -> Event {
origin: Some(Origin::WakeUp),
});
}
// A turn's end, or a subagent's run's end, with its reply; a subagent's names no model. The
// end of a turn already past when the hook took it would end the turn running now, so it
// ends none, and its reply, of a turn the next start ended, is not this one's.
"session.execution.succeeded"
| "session.execution.failed"
| "session.execution.interrupted" => {
if raw.subagent_session_id.is_some() {
happened.push(Happened::SubagentEnd);
} else if !raw.studio_late {
happened.push(Happened::TurnEnd);
}
if !raw.studio_late {
happened.push(Happened::Reply(raw.last_assistant_message.clone()));
}
if let Some(model) = raw.model.clone() {
happened.push(Happened::Model(model));
}
}
| "session.execution.interrupted" => happened = ended(&raw),
"tool.execute.before" => happened.push(Happened::ToolStart {
tool: call(),
id: id.clone(),
Expand Down
6 changes: 5 additions & 1 deletion core/src/studio/take.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,8 @@ struct Take<'a> {
}

impl Take<'_> {
/// The process facts every event carries: its pid, mode, model, branch and transcript format.
/// The process facts every event carries: its pid, mode, model, branch, context size and
/// transcript format.
fn follow_process(&mut self) {
let (session, event) = (&mut *self.session, self.event);
// A deleted session that starts again, by a resume, is back in the list; a late end is not.
Expand All @@ -188,6 +189,9 @@ impl Take<'_> {
if let Some(branch) = event.branch() {
session.transcript.branch = Some(branch.into());
}
if let Some(tokens) = event.context() {
session.transcript.context = Some(transcript::Context { tokens });
}
session.transcript_file.format = event.capabilities.transcript_format;
}

Expand Down
17 changes: 17 additions & 0 deletions core/tests/fixtures/opencode/context.jsonl
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{"cwd":"/Users/me/work/hello","hook_event_name":"session.prompt","prompt":"Read README.md, then write notes.txt containing only its second line, then run cat notes.txt. Reply in one short sentence.","prompt_id":"msg_21fe7f01d001ysG7ArSdusep7P","sent_ms":1795831623846,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831623855,"studio_touched_roots":["/Users/me/work/hello"],"studio_turn_start":{"/Users/me/work/hello":"94543e80539b6f9c169849ae8a16f8b642d281fa"}}
{"cwd":"/Users/me/work/hello","hook_event_name":"tool.execute.before","sent_ms":1795831626389,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831626396,"studio_touched_roots":["/Users/me/work/hello"],"tool_input":{"path":"README.md"},"tool_name":"read","tool_use_id":"chatcmpl-tool-87c3fbae8134bbe2"}
{"cwd":"/Users/me/work/hello","error":null,"exit":null,"hook_event_name":"tool.execute.after","sent_ms":1795831626393,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","status":"completed","studio_agent":"opencode","studio_received_ms":1795831626399,"studio_touched_roots":["/Users/me/work/hello"],"tool_input":{"path":"README.md"},"tool_name":"read","tool_use_id":"chatcmpl-tool-87c3fbae8134bbe2"}
{"cwd":"/Users/me/work/hello","hook_event_name":"tool.execute.before","sent_ms":1795831628961,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831628966,"studio_touched_roots":["/Users/me/work/hello"],"tool_input":{"content":"second line\n","path":"notes.txt"},"tool_name":"write","tool_use_id":"chatcmpl-tool-b08bf788d4909d9d"}
{"cwd":"/Users/me/work/hello","error":null,"exit":null,"hook_event_name":"tool.execute.after","sent_ms":1795831628962,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","status":"completed","studio_agent":"opencode","studio_received_ms":1795831628968,"studio_touched_roots":["/Users/me/work/hello"],"tool_input":{"content":"second line\n","path":"notes.txt"},"tool_name":"write","tool_use_id":"chatcmpl-tool-b08bf788d4909d9d"}
{"cwd":"/Users/me/work/hello","hook_event_name":"tool.execute.before","sent_ms":1795831630853,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831630860,"studio_touched_roots":["/Users/me/work/hello"],"tool_input":{"command":"cat notes.txt"},"tool_name":"shell","tool_use_id":"chatcmpl-tool-a190b1ec91f1f266"}
{"cwd":"/Users/me/work/hello","error":null,"exit":0,"hook_event_name":"tool.execute.after","sent_ms":1795831630862,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","status":"completed","studio_agent":"opencode","studio_received_ms":1795831630870,"studio_touched_roots":["/Users/me/work/hello"],"tool_input":{"command":"cat notes.txt"},"tool_name":"shell","tool_use_id":"chatcmpl-tool-a190b1ec91f1f266"}
{"context_tokens":11215,"cwd":"/Users/me/work/hello","hook_event_name":"session.execution.succeeded","last_assistant_message":"Wrote the README's second line to notes.txt and confirmed it with cat.","model":"big-pickle","sent_ms":1795831632916,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831632921,"studio_turn_end":{"/Users/me/work/hello":"d985af22f43627f8691cf7d1ca262c8c68b9f836"}}
{"cwd":"/Users/me/work/hello","hook_event_name":"session.prompt","prompt":"Use the subagent tool to start a general subagent that reads README.md and reports its first line. Then reply with that line.","prompt_id":"msg_21fe83569001dfmCc0LHxXuVl9","sent_ms":1795831641450,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831641458,"studio_touched_roots":["/Users/me/work/hello"],"studio_turn_start":{"/Users/me/work/hello":"d985af22f43627f8691cf7d1ca262c8c68b9f836"}}
{"cwd":"/Users/me/work/hello","hook_event_name":"tool.execute.before","sent_ms":1795831643666,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831643670,"studio_touched_roots":["/Users/me/work/hello"],"tool_input":{"agent":"general","description":"Read README first line","prompt":"Read the file README.md in the working directory /Users/me/work/hello and report its first line exactly. Do not modify any files. Reply with only that line."},"tool_name":"subagent","tool_use_id":"chatcmpl-tool-837891808d081697"}
{"cwd":"/Users/me/work/hello","error":null,"exit":null,"hook_event_name":"tool.execute.after","sent_ms":1795831643678,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","spawned_session_id":"ses_de017c1ecffee7use05OD8E0Il","status":"completed","studio_agent":"opencode","studio_received_ms":1795831643682,"studio_touched_roots":["/Users/me/work/hello"],"tool_input":{"agent":"general","description":"Read README first line","prompt":"Read the file README.md in the working directory /Users/me/work/hello and report its first line exactly. Do not modify any files. Reply with only that line."},"tool_name":"subagent","tool_use_id":"chatcmpl-tool-837891808d081697"}
{"context_tokens":11516,"cwd":"/Users/me/work/hello","hook_event_name":"session.execution.succeeded","last_assistant_message":"I've launched the subagent; I'll reply with the first line as soon as it reports back.","model":"big-pickle","sent_ms":1795831646316,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831646324,"studio_turn_end":{"/Users/me/work/hello":"d985af22f43627f8691cf7d1ca262c8c68b9f836"}}
{"cwd":"/Users/me/work/hello","hook_event_name":"tool.execute.before","sent_ms":1795831646398,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831646405,"studio_touched_roots":["/Users/me/work/hello"],"studio_turn_start":{"/Users/me/work/hello":"d985af22f43627f8691cf7d1ca262c8c68b9f836"},"subagent_session_id":"ses_de017c1ecffee7use05OD8E0Il","tool_input":{"limit":1,"path":"README.md"},"tool_name":"read","tool_use_id":"chatcmpl-tool-b6ab4a1106c82378"}
{"cwd":"/Users/me/work/hello","error":null,"exit":null,"hook_event_name":"tool.execute.after","sent_ms":1795831646402,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","status":"completed","studio_agent":"opencode","studio_received_ms":1795831646411,"studio_touched_roots":["/Users/me/work/hello"],"subagent_session_id":"ses_de017c1ecffee7use05OD8E0Il","tool_input":{"limit":1,"path":"README.md"},"tool_name":"read","tool_use_id":"chatcmpl-tool-b6ab4a1106c82378"}
{"cwd":"/Users/me/work/hello","hook_event_name":"session.execution.succeeded","last_assistant_message":"# Hello","sent_ms":1795831648919,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831648927,"studio_turn_end":{"/Users/me/work/hello":"d985af22f43627f8691cf7d1ca262c8c68b9f836"},"subagent_session_id":"ses_de017c1ecffee7use05OD8E0Il"}
{"cwd":"/Users/me/work/hello","hook_event_name":"session.execution.started","sent_ms":1795831648932,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831648941,"studio_touched_roots":["/Users/me/work/hello"],"studio_turn_start":{"/Users/me/work/hello":"d985af22f43627f8691cf7d1ca262c8c68b9f836"}}
{"context_tokens":11689,"cwd":"/Users/me/work/hello","hook_event_name":"session.execution.succeeded","last_assistant_message":"# Hello","model":"big-pickle","sent_ms":1795831651370,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831651376,"studio_turn_end":{"/Users/me/work/hello":"d985af22f43627f8691cf7d1ca262c8c68b9f836"}}
99 changes: 99 additions & 0 deletions core/tests/opencode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ fn the_recorded_run_replays_into_its_sessions_turns_and_tools() {
);
assert!(hello.turns.iter().all(|t| t.ended_at.is_some()));
assert_eq!(hello.state, State::YourTurn);
// The plugin before #719 sent no context size.
assert_eq!(hello.transcript.context, None);
let id = |s: &str| format!("chatcmpl-tool-{s}");
assert_eq!(
calls(&studio, HELLO),
Expand Down Expand Up @@ -324,3 +326,100 @@ fn opencode_lines_the_hook_took_late_end_no_turn_and_their_calls_are_the_turn_be
[("call_0".into(), "write".into(), Some(0))]
);
}

/// A top-level turn's end carries its latest step's input tokens (`context_tokens`, #719), which are
/// the session's context size. An end without the field (a turn that ended before any step did, or
/// the plugin before #719), a subagent's run's end and a late end leave it as it was.
#[test]
fn a_turn_ends_count_is_the_sessions_context_size_and_an_end_without_one_keeps_it() {
let line = |name: &str, at: u64, mut fields: Value| {
fields["cwd"] = "/Users/me/work/hello".into();
fields["studio_agent"] = OPENCODE_CAPABILITIES.agent.into();
server_line(HELLO, name, at, fields)
};
let prompt = |at: u64| {
line(
"session.prompt",
at,
json!({ "prompt_id": format!("msg_{at}") }),
)
};
let end = |at: u64, fields: Value| line("session.execution.succeeded", at, fields);
let first = [prompt(10), end(20, json!({ "context_tokens": 12_091 }))];
let cases = [
(
"a later end's count",
vec![prompt(30), end(40, json!({ "context_tokens": 13_000 }))],
13_000,
),
(
"an end without a count",
vec![prompt(30), end(40, json!({}))],
12_091,
),
(
"a subagent's end",
vec![
prompt(30),
end(
40,
json!({ "subagent_session_id": "ses_child", "context_tokens": 99 }),
),
],
12_091,
),
(
"a late end",
vec![
prompt(30),
end(40, json!({ "studio_late": true, "context_tokens": 99 })),
],
12_091,
),
];
for (case, then, tokens) in cases {
let lines: Vec<_> = first.iter().cloned().chain(then).collect();
let studio = Studio::replayed(&lines);
let context = studio.session(HELLO).unwrap().transcript.context.clone();
assert_eq!(context.map(|c| c.tokens), Some(tokens), "{case}");
}
}

/// `fixtures/opencode/context.jsonl`, a real run (2026-11-28, OpenCode 2.4.2's service) of the
/// plugin since #719: a first turn read, wrote and ran a command; a second, by `opencode run -s`,
/// started a background subagent that read a file, whose result woke the session. A scratch plugin
/// beside it logged each `session.step.ended`, whose `input + cache.read + cache.write` was 11,215,
/// 11,516 and 11,689 at the session's three turn ends, and 10,180 and 10,239 at its subagent's steps.
/// The session's context size is its last top-level step's, from each turn's end; its subagent's
/// steps never set it, as its run's end carries no count.
#[test]
fn an_opencode_sessions_context_size_is_its_last_top_level_steps_input_tokens() {
let lines: Vec<_> = include_str!("fixtures/opencode/context.jsonl")
.lines()
.collect();
let id = "ses_de0180feeffehT93YWrZ2rP3WY";
let tokens_after = |n: usize| {
let studio = Studio::replayed(&lines[..n]);
let session = studio.session(id).unwrap();
session.transcript.context.as_ref().map(|c| c.tokens)
};
// Each turn's end, the subagent's run's end, the wake-up's start and its end.
let tokens: Vec<_> = [7, 8, 12, 15, 16, 17].map(tokens_after).into();
assert_eq!(
tokens,
[
None,
Some(11_215),
Some(11_516),
Some(11_516),
Some(11_516),
Some(11_689)
]
);
let studio = Studio::replayed(&lines);
let session = studio.session(id).unwrap();
assert!(session.capabilities.context);
assert_eq!(session.turns.len(), 3);
assert_eq!(session.agents.len(), 1);
assert_eq!(session.state, State::YourTurn);
}
2 changes: 1 addition & 1 deletion docs/studio/CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ What the list and the rail call an agent session: the name Daniel gave it, else
_Avoid_: Title

**Context size**:
How many tokens an agent session's context holds: the input tokens of its latest message, read from its transcript, shown in its row as "85k". The control room knows no window size, so it shows no share of it.
How many tokens an agent session's context holds: the input tokens of its latest message, read from its transcript (an OpenCode session's from its turns' ends, #719), shown in its row as "85k". The control room knows no window size, so it shows no share of it.

**Context share** (retired):
Retired with the status line snapshots that measured it (#416); its code is in `archive/`. How much of its context window an agent session used, as a percentage, from the session's status line snapshot: its tokens, its window size, and Claude Code's own percent used and left. Only sessions the desktop app started saved a snapshot.
Expand Down
Loading
Loading