blob: 62d3a6f26b4097c20d69b6669d4ef8ddcffb4f3f [file]
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//! Interactive Claude PTY input and native transcript observation.
use super::content_text;
use super::*;
use maka_plugin_core::{operation::OperationCleanup, terminal::TerminalSize};
use std::{path::Path, time::Duration};
use tokio::io::{AsyncReadExt, AsyncSeekExt};
/// The Host ends the Claude process when a turn settles, so work Claude
/// leaves in the background loses its completion notice.
const TURN_END_NOTE: &str = "Maka ends this Claude Code process as soon as your turn ends. \
After that, nothing watches background work you leave running (background shell commands, \
background agents, monitors, scheduled wake-ups): background agents stop, and you are not \
notified when a background command finishes. If you need the result of background work, wait \
for it before you end the turn. If you start something that must keep running after the turn, \
such as a server, say so in your reply.";
/// Whether the user's launch arguments already append to Claude's system
/// prompt; the turn-end note then stays out so it cannot replace that text.
fn appends_system_prompt(args: &[String]) -> bool {
args.iter().any(|arg| {
matches!(
arg.split('=').next(),
Some("--append-system-prompt" | "--append-system-prompt-file")
)
})
}
fn launch_args(
session: &str,
resume: bool,
mcp_config: &Path,
user_args: &[String],
) -> Vec<std::ffi::OsString> {
let mut args: Vec<std::ffi::OsString> = vec![
"--dangerously-skip-permissions".into(),
"--ax-screen-reader".into(),
if resume { "--resume" } else { "--session-id" }.into(),
session.into(),
"--mcp-config".into(),
mcp_config.into(),
// These tools wait for an answer in Claude's own terminal UI, which the
// Host never shows. Questions go through the Host's AskUserQuestion tool.
"--disallowedTools".into(),
"AskUserQuestion,EnterPlanMode,ExitPlanMode".into(),
];
if !appends_system_prompt(user_args) {
args.extend(["--append-system-prompt".into(), TURN_END_NOTE.into()]);
}
args
}
#[expect(
clippy::too_many_arguments,
reason = "one terminal owns the native session, tool bridge and active user input"
)]
pub(in crate::executor::external) async fn execute(
config: &NativeCommand,
cwd: &str,
request: &Value,
journal: &mut journal::ProtocolSession,
output: Arc<dyn OutputSink>,
bridge: Arc<mcp::Bridge>,
stop: CancellationToken,
steering: &mut steering::Steering,
owner: maka_process::isolated::TaskOwner,
) -> Result<Outcome, Error> {
let observation = journal.observation();
let resume = journal.native_session().is_some();
let session = journal
.native_session()
.map(str::to_owned)
.unwrap_or_else(|| Uuid::new_v4().to_string());
let prepared = async {
let cwd_path = tokio::fs::canonicalize(cwd)
.await
.map_err(|error| Error::Provider(error.to_string()))?;
let policy_path = maka_sandbox::policy_path_from_resolved(&cwd_path)
.map_err(|error| Error::Invalid(error.to_string()))?;
let cwd = policy_path
.to_str()
.ok_or_else(|| Error::Invalid("Claude cwd must be UTF-8".into()))?
.to_owned();
let status = bridge.directory().join("context.json");
let mut cursor = Cursor::fence(transcript(config, &cwd, &session)?, resume).await?;
cursor.status_path = Some(status.clone());
let mcp_path = bridge.directory().join("mcp.json");
tokio::fs::write(
&mcp_path,
serde_json::to_vec(&bridge.claude()).expect("MCP configuration is JSON"),
)
.await
.map_err(|error| Error::Provider(format!("Claude MCP configuration failed: {error}")))?;
let mut command = status_command(config, &cwd, &status).await?;
command.args(launch_args(&session, resume, &mcp_path, &config.args));
if let Some(model) = request["model"]
.as_str()
.filter(|model| *model != "default")
{
command.arg("--model").arg(model);
}
if let Some(effort) = request["effort"].as_str() {
command.arg("--effort").arg(effort);
}
journal.opened(session.clone())?;
Ok::<_, Error>((cwd, cursor, command))
}
.await;
let (cwd, mut cursor, command) = match prepared {
Ok(prepared) => prepared,
Err(error) => {
let error = if stop.is_cancelled() {
Error::Cancelled
} else {
error
};
return runtime::fail_without_launch(&observation, owner, error).await;
}
};
let cwd = cwd.as_str();
let mut ticket = observation
.resources
.reserve()
.map_err(|_| Error::ObservationRetired)?;
ticket.start();
let process = match owner
.spawn_pty(
command,
TerminalSize::new(120, 40).expect("fixed terminal dimensions"),
)
.await
{
Ok(process) => process,
Err(maka_process::isolated::SpawnError::Closed(error)) => {
ticket.complete(Ok(()));
observation
.binding
.cleanup(OperationCleanup::Confirmed)
.await?;
return if stop.is_cancelled() {
Err(Error::Cancelled)
} else if observation.retired.is_cancelled() {
Err(Error::ObservationRetired)
} else {
runtime::preparation_failure(runtime::isolation_error(error))
};
}
Err(maka_process::isolated::SpawnError::Unconfirmed(failure)) => {
ticket.unconfirmed(failure.to_string(), failure);
return Err(Error::CleanupUnconfirmed);
}
};
let maka_process::pipe::Spawned {
mut child,
mut stdin,
mut stdout,
mut stderr,
} = process;
let (screen_sender, mut screen) = tokio::sync::watch::channel(input::Screen::default());
let terminal_done = CancellationToken::new();
let settled = CancellationToken::new();
let terminal = {
let terminal_done = terminal_done.clone();
tokio::spawn(async move {
let result = async {
let mut decoder = input::Decoder::default();
let mut buffer = [0; 8192];
loop {
let count = stdout.read(&mut buffer).await?;
if count == 0 {
return Ok::<_, std::io::Error>(());
}
screen_sender.send_modify(|screen| decoder.push(screen, &buffer[..count]));
}
}
.await;
terminal_done.cancel();
(result, stdout)
})
};
let physical = {
let observation = observation.clone();
let stop = stop.clone();
let settled = settled.clone();
tokio::spawn(async move {
let process =
runtime::settle_original_child(&mut child, &observation, &stop, &settled).await;
if process.is_ok()
&& let Err(error) = observation
.binding
.cleanup(OperationCleanup::Confirmed)
.await
{
tracing::error!(%error, "Claude PTY cleanup ACK remains pending");
}
(process, child)
})
};
let diagnostic =
tokio::spawn(async move { tokio::io::copy(&mut stderr, &mut tokio::io::sink()).await });
let mut start = Start::Interactive;
let result = {
let work = async {
let prompt = input::text(runtime::string(request, "/message")?);
let images = request["images"].as_array().expect("canonical images");
let update = journal.instruction_update(request["instructions"].as_str());
let input = if let Some(update) = update {
let bootstrap = input::text(&runtime::bootstrap_message(&update.text));
let sent = unless_stopped(
&stop,
input::submit(
&mut stdin,
&mut screen,
cwd,
&bootstrap,
&[],
&bridge,
&mut start,
),
)
.await?;
let outcome = observe(
&mut cursor,
&session,
&sent,
&BootstrapOutput(output.as_ref()),
&mut stdin,
&mut screen,
&mut start,
&stop,
None,
)
.await?;
if !matches!(outcome, Outcome::Completed { .. }) {
return Ok(outcome);
}
journal.confirm_instructions(update).await?;
unless_stopped(
&stop,
input::send(&mut stdin, &mut screen, &prompt, images, &mut start),
)
.await?
} else {
unless_stopped(
&stop,
input::submit(
&mut stdin,
&mut screen,
cwd,
&prompt,
images,
&bridge,
&mut start,
),
)
.await?
};
observe(
&mut cursor,
&session,
&input,
output.as_ref(),
&mut stdin,
&mut screen,
&mut start,
&stop,
Some((journal, steering)),
)
.await
};
// `work` answers the stop itself, between two outputs. Dropping it here
// could leave an output recorded by the Host but not acknowledged to it.
tokio::select! {
biased;
() = observation.retired.cancelled() => Err(Error::ObservationRetired),
() = bridge.failed.cancelled() => Err(Error::Unknown),
result = work => result,
() = terminal_done.cancelled() => Err(Error::Unknown),
}
};
let result = match result {
Ok(outcome) => journal.closed(outcome.clone()).await.map(|()| outcome),
Err(Error::Cancelled) if stop.is_cancelled() => {
if start == Start::Submitted {
let _ =
tokio::time::timeout(Duration::from_secs(1), input::write(&mut stdin, b"\x1b"))
.await;
}
let outcome = Outcome::Cancelled { reason: None };
journal.closed(outcome.clone()).await.map(|()| outcome)
}
Err(error) if start == Start::Interactive && !stop.is_cancelled() => {
runtime::preparation_failure(error)
}
Err(error) => Err(error),
};
bridge.close_admission();
settled.cancel();
let (finished, finish) = tokio::sync::oneshot::channel();
tokio::spawn(async move {
use maka_agent_ports::executor::RootSettlementOwner;
let host = async {
if let Err(error) = bridge.close().await {
tracing::error!(%error, "Claude bridge settlement remains pending");
}
bridge.clone().original_root_cleanup_signal().await;
};
let (physical, terminal, diagnostic, ()) =
tokio::join!(physical, terminal, diagnostic, host);
let cleanup = match (&physical, &terminal, &diagnostic) {
(Ok((Ok(()), _)), Ok((Ok(()), _)), Ok(Ok(_))) => Ok(()),
_ => Err("Claude PTY cleanup could not be confirmed"),
};
match cleanup {
Ok(()) => ticket.complete(Ok(())),
Err(reason) => ticket.unconfirmed(
reason.into(),
(physical, terminal, diagnostic, stdin, bridge),
),
}
let _ = finished.send(cleanup);
});
if !matches!(
tokio::time::timeout(Duration::from_secs(6), finish).await,
Ok(Ok(Ok(())))
) {
tracing::warn!("Claude PTY cleanup retained beyond the observer drain budget");
}
result
}
async fn status_command(
config: &NativeCommand,
cwd: &str,
status: &Path,
) -> Result<maka_process::Command, Error> {
// Claude accepts one --settings override. Preserve the other invocation settings.
let mut config = config.clone();
let mut settings = serde_json::Map::new();
let mut args = std::mem::take(&mut config.args).into_iter();
while let Some(arg) = args.next() {
let value = if arg == "--settings" {
args.next()
.ok_or_else(|| Error::Invalid("Missing Claude --settings value".into()))?
} else if let Some(value) = arg.strip_prefix("--settings=") {
value.to_owned()
} else {
config.args.push(arg);
continue;
};
let bytes = if value.trim_start().starts_with('{') {
value.into_bytes()
} else {
tokio::fs::read(Path::new(cwd).join(value))
.await
.map_err(|e| Error::Provider(format!("Claude settings: {e}")))?
};
settings = serde_json::from_slice(&bytes)
.map_err(|e| Error::Invalid(format!("Claude settings: {e}")))?;
}
#[cfg(windows)]
let capture = "powershell.exe -NoProfile -NonInteractive -Command '$p=$env:MAKA_CLAUDE_STATUS; $t=[IO.Path]::ChangeExtension($p,$PID); [IO.File]::WriteAllText($t,[Console]::In.ReadToEnd()); Move-Item -LiteralPath $t -Destination $p -Force'";
#[cfg(not(windows))]
let capture =
r#"tmp="$MAKA_CLAUDE_STATUS.$$"; cat > "$tmp" && mv -f "$tmp" "$MAKA_CLAUDE_STATUS""#;
settings.insert(
"statusLine".into(),
serde_json::json!({"type":"command","command":capture}),
);
let mut command = runtime::command(&config, cwd).await?;
command
.env("MAKA_CLAUDE_STATUS", status.as_os_str())
.arg("--settings")
.arg(Value::Object(settings).to_string());
Ok(command)
}
async fn context_usage(path: &Path, session: &str, row: &Value) -> Option<Output> {
let bytes = match tokio::fs::read(path).await {
Ok(bytes) => bytes,
Err(error) => {
if error.kind() != std::io::ErrorKind::NotFound {
tracing::debug!(%error, "Claude status line unavailable");
}
return None;
}
};
let status: Value = serde_json::from_slice(&bytes).ok()?;
if status["session_id"] != session {
return None;
}
let context = &status["context_window"];
let window = std::num::NonZeroU64::new(context["context_window_size"].as_u64()?)?;
let usage = if let Some(usage) = row.pointer("/message/usage") {
if status.pointer("/model/id")?.as_str()? != row.pointer("/message/model")?.as_str()? {
return None;
}
usage
} else {
&context["current_usage"]
};
let used = usage["input_tokens"]
.as_u64()?
.checked_add(usage["cache_read_input_tokens"].as_u64().unwrap_or(0))?
.checked_add(usage["cache_creation_input_tokens"].as_u64().unwrap_or(0))?;
Some(Output::ContextUsage(
maka_agent_facts::executor::ContextUsage {
used,
window,
model: status
.pointer("/model/id")
.and_then(Value::as_str)
.map(str::to_owned),
},
))
}
fn transcript(config: &NativeCommand, cwd: &str, session: &str) -> Result<PathBuf, Error> {
let root = configuration_directory(|key| {
config
.env
.get(key)
.cloned()
.or_else(|| std::env::var(key).ok())
})?;
// Native Claude encodes each non-ASCII-alphanumeric UTF-16 code unit as '-'.
let project: String = cwd
.encode_utf16()
.map(|ch| {
if ch <= 127 && (ch as u8).is_ascii_alphanumeric() {
char::from(ch as u8)
} else {
'-'
}
})
.collect();
Ok(root
.join("projects")
.join(project)
.join(format!("{session}.jsonl")))
}
fn configuration_directory(env: impl Fn(&str) -> Option<String>) -> Result<PathBuf, Error> {
env("CLAUDE_CONFIG_DIR")
.map(PathBuf::from)
.or_else(|| {
env("HOME")
.or_else(|| env("USERPROFILE"))
.map(|home| PathBuf::from(home).join(".claude"))
})
.ok_or_else(|| Error::Invalid("Claude configuration directory is unavailable".into()))
}
struct Cursor {
status_path: Option<PathBuf>,
path: PathBuf,
opened: Option<OpenedTranscript>,
}
struct OpenedTranscript {
file: tokio::fs::File,
identity: TranscriptIdentity,
offset: u64,
pending: Vec<u8>,
scanned: usize,
}
#[cfg(unix)]
type TranscriptIdentity = (u64, u64);
#[cfg(windows)]
type TranscriptIdentity = (u64, [u8; 16]);
#[cfg(unix)]
fn transcript_identity(metadata: &std::fs::Metadata) -> TranscriptIdentity {
use std::os::unix::fs::MetadataExt;
(metadata.dev(), metadata.ino())
}
async fn opened_identity(file: &tokio::fs::File) -> std::io::Result<TranscriptIdentity> {
#[cfg(unix)]
{
Ok(transcript_identity(&file.metadata().await?))
}
#[cfg(windows)]
{
let file = file.try_clone().await?.into_std().await;
tokio::task::spawn_blocking(move || {
let info = maka_sandbox::windows::file_identity(&file)?;
Ok((info.VolumeSerialNumber, info.FileId.Identifier))
})
.await
.map_err(std::io::Error::other)?
}
}
async fn named_transcript(path: &Path) -> std::io::Result<(TranscriptIdentity, u64)> {
#[cfg(unix)]
{
let metadata = tokio::fs::metadata(path).await?;
Ok((transcript_identity(&metadata), metadata.len()))
}
#[cfg(windows)]
{
let path = path.to_owned();
tokio::task::spawn_blocking(move || {
let file = std::fs::File::open(path)?;
let info = maka_sandbox::windows::file_identity(&file)?;
Ok((
(info.VolumeSerialNumber, info.FileId.Identifier),
file.metadata()?.len(),
))
})
.await
.map_err(std::io::Error::other)?
}
}
impl Cursor {
async fn fence(path: PathBuf, resume: bool) -> Result<Self, Error> {
let opened = match tokio::fs::File::open(&path).await {
Ok(mut file) => {
let offset = file
.seek(std::io::SeekFrom::End(0))
.await
.map_err(|e| Error::Provider(e.to_string()))?;
let identity = opened_identity(&file)
.await
.map_err(|e| Error::Provider(e.to_string()))?;
Some(OpenedTranscript {
file,
identity,
offset,
pending: Vec::new(),
scanned: 0,
})
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound && !resume => None,
Err(error) => {
return Err(Error::Invalid(format!(
"Claude original transcript unavailable: {error}"
)));
}
};
Ok(Self {
path,
opened,
status_path: None,
})
}
async fn next(&mut self) -> Result<Option<Value>, Error> {
let (identity, length) = match named_transcript(&self.path).await {
Ok(m) => m,
Err(e) if e.kind() == std::io::ErrorKind::NotFound && self.opened.is_none() => {
return Ok(None);
}
Err(_) => return Err(Error::Invalid("Claude live transcript disappeared".into())),
};
let opened = match &mut self.opened {
Some(opened) => {
if identity != opened.identity {
return Err(Error::Invalid("Claude live transcript rotated".into()));
}
if length < opened.offset {
return Err(Error::Invalid("Claude live transcript truncated".into()));
}
opened
}
slot @ None => {
let file = tokio::fs::File::open(&self.path)
.await
.map_err(|e| Error::Provider(e.to_string()))?;
let identity = opened_identity(&file)
.await
.map_err(|e| Error::Provider(e.to_string()))?;
slot.insert(OpenedTranscript {
file,
identity,
offset: 0,
pending: Vec::new(),
scanned: 0,
})
}
};
loop {
if let Some(relative) = opened.pending[opened.scanned..]
.iter()
.position(|b| *b == b'\n')
{
let end = opened.scanned + relative;
opened.scanned = 0;
let line = opened.pending.drain(..=end).collect::<Vec<_>>();
return runtime::parse_json(line, "complete Claude JSONL line")
.await
.map(Some);
}
opened.scanned = opened.pending.len();
let mut bytes = [0u8; 8192];
let count = opened
.file
.read(&mut bytes)
.await
.map_err(|e| Error::Provider(e.to_string()))?;
if count == 0 {
return Ok(None);
}
opened.offset += count as u64;
opened.pending.extend_from_slice(&bytes[..count]);
if opened.pending.len() > runtime::MAX_MESSAGE_BYTES {
return Err(Error::Invalid(
"Claude live JSONL line exceeds 256 MiB".into(),
));
}
}
}
}
struct BootstrapOutput<'a>(&'a dyn OutputSink);
impl OutputSink for BootstrapOutput<'_> {
fn emit(&self, output: Output) -> BoxFuture<'_, Result<(), Error>> {
match output {
Output::MessageStart { .. }
| Output::MessageEnd { .. }
| Output::OutputDelta { .. }
| Output::ThinkingDelta { .. }
| Output::ContextUsage(_)
| Output::TurnUsage { .. }
| Output::SessionTitle { .. } => Box::pin(async { Ok(()) }),
output => self.0.emit(output),
}
}
}
#[expect(
clippy::too_many_arguments,
reason = "observations and additional input share the original PTY and invocation"
)]
async fn observe(
cursor: &mut Cursor,
session: &str,
input: &input::Submitted,
output: &dyn OutputSink,
io: &mut (impl tokio::io::AsyncWrite + Unpin + Send),
screen: &mut tokio::sync::watch::Receiver<input::Screen>,
start: &mut Start,
stop: &CancellationToken,
task: Option<(&mut journal::ProtocolSession, &mut steering::Steering)>,
) -> Result<Outcome, Error> {
let (mut journal, mut steering) = match task {
Some((journal, steering)) => (Some(journal), Some(steering)),
None => (None, None),
};
let status_path = cursor.status_path.clone();
let mut last_context = None;
let mut deadline = Some(input_deadline(&input.prompt));
let mut turn = LiveTurn {
session,
input,
admitted: false,
pending: Default::default(),
assistant: false,
open_message: None,
final_message_id: None,
closed_message_ids: Default::default(),
row_ids: Default::default(),
host_tool_calls: Default::default(),
api_failure: None,
usage: Default::default(),
duration_ms: 0,
waits: Default::default(),
};
let result = async {
loop {
// Keep this future across ready/take/paste. Dropping Cursor::next after it
// drained a large row would also discard its in-flight blocking JSON parse.
let next = async {
loop {
if let Some(row) = cursor.next().await? {
return Ok::<_, Error>(row);
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
};
tokio::pin!(next);
let row = loop {
tokio::select! {
biased;
() = stop.cancelled() => return Err(Error::Cancelled),
row = &mut next => break row?,
ready = async {
match steering.as_deref_mut() {
Some(steering) => steering.ready().await,
None => std::future::pending().await,
}
}, if turn.admitted => {
ready?;
}
() = async {
match deadline {
Some(at) => tokio::time::sleep_until(at).await,
None => std::future::pending().await,
}
} => {
return Err(Error::Invalid(
"Claude native JSONL did not confirm prompt admission within the input budget".into(),
));
}
}
// Commit only outside select: cancellation of ready cannot consume input.
if let Some(steering) = steering.as_deref_mut()
&& let Some(request) = steering.take().await?
{
let images = request["images"]
.as_array()
.expect("canonical steering images");
let prompt = input::text(runtime::string(&request, "/message")?);
turn.pending.push_back(
unless_stopped(stop, input::send(io, screen, &prompt, images, start)).await?,
);
}
};
if turn.admitted && row["isSidechain"] != true
&& (row["type"] == "assistant" || (row["type"] == "system" && last_context.is_none()))
&& let Some(path) = &status_path
&& let Some(context) = context_usage(path, session, &row).await
&& last_context.as_ref() != Some(&context)
{
output.emit(context.clone()).await?;
last_context = Some(context);
}
let terminal = row["type"] == "system"
&& row["subtype"] == "turn_duration"
&& row.get("isSidechain").and_then(Value::as_bool) != Some(true);
// A ready batch at the final native boundary still belongs to this PTY.
// Take it before row() can settle; an empty take does not create a new turn.
if terminal
&& turn.admitted
&& row.get("sessionId").and_then(Value::as_str) == Some(session)
&& turn.pending.is_empty()
&& let Some(steering) = steering.as_deref_mut()
&& let Some(request) = steering.take().await?
{
let images = request["images"]
.as_array()
.expect("canonical steering images");
let prompt = input::text(runtime::string(&request, "/message")?);
turn.pending.push_back(
unless_stopped(stop, input::send(io, screen, &prompt, images, start)).await?,
);
}
let pending = turn.pending.len();
let admitted = turn.admitted;
if let Some(outcome) = turn.row(row, output).await? {
return Ok(outcome);
}
if !admitted
&& turn.admitted
&& let Some(journal) = journal.take()
{
journal
.bind_task(NativeTask::ClaudePty {
session: session.into(),
})
.await?;
}
if (!admitted && turn.admitted) || turn.pending.len() < pending {
// A native busy queue can wait on arbitrarily long running tools.
deadline = None;
}
if terminal
&& turn.admitted
&& deadline.is_none()
&& let Some(input) = turn.pending.front()
{
// Once a native turn ends, the queued input must be admitted, not lost.
deadline = Some(input_deadline(&input.prompt));
}
}
}
.await;
// The Host accepts the end of a turn only when every message it saw start has ended.
if matches!(result, Err(Error::Cancelled)) {
turn.end_message(output).await?;
}
result
}
/// Terminal input publishes nothing to the Host, so a stop may end it at any point.
async fn unless_stopped<T>(
stop: &CancellationToken,
input: impl Future<Output = Result<T, Error>>,
) -> Result<T, Error> {
tokio::select! {
biased;
() = stop.cancelled() => Err(Error::Cancelled),
result = input => result,
}
}
fn input_deadline(prompt: &str) -> tokio::time::Instant {
tokio::time::Instant::now()
+ runtime::SETUP_TIMEOUT
+ Duration::from_secs(prompt.len() as u64 / (32 * 1024))
}
/// Whether a transcript row's content records this input. Claude writes the image
/// markers first and records a pasted prompt between `<pasted_content id="…">` tags.
fn matches_input(content: &Value, input: &input::Submitted) -> bool {
content_text(content)
.strip_prefix(input.markers.as_str())
.is_some_and(|text| text == input.prompt || matches_pasted(text, &input.prompt))
&& content.as_array().map_or(input.images == 0, |blocks| {
!blocks.iter().any(|b| b["type"] == "tool_result")
&& blocks.iter().filter(|b| b["type"] == "image").count() == input.images
})
}
/// Claude ends the pasted text with a newline only when it has none, so the
/// record alone does not say whether the prompt ended with one.
fn matches_pasted(text: &str, prompt: &str) -> bool {
let Some((id, body)) = text
.trim_start_matches('\n')
.strip_prefix("<pasted_content id=\"")
.and_then(|rest| rest.split_once("\">\n"))
else {
return false;
};
let Some(rest) = body.strip_prefix(prompt) else {
return false;
};
let rest = if prompt.ends_with('\n') {
Some(rest)
} else {
rest.strip_prefix('\n')
};
!id.is_empty()
&& !id.contains(['"', '\n'])
&& rest.is_some_and(|rest| {
rest.trim_end_matches('\n') == format!("</pasted_content id=\"{id}\">")
})
}
/// The content of a row that records submitted input. Claude gives input that
/// arrives while it works to the running turn as a `queued_command` attachment
/// and writes no user row for it.
fn input_content(row: &Value) -> Option<&Value> {
match row.get("type").and_then(Value::as_str)? {
"user" => row.pointer("/message/content"),
"attachment" if row["attachment"]["type"] == "queued_command" => {
row.pointer("/attachment/prompt")
}
_ => None,
}
}
struct LiveTurn<'a> {
session: &'a str,
input: &'a input::Submitted,
admitted: bool,
pending: std::collections::VecDeque<input::Submitted>,
assistant: bool,
open_message: Option<AssistantMessage>,
final_message_id: Option<String>,
closed_message_ids: std::collections::BTreeSet<String>,
row_ids: std::collections::BTreeSet<String>,
host_tool_calls: std::collections::BTreeSet<String>,
api_failure: Option<String>,
usage: BTreeMap<String, maka_agent_facts::model::ModelUsage>,
duration_ms: u64,
waits: crate::model_time::ToolIntervals,
}
struct AssistantMessage {
id: String,
has_body: bool,
has_thinking: bool,
}
impl LiveTurn<'_> {
async fn end_message(&mut self, output: &dyn OutputSink) -> Result<(), Error> {
if let Some(message) = self.open_message.take() {
output
.emit(Output::MessageEnd {
message_id: message.id.clone(),
})
.await?;
self.closed_message_ids.insert(message.id.clone());
if message.has_body {
self.final_message_id = Some(message.id);
}
}
Ok(())
}
async fn row(&mut self, row: Value, output: &dyn OutputSink) -> Result<Option<Outcome>, Error> {
if row
.get("sessionId")
.and_then(Value::as_str)
.is_some_and(|id| id != self.session)
{
return Err(Error::Invalid(
"Claude live transcript session mismatch".into(),
));
}
let at = || {
row["timestamp"]
.as_str()?
.parse::<jiff::Timestamp>()
.ok()?
.as_millisecond()
.try_into()
.ok()
};
let kind = row.get("type").and_then(Value::as_str).unwrap_or_default();
if row.get("isSidechain").and_then(Value::as_bool) == Some(true) {
return Ok(None);
}
if !self.admitted {
if kind == "user"
&& row
.pointer("/message/content")
.is_some_and(|v| matches_input(v, self.input))
{
if row.get("sessionId").and_then(Value::as_str) != Some(self.session) {
return Err(Error::Invalid(
"Claude prompt missing native session identity".into(),
));
}
self.admitted = true;
}
return Ok(None);
}
if let Some(input) = self.pending.front()
&& input_content(&row).is_some_and(|v| matches_input(v, input))
{
if row.get("sessionId").and_then(Value::as_str) != Some(self.session) {
return Err(Error::Invalid(
"Claude steering missing native session identity".into(),
));
}
self.end_message(output).await?;
self.pending.pop_front();
// A previous assistant cannot prove that this additional input was answered.
self.assistant = false;
return Ok(None);
}
if kind == "assistant" {
if row.get("isApiErrorMessage").and_then(Value::as_bool) == Some(true) {
self.api_failure.get_or_insert_with(|| {
format!(
"Claude API request failed: {}",
content_text(&row["message"]["content"])
)
});
self.assistant = true;
return Ok(None);
}
let content = &row["message"]["content"];
let row_id = runtime::string(&row, "/uuid")?;
if !self.row_ids.insert(row_id.into()) {
return Ok(None);
}
self.assistant = true;
let id = runtime::string(&row, "/message/id")?;
if let Some(usage) = row.pointer("/message/usage") {
let tokens = maka_agent_facts::model::ModelUsage {
input_tokens: usage["input_tokens"].as_u64(),
output_tokens: usage["output_tokens"].as_u64(),
cache_read_tokens: usage["cache_read_input_tokens"].as_u64(),
cache_write_tokens: usage["cache_creation_input_tokens"].as_u64(),
..Default::default()
};
if tokens != Default::default() {
self.usage.insert(id.into(), tokens);
}
}
if self
.open_message
.as_ref()
.map(|message| message.id.as_str())
!= Some(id)
{
self.end_message(output).await?;
if self.closed_message_ids.contains(id) {
return Ok(None);
}
output
.emit(Output::MessageStart {
message_id: id.into(),
})
.await?;
self.open_message = Some(AssistantMessage {
id: id.into(),
has_body: false,
has_thinking: false,
});
}
if let Some(blocks) = content.as_array() {
for block in blocks {
match block.get("type").and_then(Value::as_str) {
Some("server_tool_use") => self.waits.unmeasured_tool(),
Some("text") => {
let text = runtime::string(block, "/text")?;
if !text.is_empty() {
let message =
self.open_message.as_mut().expect("started API message");
let emitted = if message.has_body {
format!("\n\n{text}")
} else {
text.into()
};
message.has_body = true;
output
.emit(Output::OutputDelta {
message_id: id.into(),
text: emitted,
})
.await?;
}
}
Some("tool_use") => {
self.waits.start(runtime::string(block, "/id")?, at());
let name = runtime::string(block, "/name")?;
if matches!(name, "AskUserQuestion" | "EnterPlanMode" | "ExitPlanMode")
{
return Err(Error::Invalid("Claude requested unsupported interactive question or plan UI; use Host tools".into()));
}
if name.starts_with("mcp__maka__") {
self.host_tool_calls
.insert(runtime::string(block, "/id")?.into());
} else {
output
.emit(Output::ToolStart {
tool_call_id: runtime::string(block, "/id")?.into(),
name: name.into(),
input: block.get("input").cloned().unwrap_or(Value::Null),
})
.await?;
}
}
Some("thinking") => {
if let Some(text) = block.get("thinking").and_then(Value::as_str)
&& !text.is_empty()
{
let message =
self.open_message.as_mut().expect("started API message");
let emitted = if message.has_thinking {
format!("\n\n{text}")
} else {
text.into()
};
message.has_thinking = true;
output
.emit(Output::ThinkingDelta {
message_id: id.into(),
text: emitted,
})
.await?;
}
}
_ => {}
}
}
} else if let Some(text) = content.as_str()
&& !text.is_empty()
{
let message = self.open_message.as_mut().expect("started API message");
let emitted = if message.has_body {
format!("\n\n{text}")
} else {
text.into()
};
message.has_body = true;
output
.emit(Output::OutputDelta {
message_id: id.into(),
text: emitted,
})
.await?;
}
} else if kind == "user" {
if let Some(blocks) = row.pointer("/message/content").and_then(Value::as_array) {
for block in blocks {
if block.get("type").and_then(Value::as_str) == Some("tool_result") {
self.waits
.end(runtime::string(block, "/tool_use_id")?, at());
if self
.host_tool_calls
.contains(runtime::string(block, "/tool_use_id")?)
{
continue;
}
output
.emit(Output::ToolResult {
tool_call_id: runtime::string(block, "/tool_use_id")?.into(),
text: content_text(&block["content"]),
is_error: block.get("is_error").and_then(Value::as_bool)
== Some(true),
details: None,
})
.await?;
}
}
}
} else if kind == "system"
&& row.get("subtype").and_then(Value::as_str) == Some("turn_duration")
{
if row.get("sessionId").and_then(Value::as_str) != Some(self.session) {
return Err(Error::Invalid(
"Claude terminal lacks native session identity".into(),
));
}
if self.api_failure.is_none() {
self.end_message(output).await?;
}
if let Some(duration) = row["durationMs"].as_u64() {
self.duration_ms = self.duration_ms.saturating_add(duration);
} else {
self.waits.unmeasured_tool();
}
// The old native turn can finish after the next input was journaled.
// Neither an unconsumed input nor one without its own assistant may settle.
if !self.pending.is_empty() || !self.assistant {
return Ok(None);
}
if !self.usage.is_empty() || self.duration_ms != 0 {
use maka_agent_facts::{executor::TurnUsage, model::ModelUsage};
let sum = |get: fn(&ModelUsage) -> Option<u64>| {
let mut samples = self.usage.values();
let first = get(samples.next()?)?;
samples.try_fold(first, |total, next| total.checked_add(get(next)?))
};
output
.turn_usage(
TurnUsage {
tokens: ModelUsage {
input_tokens: sum(|usage| usage.input_tokens),
output_tokens: sum(|usage| usage.output_tokens),
cache_read_tokens: sum(|usage| usage.cache_read_tokens),
cache_write_tokens: sum(|usage| usage.cache_write_tokens),
..Default::default()
},
total_tokens: None,
duration_ms: (self.duration_ms != 0).then_some(self.duration_ms),
},
self.waits.model_ms(self.duration_ms),
)
.await?;
}
return Ok(Some(match self.api_failure.take() {
Some(message) => Outcome::Failed {
message,
code: Some("native_api_failed".into()),
recoverable: false,
},
None => Outcome::Completed {
message_id: self.final_message_id.clone(),
},
}));
}
Ok(None)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn transcript_uses_the_windows_launch_directory_spelling() {
let config = NativeCommand {
executable: "claude".into(),
args: vec![],
env: [("CLAUDE_CONFIG_DIR".into(), "config".into())].into(),
};
let cwd = r"C:\Work\my.repo";
#[cfg(windows)]
let projected =
maka_sandbox::policy_path_from_resolved(Path::new(r"\\?\C:\Work\my.repo")).unwrap();
#[cfg(windows)]
assert_eq!(projected.to_str(), Some(cwd));
assert_eq!(
transcript(&config, cwd, "session").unwrap(),
Path::new("config")
.join("projects")
.join("C--Work-my-repo")
.join("session.jsonl")
);
}
fn submitted(markers: &str, prompt: &str, images: usize) -> input::Submitted {
input::Submitted {
markers: markers.into(),
prompt: prompt.into(),
images,
}
}
fn with_images(text: &str, images: usize) -> Value {
let mut blocks = vec![json!({"type":"text","text":text})];
blocks.resize(images + 1, json!({"type":"image","source":{}}));
Value::Array(blocks)
}
#[test]
fn launch_args_appends_turn_end_note_unless_user_appends_system_prompt() {
let unrelated = ["--model".to_owned(), "opus".to_owned()];
for (resume, user_args) in [(false, &[][..]), (true, &unrelated[..])] {
let args = launch_args("session", resume, Path::new("mcp.json"), user_args);
let note = args
.iter()
.position(|arg| arg == "--append-system-prompt")
.and_then(|index| args.get(index + 1));
assert_eq!(note.and_then(|value| value.to_str()), Some(TURN_END_NOTE));
}
for user_args in [
vec![
"--append-system-prompt".to_owned(),
"Answer in French.".to_owned(),
],
vec!["--append-system-prompt=Answer in French.".to_owned()],
vec![
"--append-system-prompt-file".to_owned(),
"notes.md".to_owned(),
],
vec!["--append-system-prompt-file=notes.md".to_owned()],
] {
let args = launch_args("session", false, Path::new("mcp.json"), &user_args);
assert!(
!args.iter().any(|arg| arg == "--append-system-prompt"),
"{user_args:?}"
);
}
}
// Shapes recorded by Claude Code 2.1.327 and 2.1.328.
#[test]
fn input_matches_the_rows_that_record_it() {
let lines = "line 1\nline 2\nline 3\nline 4";
let pasted = |body: &str| {
format!("\n\n<pasted_content id=\"5748\">\n{body}</pasted_content id=\"5748\">\n")
};
for (content, input) in [
(json!("short"), submitted("", "short", 0)),
(
with_images("[Image #1]short", 1),
submitted("[Image #1]", "short", 1),
),
(
json!(pasted("line 1\nline 2\nline 3\nline 4\n")),
submitted("", lines, 0),
),
(
json!(pasted("alpha\nbeta\ngamma\n")),
submitted("", "alpha\nbeta\ngamma\n", 0),
),
(
json!(pasted("alpha\nbeta\ngamma\n\n")),
submitted("", "alpha\nbeta\ngamma\n\n", 0),
),
(
json!(pasted("\nline 1\nline 2\nline 3\nline 4\n")),
submitted("", &format!("\n{lines}"), 0),
),
(
with_images(
&format!("[Image #1]{}", pasted("line 1\nline 2\nline 3\nline 4\n")),
1,
),
submitted("[Image #1]", lines, 1),
),
(
with_images(
&format!(
"[Image #3] [Image #4]{}",
pasted("line 1\nline 2\nline 3\nline 4\n")
),
2,
),
submitted("[Image #3] [Image #4]", lines, 2),
),
] {
assert!(matches_input(&content, &input), "{content}");
}
}
#[test]
fn input_does_not_match_other_rows() {
let pasted =
"\n\n<pasted_content id=\"5748\">\nline 1\nline 2\n</pasted_content id=\"5748\">\n";
for (content, input) in [
(json!("other"), submitted("", "short", 0)),
(
json!(
"\n\n<pasted_content id=\"5748\">\nline 1\nline 2\n</pasted_content id=\"9e17\">\n"
),
submitted("", "line 1\nline 2", 0),
),
// The record has one newline fewer than a prompt that ends with two.
(json!(pasted), submitted("", "line 1\nline 2\n\n", 0)),
(json!(pasted), submitted("", "line 1", 0)),
(
json!([{"type":"tool_result","tool_use_id":"call","content":"short"},{"type":"text","text":"short"}]),
submitted("", "short", 0),
),
(
with_images("[Image #1]short", 2),
submitted("[Image #1]", "short", 1),
),
(with_images("short", 1), submitted("[Image #1]", "short", 1)),
(json!("short"), submitted("", "short", 1)),
] {
assert!(!matches_input(&content, &input), "{content}");
}
}
// Row shapes recorded by Claude Code 2.1.327.
#[test]
fn input_given_to_the_running_turn_is_read_from_its_attachment() {
let queued = |prompt: Value| json!({"type":"attachment","sessionId":"session","attachment":{"type":"queued_command","prompt":prompt,"commandMode":"prompt"}});
let pasted = "<pasted_content id=\"9c2b\">\nline 1\nline 2\nline 3\nline 4\n</pasted_content id=\"9c2b\">";
for (row, input) in [
(
queued(json!("one more thing")),
submitted("", "one more thing", 0),
),
(
queued(json!(pasted)),
submitted("", "line 1\nline 2\nline 3\nline 4", 0),
),
(
queued(with_images("[Image #2]look", 1)),
submitted("[Image #2]", "look", 1),
),
] {
assert!(
input_content(&row).is_some_and(|content| matches_input(content, &input)),
"{row}"
);
}
for row in [
json!({"type":"queue-operation","operation":"enqueue","content":"one more thing"}),
json!({"type":"attachment","attachment":{"type":"output_style","prompt":"one more thing"}}),
] {
assert!(input_content(&row).is_none(), "{row}");
}
}
/// Records what the Host would see, and stops the turn when a message starts.
struct Sink {
outputs: std::sync::Mutex<Vec<Output>>,
stop: CancellationToken,
}
impl OutputSink for Sink {
fn emit(&self, output: Output) -> BoxFuture<'_, Result<(), Error>> {
if matches!(output, Output::MessageStart { .. }) {
self.stop.cancel();
}
self.outputs.lock().unwrap().push(output);
Box::pin(async { Ok(()) })
}
}
#[tokio::test]
async fn a_stop_ends_the_message_that_is_still_open() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("session.jsonl");
let mut cursor = Cursor::fence(path.clone(), false).await.unwrap();
let rows = [
json!({"type":"user","sessionId":"session","message":{"role":"user","content":"prompt"}}),
json!({"type":"assistant","sessionId":"session","uuid":"row","message":{"id":"message","content":[{"type":"text","text":"Sleeping."}]}}),
];
let lines: String = rows.iter().map(|row| format!("{row}\n")).collect();
tokio::fs::write(&path, lines).await.unwrap();
let stop = CancellationToken::new();
let sink = Sink {
outputs: Default::default(),
stop: stop.clone(),
};
let (_screen, mut screen) = tokio::sync::watch::channel(input::Screen::default());
let result = observe(
&mut cursor,
"session",
&submitted("", "prompt", 0),
&sink,
&mut tokio::io::sink(),
&mut screen,
&mut Start::Submitted,
&stop,
None,
)
.await;
assert!(matches!(result, Err(Error::Cancelled)));
let outputs = sink.outputs.lock().unwrap();
assert!(
matches!(outputs.last(), Some(Output::MessageEnd { message_id }) if message_id == "message")
);
}
}