Skip to content
Open
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed

- PTY tasks and deliveries are checked against conservative recipient wire limits, including their message envelopes, before launch or queue handoff. Fleet deliveries rejected before custody remain available for redelivery.

### Removed

- Python workflows, the `agent-relay.py` node provider, and the `agent-relay-sdk` package. Local workflows are YAML, TypeScript, JavaScript, or shell. Cloud and worker workflows are YAML or TypeScript. Node definitions are TypeScript or JavaScript. SDKs are TypeScript and Swift.
Expand Down
26 changes: 26 additions & 0 deletions crates/broker/src/injection_wire.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,32 @@ pub(crate) const MAX_INJECTION_BODY_BYTES: usize = 16 * 1024;
pub(crate) const ENVELOPE_RESERVE_BYTES: usize = 2 * 1024;
pub(crate) const MAX_BODY_BYTES: usize = MAX_INJECTION_BODY_BYTES - ENVELOPE_RESERVE_BYTES;

/// Use the worker's pacing defaults before a terminal can advertise paste support.
pub(crate) fn resolve_inject_rate(cli: &str, override_value: Option<&str>) -> Duration {
let name = cli.rsplit(['/', '\\']).next().unwrap_or(cli);
let default = if name.eq_ignore_ascii_case("codex")
|| name.eq_ignore_ascii_case("codex.exe")
|| crate::readiness::is_devin_cli(cli)
{
0
} else {
5
};
Duration::from_millis(
override_value
.and_then(|value| value.trim().parse().ok())
.unwrap_or(default),
)
}

/// Conservative wire ceiling when no live terminal capability is available.
pub(crate) fn preflight_limit(cli: &str, rate: Option<&str>, paste_disabled: bool) -> usize {
effective_limit(
select_wire(cli, false, paste_disabled),
resolve_inject_rate(cli, rate),
)
}

/// The spawn error for an initial PTY task that cannot fit its envelope.
pub(crate) fn task_too_large_error(task: &str) -> Option<String> {
(task.len() > MAX_BODY_BYTES).then(|| {
Expand Down
38 changes: 4 additions & 34 deletions crates/broker/src/pty_worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ use crate::broker::{
};
use crate::cli::command_parse::parse_cli_command;
use crate::cli::PtyCommand;
use crate::injection_wire::resolve_inject_rate;
use crate::readiness::{
detect_cli_ready, devin_trust_prompt_active, is_devin_cli, is_muse_cli, GridReadinessSnapshot,
};
Expand Down Expand Up @@ -198,37 +199,6 @@ fn human_write_takes_ownership(byte_len: usize, admitted: bool) -> bool {
byte_len > 0 && admitted
}

/// Default per-atom gap for escape-aware paced injection, in milliseconds.
/// Overridable at runtime via `RELAY_INJECT_RATE_MS`; `0` disables pacing and
/// restores the single bulk write. Kept small because a full injection
/// (envelope plus an optional MCP reminder) can span a few hundred atoms and
/// the gap multiplies across every one.
const DEFAULT_INJECT_RATE_MS: u64 = 5;

/// Codex redraws its full-screen input UI for each received character. Paced
/// writes therefore amplify into minutes-long initial task delivery, while its
/// bulk-input path accepts the same reminder and task immediately.
fn default_inject_rate_ms(cli: &str) -> u64 {
let cli = cli_basename(cli);
if cli.eq_ignore_ascii_case("codex")
|| cli.eq_ignore_ascii_case("codex.exe")
|| crate::readiness::is_devin_cli(cli)
{
0
} else {
DEFAULT_INJECT_RATE_MS
}
}

/// Resolve the injection pacing gap from an optional override. Keeping this
/// pure avoids process-environment races in tests.
fn resolve_inject_rate(cli: &str, override_value: Option<&str>) -> Duration {
let ms = override_value
.and_then(|value| value.trim().parse::<u64>().ok())
.unwrap_or_else(|| default_inject_rate_ms(cli));
Duration::from_millis(ms)
}

/// Resolve the injection pacing gap from `RELAY_INJECT_RATE_MS`, falling back
/// to the CLI-specific default. Explicit values still override every CLI.
fn inject_rate_from_env(cli: &str) -> Duration {
Expand Down Expand Up @@ -4114,15 +4084,15 @@ mod tests {
fn non_codex_clis_keep_paced_injection_default() {
assert_eq!(
resolve_inject_rate("claude", None),
Duration::from_millis(DEFAULT_INJECT_RATE_MS)
Duration::from_millis(5)
);
assert_eq!(
resolve_inject_rate("gemini", Some("invalid")),
Duration::from_millis(DEFAULT_INJECT_RATE_MS)
Duration::from_millis(5)
);
assert_eq!(
resolve_inject_rate("opencode", Some(" ")),
Duration::from_millis(DEFAULT_INJECT_RATE_MS)
Duration::from_millis(5)
);
}

Expand Down
46 changes: 25 additions & 21 deletions crates/broker/src/runtime/delivery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -861,27 +861,6 @@ pub(crate) async fn queue_and_try_delivery_raw(
withheld_fleet_ack: Option<crate::fleet_wire::Deliver>,
withheld_fleet_ack_floor: Option<u64>,
) -> Result<DeliveryId> {
// The envelope-sized cap exists because PTY delivery types the message into
// a terminal, so it applies to PTY and unknown recipients. The headless CLI
// runner (no harness config) hands the body to its provider as one argv
// entry, so it is bounded by the portable single-argument ceiling instead.
// App-server and native harness workers receive deliveries as frames and
// need neither bound.
let recipient = workers.workers.get(worker_name).map(|handle| &handle.spec);
if recipient.is_none_or(|spec| spec.runtime == AgentRuntime::Pty) {
anyhow::ensure!(
body.len() <= crate::injection_wire::MAX_BODY_BYTES,
"injection_too_large: body limit is {} bytes so the formatted envelope fits the {}-byte PTY limit; use a brief file pointer",
crate::injection_wire::MAX_BODY_BYTES,
crate::injection_wire::MAX_INJECTION_BODY_BYTES
);
} else if recipient.is_some_and(|spec| spec.harness_config.is_none()) {
anyhow::ensure!(
body.len() <= crate::worker::MUSE_STARTUP_PROMPT_MAX_BYTES,
"injection_too_large: a headless agent receives the body as one process argument, limited to {} bytes; use a brief file pointer",
crate::worker::MUSE_STARTUP_PROMPT_MAX_BYTES
);
}
// Fleet delivery IDs are stable across Relaycast retries. Preserve that
// identity all the way into the worker so its completed-delivery cache can
// re-ACK a replay without pasting the instruction a second time. Local
Expand Down Expand Up @@ -932,6 +911,13 @@ pub(crate) async fn insert_and_attempt_delivery(
withheld_fleet_ack: Option<crate::fleet_wire::Deliver>,
explicit_withheld_fleet_ack_floor: Option<u64>,
) -> Result<DeliveryId> {
// Reject before local custody or any handoff. The fleet caller retains
// Relaycast ownership on Err and does not commit receipt of the rejected frame.
crate::worker::validate_delivery_size(
workers.workers.get(worker_name).map(|handle| &handle.spec),
worker_name,
&delivery,
)?;
let delivery_id = delivery.delivery_id.clone();
let withheld_fleet_ack_floor = withheld_fleet_ack
.as_ref()
Expand Down Expand Up @@ -1027,6 +1013,24 @@ pub(crate) async fn retry_pending_delivery(
return Ok(DeliveryAttemptOutcome::Noop);
}

// A restored, never-handed-off delivery still needs admission validation.
// Once handed off, preserve retry/dedup and ACK handling: the worker may
// already have accepted it using a paste-capable wire.
if pending.attempts == 0 {
if let Err(error) = crate::worker::validate_delivery_size(
workers
.workers
.get(&pending.worker_name)
.map(|handle| &handle.spec),
&pending.worker_name,
&pending.delivery,
) {
return Ok(DeliveryAttemptOutcome::Failed {
pending: Box::new(pending_deliveries.remove(delivery_id).unwrap_or(pending)),
last_error: error.to_string(),
});
}
}
match workers
.deliver(&pending.worker_name, pending.delivery.clone())
.await
Expand Down
125 changes: 125 additions & 0 deletions crates/broker/src/runtime/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4781,6 +4781,131 @@ async fn pty_body_cap_applies_only_to_pty_recipients() {
.expect("frame-delivered headless workers have no argv ceiling");
}

#[tokio::test]
async fn recipient_wire_guard_checks_shared_insertion_before_taking_custody() {
let mut workers = make_worker_registry_with_worker("Worker").await;
let mut pending = HashMap::new();
let mut delivery = make_pending_delivery("wire-size", "Worker").delivery;
delivery.body = "x".repeat(1400); // Fits the typed body limit, but not its envelope.
let ack = fleet_deliver(1);
for runtime in [AgentRuntime::Pty, AgentRuntime::Headless] {
workers.workers.get_mut("Worker").unwrap().spec.runtime = runtime.clone();
if runtime == AgentRuntime::Headless {
delivery.body = "x".repeat(crate::worker::MUSE_STARTUP_PROMPT_MAX_BYTES + 1);
}
let error = super::insert_and_attempt_delivery(
&mut workers,
&mut pending,
"Worker",
delivery.clone(),
Duration::from_secs(1),
Some(ack.clone()),
None,
)
.await
.unwrap_err();
assert!(error.to_string().contains("injection_too_large"));
assert!(
pending.is_empty(),
"rejecting a prebuilt fleet delivery must not acquire its ack"
);
}
cleanup_worker_registry(workers).await;
}

#[tokio::test]
async fn worker_missing_oversize_replay_retains_relaycast_ownership_and_sequence() {
let (tx, _rx) = mpsc::channel(16);
let workers = WorkerRegistry::new(tx, vec![], PathBuf::from("/tmp/size-guard"), Instant::now());
let mut fixture = worker_event_runtime_fixture(workers, HashMap::new());
let mut deliver = fleet_deliver(1);
deliver.payload = json!({"type":"message.created", "text":"x".repeat(2000)});
fixture
.runtime
.fleet_delivery_book
.bind_authoritative_identity(&deliver.agent, &deliver.agent_id);
for _ in 0..2 {
fixture
.runtime
.handle_fleet_deliver(deliver.clone(), None)
.await;
assert!(fixture.runtime.pending_deliveries.is_empty());
assert_eq!(
fixture
.runtime
.fleet_delivery_book
.acked_up_to_seq(&deliver.agent_id),
0
);
assert!(
matches!(
fixture.runtime.fleet_delivery_book.observe(&deliver),
crate::node_control::DeliveryDecision::Deliver { .. }
),
"rejection must not commit receipt or make exact redelivery a duplicate"
);
assert!(!fixture
.runtime
.terminal_failed_deliveries
.contains(deliver.delivery_id.as_str()));
while let Ok(command) = fixture.fleet_control_rx.try_recv() {
assert!(!matches!(
command,
FleetControlCommand::Send(BrokerToRelaycast::DeliveryAck(_))
));
}
}
// An already-owned predecessor's acknowledgement remains withheld as well.
let mut owned = make_pending_delivery("owned", "worker-a");
owned.attempts = 0;
owned.withheld_fleet_ack = Some(deliver.clone());
owned.delivery.body = "x".repeat(2000);
let mut workers = make_worker_registry_with_worker("worker-a").await;
let id = owned.delivery.delivery_id.clone();
let mut pending = HashMap::from([(id.clone(), owned)]);
let outcome =
super::retry_pending_delivery(&id, &mut workers, &mut pending, Duration::from_secs(1))
.await
.unwrap();
let super::DeliveryAttemptOutcome::Failed {
pending: failed, ..
} = outcome
else {
panic!("oversize replay must fail before handoff")
};
assert_eq!(
failed.withheld_fleet_ack.unwrap().delivery_id,
deliver.delivery_id
);
cleanup_worker_registry(workers).await;
}

#[tokio::test]
async fn recipient_wire_guard_preserves_already_handed_off_retry_and_ack() {
let mut workers = make_worker_registry_with_worker("Worker").await;
let mut owned = make_pending_delivery("already-handed-off", "Worker");
owned.delivery.body = "x".repeat(2000);
let ack = fleet_deliver(1);
owned.withheld_fleet_ack = Some(ack.clone());
owned.withheld_fleet_ack_floor = Some(ack.seq);
let id = owned.delivery.delivery_id.clone();
let mut pending = HashMap::from([(id.clone(), owned)]);
let outcome = retry_pending_delivery(&id, &mut workers, &mut pending, Duration::from_secs(1))
.await
.unwrap();
assert!(matches!(
outcome,
DeliveryAttemptOutcome::Attempted { attempts: 2, .. }
));
let retained = &pending[&id];
assert_eq!(
retained.withheld_fleet_ack.as_ref().unwrap().delivery_id,
ack.delivery_id
);
assert_eq!(retained.withheld_fleet_ack_floor, Some(ack.seq));
cleanup_worker_registry(workers).await;
}

#[tokio::test]
async fn delivery_retry_transient_blip_emits_failed_event_for_present_worker() {
let worker_name = "worker-blip";
Expand Down
Loading