Implement environment-bound exec plumbing

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
starr-openai
2026-03-20 18:52:02 -07:00
co-authored by Codex
parent fc135afd78
commit 2de2b1bfbd
77 changed files with 1775 additions and 53 deletions
+2
View File
@@ -1039,6 +1039,7 @@ mod tests {
.request_typed(ClientRequest::ThreadStart {
request_id: RequestId::Integer(2),
params: ThreadStartParams {
environment_id: None,
ephemeral: Some(true),
..ThreadStartParams::default()
},
@@ -1058,6 +1059,7 @@ mod tests {
.request_typed(ClientRequest::ThreadStart {
request_id: RequestId::Integer(3),
params: ThreadStartParams {
environment_id: None,
ephemeral: Some(true),
..ThreadStartParams::default()
},
@@ -201,6 +201,13 @@
"null"
]
},
"environmentId": {
"description": "Optional executor environment binding for this command.",
"type": [
"string",
"null"
]
},
"outputBytesCap": {
"description": "Optional per-stream stdout/stderr capture cap in bytes.\n\nWhen omitted, the server default applies. Cannot be combined with `disableOutputCap`.",
"format": "uint",
@@ -2492,6 +2499,13 @@
"null"
]
},
"environmentId": {
"description": "Optional executor environment binding for the forked thread.",
"type": [
"string",
"null"
]
},
"ephemeral": {
"type": "boolean"
},
@@ -2789,6 +2803,13 @@
"null"
]
},
"environmentId": {
"description": "Optional executor environment binding for the resumed thread.",
"type": [
"string",
"null"
]
},
"model": {
"description": "Configuration overrides for the resumed thread, if any.",
"type": [
@@ -2967,6 +2988,13 @@
"null"
]
},
"environmentId": {
"description": "Optional executor environment binding for this thread.",
"type": [
"string",
"null"
]
},
"ephemeral": {
"type": [
"boolean",
@@ -5924,6 +5924,13 @@
"null"
]
},
"environmentId": {
"description": "Optional executor environment binding for this command.",
"type": [
"string",
"null"
]
},
"outputBytesCap": {
"description": "Optional per-stream stdout/stderr capture cap in bytes.\n\nWhen omitted, the server default applies. Cannot be combined with `disableOutputCap`.",
"format": "uint",
@@ -11822,6 +11829,13 @@
"null"
]
},
"environmentId": {
"description": "Optional executor environment binding for the forked thread.",
"type": [
"string",
"null"
]
},
"ephemeral": {
"type": "boolean"
},
@@ -11892,6 +11906,9 @@
"cwd": {
"type": "string"
},
"environmentId": {
"type": "string"
},
"model": {
"type": "string"
},
@@ -11929,6 +11946,7 @@
"approvalPolicy",
"approvalsReviewer",
"cwd",
"environmentId",
"model",
"modelProvider",
"sandbox",
@@ -13016,6 +13034,13 @@
"null"
]
},
"environmentId": {
"description": "Optional executor environment binding for the resumed thread.",
"type": [
"string",
"null"
]
},
"model": {
"description": "Configuration overrides for the resumed thread, if any.",
"type": [
@@ -13093,6 +13118,9 @@
"cwd": {
"type": "string"
},
"environmentId": {
"type": "string"
},
"model": {
"type": "string"
},
@@ -13130,6 +13158,7 @@
"approvalPolicy",
"approvalsReviewer",
"cwd",
"environmentId",
"model",
"modelProvider",
"sandbox",
@@ -13292,6 +13321,13 @@
"null"
]
},
"environmentId": {
"description": "Optional executor environment binding for this thread.",
"type": [
"string",
"null"
]
},
"ephemeral": {
"type": [
"boolean",
@@ -13374,6 +13410,9 @@
"cwd": {
"type": "string"
},
"environmentId": {
"type": "string"
},
"model": {
"type": "string"
},
@@ -13411,6 +13450,7 @@
"approvalPolicy",
"approvalsReviewer",
"cwd",
"environmentId",
"model",
"modelProvider",
"sandbox",
@@ -2557,6 +2557,13 @@
"null"
]
},
"environmentId": {
"description": "Optional executor environment binding for this command.",
"type": [
"string",
"null"
]
},
"outputBytesCap": {
"description": "Optional per-stream stdout/stderr capture cap in bytes.\n\nWhen omitted, the server default applies. Cannot be combined with `disableOutputCap`.",
"format": "uint",
@@ -9582,6 +9589,13 @@
"null"
]
},
"environmentId": {
"description": "Optional executor environment binding for the forked thread.",
"type": [
"string",
"null"
]
},
"ephemeral": {
"type": "boolean"
},
@@ -9652,6 +9666,9 @@
"cwd": {
"type": "string"
},
"environmentId": {
"type": "string"
},
"model": {
"type": "string"
},
@@ -9689,6 +9706,7 @@
"approvalPolicy",
"approvalsReviewer",
"cwd",
"environmentId",
"model",
"modelProvider",
"sandbox",
@@ -10776,6 +10794,13 @@
"null"
]
},
"environmentId": {
"description": "Optional executor environment binding for the resumed thread.",
"type": [
"string",
"null"
]
},
"model": {
"description": "Configuration overrides for the resumed thread, if any.",
"type": [
@@ -10853,6 +10878,9 @@
"cwd": {
"type": "string"
},
"environmentId": {
"type": "string"
},
"model": {
"type": "string"
},
@@ -10890,6 +10918,7 @@
"approvalPolicy",
"approvalsReviewer",
"cwd",
"environmentId",
"model",
"modelProvider",
"sandbox",
@@ -11052,6 +11081,13 @@
"null"
]
},
"environmentId": {
"description": "Optional executor environment binding for this thread.",
"type": [
"string",
"null"
]
},
"ephemeral": {
"type": [
"boolean",
@@ -11134,6 +11170,9 @@
"cwd": {
"type": "string"
},
"environmentId": {
"type": "string"
},
"model": {
"type": "string"
},
@@ -11171,6 +11210,7 @@
"approvalPolicy",
"approvalsReviewer",
"cwd",
"environmentId",
"model",
"modelProvider",
"sandbox",
@@ -238,6 +238,13 @@
"null"
]
},
"environmentId": {
"description": "Optional executor environment binding for this command.",
"type": [
"string",
"null"
]
},
"outputBytesCap": {
"description": "Optional per-stream stdout/stderr capture cap in bytes.\n\nWhen omitted, the server default applies. Cannot be combined with `disableOutputCap`.",
"format": "uint",
@@ -123,6 +123,13 @@
"null"
]
},
"environmentId": {
"description": "Optional executor environment binding for the forked thread.",
"type": [
"string",
"null"
]
},
"ephemeral": {
"type": "boolean"
},
@@ -2106,6 +2106,9 @@
"cwd": {
"type": "string"
},
"environmentId": {
"type": "string"
},
"model": {
"type": "string"
},
@@ -2143,6 +2146,7 @@
"approvalPolicy",
"approvalsReviewer",
"cwd",
"environmentId",
"model",
"modelProvider",
"sandbox",
@@ -1029,6 +1029,13 @@
"null"
]
},
"environmentId": {
"description": "Optional executor environment binding for the resumed thread.",
"type": [
"string",
"null"
]
},
"model": {
"description": "Configuration overrides for the resumed thread, if any.",
"type": [
@@ -2106,6 +2106,9 @@
"cwd": {
"type": "string"
},
"environmentId": {
"type": "string"
},
"model": {
"type": "string"
},
@@ -2143,6 +2146,7 @@
"approvalPolicy",
"approvalsReviewer",
"cwd",
"environmentId",
"model",
"modelProvider",
"sandbox",
@@ -150,6 +150,13 @@
"null"
]
},
"environmentId": {
"description": "Optional executor environment binding for this thread.",
"type": [
"string",
"null"
]
},
"ephemeral": {
"type": [
"boolean",
@@ -2106,6 +2106,9 @@
"cwd": {
"type": "string"
},
"environmentId": {
"type": "string"
},
"model": {
"type": "string"
},
@@ -2143,6 +2146,7 @@
"approvalPolicy",
"approvalsReviewer",
"cwd",
"environmentId",
"model",
"modelProvider",
"sandbox",
@@ -12,11 +12,15 @@ import type { SandboxPolicy } from "./SandboxPolicy";
* sent only after all `command/exec/outputDelta` notifications for that
* connection have been emitted.
*/
export type CommandExecParams = {
export type CommandExecParams = {
/**
* Command argv vector. Empty arrays are rejected.
*/
command: Array<string>,
command: Array<string>,
/**
* Optional executor environment binding for this command.
*/
environmentId?: string | null,
/**
* Optional client-supplied, connection-scoped process id.
*
@@ -25,56 +29,56 @@ command: Array<string>,
* `command/exec/terminate` calls. When omitted, buffered execution gets an
* internal id that is not exposed to the client.
*/
processId?: string | null,
processId?: string | null,
/**
* Enable PTY mode.
*
* This implies `streamStdin` and `streamStdoutStderr`.
*/
tty?: boolean,
tty?: boolean,
/**
* Allow follow-up `command/exec/write` requests to write stdin bytes.
*
* Requires a client-supplied `processId`.
*/
streamStdin?: boolean,
streamStdin?: boolean,
/**
* Stream stdout/stderr via `command/exec/outputDelta` notifications.
*
* Streamed bytes are not duplicated into the final response and require a
* client-supplied `processId`.
*/
streamStdoutStderr?: boolean,
streamStdoutStderr?: boolean,
/**
* Optional per-stream stdout/stderr capture cap in bytes.
*
* When omitted, the server default applies. Cannot be combined with
* `disableOutputCap`.
*/
outputBytesCap?: number | null,
outputBytesCap?: number | null,
/**
* Disable stdout/stderr capture truncation for this request.
*
* Cannot be combined with `outputBytesCap`.
*/
disableOutputCap?: boolean,
disableOutputCap?: boolean,
/**
* Disable the timeout entirely for this request.
*
* Cannot be combined with `timeoutMs`.
*/
disableTimeout?: boolean,
disableTimeout?: boolean,
/**
* Optional timeout in milliseconds.
*
* When omitted, the server default applies. Cannot be combined with
* `disableTimeout`.
*/
timeoutMs?: number | null,
timeoutMs?: number | null,
/**
* Optional working directory. Defaults to the server cwd.
*/
cwd?: string | null,
cwd?: string | null,
/**
* Optional environment overrides merged into the server-computed
* environment.
@@ -82,12 +86,12 @@ cwd?: string | null,
* Matching names override inherited values. Set a key to `null` to unset
* an inherited variable.
*/
env?: { [key in string]?: string | null } | null,
env?: { [key in string]?: string | null } | null,
/**
* Optional initial PTY size in character cells. Only valid when `tty` is
* true.
*/
size?: CommandExecTerminalSize | null,
size?: CommandExecTerminalSize | null,
/**
* Optional sandbox policy for this command.
*
@@ -17,6 +17,9 @@ import type { SandboxMode } from "./SandboxMode";
* Prefer using thread_id whenever possible.
*/
export type ThreadForkParams = {threadId: string, /**
* Optional executor environment binding for the forked thread.
*/
environmentId?: string | null, /**
* [UNSTABLE] Specify the rollout path to fork from.
* If specified, the thread_id param will be ignored.
*/
@@ -8,7 +8,7 @@ import type { AskForApproval } from "./AskForApproval";
import type { SandboxPolicy } from "./SandboxPolicy";
import type { Thread } from "./Thread";
export type ThreadForkResponse = { thread: Thread, model: string, modelProvider: string, serviceTier: ServiceTier | null, cwd: string, approvalPolicy: AskForApproval,
export type ThreadForkResponse = { thread: Thread, environmentId: string, model: string, modelProvider: string, serviceTier: ServiceTier | null, cwd: string, approvalPolicy: AskForApproval,
/**
* Reviewer currently used for approval requests on this thread.
*/
@@ -21,6 +21,9 @@ import type { SandboxMode } from "./SandboxMode";
* Prefer using thread_id whenever possible.
*/
export type ThreadResumeParams = {threadId: string, /**
* Optional executor environment binding for the resumed thread.
*/
environmentId?: string | null, /**
* [UNSTABLE] FOR CODEX CLOUD - DO NOT USE.
* If specified, the thread will be resumed with the provided history
* instead of loaded from disk.
@@ -8,7 +8,7 @@ import type { AskForApproval } from "./AskForApproval";
import type { SandboxPolicy } from "./SandboxPolicy";
import type { Thread } from "./Thread";
export type ThreadResumeResponse = { thread: Thread, model: string, modelProvider: string, serviceTier: ServiceTier | null, cwd: string, approvalPolicy: AskForApproval,
export type ThreadResumeResponse = { thread: Thread, environmentId: string, model: string, modelProvider: string, serviceTier: ServiceTier | null, cwd: string, approvalPolicy: AskForApproval,
/**
* Reviewer currently used for approval requests on this thread.
*/
@@ -8,7 +8,10 @@ import type { ApprovalsReviewer } from "./ApprovalsReviewer";
import type { AskForApproval } from "./AskForApproval";
import type { SandboxMode } from "./SandboxMode";
export type ThreadStartParams = {model?: string | null, modelProvider?: string | null, serviceTier?: ServiceTier | null | null, cwd?: string | null, approvalPolicy?: AskForApproval | null, /**
export type ThreadStartParams = {model?: string | null, modelProvider?: string | null, /**
* Optional executor environment binding for this thread.
*/
environmentId?: string | null, serviceTier?: ServiceTier | null | null, cwd?: string | null, approvalPolicy?: AskForApproval | null, /**
* Override where approval requests are routed for review on this thread
* and subsequent turns.
*/
@@ -8,7 +8,7 @@ import type { AskForApproval } from "./AskForApproval";
import type { SandboxPolicy } from "./SandboxPolicy";
import type { Thread } from "./Thread";
export type ThreadStartResponse = { thread: Thread, model: string, modelProvider: string, serviceTier: ServiceTier | null, cwd: string, approvalPolicy: AskForApproval,
export type ThreadStartResponse = { thread: Thread, environmentId: string, model: string, modelProvider: string, serviceTier: ServiceTier | null, cwd: string, approvalPolicy: AskForApproval,
/**
* Reviewer currently used for approval requests on this thread.
*/
@@ -3,6 +3,7 @@ use crate::protocol::v2;
impl From<v1::ExecOneOffCommandParams> for v2::CommandExecParams {
fn from(value: v1::ExecOneOffCommandParams) -> Self {
Self {
environment_id: None,
command: value.command,
process_id: None,
tty: false,
@@ -2292,6 +2292,9 @@ pub struct CommandExecTerminalSize {
pub struct CommandExecParams {
/// Command argv vector. Empty arrays are rejected.
pub command: Vec<String>,
/// Optional executor environment binding for this command.
#[ts(optional = nullable)]
pub environment_id: Option<String>,
/// Optional client-supplied, connection-scoped process id.
///
/// Required for `tty`, `streamStdin`, `streamStdoutStderr`, and follow-up
@@ -2459,6 +2462,9 @@ pub struct ThreadStartParams {
pub model: Option<String>,
#[ts(optional = nullable)]
pub model_provider: Option<String>,
/// Optional executor environment binding for this thread.
#[ts(optional = nullable)]
pub environment_id: Option<String>,
#[serde(
default,
deserialize_with = "super::serde_helpers::deserialize_double_option",
@@ -2532,6 +2538,7 @@ pub struct MockExperimentalMethodResponse {
#[ts(export_to = "v2/")]
pub struct ThreadStartResponse {
pub thread: Thread,
pub environment_id: String,
pub model: String,
pub model_provider: String,
pub service_tier: Option<ServiceTier>,
@@ -2560,6 +2567,9 @@ pub struct ThreadStartResponse {
/// Prefer using thread_id whenever possible.
pub struct ThreadResumeParams {
pub thread_id: String,
/// Optional executor environment binding for the resumed thread.
#[ts(optional = nullable)]
pub environment_id: Option<String>,
/// [UNSTABLE] FOR CODEX CLOUD - DO NOT USE.
/// If specified, the thread will be resumed with the provided history
@@ -2618,6 +2628,7 @@ pub struct ThreadResumeParams {
#[ts(export_to = "v2/")]
pub struct ThreadResumeResponse {
pub thread: Thread,
pub environment_id: String,
pub model: String,
pub model_provider: String,
pub service_tier: Option<ServiceTier>,
@@ -2644,6 +2655,9 @@ pub struct ThreadResumeResponse {
/// Prefer using thread_id whenever possible.
pub struct ThreadForkParams {
pub thread_id: String,
/// Optional executor environment binding for the forked thread.
#[ts(optional = nullable)]
pub environment_id: Option<String>,
/// [UNSTABLE] Specify the rollout path to fork from.
/// If specified, the thread_id param will be ignored.
@@ -2695,6 +2709,7 @@ pub struct ThreadForkParams {
#[ts(export_to = "v2/")]
pub struct ThreadForkResponse {
pub thread: Thread,
pub environment_id: String,
pub model: String,
pub model_provider: String,
pub service_tier: Option<ServiceTier>,
@@ -5919,6 +5934,27 @@ mod tests {
.expect("path must be absolute")
}
fn thread_fixture() -> Thread {
Thread {
id: "thr_123".to_string(),
preview: "Preview".to_string(),
ephemeral: false,
model_provider: "openai".to_string(),
created_at: 1,
updated_at: 2,
status: ThreadStatus::Idle,
path: Some(absolute_path("tmp/thread").into()),
cwd: absolute_path("tmp").into(),
cli_version: "1.0.0".to_string(),
source: SessionSource::Exec,
agent_nickname: None,
agent_role: None,
git_info: None,
name: Some("Example".to_string()),
turns: Vec::new(),
}
}
fn test_absolute_path() -> AbsolutePathBuf {
absolute_path("readable")
}
@@ -6428,6 +6464,7 @@ mod tests {
params,
CommandExecParams {
command: vec!["ls".to_string(), "-la".to_string()],
environment_id: None,
process_id: None,
tty: false,
stream_stdin: false,
@@ -6448,6 +6485,7 @@ mod tests {
fn command_exec_params_round_trips_disable_timeout() {
let params = CommandExecParams {
command: vec!["sleep".to_string(), "30".to_string()],
environment_id: None,
process_id: Some("sleep-1".to_string()),
tty: false,
stream_stdin: false,
@@ -6467,6 +6505,7 @@ mod tests {
value,
json!({
"command": ["sleep", "30"],
"environmentId": null,
"processId": "sleep-1",
"disableTimeout": true,
"timeoutMs": null,
@@ -6487,6 +6526,7 @@ mod tests {
fn command_exec_params_round_trips_disable_output_cap() {
let params = CommandExecParams {
command: vec!["yes".to_string()],
environment_id: None,
process_id: Some("yes-1".to_string()),
tty: false,
stream_stdin: false,
@@ -6506,6 +6546,7 @@ mod tests {
value,
json!({
"command": ["yes"],
"environmentId": null,
"processId": "yes-1",
"streamStdoutStderr": true,
"outputBytesCap": null,
@@ -6527,6 +6568,7 @@ mod tests {
fn command_exec_params_round_trips_env_overrides_and_unsets() {
let params = CommandExecParams {
command: vec!["printenv".to_string(), "FOO".to_string()],
environment_id: Some("env-1".to_string()),
process_id: Some("env-1".to_string()),
tty: false,
stream_stdin: false,
@@ -6550,6 +6592,7 @@ mod tests {
value,
json!({
"command": ["printenv", "FOO"],
"environmentId": "env-1",
"processId": "env-1",
"outputBytesCap": null,
"timeoutMs": null,
@@ -6615,6 +6658,7 @@ mod tests {
fn command_exec_params_round_trip_with_size() {
let params = CommandExecParams {
command: vec!["top".to_string()],
environment_id: None,
process_id: Some("pty-1".to_string()),
tty: true,
stream_stdin: false,
@@ -6637,6 +6681,7 @@ mod tests {
value,
json!({
"command": ["top"],
"environmentId": null,
"processId": "pty-1",
"tty": true,
"outputBytesCap": null,
@@ -6656,6 +6701,293 @@ mod tests {
assert_eq!(decoded, params);
}
#[test]
fn thread_start_params_round_trips_environment_id() {
let params = ThreadStartParams {
environment_id: Some("env-1".to_string()),
..Default::default()
};
let value = serde_json::to_value(&params).expect("serialize thread/start params");
assert_eq!(
value,
json!({
"model": null,
"modelProvider": null,
"environmentId": "env-1",
"cwd": null,
"approvalPolicy": null,
"approvalsReviewer": null,
"sandbox": null,
"config": null,
"serviceName": null,
"baseInstructions": null,
"developerInstructions": null,
"personality": null,
"ephemeral": null,
"dynamicTools": null,
"mockExperimentalField": null,
"experimentalRawEvents": false,
"persistExtendedHistory": false,
})
);
let decoded =
serde_json::from_value::<ThreadStartParams>(value).expect("deserialize round-trip");
assert_eq!(decoded, params);
}
#[test]
fn thread_resume_params_round_trips_environment_id() {
let params = ThreadResumeParams {
thread_id: "thr_1".to_string(),
environment_id: Some("env-2".to_string()),
..Default::default()
};
let value = serde_json::to_value(&params).expect("serialize thread/resume params");
assert_eq!(
value,
json!({
"threadId": "thr_1",
"environmentId": "env-2",
"history": null,
"path": null,
"model": null,
"modelProvider": null,
"cwd": null,
"approvalPolicy": null,
"approvalsReviewer": null,
"sandbox": null,
"config": null,
"baseInstructions": null,
"developerInstructions": null,
"personality": null,
"persistExtendedHistory": false,
})
);
let decoded =
serde_json::from_value::<ThreadResumeParams>(value).expect("deserialize round-trip");
assert_eq!(decoded, params);
}
#[test]
fn thread_fork_params_round_trips_environment_id() {
let params = ThreadForkParams {
thread_id: "thr_2".to_string(),
environment_id: Some("env-3".to_string()),
..Default::default()
};
let value = serde_json::to_value(&params).expect("serialize thread/fork params");
assert_eq!(
value,
json!({
"threadId": "thr_2",
"environmentId": "env-3",
"path": null,
"model": null,
"modelProvider": null,
"cwd": null,
"approvalPolicy": null,
"approvalsReviewer": null,
"sandbox": null,
"config": null,
"baseInstructions": null,
"developerInstructions": null,
"persistExtendedHistory": false,
})
);
let decoded =
serde_json::from_value::<ThreadForkParams>(value).expect("deserialize round-trip");
assert_eq!(decoded, params);
}
#[test]
fn thread_start_response_round_trips_environment_id() {
let response = ThreadStartResponse {
thread: thread_fixture(),
environment_id: "env-1".to_string(),
model: "gpt-5".to_string(),
model_provider: "openai".to_string(),
service_tier: Some(ServiceTier::Fast),
cwd: absolute_path("tmp").into(),
approval_policy: AskForApproval::Never,
approvals_reviewer: ApprovalsReviewer::User,
sandbox: SandboxPolicy::ReadOnly {
access: ReadOnlyAccess::FullAccess,
network_access: false,
},
reasoning_effort: None,
};
let value = serde_json::to_value(&response).expect("serialize thread/start response");
assert_eq!(
value,
json!({
"thread": {
"id": "thr_123",
"preview": "Preview",
"ephemeral": false,
"modelProvider": "openai",
"createdAt": 1,
"updatedAt": 2,
"status": {"type": "idle"},
"path": absolute_path_string("tmp/thread"),
"cwd": absolute_path_string("tmp"),
"cliVersion": "1.0.0",
"source": "exec",
"agentNickname": null,
"agentRole": null,
"gitInfo": null,
"name": "Example",
"turns": [],
},
"environmentId": "env-1",
"model": "gpt-5",
"modelProvider": "openai",
"serviceTier": "fast",
"cwd": absolute_path_string("tmp"),
"approvalPolicy": "never",
"approvalsReviewer": "user",
"sandbox": {
"type": "readOnly",
"access": {"type": "fullAccess"},
"networkAccess": false,
},
"reasoningEffort": null,
})
);
let decoded =
serde_json::from_value::<ThreadStartResponse>(value).expect("deserialize round-trip");
assert_eq!(decoded, response);
}
#[test]
fn thread_resume_response_round_trips_environment_id() {
let response = ThreadResumeResponse {
thread: thread_fixture(),
environment_id: "env-2".to_string(),
model: "gpt-5".to_string(),
model_provider: "openai".to_string(),
service_tier: Some(ServiceTier::Fast),
cwd: absolute_path("tmp").into(),
approval_policy: AskForApproval::Never,
approvals_reviewer: ApprovalsReviewer::User,
sandbox: SandboxPolicy::ReadOnly {
access: ReadOnlyAccess::FullAccess,
network_access: false,
},
reasoning_effort: Some(ReasoningEffort::Low),
};
let value = serde_json::to_value(&response).expect("serialize thread/resume response");
assert_eq!(
value,
json!({
"thread": {
"id": "thr_123",
"preview": "Preview",
"ephemeral": false,
"modelProvider": "openai",
"createdAt": 1,
"updatedAt": 2,
"status": {"type": "idle"},
"path": absolute_path_string("tmp/thread"),
"cwd": absolute_path_string("tmp"),
"cliVersion": "1.0.0",
"source": "exec",
"agentNickname": null,
"agentRole": null,
"gitInfo": null,
"name": "Example",
"turns": [],
},
"environmentId": "env-2",
"model": "gpt-5",
"modelProvider": "openai",
"serviceTier": "fast",
"cwd": absolute_path_string("tmp"),
"approvalPolicy": "never",
"approvalsReviewer": "user",
"sandbox": {
"type": "readOnly",
"access": {"type": "fullAccess"},
"networkAccess": false,
},
"reasoningEffort": "low",
})
);
let decoded =
serde_json::from_value::<ThreadResumeResponse>(value).expect("deserialize round-trip");
assert_eq!(decoded, response);
}
#[test]
fn thread_fork_response_round_trips_environment_id() {
let response = ThreadForkResponse {
thread: thread_fixture(),
environment_id: "env-3".to_string(),
model: "gpt-5".to_string(),
model_provider: "openai".to_string(),
service_tier: Some(ServiceTier::Fast),
cwd: absolute_path("tmp").into(),
approval_policy: AskForApproval::Never,
approvals_reviewer: ApprovalsReviewer::User,
sandbox: SandboxPolicy::ReadOnly {
access: ReadOnlyAccess::FullAccess,
network_access: false,
},
reasoning_effort: Some(ReasoningEffort::Medium),
};
let value = serde_json::to_value(&response).expect("serialize thread/fork response");
assert_eq!(
value,
json!({
"thread": {
"id": "thr_123",
"preview": "Preview",
"ephemeral": false,
"modelProvider": "openai",
"createdAt": 1,
"updatedAt": 2,
"status": {"type": "idle"},
"path": absolute_path_string("tmp/thread"),
"cwd": absolute_path_string("tmp"),
"cliVersion": "1.0.0",
"source": "exec",
"agentNickname": null,
"agentRole": null,
"gitInfo": null,
"name": "Example",
"turns": [],
},
"environmentId": "env-3",
"model": "gpt-5",
"modelProvider": "openai",
"serviceTier": "fast",
"cwd": absolute_path_string("tmp"),
"approvalPolicy": "never",
"approvalsReviewer": "user",
"sandbox": {
"type": "readOnly",
"access": {"type": "fullAccess"},
"networkAccess": false,
},
"reasoningEffort": "medium",
})
);
let decoded =
serde_json::from_value::<ThreadForkResponse>(value).expect("deserialize round-trip");
assert_eq!(decoded, response);
}
#[test]
fn command_exec_resize_round_trips() {
let params = CommandExecResizeParams {
@@ -715,6 +715,7 @@ async fn trigger_zsh_fork_multi_cmd_approval(
println!("< initialize response: {initialize:?}");
let thread_response = client.thread_start(ThreadStartParams {
environment_id: None,
dynamic_tools: dynamic_tools.clone(),
..Default::default()
})?;
@@ -809,6 +810,7 @@ async fn resume_message_v2(
println!("< initialize response: {initialize:?}");
let resume_response = client.thread_resume(ThreadResumeParams {
environment_id: None,
thread_id,
..Default::default()
})?;
@@ -841,6 +843,7 @@ async fn thread_resume_follow(
println!("< initialize response: {initialize:?}");
let resume_response = client.thread_resume(ThreadResumeParams {
environment_id: None,
thread_id,
..Default::default()
})?;
@@ -953,6 +956,7 @@ async fn send_message_v2_with_policies(
println!("< initialize response: {initialize:?}");
let thread_response = client.thread_start(ThreadStartParams {
environment_id: None,
dynamic_tools: policies.dynamic_tools.clone(),
..Default::default()
})?;
@@ -992,6 +996,7 @@ async fn send_follow_up_v2(
println!("< initialize response: {initialize:?}");
let thread_response = client.thread_start(ThreadStartParams {
environment_id: None,
dynamic_tools: dynamic_tools.clone(),
..Default::default()
})?;
@@ -1212,6 +1217,7 @@ fn live_elicitation_timeout_pause(
println!("< initialize response: {initialize:?}");
let thread_response = client.thread_start(ThreadStartParams {
environment_id: None,
model: Some(model),
..Default::default()
})?;
+6 -2
View File
@@ -69,6 +69,7 @@ Use the thread APIs to create, list, or archive conversations. Drive a conversat
- Initialize once per connection: Immediately after opening a transport connection, send an `initialize` request with your client metadata, then emit an `initialized` notification. Any other request on that connection before this handshake gets rejected.
- Start (or resume) a thread: Call `thread/start` to open a fresh conversation. The response returns the thread object and you’ll also get a `thread/started` notification. If you’re continuing an existing conversation, call `thread/resume` with its ID instead. If you want to branch from an existing conversation, call `thread/fork` to create a new thread id with copied history. Like `thread/start`, `thread/fork` also accepts `ephemeral: true` for an in-memory temporary thread.
The returned `thread.ephemeral` flag tells you whether the session is intentionally in-memory only; when it is `true`, `thread.path` is `null`.
These methods also accept optional `environmentId` when you need to bind the session to a specific executor environment; omit it to use the server default environment.
- Begin a turn: To send user input, call `turn/start` with the target `threadId` and the user's input. Optional fields let you override model, cwd, sandbox policy, approval policy, approvals reviewer, etc. This immediately returns the new turn object. The app-server emits `turn/started` when that turn actually begins running.
- Stream events: After `turn/start`, keep reading JSON-RPC notifications on stdout. You’ll see `item/started`, `item/completed`, deltas like `item/agentMessage/delta`, tool progress, etc. These represent streaming model output plus any side effects (commands, tool calls, reasoning notes).
- Finish the turn: When the model is done (or the turn is interrupted via making the `turn/interrupt` call), the server sends `turn/completed` with the final turn state and token usage.
@@ -147,7 +148,7 @@ Example with notification opt-out:
- `thread/realtime/appendText` — append text input to the active realtime session (experimental); returns `{}`.
- `thread/realtime/stop` — stop the active realtime session for the thread (experimental); returns `{}`.
- `review/start` — kick off Codex’s automated reviewer for a thread; responds like `turn/start` and emits `item/started`/`item/completed` notifications with `enteredReviewMode` and `exitedReviewMode` items, plus a final assistant `agentMessage` containing the review.
- `command/exec` — run a single command under the server sandbox without starting a thread/turn (handy for utilities and validation).
- `command/exec` — run a single command under the server sandbox without starting a thread/turn (handy for utilities and validation); also accepts optional `environmentId` when the client needs to target a specific executor environment.
- `command/exec/write` — write base64-decoded stdin bytes to a running `command/exec` session or close stdin; returns `{}`.
- `command/exec/resize` — resize a running PTY-backed `command/exec` session by `processId`; returns `{}`.
- `command/exec/terminate` — terminate a running `command/exec` session by `processId`; returns `{}`.
@@ -192,6 +193,7 @@ Start a fresh thread when you need a new Codex conversation.
// Optionally set config settings. If not specified, will use the user's
// current config settings.
"model": "gpt-5.1-codex",
"environmentId": "local", // optional; binds this thread to a specific executor environment
"cwd": "/Users/me/project",
"approvalPolicy": "never",
"sandbox": "workspaceWrite",
@@ -235,6 +237,7 @@ Example:
```json
{ "method": "thread/resume", "id": 11, "params": {
"threadId": "thr_123",
"environmentId": "local",
"personality": "friendly"
} }
{ "id": 11, "result": { "thread": { "id": "thr_123", … } } }
@@ -243,7 +246,7 @@ Example:
To branch from a stored session, call `thread/fork` with the `thread.id`. This creates a new thread id and emits a `thread/started` notification for it. Pass `ephemeral: true` when the fork should stay in-memory only:
```json
{ "method": "thread/fork", "id": 12, "params": { "threadId": "thr_123", "ephemeral": true } }
{ "method": "thread/fork", "id": 12, "params": { "threadId": "thr_123", "environmentId": "local", "ephemeral": true } }
{ "id": 12, "result": { "thread": { "id": "thr_456", … } } }
{ "method": "thread/started", "params": { "thread": { … } } }
```
@@ -665,6 +668,7 @@ Run a standalone command (argv vector) in the server’s sandbox without creatin
```json
{ "method": "command/exec", "id": 32, "params": {
"command": ["ls", "-la"],
"environmentId": "local", // optional; binds this request to a specific executor environment
"processId": "ls-1", // optional string; required for streaming and ability to terminate the process
"cwd": "/Users/me/project", // optional; defaults to server cwd
"env": { "FOO": "override" }, // optional; merges into the server env and overrides matching names
@@ -239,6 +239,7 @@ use codex_core::state_db::reconcile_rollout;
use codex_core::windows_sandbox::WindowsSandboxLevelExt;
use codex_core::windows_sandbox::WindowsSandboxSetupMode as CoreWindowsSandboxSetupMode;
use codex_core::windows_sandbox::WindowsSandboxSetupRequest;
use codex_exec_server::Environment;
use codex_feedback::CodexFeedback;
use codex_login::ServerOptions as LoginServerOptions;
use codex_login::ShutdownHandle;
@@ -1553,6 +1554,7 @@ impl CodexMessageProcessor {
let CommandExecParams {
command,
environment_id,
process_id,
tty,
stream_stdin,
@@ -1566,6 +1568,24 @@ impl CodexMessageProcessor {
size,
sandbox_policy,
} = params;
let configured_environment_id = Environment::default_environment_id(
self.config.experimental_exec_server_url.as_deref(),
);
let environment_id = match environment_id {
Some(environment_id) if environment_id != configured_environment_id => {
let error = JSONRPCErrorError {
code: INVALID_REQUEST_ERROR_CODE,
message: format!(
"unsupported environmentId `{environment_id}`; configured environment is `{configured_environment_id}`"
),
data: None,
};
self.outgoing.send_error(request, error).await;
return;
}
Some(environment_id) => environment_id,
None => configured_environment_id,
};
if size.is_some() && !tty {
let error = JSONRPCErrorError {
@@ -1751,6 +1771,7 @@ impl CodexMessageProcessor {
.start(StartCommandExecParams {
outgoing,
request_id: request_for_task,
environment_id,
process_id,
exec_request,
started_network_proxy: started_network_proxy_for_task,
@@ -1830,6 +1851,7 @@ impl CodexMessageProcessor {
let ThreadStartParams {
model,
model_provider,
environment_id,
service_tier,
cwd,
approval_policy,
@@ -1846,6 +1868,21 @@ impl CodexMessageProcessor {
ephemeral,
persist_extended_history,
} = params;
let configured_environment_id = Environment::default_environment_id(
self.config.experimental_exec_server_url.as_deref(),
);
if let Some(environment_id) = environment_id
&& environment_id != configured_environment_id
{
self.send_invalid_request_error(
request_id,
format!(
"unsupported environmentId `{environment_id}`; configured environment is `{configured_environment_id}`"
),
)
.await;
return;
}
let mut typesafe_overrides = self.build_thread_config_overrides(
model,
model_provider,
@@ -2077,6 +2114,7 @@ impl CodexMessageProcessor {
let response = ThreadStartResponse {
thread: thread.clone(),
environment_id: config_snapshot.environment_id,
model: config_snapshot.model,
model_provider: config_snapshot.model_provider_id,
service_tier: config_snapshot.service_tier,
@@ -3400,6 +3438,7 @@ impl CodexMessageProcessor {
let ThreadResumeParams {
thread_id,
environment_id,
history,
path,
model,
@@ -3415,6 +3454,21 @@ impl CodexMessageProcessor {
personality,
persist_extended_history,
} = params;
let configured_environment_id = Environment::default_environment_id(
self.config.experimental_exec_server_url.as_deref(),
);
if let Some(environment_id) = environment_id
&& environment_id != configured_environment_id
{
self.send_invalid_request_error(
request_id,
format!(
"unsupported environmentId `{environment_id}`; configured environment is `{configured_environment_id}`"
),
)
.await;
return;
}
let thread_history = if let Some(history) = history {
let Some(thread_history) = self
@@ -3549,9 +3603,9 @@ impl CodexMessageProcessor {
thread_status,
/*has_live_in_progress_turn*/ false,
);
let response = ThreadResumeResponse {
thread,
environment_id: configured_environment_id,
model: session_configured.model,
model_provider: session_configured.model_provider_id,
service_tier: session_configured.service_tier,
@@ -3902,6 +3956,7 @@ impl CodexMessageProcessor {
async fn thread_fork(&mut self, request_id: ConnectionRequestId, params: ThreadForkParams) {
let ThreadForkParams {
thread_id,
environment_id,
path,
model,
model_provider,
@@ -3916,6 +3971,21 @@ impl CodexMessageProcessor {
ephemeral,
persist_extended_history,
} = params;
let configured_environment_id = Environment::default_environment_id(
self.config.experimental_exec_server_url.as_deref(),
);
if let Some(environment_id) = environment_id
&& environment_id != configured_environment_id
{
self.send_invalid_request_error(
request_id,
format!(
"unsupported environmentId `{environment_id}`; configured environment is `{configured_environment_id}`"
),
)
.await;
return;
}
let (rollout_path, source_thread_id) = if let Some(path) = path {
(path, None)
@@ -4156,6 +4226,7 @@ impl CodexMessageProcessor {
let response = ThreadForkResponse {
thread: thread.clone(),
environment_id: configured_environment_id,
model: session_configured.model,
model_provider: session_configured.model_provider_id,
service_tier: session_configured.service_tier,
@@ -7309,6 +7380,7 @@ async fn handle_pending_thread_resume_request(
}
let ThreadConfigSnapshot {
environment_id,
model,
model_provider_id,
service_tier,
@@ -7321,6 +7393,7 @@ async fn handle_pending_thread_resume_request(
} = pending.config_snapshot;
let response = ThreadResumeResponse {
thread,
environment_id,
model,
model_provider: model_provider_id,
service_tier,
@@ -8419,6 +8492,7 @@ mod tests {
fn collect_resume_override_mismatches_includes_service_tier() {
let request = ThreadResumeParams {
thread_id: "thread-1".to_string(),
environment_id: None,
history: None,
path: None,
model: None,
@@ -8435,6 +8509,7 @@ mod tests {
persist_extended_history: false,
};
let config_snapshot = ThreadConfigSnapshot {
environment_id: "local".to_string(),
model: "gpt-5".to_string(),
model_provider_id: "openai".to_string(),
service_tier: Some(codex_protocol::config_types::ServiceTier::Flex),
+5 -1
View File
@@ -89,6 +89,7 @@ struct CommandControlRequest {
pub(crate) struct StartCommandExecParams {
pub(crate) outgoing: Arc<OutgoingMessageSender>,
pub(crate) request_id: ConnectionRequestId,
pub(crate) environment_id: String,
pub(crate) process_id: Option<String>,
pub(crate) exec_request: ExecRequest,
pub(crate) started_network_proxy: Option<StartedNetworkProxy>,
@@ -149,6 +150,7 @@ impl CommandExecManager {
let StartCommandExecParams {
outgoing,
request_id,
environment_id,
process_id,
exec_request,
started_network_proxy,
@@ -158,7 +160,6 @@ impl CommandExecManager {
output_bytes_cap,
size,
} = params;
let environment_id = environment_id_from_cwd(exec_request.cwd.as_path());
if process_id.is_none() && (tty || stream_stdin || stream_stdout_stderr) {
return Err(invalid_request(
"command/exec tty or streaming requires a client-supplied processId".to_string(),
@@ -801,6 +802,7 @@ mod tests {
connection_id: ConnectionId(1),
request_id: codex_app_server_protocol::RequestId::Integer(42),
},
environment_id: "test-env".to_string(),
process_id: Some("proc-42".to_string()),
exec_request: windows_sandbox_exec_request(),
started_network_proxy: None,
@@ -834,6 +836,7 @@ mod tests {
.start(StartCommandExecParams {
outgoing: Arc::new(OutgoingMessageSender::new(tx)),
request_id: request_id.clone(),
environment_id: "test-env".to_string(),
process_id: Some("proc-99".to_string()),
exec_request: windows_sandbox_exec_request(),
started_network_proxy: None,
@@ -883,6 +886,7 @@ mod tests {
.start(StartCommandExecParams {
outgoing: Arc::new(OutgoingMessageSender::new(tx)),
request_id: request_id.clone(),
environment_id: "test-env".to_string(),
process_id: Some("proc-100".to_string()),
exec_request: ExecRequest {
command: vec!["sh".to_string(), "-lc".to_string(), "sleep 30".to_string()],
+8 -8
View File
@@ -54,7 +54,7 @@ impl FsApi {
) -> Result<FsReadFileResponse, JSONRPCErrorError> {
tracing::debug!(
environment_id = %self.environment_id,
path = %params.path,
path = ?params.path,
"fs/readFile"
);
let bytes = self
@@ -73,7 +73,7 @@ impl FsApi {
) -> Result<FsWriteFileResponse, JSONRPCErrorError> {
tracing::debug!(
environment_id = %self.environment_id,
path = %params.path,
path = ?params.path,
"fs/writeFile"
);
let bytes = STANDARD.decode(params.data_base64).map_err(|err| {
@@ -94,7 +94,7 @@ impl FsApi {
) -> Result<FsCreateDirectoryResponse, JSONRPCErrorError> {
tracing::debug!(
environment_id = %self.environment_id,
path = %params.path,
path = ?params.path,
"fs/createDirectory"
);
self.file_system
@@ -115,7 +115,7 @@ impl FsApi {
) -> Result<FsGetMetadataResponse, JSONRPCErrorError> {
tracing::debug!(
environment_id = %self.environment_id,
path = %params.path,
path = ?params.path,
"fs/getMetadata"
);
let metadata = self
@@ -137,7 +137,7 @@ impl FsApi {
) -> Result<FsReadDirectoryResponse, JSONRPCErrorError> {
tracing::debug!(
environment_id = %self.environment_id,
path = %params.path,
path = ?params.path,
"fs/readDirectory"
);
let entries = self
@@ -163,7 +163,7 @@ impl FsApi {
) -> Result<FsRemoveResponse, JSONRPCErrorError> {
tracing::debug!(
environment_id = %self.environment_id,
path = %params.path,
path = ?params.path,
"fs/remove"
);
self.file_system
@@ -185,8 +185,8 @@ impl FsApi {
) -> Result<FsCopyResponse, JSONRPCErrorError> {
tracing::debug!(
environment_id = %self.environment_id,
source_path = %params.source_path,
destination_path = %params.destination_path,
source_path = ?params.source_path,
destination_path = ?params.destination_path,
"fs/copy"
);
self.file_system
+1
View File
@@ -814,6 +814,7 @@ mod tests {
.request(ClientRequest::ThreadStart {
request_id: RequestId::Integer(2),
params: ThreadStartParams {
environment_id: None,
ephemeral: Some(true),
..ThreadStartParams::default()
},
+1 -1
View File
@@ -63,8 +63,8 @@ use codex_core::default_client::get_codex_user_agent;
use codex_core::default_client::set_default_client_residency_requirement;
use codex_core::default_client::set_default_originator;
use codex_core::models_manager::collaboration_mode_presets::CollaborationModesConfig;
use codex_feedback::CodexFeedback;
use codex_exec_server::Environment;
use codex_feedback::CodexFeedback;
use codex_protocol::ThreadId;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::W3cTraceContext;
@@ -195,6 +195,7 @@ impl TracingHarness {
ClientRequest::ThreadStart {
request_id: RequestId::Integer(request_id),
params: ThreadStartParams {
environment_id: None,
ephemeral: Some(true),
..ThreadStartParams::default()
},
@@ -401,6 +401,7 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(codex_app_server_protocol::ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -507,6 +508,7 @@ async fn external_auth_refresh_error_fails_turn() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(codex_app_server_protocol::ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -629,6 +631,7 @@ async fn external_auth_refresh_mismatched_workspace_fails_turn() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(codex_app_server_protocol::ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -744,6 +747,7 @@ async fn external_auth_refresh_invalid_access_token_fails_turn() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(codex_app_server_protocol::ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -45,6 +45,7 @@ async fn command_exec_without_streams_can_be_terminated() -> Result<()> {
let command_request_id = mcp
.send_command_exec_request(CommandExecParams {
command: vec!["sh".to_string(), "-lc".to_string(), "sleep 30".to_string()],
environment_id: None,
process_id: Some(process_id.clone()),
tty: false,
stream_stdin: false,
@@ -97,6 +98,7 @@ async fn command_exec_without_process_id_keeps_buffered_compatibility() -> Resul
"-lc".to_string(),
"printf 'legacy-out'; printf 'legacy-err' >&2".to_string(),
],
environment_id: None,
process_id: None,
tty: false,
stream_stdin: false,
@@ -148,6 +150,7 @@ async fn command_exec_env_overrides_merge_with_server_environment_and_support_un
"-lc".to_string(),
"printf '%s|%s|%s|%s' \"$COMMAND_EXEC_BASELINE\" \"$COMMAND_EXEC_EXTRA\" \"${RUST_LOG-unset}\" \"$CODEX_HOME\"".to_string(),
],
environment_id: None,
process_id: None,
tty: false,
stream_stdin: false,
@@ -197,6 +200,7 @@ async fn command_exec_rejects_disable_timeout_with_timeout_ms() -> Result<()> {
let command_request_id = mcp
.send_command_exec_request(CommandExecParams {
command: vec!["sh".to_string(), "-lc".to_string(), "sleep 1".to_string()],
environment_id: None,
process_id: Some("invalid-timeout-1".to_string()),
tty: false,
stream_stdin: false,
@@ -234,6 +238,7 @@ async fn command_exec_rejects_disable_output_cap_with_output_bytes_cap() -> Resu
let command_request_id = mcp
.send_command_exec_request(CommandExecParams {
command: vec!["sh".to_string(), "-lc".to_string(), "sleep 1".to_string()],
environment_id: None,
process_id: Some("invalid-cap-1".to_string()),
tty: false,
stream_stdin: false,
@@ -271,6 +276,7 @@ async fn command_exec_rejects_negative_timeout_ms() -> Result<()> {
let command_request_id = mcp
.send_command_exec_request(CommandExecParams {
command: vec!["sh".to_string(), "-lc".to_string(), "sleep 1".to_string()],
environment_id: None,
process_id: Some("negative-timeout-1".to_string()),
tty: false,
stream_stdin: false,
@@ -308,6 +314,7 @@ async fn command_exec_without_process_id_rejects_streaming() -> Result<()> {
let command_request_id = mcp
.send_command_exec_request(CommandExecParams {
command: vec!["sh".to_string(), "-lc".to_string(), "cat".to_string()],
environment_id: None,
process_id: None,
tty: false,
stream_stdin: false,
@@ -349,6 +356,7 @@ async fn command_exec_non_streaming_respects_output_cap() -> Result<()> {
"-lc".to_string(),
"printf 'abcdef'; printf 'uvwxyz' >&2".to_string(),
],
environment_id: None,
process_id: Some("cap-1".to_string()),
tty: false,
stream_stdin: false,
@@ -396,6 +404,7 @@ async fn command_exec_streaming_does_not_buffer_output() -> Result<()> {
"-lc".to_string(),
"printf 'abcdefghij'; sleep 30".to_string(),
],
environment_id: None,
process_id: Some(process_id.clone()),
tty: false,
stream_stdin: false,
@@ -456,6 +465,7 @@ async fn command_exec_pipe_streams_output_and_accepts_write() -> Result<()> {
"-lc".to_string(),
"printf 'out-start\\n'; printf 'err-start\\n' >&2; IFS= read line; printf 'out:%s\\n' \"$line\"; printf 'err:%s\\n' \"$line\" >&2".to_string(),
],
environment_id: None,
process_id: Some(process_id.clone()),
tty: false,
stream_stdin: true,
@@ -547,6 +557,7 @@ async fn command_exec_tty_implies_streaming_and_reports_pty_output() -> Result<(
"-lc".to_string(),
"stty -echo; if [ -t 0 ]; then printf 'tty\\n'; else printf 'notty\\n'; fi; IFS= read line; printf 'echo:%s\\n' \"$line\"".to_string(),
],
environment_id: None,
process_id: Some(process_id.clone()),
tty: true,
stream_stdin: false,
@@ -625,6 +636,7 @@ async fn command_exec_tty_supports_initial_size_and_resize() -> Result<()> {
"-lc".to_string(),
"stty -echo; printf 'start:%s\\n' \"$(stty size)\"; IFS= read _line; printf 'after:%s\\n' \"$(stty size)\"".to_string(),
],
environment_id: None,
process_id: Some(process_id.clone()),
tty: true,
stream_stdin: false,
@@ -321,6 +321,7 @@ async fn thread_compact_start_rejects_unknown_thread_id() -> Result<()> {
async fn start_thread(mcp: &mut McpProcess) -> Result<String> {
let thread_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -184,6 +184,7 @@ async fn send_thread_start_request(stream: &mut WsClient, id: i64) -> Result<()>
"thread/start",
id,
Some(serde_json::to_value(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})?),
@@ -67,6 +67,7 @@ async fn thread_start_injects_dynamic_tools_into_model_requests() -> Result<()>
// Thread start injects dynamic tools into the thread's tool registry.
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
dynamic_tools: Some(vec![dynamic_tool.clone()]),
..Default::default()
})
@@ -146,6 +147,7 @@ async fn thread_start_keeps_hidden_dynamic_tools_out_of_model_requests() -> Resu
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
dynamic_tools: Some(vec![dynamic_tool.clone()]),
..Default::default()
})
@@ -232,6 +234,7 @@ async fn dynamic_tool_call_round_trip_sends_text_content_items_to_model() -> Res
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
dynamic_tools: Some(vec![dynamic_tool]),
..Default::default()
})
@@ -401,6 +404,7 @@ async fn dynamic_tool_call_round_trip_sends_content_items_to_model() -> Result<(
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
dynamic_tools: Some(vec![dynamic_tool]),
..Default::default()
})
@@ -108,6 +108,7 @@ async fn thread_start_mock_field_requires_experimental_api_capability() -> Resul
let request_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
mock_experimental_field: Some("mock".to_string()),
..Default::default()
})
@@ -145,6 +146,7 @@ async fn thread_start_without_dynamic_tools_allows_without_experimental_api_capa
let request_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -181,6 +183,7 @@ async fn thread_start_granular_approval_policy_requires_experimental_api_capabil
let request_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
approval_policy: Some(AskForApproval::Granular {
sandbox_approval: true,
rules: false,
@@ -118,6 +118,7 @@ async fn mcp_server_elicitation_round_trip() -> Result<()> {
let thread_start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -37,6 +37,7 @@ async fn turn_start_accepts_output_schema_v2() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
..Default::default()
})
.await?;
@@ -119,6 +120,7 @@ async fn turn_start_output_schema_is_per_turn_v2() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
..Default::default()
})
.await?;
@@ -130,6 +130,7 @@ async fn plan_mode_without_proposed_plan_does_not_emit_plan_item() -> Result<()>
async fn start_plan_mode_turn(mcp: &mut McpProcess) -> Result<codex_app_server_protocol::Turn> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -35,6 +35,7 @@ async fn request_permissions_round_trip() -> Result<()> {
let thread_start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -37,6 +37,7 @@ async fn request_user_input_round_trip() -> Result<()> {
let thread_start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -408,6 +408,7 @@ async fn review_start_rejects_empty_custom_instructions() -> Result<()> {
async fn start_default_thread(mcp: &mut McpProcess) -> Result<String> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -45,6 +45,7 @@ async fn openai_model_header_mismatch_emits_model_rerouted_notification_v2() ->
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some(REQUESTED_MODEL.to_string()),
..Default::default()
})
@@ -118,6 +119,7 @@ async fn response_model_field_mismatch_emits_model_rerouted_notification_v2_when
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some(REQUESTED_MODEL.to_string()),
..Default::default()
})
@@ -228,6 +228,7 @@ async fn skills_changed_notification_is_emitted_after_skill_change() -> Result<(
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let thread_start_request_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: None,
model_provider: None,
service_tier: None,
@@ -39,6 +39,7 @@ async fn thread_archive_requires_materialized_rollout() -> Result<()> {
// Start a thread.
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -171,6 +172,7 @@ async fn thread_archive_clears_stale_subscriptions_before_resume() -> Result<()>
let start_id = primary
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -245,6 +247,7 @@ async fn thread_archive_clears_stale_subscriptions_before_resume() -> Result<()>
let resume_id = secondary
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: thread.id.clone(),
..Default::default()
})
@@ -77,6 +77,7 @@ async fn thread_fork_creates_new_thread_and_emits_started() -> Result<()> {
let fork_id = mcp
.send_thread_fork_request(ThreadForkParams {
environment_id: None,
thread_id: conversation_id.clone(),
..Default::default()
})
@@ -188,6 +189,7 @@ async fn thread_fork_rejects_unmaterialized_thread() -> Result<()> {
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -201,6 +203,7 @@ async fn thread_fork_rejects_unmaterialized_thread() -> Result<()> {
let fork_id = mcp
.send_thread_fork_request(ThreadForkParams {
environment_id: None,
thread_id: thread.id,
..Default::default()
})
@@ -286,6 +289,7 @@ async fn thread_fork_surfaces_cloud_requirements_load_errors() -> Result<()> {
let fork_id = mcp
.send_thread_fork_request(ThreadForkParams {
environment_id: None,
thread_id: conversation_id,
..Default::default()
})
@@ -339,6 +343,7 @@ async fn thread_fork_ephemeral_remains_pathless_and_omits_listing() -> Result<()
let fork_id = mcp
.send_thread_fork_request(ThreadForkParams {
environment_id: None,
thread_id: conversation_id.clone(),
ephemeral: true,
..Default::default()
@@ -198,6 +198,7 @@ async fn thread_list_reports_system_error_idle_flag_after_failed_turn() -> Resul
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -125,6 +125,7 @@ stream_max_retries = 0
async fn start_thread(mcp: &mut McpProcess) -> Result<String> {
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.1".to_string()),
..Default::default()
})
@@ -44,6 +44,7 @@ async fn thread_metadata_update_patches_git_branch_and_returns_updated_thread()
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -134,6 +135,7 @@ async fn thread_metadata_update_rejects_empty_git_info_patch() -> Result<()> {
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -256,6 +258,7 @@ async fn thread_metadata_update_repairs_loaded_thread_without_resetting_summary(
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: thread_id.clone(),
..Default::default()
})
@@ -45,6 +45,7 @@ async fn thread_name_updated_broadcasts_for_loaded_threads() -> Result<()> {
"thread/resume",
10,
Some(serde_json::to_value(ThreadResumeParams {
environment_id: None,
thread_id: conversation_id.clone(),
..Default::default()
})?),
@@ -163,6 +163,7 @@ async fn thread_read_loaded_thread_returns_precomputed_path_before_materializati
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -323,6 +324,7 @@ async fn thread_name_set_is_reflected_in_read_list_and_resume() -> Result<()> {
// Resume should also surface the name.
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: conversation_id.clone(),
..Default::default()
})
@@ -367,6 +369,7 @@ async fn thread_read_include_turns_rejects_unmaterialized_loaded_thread() -> Res
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -423,6 +426,7 @@ async fn thread_read_reports_system_error_idle_flag_after_failed_turn() -> Resul
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -115,6 +115,7 @@ async fn thread_resume_rejects_unmaterialized_thread() -> Result<()> {
// Start a thread.
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.1-codex-max".to_string()),
..Default::default()
})
@@ -129,6 +130,7 @@ async fn thread_resume_rejects_unmaterialized_thread() -> Result<()> {
// Resume should fail before the first user message materializes rollout storage.
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: thread.id.clone(),
..Default::default()
})
@@ -179,6 +181,7 @@ async fn thread_resume_returns_rollout_history() -> Result<()> {
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: conversation_id.clone(),
..Default::default()
})
@@ -390,6 +393,7 @@ stream_max_retries = 0
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id,
..Default::default()
})
@@ -466,6 +470,7 @@ async fn thread_resume_and_read_interrupt_incomplete_rollout_turn_when_thread_is
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: conversation_id,
..Default::default()
})
@@ -485,6 +490,7 @@ async fn thread_resume_and_read_interrupt_incomplete_rollout_turn_when_thread_is
let second_resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: thread.id.clone(),
..Default::default()
})
@@ -539,6 +545,7 @@ async fn thread_resume_without_overrides_does_not_change_updated_at_or_mtime() -
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: thread_id.clone(),
..Default::default()
})
@@ -594,6 +601,7 @@ async fn thread_resume_keeps_in_flight_turn_streaming() -> Result<()> {
let start_id = primary
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.1-codex-max".to_string()),
..Default::default()
})
@@ -653,6 +661,7 @@ async fn thread_resume_keeps_in_flight_turn_streaming() -> Result<()> {
let resume_id = secondary
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: thread.id,
..Default::default()
})
@@ -701,6 +710,7 @@ async fn thread_resume_rejects_history_when_thread_is_running() -> Result<()> {
let start_id = primary
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.1-codex-max".to_string()),
..Default::default()
})
@@ -760,6 +770,7 @@ async fn thread_resume_rejects_history_when_thread_is_running() -> Result<()> {
let resume_id = primary
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: thread_id.clone(),
history: Some(vec![ResponseItem::Message {
id: None,
@@ -817,6 +828,7 @@ async fn thread_resume_rejects_mismatched_path_when_thread_is_running() -> Resul
let start_id = primary
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.1-codex-max".to_string()),
..Default::default()
})
@@ -876,6 +888,7 @@ async fn thread_resume_rejects_mismatched_path_when_thread_is_running() -> Resul
let resume_id = primary
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: thread_id.clone(),
path: Some(PathBuf::from("/tmp/does-not-match-running-rollout.jsonl")),
..Default::default()
@@ -923,6 +936,7 @@ async fn thread_resume_rejoins_running_thread_even_with_override_mismatch() -> R
let start_id = primary
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.1-codex-max".to_string()),
..Default::default()
})
@@ -979,6 +993,7 @@ async fn thread_resume_rejoins_running_thread_even_with_override_mismatch() -> R
let resume_id = primary
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: thread.id.clone(),
model: Some("not-the-running-model".to_string()),
cwd: Some("/tmp".to_string()),
@@ -1036,6 +1051,7 @@ async fn thread_resume_replays_pending_command_execution_request_approval() -> R
let start_id = primary
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.1-codex-max".to_string()),
..Default::default()
})
@@ -1097,6 +1113,7 @@ async fn thread_resume_replays_pending_command_execution_request_approval() -> R
let resume_id = primary
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: thread.id.clone(),
..Default::default()
})
@@ -1173,6 +1190,7 @@ async fn thread_resume_replays_pending_file_change_request_approval() -> Result<
let start_id = primary
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.1-codex-max".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -1263,6 +1281,7 @@ async fn thread_resume_replays_pending_file_change_request_approval() -> Result<
let resume_id = primary
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: thread.id.clone(),
..Default::default()
})
@@ -1333,6 +1352,7 @@ async fn thread_resume_with_overrides_defers_updated_at_until_turn_start() -> Re
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id,
model: Some("mock-model".to_string()),
..Default::default()
@@ -1393,6 +1413,7 @@ async fn thread_resume_fails_when_required_mcp_server_fails_to_initialize() -> R
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: rollout.conversation_id,
..Default::default()
})
@@ -1482,6 +1503,7 @@ async fn thread_resume_surfaces_cloud_requirements_load_errors() -> Result<()> {
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: conversation_id,
..Default::default()
})
@@ -1522,6 +1544,7 @@ async fn thread_resume_prefers_path_over_thread_id() -> Result<()> {
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.1-codex-max".to_string()),
..Default::default()
})
@@ -1557,6 +1580,7 @@ async fn thread_resume_prefers_path_over_thread_id() -> Result<()> {
let thread_path = thread.path.clone().expect("thread path");
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: "not-a-valid-thread-id".to_string(),
path: Some(thread_path),
..Default::default()
@@ -1602,6 +1626,7 @@ async fn thread_resume_supports_history_and_overrides() -> Result<()> {
// Resume with explicit history and override the model.
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id,
history: Some(history),
model: Some("mock-model".to_string()),
@@ -1642,6 +1667,7 @@ async fn start_materialized_thread_and_restart(
let start_id = first_mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.1-codex-max".to_string()),
..Default::default()
})
@@ -1716,6 +1742,7 @@ async fn thread_resume_accepts_personality_override() -> Result<()> {
let start_id = primary
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.2-codex".to_string()),
..Default::default()
})
@@ -1753,6 +1780,7 @@ async fn thread_resume_accepts_personality_override() -> Result<()> {
let resume_id = secondary
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: thread.id,
model: Some("gpt-5.2-codex".to_string()),
personality: Some(Personality::Friendly),
@@ -41,6 +41,7 @@ async fn thread_rollback_drops_last_turns_and_persists_to_rollout() -> Result<()
// Start a thread.
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -144,6 +145,7 @@ async fn thread_rollback_drops_last_turns_and_persists_to_rollout() -> Result<()
// Resume and confirm the history is pruned.
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id: thread.id,
..Default::default()
})
@@ -57,6 +57,7 @@ async fn thread_shell_command_runs_as_standalone_turn_and_persists_history() ->
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
persist_extended_history: true,
..Default::default()
})
@@ -186,6 +187,7 @@ async fn thread_shell_command_uses_existing_active_turn() -> Result<()> {
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
persist_extended_history: true,
..Default::default()
})
@@ -48,6 +48,7 @@ async fn thread_start_creates_thread_and_emits_started() -> Result<()> {
// Start a v2 thread with an explicit model override.
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.1".to_string()),
..Default::default()
})
@@ -173,6 +174,7 @@ model_reasoning_effort = "high"
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
cwd: Some(workspace.path().to_string_lossy().into_owned()),
..Default::default()
})
@@ -203,6 +205,7 @@ async fn thread_start_accepts_flex_service_tier() -> Result<()> {
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
service_tier: Some(Some(ServiceTier::Flex)),
..Default::default()
})
@@ -231,6 +234,7 @@ async fn thread_start_accepts_metrics_service_name() -> Result<()> {
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
service_name: Some("my_app_server_client".to_string()),
..Default::default()
})
@@ -258,6 +262,7 @@ async fn thread_start_ephemeral_remains_pathless() -> Result<()> {
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.1".to_string()),
ephemeral: Some(true),
..Default::default()
@@ -34,6 +34,7 @@ async fn thread_status_changed_emits_runtime_updates() -> Result<()> {
let thread_start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -156,6 +157,7 @@ async fn thread_status_changed_can_be_opted_out() -> Result<()> {
let thread_start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -40,6 +40,7 @@ async fn thread_unarchive_moves_rollout_back_into_sessions_directory() -> Result
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -299,6 +299,7 @@ async fn thread_unsubscribe_clears_cached_status_before_resume() -> Result<()> {
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
environment_id: None,
thread_id,
..Default::default()
})
@@ -425,6 +426,7 @@ stream_max_retries = 0
async fn start_thread(mcp: &mut McpProcess) -> Result<String> {
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -58,6 +58,7 @@ async fn turn_interrupt_aborts_running_turn() -> Result<()> {
// Start a v2 thread and capture its id.
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -153,6 +154,7 @@ async fn turn_interrupt_resolves_pending_command_approval_request() -> Result<()
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -103,6 +103,7 @@ async fn turn_start_sends_originator_header() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -170,6 +171,7 @@ async fn turn_start_emits_user_message_item_with_text_elements() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -256,6 +258,7 @@ async fn turn_start_accepts_text_at_limit_with_mention_item() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -315,6 +318,7 @@ async fn turn_start_rejects_combined_oversized_text_input() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -400,6 +404,7 @@ async fn turn_start_emits_notifications_and_accepts_model_override() -> Result<(
// Start a thread (v2) and capture its id.
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -534,6 +539,7 @@ async fn turn_start_accepts_collaboration_mode_override_v2() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.2-codex".to_string()),
..Default::default()
})
@@ -617,6 +623,7 @@ async fn turn_start_uses_thread_feature_overrides_for_collaboration_mode_instruc
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.2-codex".to_string()),
config: Some(HashMap::from([(
"features.default_mode_request_user_input".to_string(),
@@ -701,6 +708,7 @@ async fn turn_start_accepts_personality_override_v2() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("exp-codex-personality".to_string()),
..Default::default()
})
@@ -782,6 +790,7 @@ async fn turn_start_change_personality_mid_thread_v2() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("exp-codex-personality".to_string()),
..Default::default()
})
@@ -908,6 +917,7 @@ async fn turn_start_uses_migrated_pragmatic_personality_without_override_v2() ->
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.2-codex".to_string()),
..Default::default()
})
@@ -977,6 +987,7 @@ async fn turn_start_accepts_local_image_input() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -1063,6 +1074,7 @@ async fn turn_start_exec_approval_toggle_v2() -> Result<()> {
// thread/start
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -1205,6 +1217,7 @@ async fn turn_start_exec_approval_decline_v2() -> Result<()> {
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -1358,6 +1371,7 @@ async fn turn_start_updates_sandbox_and_cwd_between_turns_v2() -> Result<()> {
// thread/start
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -1507,6 +1521,7 @@ async fn turn_start_file_change_approval_v2() -> Result<()> {
let start_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -1726,6 +1741,7 @@ async fn turn_start_emits_spawn_agent_item_with_model_metadata_v2() -> Result<()
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.2-codex".to_string()),
..Default::default()
})
@@ -1940,6 +1956,7 @@ config_file = "./custom-role.toml"
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("gpt-5.2-codex".to_string()),
..Default::default()
})
@@ -2083,6 +2100,7 @@ async fn turn_start_file_change_approval_accept_for_session_persists_v2() -> Res
let start_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -2264,6 +2282,7 @@ async fn turn_start_file_change_approval_decline_v2() -> Result<()> {
let start_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -2410,6 +2429,7 @@ async fn command_execution_notifications_include_process_id() -> Result<()> {
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -102,6 +102,7 @@ async fn turn_start_shell_zsh_fork_executes_command_v2() -> Result<()> {
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -221,6 +222,7 @@ async fn turn_start_shell_zsh_fork_exec_approval_decline_v2() -> Result<()> {
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -354,6 +356,7 @@ async fn turn_start_shell_zsh_fork_exec_approval_cancel_v2() -> Result<()> {
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -513,6 +516,7 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2()
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
@@ -39,6 +39,7 @@ async fn turn_steer_requires_active_turn() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -102,6 +103,7 @@ async fn turn_steer_rejects_oversized_text_input() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
@@ -205,6 +207,7 @@ async fn turn_steer_returns_active_turn_id() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
environment_id: None,
model: Some("mock-model".to_string()),
..Default::default()
})
+9 -2
View File
@@ -722,7 +722,13 @@ impl Codex {
pub(crate) async fn thread_config_snapshot(&self) -> ThreadConfigSnapshot {
let state = self.session.state.lock().await;
state.session_configuration.thread_config_snapshot()
state.session_configuration.thread_config_snapshot(
self.session
.services
.environment
.environment_id()
.to_string(),
)
}
pub(crate) fn state_db(&self) -> Option<state_db::StateDbHandle> {
@@ -1063,8 +1069,9 @@ impl SessionConfiguration {
&self.codex_home
}
fn thread_config_snapshot(&self) -> ThreadConfigSnapshot {
fn thread_config_snapshot(&self, environment_id: String) -> ThreadConfigSnapshot {
ThreadConfigSnapshot {
environment_id,
model: self.collaboration_mode.model().to_string(),
model_provider_id: self.original_config_do_not_use.model_provider_id.clone(),
service_tier: self.service_tier,
+1
View File
@@ -30,6 +30,7 @@ use crate::state_db::StateDbHandle;
#[derive(Clone, Debug)]
pub struct ThreadConfigSnapshot {
pub environment_id: String,
pub model: String,
pub model_provider_id: String,
pub service_tier: Option<ServiceTier>,
+2
View File
@@ -385,6 +385,7 @@ pub fn build_thread_start_params(
cwd: Option<String>,
) -> ThreadStartParams {
ThreadStartParams {
environment_id: None,
model,
model_provider,
cwd,
@@ -402,6 +403,7 @@ pub fn build_thread_resume_params(
cwd: Option<String>,
) -> ThreadResumeParams {
ThreadResumeParams {
environment_id: None,
thread_id,
model,
model_provider,
+64
View File
@@ -25,16 +25,31 @@ use tracing::warn;
use crate::connection::JsonRpcConnection;
use crate::process::ExecServerEvent;
use crate::protocol::ENVIRONMENT_CAPABILITIES_METHOD;
use crate::protocol::ENVIRONMENT_GET_METHOD;
use crate::protocol::ENVIRONMENT_LIST_METHOD;
use crate::protocol::EXEC_EXITED_METHOD;
use crate::protocol::EXEC_METHOD;
use crate::protocol::EXEC_OUTPUT_DELTA_METHOD;
use crate::protocol::EXEC_READ_METHOD;
use crate::protocol::EXEC_RESIZE_METHOD;
use crate::protocol::EXEC_TERMINATE_METHOD;
use crate::protocol::EXEC_WAIT_METHOD;
use crate::protocol::EXEC_WRITE_METHOD;
use crate::protocol::EnvironmentCapabilitiesParams;
use crate::protocol::EnvironmentCapabilitiesResponse;
use crate::protocol::EnvironmentGetParams;
use crate::protocol::EnvironmentGetResponse;
use crate::protocol::EnvironmentListParams;
use crate::protocol::EnvironmentListResponse;
use crate::protocol::ExecExitedNotification;
use crate::protocol::ExecOutputDeltaNotification;
use crate::protocol::ExecParams;
use crate::protocol::ExecResizeParams;
use crate::protocol::ExecResizeResponse;
use crate::protocol::ExecResponse;
use crate::protocol::ExecWaitParams;
use crate::protocol::ExecWaitResponse;
use crate::protocol::FS_COPY_METHOD;
use crate::protocol::FS_CREATE_DIRECTORY_METHOD;
use crate::protocol::FS_GET_METADATA_METHOD;
@@ -245,6 +260,55 @@ impl ExecServerClient {
.map_err(Into::into)
}
pub async fn resize(
&self,
params: ExecResizeParams,
) -> Result<ExecResizeResponse, ExecServerError> {
self.inner
.client
.call(EXEC_RESIZE_METHOD, &params)
.await
.map_err(Into::into)
}
pub async fn wait(&self, params: ExecWaitParams) -> Result<ExecWaitResponse, ExecServerError> {
self.inner
.client
.call(EXEC_WAIT_METHOD, &params)
.await
.map_err(Into::into)
}
pub async fn environment_list(&self) -> Result<EnvironmentListResponse, ExecServerError> {
self.inner
.client
.call(ENVIRONMENT_LIST_METHOD, &EnvironmentListParams::default())
.await
.map_err(Into::into)
}
pub async fn environment_get(
&self,
params: EnvironmentGetParams,
) -> Result<EnvironmentGetResponse, ExecServerError> {
self.inner
.client
.call(ENVIRONMENT_GET_METHOD, &params)
.await
.map_err(Into::into)
}
pub async fn environment_capabilities(
&self,
params: EnvironmentCapabilitiesParams,
) -> Result<EnvironmentCapabilitiesResponse, ExecServerError> {
self.inner
.client
.call(ENVIRONMENT_CAPABILITIES_METHOD, &params)
.await
.map_err(Into::into)
}
pub async fn fs_read_file(
&self,
params: FsReadFileParams,
+316 -15
View File
@@ -1,5 +1,9 @@
use std::sync::Arc;
use async_trait::async_trait;
use base64::Engine as _;
use codex_utils_absolute_path::AbsolutePathBuf;
use crate::ExecServerClient;
use crate::ExecServerError;
use crate::RemoteExecServerConnectArgs;
@@ -7,8 +11,196 @@ use crate::fs;
use crate::fs::ExecutorFileSystem;
use crate::local_process::LocalProcess;
use crate::process::ExecProcess;
use crate::protocol::EnvironmentCapabilities;
use crate::protocol::EnvironmentCapabilitiesParams;
use crate::protocol::EnvironmentGetParams;
use crate::protocol::EnvironmentGetResponse;
use crate::protocol::EnvironmentInfo;
use crate::protocol::EnvironmentListResponse;
use crate::remote_process::RemoteProcess;
#[derive(Clone)]
struct EnvironmentFileSystem {
filesystem: Arc<dyn ExecutorFileSystem>,
}
#[async_trait]
impl ExecutorFileSystem for EnvironmentFileSystem {
async fn read_file(&self, path: &AbsolutePathBuf) -> crate::fs::FileSystemResult<Vec<u8>> {
self.filesystem.read_file(path).await
}
async fn write_file(
&self,
path: &AbsolutePathBuf,
contents: Vec<u8>,
) -> crate::fs::FileSystemResult<()> {
self.filesystem.write_file(path, contents).await
}
async fn create_directory(
&self,
path: &AbsolutePathBuf,
options: crate::fs::CreateDirectoryOptions,
) -> crate::fs::FileSystemResult<()> {
self.filesystem.create_directory(path, options).await
}
async fn get_metadata(
&self,
path: &AbsolutePathBuf,
) -> crate::fs::FileSystemResult<crate::fs::FileMetadata> {
self.filesystem.get_metadata(path).await
}
async fn read_directory(
&self,
path: &AbsolutePathBuf,
) -> crate::fs::FileSystemResult<Vec<crate::fs::ReadDirectoryEntry>> {
self.filesystem.read_directory(path).await
}
async fn remove(
&self,
path: &AbsolutePathBuf,
options: crate::fs::RemoveOptions,
) -> crate::fs::FileSystemResult<()> {
self.filesystem.remove(path, options).await
}
async fn copy(
&self,
source_path: &AbsolutePathBuf,
destination_path: &AbsolutePathBuf,
options: crate::fs::CopyOptions,
) -> crate::fs::FileSystemResult<()> {
self.filesystem
.copy(source_path, destination_path, options)
.await
}
}
#[derive(Clone)]
struct RemoteEnvironmentFileSystem {
client: ExecServerClient,
}
#[async_trait]
impl ExecutorFileSystem for RemoteEnvironmentFileSystem {
async fn read_file(&self, path: &AbsolutePathBuf) -> crate::fs::FileSystemResult<Vec<u8>> {
let response = self
.client
.fs_read_file(codex_app_server_protocol::FsReadFileParams { path: path.clone() })
.await
.map_err(exec_server_error_to_io)?;
base64::engine::general_purpose::STANDARD
.decode(response.data_base64)
.map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))
}
async fn write_file(
&self,
path: &AbsolutePathBuf,
contents: Vec<u8>,
) -> crate::fs::FileSystemResult<()> {
self.client
.fs_write_file(codex_app_server_protocol::FsWriteFileParams {
path: path.clone(),
data_base64: base64::engine::general_purpose::STANDARD.encode(contents),
})
.await
.map_err(exec_server_error_to_io)?;
Ok(())
}
async fn create_directory(
&self,
path: &AbsolutePathBuf,
options: crate::fs::CreateDirectoryOptions,
) -> crate::fs::FileSystemResult<()> {
self.client
.fs_create_directory(codex_app_server_protocol::FsCreateDirectoryParams {
path: path.clone(),
recursive: Some(options.recursive),
})
.await
.map_err(exec_server_error_to_io)?;
Ok(())
}
async fn get_metadata(
&self,
path: &AbsolutePathBuf,
) -> crate::fs::FileSystemResult<crate::fs::FileMetadata> {
let response = self
.client
.fs_get_metadata(codex_app_server_protocol::FsGetMetadataParams { path: path.clone() })
.await
.map_err(exec_server_error_to_io)?;
Ok(crate::fs::FileMetadata {
is_directory: response.is_directory,
is_file: response.is_file,
created_at_ms: response.created_at_ms,
modified_at_ms: response.modified_at_ms,
})
}
async fn read_directory(
&self,
path: &AbsolutePathBuf,
) -> crate::fs::FileSystemResult<Vec<crate::fs::ReadDirectoryEntry>> {
let response = self
.client
.fs_read_directory(codex_app_server_protocol::FsReadDirectoryParams {
path: path.clone(),
})
.await
.map_err(exec_server_error_to_io)?;
Ok(response
.entries
.into_iter()
.map(|entry| crate::fs::ReadDirectoryEntry {
file_name: entry.file_name,
is_directory: entry.is_directory,
is_file: entry.is_file,
})
.collect())
}
async fn remove(
&self,
path: &AbsolutePathBuf,
options: crate::fs::RemoveOptions,
) -> crate::fs::FileSystemResult<()> {
self.client
.fs_remove(codex_app_server_protocol::FsRemoveParams {
path: path.clone(),
recursive: Some(options.recursive),
force: Some(options.force),
})
.await
.map_err(exec_server_error_to_io)?;
Ok(())
}
async fn copy(
&self,
source_path: &AbsolutePathBuf,
destination_path: &AbsolutePathBuf,
options: crate::fs::CopyOptions,
) -> crate::fs::FileSystemResult<()> {
self.client
.fs_copy(codex_app_server_protocol::FsCopyParams {
source_path: source_path.clone(),
destination_path: destination_path.clone(),
recursive: options.recursive,
})
.await
.map_err(exec_server_error_to_io)?;
Ok(())
}
}
pub trait ExecutorEnvironment: Send + Sync {
fn get_executor(&self) -> Arc<dyn ExecProcess>;
}
@@ -16,14 +208,20 @@ pub trait ExecutorEnvironment: Send + Sync {
#[derive(Clone)]
pub struct Environment {
experimental_exec_server_url: Option<String>,
environment_id: String,
capabilities: EnvironmentCapabilities,
executor: Arc<dyn ExecProcess>,
filesystem: Arc<dyn ExecutorFileSystem>,
}
impl Default for Environment {
fn default() -> Self {
Self {
experimental_exec_server_url: None,
environment_id: "local".to_string(),
capabilities: EnvironmentCapabilities::default(),
executor: Arc::new(LocalProcess::default()),
filesystem: Arc::new(fs::LocalFileSystem),
}
}
}
@@ -35,27 +233,42 @@ impl std::fmt::Debug for Environment {
"experimental_exec_server_url",
&self.experimental_exec_server_url,
)
.field(
"has_remote_exec_server_client",
&self.experimental_exec_server_url.is_some(),
)
.field("environment_id", &self.environment_id)
.field("capabilities", &self.capabilities)
.finish()
}
}
impl Environment {
pub fn default_environment_id(experimental_exec_server_url: Option<&str>) -> String {
experimental_exec_server_url.map_or_else(
|| "local".to_string(),
|websocket_url| format!("remote:{websocket_url}"),
)
}
pub async fn create(
experimental_exec_server_url: Option<String>,
) -> Result<Self, ExecServerError> {
let executor: Arc<dyn ExecProcess> =
let (environment_id, executor, filesystem, capabilities) =
if let Some(websocket_url) = experimental_exec_server_url.as_deref() {
Arc::new(RemoteProcess::new(
ExecServerClient::connect_websocket(RemoteExecServerConnectArgs::new(
websocket_url.to_string(),
"codex-core".to_string(),
))
.await?,
let client = ExecServerClient::connect_websocket(RemoteExecServerConnectArgs::new(
websocket_url.to_string(),
"codex-core".to_string(),
))
.await?;
let environment_id = Environment::default_environment_id(Some(websocket_url));
let capabilities = client
.environment_capabilities(EnvironmentCapabilitiesParams {
environment_id: environment_id.clone(),
})
.await
.map(|response| response.capabilities)
.unwrap_or_else(|_| EnvironmentCapabilities::default());
let executor = Arc::new(RemoteProcess::new(client.clone())) as Arc<dyn ExecProcess>;
let filesystem =
Arc::new(RemoteEnvironmentFileSystem { client }) as Arc<dyn ExecutorFileSystem>;
(environment_id, executor, filesystem, capabilities)
} else {
let process = LocalProcess::default();
process
@@ -65,12 +278,20 @@ impl Environment {
message: error.message,
})?;
process.initialized().map_err(ExecServerError::Protocol)?;
Arc::new(process)
(
Environment::default_environment_id(None),
Arc::new(process) as Arc<dyn ExecProcess>,
Arc::new(fs::LocalFileSystem) as Arc<dyn ExecutorFileSystem>,
EnvironmentCapabilities::default(),
)
};
Ok(Self {
experimental_exec_server_url,
environment_id,
capabilities,
executor,
filesystem,
})
}
@@ -78,30 +299,110 @@ impl Environment {
self.experimental_exec_server_url.as_deref()
}
pub fn environment_id(&self) -> &str {
&self.environment_id
}
pub fn capabilities(&self) -> &EnvironmentCapabilities {
&self.capabilities
}
pub fn info(&self) -> EnvironmentInfo {
EnvironmentInfo {
environment_id: self.environment_id.clone(),
experimental_exec_server_url: self.experimental_exec_server_url.clone(),
capabilities: self.capabilities.clone(),
}
}
pub fn list_response(&self) -> EnvironmentListResponse {
EnvironmentListResponse {
environments: vec![self.info()],
}
}
pub fn get_response(
&self,
params: EnvironmentGetParams,
) -> Result<EnvironmentGetResponse, ExecServerError> {
if params.environment_id != self.environment_id {
return Err(ExecServerError::Protocol(format!(
"unknown environment id `{}`",
params.environment_id
)));
}
Ok(EnvironmentGetResponse {
environment: self.info(),
})
}
pub fn get_executor(&self) -> Arc<dyn ExecProcess> {
Arc::clone(&self.executor)
}
pub fn get_filesystem(&self) -> impl ExecutorFileSystem + use<> {
fs::LocalFileSystem
EnvironmentFileSystem {
filesystem: Arc::clone(&self.filesystem),
}
}
}
fn exec_server_error_to_io(err: ExecServerError) -> std::io::Error {
std::io::Error::other(err.to_string())
}
impl ExecutorEnvironment for Environment {
fn get_executor(&self) -> Arc<dyn ExecProcess> {
self.get_executor()
Arc::clone(&self.executor)
}
}
#[cfg(test)]
mod tests {
use super::Environment;
use super::EnvironmentCapabilities;
use crate::fs::ExecutorFileSystem;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
#[tokio::test]
async fn create_without_remote_exec_server_url_does_not_connect() {
async fn default_environment_uses_local_identity_and_capabilities() {
let environment = Environment::default();
assert_eq!(environment.experimental_exec_server_url(), None);
assert_eq!(environment.environment_id(), "local");
assert_eq!(
environment.capabilities(),
&EnvironmentCapabilities::default()
);
}
#[tokio::test]
async fn create_without_remote_exec_server_url_uses_local_identity_and_capabilities() {
let environment = Environment::create(None).await.expect("create environment");
assert_eq!(environment.experimental_exec_server_url(), None);
assert_eq!(environment.environment_id(), "local");
assert_eq!(
environment.capabilities(),
&EnvironmentCapabilities::default()
);
}
#[tokio::test]
async fn default_environment_filesystem_delegates_to_local_filesystem() {
let temp_dir = tempdir().expect("temp dir");
let file_path = AbsolutePathBuf::try_from(temp_dir.path().join("example.txt"))
.expect("absolute file path");
std::fs::write(file_path.as_path(), b"delegated filesystem").expect("write sample file");
let bytes = Environment::default()
.get_filesystem()
.read_file(&file_path)
.await
.expect("read sample file");
assert_eq!(bytes, b"delegated filesystem");
}
}
+13
View File
@@ -40,11 +40,24 @@ pub use fs::ReadDirectoryEntry;
pub use fs::RemoveOptions;
pub use process::ExecProcess;
pub use process::ExecServerEvent;
pub use protocol::EnvironmentCapabilities;
pub use protocol::EnvironmentCapabilitiesParams;
pub use protocol::EnvironmentCapabilitiesResponse;
pub use protocol::EnvironmentGetParams;
pub use protocol::EnvironmentGetResponse;
pub use protocol::EnvironmentInfo;
pub use protocol::EnvironmentListParams;
pub use protocol::EnvironmentListResponse;
pub use protocol::ExecExitedNotification;
pub use protocol::ExecOutputDeltaNotification;
pub use protocol::ExecOutputStream;
pub use protocol::ExecParams;
pub use protocol::ExecResizeParams;
pub use protocol::ExecResizeResponse;
pub use protocol::ExecResponse;
pub use protocol::ExecTerminalSize;
pub use protocol::ExecWaitParams;
pub use protocol::ExecWaitResponse;
pub use protocol::InitializeParams;
pub use protocol::InitializeResponse;
pub use protocol::ReadParams;
+97
View File
@@ -22,7 +22,11 @@ use crate::protocol::ExecExitedNotification;
use crate::protocol::ExecOutputDeltaNotification;
use crate::protocol::ExecOutputStream;
use crate::protocol::ExecParams;
use crate::protocol::ExecResizeParams;
use crate::protocol::ExecResizeResponse;
use crate::protocol::ExecResponse;
use crate::protocol::ExecWaitParams;
use crate::protocol::ExecWaitResponse;
use crate::protocol::InitializeResponse;
use crate::protocol::ProcessOutputChunk;
use crate::protocol::ReadParams;
@@ -353,6 +357,88 @@ impl LocalProcess {
Ok(WriteResponse { accepted: true })
}
pub(crate) async fn resize_process(
&self,
params: ExecResizeParams,
) -> Result<ExecResizeResponse, JSONRPCErrorError> {
self.require_initialized_for("exec")?;
let size = TerminalSize {
rows: params.size.rows,
cols: params.size.cols,
};
{
let process_map = self.inner.processes.lock().await;
let process = process_map.get(&params.process_id).ok_or_else(|| {
invalid_request(format!("unknown process id {}", params.process_id))
})?;
let ProcessEntry::Running(process) = process else {
return Err(invalid_request(format!(
"process id {} is starting",
params.process_id
)));
};
if process.exit_code.is_some() {
return Err(invalid_request(format!(
"process id {} has already exited",
params.process_id
)));
}
if !process.tty {
return Err(invalid_request(format!(
"process id {} is not attached to a tty",
params.process_id
)));
}
process
.session
.resize(size)
.map_err(|err| internal_error(err.to_string()))?;
}
Ok(ExecResizeResponse {})
}
pub(crate) async fn wait_process(
&self,
params: ExecWaitParams,
) -> Result<ExecWaitResponse, JSONRPCErrorError> {
self.require_initialized_for("exec")?;
let wait = Duration::from_millis(params.wait_ms.unwrap_or(0));
let deadline = tokio::time::Instant::now() + wait;
loop {
let (response, output_notify) = {
let process_map = self.inner.processes.lock().await;
let process = process_map.get(&params.process_id).ok_or_else(|| {
invalid_request(format!("unknown process id {}", params.process_id))
})?;
let ProcessEntry::Running(process) = process else {
return Err(invalid_request(format!(
"process id {} is starting",
params.process_id
)));
};
(
ExecWaitResponse {
exited: process.exit_code.is_some(),
exit_code: process.exit_code,
},
Arc::clone(&process.output_notify),
)
};
if response.exited || tokio::time::Instant::now() >= deadline {
return Ok(response);
}
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
if remaining.is_zero() {
return Ok(response);
}
let _ = tokio::time::timeout(remaining, output_notify.notified()).await;
}
}
pub(crate) async fn terminate_process(
&self,
params: TerminateParams,
@@ -399,6 +485,17 @@ impl ExecProcess for LocalProcess {
.map_err(map_handler_error)
}
async fn resize(
&self,
params: ExecResizeParams,
) -> Result<ExecResizeResponse, ExecServerError> {
self.resize_process(params).await.map_err(map_handler_error)
}
async fn wait(&self, params: ExecWaitParams) -> Result<ExecWaitResponse, ExecServerError> {
self.wait_process(params).await.map_err(map_handler_error)
}
async fn terminate(&self, process_id: &str) -> Result<TerminateResponse, ExecServerError> {
self.terminate_process(TerminateParams {
process_id: process_id.to_string(),
+9
View File
@@ -5,7 +5,11 @@ use crate::ExecServerError;
use crate::protocol::ExecExitedNotification;
use crate::protocol::ExecOutputDeltaNotification;
use crate::protocol::ExecParams;
use crate::protocol::ExecResizeParams;
use crate::protocol::ExecResizeResponse;
use crate::protocol::ExecResponse;
use crate::protocol::ExecWaitParams;
use crate::protocol::ExecWaitResponse;
use crate::protocol::ReadParams;
use crate::protocol::ReadResponse;
use crate::protocol::TerminateResponse;
@@ -29,6 +33,11 @@ pub trait ExecProcess: Send + Sync {
chunk: Vec<u8>,
) -> Result<WriteResponse, ExecServerError>;
async fn resize(&self, params: ExecResizeParams)
-> Result<ExecResizeResponse, ExecServerError>;
async fn wait(&self, params: ExecWaitParams) -> Result<ExecWaitResponse, ExecServerError>;
async fn terminate(&self, process_id: &str) -> Result<TerminateResponse, ExecServerError>;
fn subscribe_events(&self) -> broadcast::Receiver<ExecServerEvent>;
+223
View File
@@ -11,8 +11,13 @@ pub const EXEC_METHOD: &str = "process/start";
pub const EXEC_READ_METHOD: &str = "process/read";
pub const EXEC_WRITE_METHOD: &str = "process/write";
pub const EXEC_TERMINATE_METHOD: &str = "process/terminate";
pub const EXEC_RESIZE_METHOD: &str = "process/resize";
pub const EXEC_WAIT_METHOD: &str = "process/wait";
pub const EXEC_OUTPUT_DELTA_METHOD: &str = "process/output";
pub const EXEC_EXITED_METHOD: &str = "process/exited";
pub const ENVIRONMENT_LIST_METHOD: &str = "environment/list";
pub const ENVIRONMENT_GET_METHOD: &str = "environment/get";
pub const ENVIRONMENT_CAPABILITIES_METHOD: &str = "environment/capabilities";
pub const FS_READ_FILE_METHOD: &str = "fs/readFile";
pub const FS_WRITE_FILE_METHOD: &str = "fs/writeFile";
pub const FS_CREATE_DIRECTORY_METHOD: &str = "fs/createDirectory";
@@ -60,6 +65,38 @@ pub struct ExecParams {
pub arg0: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecTerminalSize {
pub rows: u16,
pub cols: u16,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecResizeParams {
pub process_id: String,
pub size: ExecTerminalSize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecResizeResponse {}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecWaitParams {
pub process_id: String,
pub wait_ms: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecWaitResponse {
pub exited: bool,
pub exit_code: Option<i32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecResponse {
@@ -140,6 +177,67 @@ pub struct ExecExitedNotification {
pub exit_code: i32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvironmentCapabilities {
pub filesystem: bool,
pub process_resize: bool,
pub process_wait: bool,
}
impl Default for EnvironmentCapabilities {
fn default() -> Self {
Self {
filesystem: true,
process_resize: true,
process_wait: true,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvironmentInfo {
pub environment_id: String,
pub experimental_exec_server_url: Option<String>,
pub capabilities: EnvironmentCapabilities,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvironmentListParams {}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvironmentListResponse {
pub environments: Vec<EnvironmentInfo>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvironmentGetParams {
pub environment_id: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvironmentGetResponse {
pub environment: EnvironmentInfo,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvironmentCapabilitiesParams {
pub environment_id: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvironmentCapabilitiesResponse {
pub environment_id: String,
pub capabilities: EnvironmentCapabilities,
}
mod base64_bytes {
use super::BASE64_STANDARD;
use base64::Engine as _;
@@ -164,3 +262,128 @@ mod base64_bytes {
.map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::EnvironmentCapabilities;
use super::EnvironmentCapabilitiesParams;
use super::EnvironmentCapabilitiesResponse;
use super::EnvironmentGetParams;
use super::EnvironmentGetResponse;
use super::EnvironmentInfo;
use super::EnvironmentListParams;
use super::EnvironmentListResponse;
use super::ExecResizeParams;
use super::ExecTerminalSize;
use super::ExecWaitParams;
use super::ExecWaitResponse;
use pretty_assertions::assert_eq;
#[test]
fn environment_payloads_round_trip() {
let capabilities = EnvironmentCapabilities::default();
let info = EnvironmentInfo {
environment_id: "local".to_string(),
experimental_exec_server_url: None,
capabilities: capabilities.clone(),
};
let list_response = EnvironmentListResponse {
environments: vec![info.clone()],
};
let get_response = EnvironmentGetResponse {
environment: info.clone(),
};
let capabilities_response = EnvironmentCapabilitiesResponse {
environment_id: info.environment_id,
capabilities,
};
assert_eq!(
serde_json::to_value(EnvironmentListParams {}).expect("serialize list params"),
serde_json::json!({})
);
assert_eq!(
serde_json::from_value::<EnvironmentListParams>(serde_json::json!({}))
.expect("deserialize list params"),
EnvironmentListParams {}
);
assert_eq!(
serde_json::from_value::<EnvironmentListResponse>(
serde_json::to_value(&list_response).expect("serialize list response"),
)
.expect("deserialize list response"),
list_response
);
assert_eq!(
serde_json::from_value::<EnvironmentGetParams>(serde_json::json!({
"environmentId": "local"
}))
.expect("deserialize get params"),
EnvironmentGetParams {
environment_id: "local".to_string(),
}
);
assert_eq!(
serde_json::from_value::<EnvironmentGetResponse>(
serde_json::to_value(&get_response).expect("serialize get response"),
)
.expect("deserialize get response"),
get_response
);
assert_eq!(
serde_json::from_value::<EnvironmentCapabilitiesParams>(serde_json::json!({
"environmentId": "local"
}))
.expect("deserialize capabilities params"),
EnvironmentCapabilitiesParams {
environment_id: "local".to_string(),
}
);
assert_eq!(
serde_json::from_value::<EnvironmentCapabilitiesResponse>(
serde_json::to_value(&capabilities_response)
.expect("serialize capabilities response"),
)
.expect("deserialize capabilities response"),
capabilities_response
);
}
#[test]
fn process_payloads_round_trip() {
let resize_params = ExecResizeParams {
process_id: "proc-1".to_string(),
size: ExecTerminalSize { rows: 24, cols: 80 },
};
let wait_params = ExecWaitParams {
process_id: "proc-1".to_string(),
wait_ms: Some(250),
};
let wait_response = ExecWaitResponse {
exited: true,
exit_code: Some(0),
};
assert_eq!(
serde_json::from_value::<ExecResizeParams>(
serde_json::to_value(&resize_params).expect("serialize resize params"),
)
.expect("deserialize resize params"),
resize_params
);
assert_eq!(
serde_json::from_value::<ExecWaitParams>(
serde_json::to_value(&wait_params).expect("serialize wait params"),
)
.expect("deserialize wait params"),
wait_params
);
assert_eq!(
serde_json::from_value::<ExecWaitResponse>(
serde_json::to_value(&wait_response).expect("serialize wait response"),
)
.expect("deserialize wait response"),
wait_response
);
}
}
@@ -6,7 +6,11 @@ use crate::ExecServerClient;
use crate::ExecServerError;
use crate::ExecServerEvent;
use crate::protocol::ExecParams;
use crate::protocol::ExecResizeParams;
use crate::protocol::ExecResizeResponse;
use crate::protocol::ExecResponse;
use crate::protocol::ExecWaitParams;
use crate::protocol::ExecWaitResponse;
use crate::protocol::ReadParams;
use crate::protocol::ReadResponse;
use crate::protocol::TerminateResponse;
@@ -41,6 +45,17 @@ impl ExecProcess for RemoteProcess {
self.client.write(process_id, chunk).await
}
async fn resize(
&self,
params: ExecResizeParams,
) -> Result<ExecResizeResponse, ExecServerError> {
self.client.resize(params).await
}
async fn wait(&self, params: ExecWaitParams) -> Result<ExecWaitResponse, ExecServerError> {
self.client.wait(params).await
}
async fn terminate(&self, process_id: &str) -> Result<TerminateResponse, ExecServerError> {
self.client.terminate(process_id).await
}
@@ -35,8 +35,14 @@ pub(crate) struct ExecServerFileSystem {
impl Default for ExecServerFileSystem {
fn default() -> Self {
Self::new(&Environment::default())
}
}
impl ExecServerFileSystem {
pub(crate) fn new(environment: &Environment) -> Self {
Self {
file_system: Arc::new(Environment::default().get_filesystem()),
file_system: Arc::new(environment.get_filesystem()),
}
}
}
+78 -1
View File
@@ -14,8 +14,21 @@ use codex_app_server_protocol::FsWriteFileParams;
use codex_app_server_protocol::FsWriteFileResponse;
use codex_app_server_protocol::JSONRPCErrorError;
use crate::Environment;
use crate::EnvironmentCapabilities;
use crate::EnvironmentCapabilitiesParams;
use crate::EnvironmentCapabilitiesResponse;
use crate::EnvironmentGetParams;
use crate::EnvironmentGetResponse;
use crate::EnvironmentInfo;
use crate::EnvironmentListParams;
use crate::EnvironmentListResponse;
use crate::protocol::ExecParams;
use crate::protocol::ExecResizeParams;
use crate::protocol::ExecResizeResponse;
use crate::protocol::ExecResponse;
use crate::protocol::ExecWaitParams;
use crate::protocol::ExecWaitResponse;
use crate::protocol::InitializeResponse;
use crate::protocol::ReadParams;
use crate::protocol::ReadResponse;
@@ -30,13 +43,20 @@ use crate::server::process_handler::ExecServerProcess;
pub(crate) struct ExecServerHandler {
process: ExecServerProcess,
file_system: ExecServerFileSystem,
environment: EnvironmentInfo,
}
impl ExecServerHandler {
pub(crate) fn new(notifications: RpcNotificationSender) -> Self {
let environment = EnvironmentInfo {
environment_id: Environment::default_environment_id(None),
experimental_exec_server_url: None,
capabilities: EnvironmentCapabilities::default(),
};
Self {
process: ExecServerProcess::new(notifications),
file_system: ExecServerFileSystem::default(),
file_system: ExecServerFileSystem::new(&Environment::default()),
environment,
}
}
@@ -77,6 +97,63 @@ impl ExecServerHandler {
self.process.terminate(params).await
}
pub(crate) async fn resize(
&self,
params: ExecResizeParams,
) -> Result<ExecResizeResponse, JSONRPCErrorError> {
self.process.resize(params).await
}
pub(crate) async fn wait(
&self,
params: ExecWaitParams,
) -> Result<ExecWaitResponse, JSONRPCErrorError> {
self.process.wait(params).await
}
pub(crate) async fn environment_list(
&self,
_params: EnvironmentListParams,
) -> Result<EnvironmentListResponse, JSONRPCErrorError> {
self.process.require_initialized_for("environment")?;
Ok(EnvironmentListResponse {
environments: vec![self.environment.clone()],
})
}
pub(crate) async fn environment_get(
&self,
params: EnvironmentGetParams,
) -> Result<EnvironmentGetResponse, JSONRPCErrorError> {
self.process.require_initialized_for("environment")?;
if params.environment_id != self.environment.environment_id {
return Err(crate::rpc::invalid_request(format!(
"unknown environment id `{}`",
params.environment_id
)));
}
Ok(EnvironmentGetResponse {
environment: self.environment.clone(),
})
}
pub(crate) async fn environment_capabilities(
&self,
params: EnvironmentCapabilitiesParams,
) -> Result<EnvironmentCapabilitiesResponse, JSONRPCErrorError> {
self.process.require_initialized_for("environment")?;
if params.environment_id != self.environment.environment_id {
return Err(crate::rpc::invalid_request(format!(
"unknown environment id `{}`",
params.environment_id
)));
}
Ok(EnvironmentCapabilitiesResponse {
environment_id: self.environment.environment_id.clone(),
capabilities: self.environment.capabilities.clone(),
})
}
pub(crate) async fn fs_read_file(
&self,
params: FsReadFileParams,
@@ -6,7 +6,13 @@ use pretty_assertions::assert_eq;
use tokio::sync::mpsc;
use super::ExecServerHandler;
use crate::protocol::EnvironmentCapabilitiesParams;
use crate::protocol::EnvironmentGetParams;
use crate::protocol::EnvironmentListParams;
use crate::protocol::ExecParams;
use crate::protocol::ExecResizeParams;
use crate::protocol::ExecTerminalSize;
use crate::protocol::ExecWaitParams;
use crate::protocol::InitializeResponse;
use crate::protocol::TerminateParams;
use crate::protocol::TerminateResponse;
@@ -14,13 +20,14 @@ use crate::rpc::RpcNotificationSender;
fn exec_params(process_id: &str) -> ExecParams {
let mut env = HashMap::new();
if let Some(path) = std::env::var_os("PATH") {
env.insert("PATH".to_string(), path.to_string_lossy().into_owned());
}
env.insert(
"PATH".to_string(),
std::env::var("PATH").unwrap_or_else(|_| "/usr/bin:/bin".to_string()),
);
ExecParams {
process_id: process_id.to_string(),
argv: vec![
"bash".to_string(),
"/bin/bash".to_string(),
"-lc".to_string(),
"sleep 0.1".to_string(),
],
@@ -31,6 +38,12 @@ fn exec_params(process_id: &str) -> ExecParams {
}
}
fn tty_exec_params(process_id: &str) -> ExecParams {
let mut params = exec_params(process_id);
params.tty = true;
params
}
async fn initialized_handler() -> Arc<ExecServerHandler> {
let (outgoing_tx, _outgoing_rx) = mpsc::channel(16);
let handler = Arc::new(ExecServerHandler::new(RpcNotificationSender::new(
@@ -100,3 +113,97 @@ async fn terminate_reports_false_after_process_exit() {
handler.shutdown().await;
}
#[tokio::test]
async fn environment_list_returns_local_environment() {
let handler = initialized_handler().await;
let response = handler
.environment_list(EnvironmentListParams {})
.await
.expect("environment list");
assert_eq!(response.environments.len(), 1);
assert_eq!(response.environments[0].environment_id, "local");
assert_eq!(response.environments[0].experimental_exec_server_url, None);
assert_eq!(
response.environments[0].capabilities,
crate::protocol::EnvironmentCapabilities::default()
);
handler.shutdown().await;
}
#[tokio::test]
async fn environment_get_returns_local_environment() {
let handler = initialized_handler().await;
let response = handler
.environment_get(EnvironmentGetParams {
environment_id: "local".to_string(),
})
.await
.expect("environment get");
assert_eq!(response.environment.environment_id, "local");
handler.shutdown().await;
}
#[tokio::test]
async fn environment_capabilities_returns_local_capabilities() {
let handler = initialized_handler().await;
let response = handler
.environment_capabilities(EnvironmentCapabilitiesParams {
environment_id: "local".to_string(),
})
.await
.expect("environment capabilities");
assert_eq!(response.environment_id, "local");
assert_eq!(
response.capabilities,
crate::protocol::EnvironmentCapabilities::default()
);
handler.shutdown().await;
}
#[tokio::test]
async fn resize_and_wait_are_routed_for_running_processes() {
let handler = initialized_handler().await;
handler
.exec(tty_exec_params("proc-tty"))
.await
.expect("start tty process");
handler
.resize(ExecResizeParams {
process_id: "proc-tty".to_string(),
size: ExecTerminalSize { rows: 24, cols: 80 },
})
.await
.expect("resize tty process");
let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
loop {
let response = handler
.wait(ExecWaitParams {
process_id: "proc-tty".to_string(),
wait_ms: Some(50),
})
.await
.expect("wait response");
if response.exited {
assert_eq!(response.exit_code, Some(0));
break;
}
assert!(
tokio::time::Instant::now() < deadline,
"process should have exited within 1s"
);
}
handler.shutdown().await;
}
@@ -2,7 +2,11 @@ use codex_app_server_protocol::JSONRPCErrorError;
use crate::local_process::LocalProcess;
use crate::protocol::ExecParams;
use crate::protocol::ExecResizeParams;
use crate::protocol::ExecResizeResponse;
use crate::protocol::ExecResponse;
use crate::protocol::ExecWaitParams;
use crate::protocol::ExecWaitResponse;
use crate::protocol::InitializeResponse;
use crate::protocol::ReadParams;
use crate::protocol::ReadResponse;
@@ -67,4 +71,18 @@ impl ExecServerProcess {
) -> Result<TerminateResponse, JSONRPCErrorError> {
self.process.terminate_process(params).await
}
pub(crate) async fn resize(
&self,
params: ExecResizeParams,
) -> Result<ExecResizeResponse, JSONRPCErrorError> {
self.process.resize_process(params).await
}
pub(crate) async fn wait(
&self,
params: ExecWaitParams,
) -> Result<ExecWaitResponse, JSONRPCErrorError> {
self.process.wait_process(params).await
}
}
@@ -1,10 +1,20 @@
use std::sync::Arc;
use crate::protocol::ENVIRONMENT_CAPABILITIES_METHOD;
use crate::protocol::ENVIRONMENT_GET_METHOD;
use crate::protocol::ENVIRONMENT_LIST_METHOD;
use crate::protocol::EXEC_METHOD;
use crate::protocol::EXEC_READ_METHOD;
use crate::protocol::EXEC_RESIZE_METHOD;
use crate::protocol::EXEC_TERMINATE_METHOD;
use crate::protocol::EXEC_WAIT_METHOD;
use crate::protocol::EXEC_WRITE_METHOD;
use crate::protocol::EnvironmentCapabilitiesParams;
use crate::protocol::EnvironmentGetParams;
use crate::protocol::EnvironmentListParams;
use crate::protocol::ExecParams;
use crate::protocol::ExecResizeParams;
use crate::protocol::ExecWaitParams;
use crate::protocol::FS_COPY_METHOD;
use crate::protocol::FS_CREATE_DIRECTORY_METHOD;
use crate::protocol::FS_GET_METADATA_METHOD;
@@ -64,6 +74,36 @@ pub(crate) fn build_router() -> RpcRouter<ExecServerHandler> {
handler.terminate(params).await
},
);
router.request(
EXEC_RESIZE_METHOD,
|handler: Arc<ExecServerHandler>, params: ExecResizeParams| async move {
handler.resize(params).await
},
);
router.request(
EXEC_WAIT_METHOD,
|handler: Arc<ExecServerHandler>, params: ExecWaitParams| async move {
handler.wait(params).await
},
);
router.request(
ENVIRONMENT_LIST_METHOD,
|handler: Arc<ExecServerHandler>, params: EnvironmentListParams| async move {
handler.environment_list(params).await
},
);
router.request(
ENVIRONMENT_GET_METHOD,
|handler: Arc<ExecServerHandler>, params: EnvironmentGetParams| async move {
handler.environment_get(params).await
},
);
router.request(
ENVIRONMENT_CAPABILITIES_METHOD,
|handler: Arc<ExecServerHandler>, params: EnvironmentCapabilitiesParams| async move {
handler.environment_capabilities(params).await
},
);
router.request(
FS_READ_FILE_METHOD,
|handler: Arc<ExecServerHandler>, params: FsReadFileParams| async move {
@@ -108,3 +148,27 @@ pub(crate) fn build_router() -> RpcRouter<ExecServerHandler> {
);
router
}
#[cfg(test)]
mod tests {
use super::build_router;
use crate::protocol::ENVIRONMENT_CAPABILITIES_METHOD;
use crate::protocol::ENVIRONMENT_GET_METHOD;
use crate::protocol::ENVIRONMENT_LIST_METHOD;
use crate::protocol::EXEC_RESIZE_METHOD;
use crate::protocol::EXEC_WAIT_METHOD;
#[test]
fn build_router_registers_process_control_and_environment_routes() {
let router = build_router();
assert!(router.request_route(EXEC_RESIZE_METHOD).is_some());
assert!(router.request_route(EXEC_WAIT_METHOD).is_some());
assert!(router.request_route(ENVIRONMENT_LIST_METHOD).is_some());
assert!(router.request_route(ENVIRONMENT_GET_METHOD).is_some());
assert!(
router
.request_route(ENVIRONMENT_CAPABILITIES_METHOD)
.is_some()
);
}
}
+3
View File
@@ -918,6 +918,7 @@ fn sandbox_mode_from_policy(
fn thread_start_params_from_config(config: &Config) -> ThreadStartParams {
ThreadStartParams {
environment_id: None,
model: config.model.clone(),
model_provider: Some(config.model_provider_id.clone()),
cwd: Some(config.cwd.to_string_lossy().to_string()),
@@ -932,6 +933,7 @@ fn thread_start_params_from_config(config: &Config) -> ThreadStartParams {
fn thread_resume_params_from_config(config: &Config, path: Option<PathBuf>) -> ThreadResumeParams {
ThreadResumeParams {
environment_id: None,
thread_id: "resume".to_string(),
path,
model: config.model.clone(),
@@ -1904,6 +1906,7 @@ mod tests {
name: Some("thread".to_string()),
turns: vec![],
},
environment_id: "local".to_string(),
model: "gpt-5.4".to_string(),
model_provider: "openai".to_string(),
service_tier: None,
@@ -807,6 +807,7 @@ fn thread_start_params_from_config(
thread_params_mode: ThreadParamsMode,
) -> ThreadStartParams {
ThreadStartParams {
environment_id: None,
model: config.model.clone(),
model_provider: thread_params_mode.model_provider_from_config(config),
cwd: thread_cwd_from_config(config, thread_params_mode),
@@ -826,6 +827,7 @@ fn thread_resume_params_from_config(
thread_params_mode: ThreadParamsMode,
) -> ThreadResumeParams {
ThreadResumeParams {
environment_id: None,
thread_id: thread_id.to_string(),
model: config.model.clone(),
model_provider: thread_params_mode.model_provider_from_config(&config),
@@ -845,6 +847,7 @@ fn thread_fork_params_from_config(
thread_params_mode: ThreadParamsMode,
) -> ThreadForkParams {
ThreadForkParams {
environment_id: None,
thread_id: thread_id.to_string(),
model: config.model.clone(),
model_provider: thread_params_mode.model_provider_from_config(&config),
@@ -1168,6 +1171,7 @@ mod tests {
error: None,
}],
},
environment_id: "local".to_string(),
model: "gpt-5.4".to_string(),
model_provider: "openai".to_string(),
service_tier: None,