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
67 changes: 50 additions & 17 deletions bt-daemon/docs/protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,35 @@ The result has the same shape as `session.flush`. The managed-run identifier is
invocation-local and prevents the shared daemon from flushing unrelated agent
sessions.

### `import.finish` (request)

Transcript import is a daemon client. It starts or upgrades the daemon exactly
as hook capture does, sends every synthesized lifecycle event with `event.log`
over one connection, then finishes each imported session with this request.
`session_id` is the import run's daemon-side session (see Durability &
idempotence), not the native session id.
The daemon waits for those captures to reach every delivery route of the
session matching `route`. With `finalize: true` it first closes the session's
open spans, as a completed transcript does; `false` only flushes, as when
`--attach` detaches. Params:
```json
{ "source": "codex", "session_id": "…", "route": { … }, "finalize": true, "timeout_ms": 120000 }
```
Result:
```json
{ "flushed": true, "pending": 0, "root_span_id": "…", "span_count": 12 }
```
`span_count` counts distinct spans the route has delivered since its actor
started. An attached import reports its parent's root span. A session that
was never accepted for delivery, for example because its credentials could not
be resolved, is an error.

### `import.reset` (request)

`{ "source": "…", "session_id": "…" }`. The native transcript was rewritten
rather than appended. After every earlier capture, translation for the source
session restarts from fresh state; output already delivered is unaffected.

### `status.get` (request)

Params: `{ "session_id": "…" }` (omit `session_id` for daemon-wide status).
Expand Down Expand Up @@ -258,14 +287,10 @@ version, `context.span_origin.<source>.version` is its coding-agent
`source_version`, and `context.span_origin.bt.version` is the daemon version at
span creation. `<source>` is the canonical name, such as `codex` or `claude-code`,
not a literal `agent` key. Unknown plugin and agent versions are explicit JSON
`null`; they never fall back to another component's version. The
destination-scoped delivery ledger persists each snapshot before export; later
updates, resume, and replay reuse it unchanged, even across upgrades.
New snapshots and delivery acknowledgements are appended as NDJSON records,
without rewriting prior entries. Recovery combines any legacy JSON checkpoint
with those records and discards an incomplete final record from an interrupted write.
A per-ledger OS file lock serializes state refresh, origin selection, tail repair,
and append across daemon and import processes. SDK delivery runs outside the lock.
`null`; they never fall back to another component's version. Translation
records each snapshot in the session's SpanOp storage when its span is created,
before delivery; later updates, resume, and replay reuse it unchanged, even
across upgrades.
New spans capture new snapshots instead of inheriting the root's versions.
Provisional roots retain their original snapshot while waiting for work.
An unmaterialized span replayed for a new destination uses its
Expand All @@ -279,7 +304,7 @@ translator. The Pi extension sends the running host package's version as
`source_version` and its package name as `payload.host_name`. The translator records
`metadata.host_name`; the session-root label remains `Pi` for every Pi-compatible host.

For acknowledged spans from legacy ledgers without saved snapshots, stateless
For spans an earlier daemon acknowledged without saving snapshots, stateless
updates omit `context.span_origin` entirely, including SDK defaults and inherited
parent origin fields. This preserves existing backend provenance without guessing
historical versions; output, timing, and unrelated propagated context still merge
Expand Down Expand Up @@ -406,18 +431,26 @@ part of the envelope or journal schema.

## Durability & idempotence

Journal recovery and explicit transcript import are separate operations.
Recovery consumes the daemon's auth-redacted event WAL to rebuild state and
may idempotently re-emit rows under their original deterministic ids. The
Transcript import and hook capture share one pipeline. The
`import <codex|claude> <session-id> [project_logs:<project-id> |
experiment:<experiment-id>]` command instead locates the selected agent's
native transcript and creates a trace for that past coding-agent session by
routing synthetic lifecycle events through the regular translator. `--parent
experiment:<experiment-id>]` command locates the selected agent's native
transcript and captures synthetic lifecycle events with the daemon, which
journals, translates and delivers them like hook events (see `import.finish`).
Each import run captures into its own daemon-side session, separate from the
native session's live capture and from earlier imports, and translates the
native session from fresh state under the native session's identity. It
therefore reproduces the native session's deterministic span ids and delivers
every span to its destination, including one that already received the session
elsewhere. Importing a session again re-delivers its rows under the same ids;
an import older than what a destination already holds may replace newer
content on the spans they share. Recovery replays the journal to rebuild state
and may idempotently re-emit rows under their original deterministic ids.
`--parent
<SpanComponents>` attaches it below an exported span and is mutually exclusive
with an object destination.

`--attach` keeps a single translator and sink alive, tails new native records,
and finalizes the active turn on Ctrl-C.
`--attach` keeps capturing new native records as the transcript grows, and
detaches on Ctrl-C without closing the native session's open spans.
`run <codex|claude|opencode|pi> [ARGS...]` launches the selected agent with
inherited stdio and injects its tracing integration for that invocation, so it
works without plugin setup. Codex and Claude receive live hook configuration;
Expand Down
6 changes: 6 additions & 0 deletions bt-daemon/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,12 @@ pub struct ImportArgs {
/// transform chain; persistent setup plugins are not included.
#[arg(long, value_name = "PATH")]
pub plugin: Vec<PathBuf>,
/// Socket path override.
#[arg(long)]
pub socket: Option<PathBuf>,
/// Fail instead of spawning a daemon if none is running.
#[arg(long)]
pub no_spawn: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
Expand Down
163 changes: 117 additions & 46 deletions bt-daemon/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,76 +260,147 @@ pub async fn forward_envelope(
host: &HostInfo,
no_spawn: bool,
) -> anyhow::Result<()> {
const MAX_HANDOVER_ATTEMPTS: usize = 3;
let mut handover_attempts = 0;
let mut capture_retry_deadline = None;
DaemonClient::new(socket, host, no_spawn).log(env).await
}

loop {
if capture_retry_deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) {
anyhow::bail!(
"replacement daemon did not accept the event at {}",
socket.display()
);
/// One reusable connection to a current daemon. It starts the daemon or hands
/// over to a newer one exactly as hook capture does, then keeps the connection
/// for every later request.
pub(crate) struct DaemonClient {
socket: std::path::PathBuf,
host: HostInfo,
no_spawn: bool,
conn: Option<Conn>,
}

impl DaemonClient {
pub(crate) fn new(socket: &Path, host: &HostInfo, no_spawn: bool) -> Self {
Self {
socket: socket.to_owned(),
host: host.clone(),
no_spawn,
conn: None,
}
}

let stream = match connect(socket).await {
Ok(stream) => stream,
Err(_) if capture_retry_deadline.is_some() && no_spawn => {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
continue;
}
Err(_) => ensure_daemon(socket, host, no_spawn).await?,
};
let mut conn = Conn::new(stream);
let initialized = match conn
.request(method::INITIALIZE, initialize_params(env, &host.version))
.await
{
Ok(initialized) => initialized,
Err(_) if capture_retry_deadline.is_some() => {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
continue;
/// Connect and initialize. `Ok(false)` is a transient failure to retry
/// while a replacement daemon takes over.
async fn open(&mut self, init: &serde_json::Value, retrying: bool) -> anyhow::Result<bool> {
const MAX_HANDOVER_ATTEMPTS: usize = 3;
let mut handover_attempts = 0;
loop {
let stream = match connect(&self.socket).await {
Ok(stream) => stream,
Err(_) if retrying && self.no_spawn => return Ok(false),
Err(_) => ensure_daemon(&self.socket, &self.host, self.no_spawn).await?,
};
let mut conn = Conn::new(stream);
let initialized = match conn.request(method::INITIALIZE, init).await {
Ok(initialized) => initialized,
Err(_) if retrying => return Ok(false),
Err(error) => return Err(error),
};
let initialized: wire::InitializeResult = serde_json::from_value(initialized)?;
if !daemon_needs_upgrade(&initialized.daemon_version, &self.host.version) {
self.conn = Some(conn);
return Ok(true);
}
Err(error) => return Err(error),
};
let initialized: wire::InitializeResult = serde_json::from_value(initialized)?;
if daemon_needs_upgrade(&initialized.daemon_version, &host.version) {
if no_spawn {
if self.no_spawn {
anyhow::bail!(
"daemon version {} is older than client {} and --no-spawn is set",
initialized.daemon_version,
host.version
self.host.version
);
}
if handover_attempts == MAX_HANDOVER_ATTEMPTS {
anyhow::bail!(
"daemon version {} is still older than client {} after {MAX_HANDOVER_ATTEMPTS} handover attempts",
initialized.daemon_version,
host.version
self.host.version
);
}
conn.request(method::DAEMON_SHUTDOWN, serde_json::json!({}))
.await?;
handover_attempts += 1;
drop(conn);
wait_for_daemon_exit(socket).await;
continue;
wait_for_daemon_exit(&self.socket).await;
}
let result = match conn.request(method::EVENT_LOG, env).await {
Ok(result) => result,
Err(_) if capture_retry_deadline.is_some() => {
}

/// Capture one event. Returns once the daemon has durably accepted it.
pub(crate) async fn log(&mut self, env: &Envelope) -> anyhow::Result<()> {
let init = initialize_params(env, &self.host.version);
let mut retry_deadline: Option<tokio::time::Instant> = None;
loop {
if retry_deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) {
anyhow::bail!(
"replacement daemon did not accept the event at {}",
self.socket.display()
);
}
let reused = self.conn.is_some();
if !reused && !self.open(&init, retry_deadline.is_some()).await? {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
continue;
}
Err(error) => return Err(error),
};
let result: wire::EventLogResult = serde_json::from_value(result)?;
if result.accepted {
return Ok(());
let Some(conn) = self.conn.as_mut() else {
continue;
};
let result = match conn.request(method::EVENT_LOG, env).await {
Ok(result) => result,
// A reused connection may belong to a daemon that has since
// exited; reconnect once before treating this as a failure.
Err(_) if reused || retry_deadline.is_some() => {
self.conn = None;
retry_deadline.get_or_insert_with(|| {
tokio::time::Instant::now() + std::time::Duration::from_secs(5)
});
continue;
}
Err(error) => {
self.conn = None;
return Err(error);
}
};
let result: wire::EventLogResult = serde_json::from_value(result)?;
if result.accepted {
return Ok(());
}
// A quiescing daemon is handing over; capture with its replacement.
self.conn = None;
retry_deadline.get_or_insert_with(|| {
tokio::time::Instant::now() + std::time::Duration::from_secs(5)
});
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
capture_retry_deadline
.get_or_insert_with(|| tokio::time::Instant::now() + std::time::Duration::from_secs(5));
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}

/// A non-capture request over the same connection.
pub(crate) async fn call<R: serde::de::DeserializeOwned>(
&mut self,
method: &str,
params: impl serde::Serialize,
) -> anyhow::Result<R> {
if self.conn.is_none() {
let init = serde_json::json!({
"protocol_version": PROTOCOL_VERSION,
"client": {
"source": "import",
"daemon_version": self.host.version,
"pid": std::process::id()
}
});
self.open(&init, false).await?;
}
let conn = self
.conn
.as_mut()
.ok_or_else(|| anyhow::anyhow!("daemon connection is unavailable"))?;
let result = conn.call(method, params).await;
if result.is_err() {
self.conn = None;
}
result
}
}

Expand Down
Loading
Loading