mirror of
https://github.com/openai/codex.git
synced 2026-11-17 22:10:37 +00:00
prototype sdkv2 on app-server
This commit is contained in:
@@ -33,6 +33,31 @@
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"additionalProperties": false,
|
||||
"description": "User has approved this command, but wants the agent to execute a replacement command instead of the originally proposed one.",
|
||||
"properties": {
|
||||
"approved_with_command_override": {
|
||||
"properties": {
|
||||
"command": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"approved_with_command_override"
|
||||
],
|
||||
"title": "ApprovedWithCommandOverrideReviewDecision",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"additionalProperties": false,
|
||||
"description": "User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.",
|
||||
|
||||
@@ -216,6 +216,31 @@
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"additionalProperties": false,
|
||||
"description": "User approved execution, but wants to replace the command before it runs.",
|
||||
"properties": {
|
||||
"acceptWithCommandOverride": {
|
||||
"properties": {
|
||||
"command": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"acceptWithCommandOverride"
|
||||
],
|
||||
"title": "AcceptWithCommandOverrideCommandExecutionApprovalDecision",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"description": "User approved the command and future prompts in the same session-scoped approval cache should run without prompting.",
|
||||
"enum": [
|
||||
|
||||
@@ -10,6 +10,31 @@
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"additionalProperties": false,
|
||||
"description": "User approved execution, but wants to replace the command before it runs.",
|
||||
"properties": {
|
||||
"acceptWithCommandOverride": {
|
||||
"properties": {
|
||||
"command": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"acceptWithCommandOverride"
|
||||
],
|
||||
"title": "AcceptWithCommandOverrideCommandExecutionApprovalDecision",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"description": "User approved the command and future prompts in the same session-scoped approval cache should run without prompting.",
|
||||
"enum": [
|
||||
|
||||
@@ -5252,6 +5252,31 @@
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"additionalProperties": false,
|
||||
"description": "User has approved this command, but wants the agent to execute a replacement command instead of the originally proposed one.",
|
||||
"properties": {
|
||||
"approved_with_command_override": {
|
||||
"properties": {
|
||||
"command": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"approved_with_command_override"
|
||||
],
|
||||
"title": "ApprovedWithCommandOverrideReviewDecision",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"additionalProperties": false,
|
||||
"description": "User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.",
|
||||
|
||||
@@ -33,6 +33,31 @@
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"additionalProperties": false,
|
||||
"description": "User has approved this command, but wants the agent to execute a replacement command instead of the originally proposed one.",
|
||||
"properties": {
|
||||
"approved_with_command_override": {
|
||||
"properties": {
|
||||
"command": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"approved_with_command_override"
|
||||
],
|
||||
"title": "ApprovedWithCommandOverrideReviewDecision",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"additionalProperties": false,
|
||||
"description": "User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.",
|
||||
|
||||
@@ -282,6 +282,31 @@
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"additionalProperties": false,
|
||||
"description": "User approved execution, but wants to replace the command before it runs.",
|
||||
"properties": {
|
||||
"acceptWithCommandOverride": {
|
||||
"properties": {
|
||||
"command": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"acceptWithCommandOverride"
|
||||
],
|
||||
"title": "AcceptWithCommandOverrideCommandExecutionApprovalDecision",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"description": "User approved the command and future prompts in the same session-scoped approval cache should run without prompting.",
|
||||
"enum": [
|
||||
|
||||
@@ -1514,6 +1514,31 @@
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"additionalProperties": false,
|
||||
"description": "User approved execution, but wants to replace the command before it runs.",
|
||||
"properties": {
|
||||
"acceptWithCommandOverride": {
|
||||
"properties": {
|
||||
"command": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"acceptWithCommandOverride"
|
||||
],
|
||||
"title": "AcceptWithCommandOverrideCommandExecutionApprovalDecision",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"description": "User approved the command and future prompts in the same session-scoped approval cache should run without prompting.",
|
||||
"enum": [
|
||||
@@ -6587,6 +6612,31 @@
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"additionalProperties": false,
|
||||
"description": "User has approved this command, but wants the agent to execute a replacement command instead of the originally proposed one.",
|
||||
"properties": {
|
||||
"approved_with_command_override": {
|
||||
"properties": {
|
||||
"command": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"approved_with_command_override"
|
||||
],
|
||||
"title": "ApprovedWithCommandOverrideReviewDecision",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"additionalProperties": false,
|
||||
"description": "User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.",
|
||||
|
||||
@@ -9801,6 +9801,31 @@
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"additionalProperties": false,
|
||||
"description": "User has approved this command, but wants the agent to execute a replacement command instead of the originally proposed one.",
|
||||
"properties": {
|
||||
"approved_with_command_override": {
|
||||
"properties": {
|
||||
"command": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"approved_with_command_override"
|
||||
],
|
||||
"title": "ApprovedWithCommandOverrideReviewDecision",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"additionalProperties": false,
|
||||
"description": "User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.",
|
||||
|
||||
@@ -7,4 +7,4 @@ import type { NetworkPolicyAmendment } from "./NetworkPolicyAmendment";
|
||||
/**
|
||||
* User's decision in response to an ExecApprovalRequest.
|
||||
*/
|
||||
export type ReviewDecision = "approved" | { "approved_execpolicy_amendment": { proposed_execpolicy_amendment: ExecPolicyAmendment, } } | "approved_for_session" | { "network_policy_amendment": { network_policy_amendment: NetworkPolicyAmendment, } } | "denied" | "abort";
|
||||
export type ReviewDecision = "approved" | { "approved_with_command_override": { command: Array<string>, } } | { "approved_execpolicy_amendment": { proposed_execpolicy_amendment: ExecPolicyAmendment, } } | "approved_for_session" | { "network_policy_amendment": { network_policy_amendment: NetworkPolicyAmendment, } } | "denied" | "abort";
|
||||
|
||||
+1
-1
@@ -4,4 +4,4 @@
|
||||
import type { ExecPolicyAmendment } from "./ExecPolicyAmendment";
|
||||
import type { NetworkPolicyAmendment } from "./NetworkPolicyAmendment";
|
||||
|
||||
export type CommandExecutionApprovalDecision = "accept" | "acceptForSession" | { "acceptWithExecpolicyAmendment": { execpolicy_amendment: ExecPolicyAmendment, } } | { "applyNetworkPolicyAmendment": { network_policy_amendment: NetworkPolicyAmendment, } } | "decline" | "cancel";
|
||||
export type CommandExecutionApprovalDecision = "accept" | { "acceptWithCommandOverride": { command: Array<string>, } } | "acceptForSession" | { "acceptWithExecpolicyAmendment": { execpolicy_amendment: ExecPolicyAmendment, } } | { "applyNetworkPolicyAmendment": { network_policy_amendment: NetworkPolicyAmendment, } } | "decline" | "cancel";
|
||||
|
||||
@@ -8,6 +8,9 @@ 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, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, serviceName?: string | null, baseInstructions?: string | null, developerInstructions?: string | null, personality?: Personality | null, ephemeral?: boolean | null, /**
|
||||
* If true, require host-visible approval before executing built-in tools.
|
||||
*/
|
||||
manualToolExecution?: boolean, /**
|
||||
* If true, opt into emitting raw Responses API items on the event stream.
|
||||
* This is for internal use only (e.g. Codex Cloud).
|
||||
*/
|
||||
|
||||
@@ -744,12 +744,15 @@ pub struct ConfigEdit {
|
||||
pub merge_strategy: MergeStrategy,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS, ExperimentalApi)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/")]
|
||||
pub enum CommandExecutionApprovalDecision {
|
||||
/// User approved the command.
|
||||
Accept,
|
||||
/// User approved execution, but wants to replace the command before it runs.
|
||||
#[experimental("item/commandExecution/requestApproval.overrideCommand")]
|
||||
AcceptWithCommandOverride { command: Vec<String> },
|
||||
/// User approved the command and future prompts in the same session-scoped
|
||||
/// approval cache should run without prompting.
|
||||
AcceptForSession,
|
||||
@@ -772,6 +775,9 @@ impl From<CoreReviewDecision> for CommandExecutionApprovalDecision {
|
||||
fn from(value: CoreReviewDecision) -> Self {
|
||||
match value {
|
||||
CoreReviewDecision::Approved => Self::Accept,
|
||||
CoreReviewDecision::ApprovedWithCommandOverride { command } => {
|
||||
Self::AcceptWithCommandOverride { command }
|
||||
}
|
||||
CoreReviewDecision::ApprovedExecpolicyAmendment {
|
||||
proposed_execpolicy_amendment,
|
||||
} => Self::AcceptWithExecpolicyAmendment {
|
||||
@@ -1871,6 +1877,10 @@ pub struct ThreadStartParams {
|
||||
#[experimental("thread/start.builtinTools")]
|
||||
#[ts(optional = nullable)]
|
||||
pub builtin_tools: Option<Vec<String>>,
|
||||
/// If true, require host-visible approval before executing built-in tools.
|
||||
#[experimental("thread/start.manualToolExecution")]
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub manual_tool_execution: bool,
|
||||
/// Test-only experimental field used to validate experimental gating and
|
||||
/// schema filtering behavior in a stable way.
|
||||
#[experimental("thread/start.mockExperimentalField")]
|
||||
@@ -5618,6 +5628,38 @@ mod tests {
|
||||
assert_eq!(serialized, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_start_params_round_trip_manual_tool_execution() {
|
||||
let params: ThreadStartParams =
|
||||
serde_json::from_value(json!({ "manualToolExecution": true }))
|
||||
.expect("params should deserialize");
|
||||
assert!(params.manual_tool_execution);
|
||||
|
||||
let serialized = serde_json::to_value(¶ms).expect("params should serialize");
|
||||
let mut expected =
|
||||
serde_json::to_value(ThreadStartParams::default()).expect("params should serialize");
|
||||
expected
|
||||
.as_object_mut()
|
||||
.expect("serialized params should be an object")
|
||||
.insert("manualToolExecution".to_string(), json!(true));
|
||||
assert_eq!(serialized, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_execution_request_approval_response_round_trip_command_override() {
|
||||
let response = CommandExecutionRequestApprovalResponse {
|
||||
decision: CommandExecutionApprovalDecision::AcceptWithCommandOverride {
|
||||
command: vec!["ls".to_string(), "-la".to_string()],
|
||||
},
|
||||
};
|
||||
|
||||
let json = serde_json::to_value(&response).expect("serialize response");
|
||||
let parsed: CommandExecutionRequestApprovalResponse =
|
||||
serde_json::from_value(json).expect("deserialize response");
|
||||
|
||||
assert_eq!(parsed, response);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_start_params_preserve_explicit_null_service_tier() {
|
||||
let params: TurnStartParams = serde_json::from_value(json!({
|
||||
|
||||
@@ -120,7 +120,7 @@ Example with notification opt-out:
|
||||
|
||||
## API Overview
|
||||
|
||||
- `thread/start` — create a new thread; emits `thread/started` (including the current `thread.status`) and auto-subscribes you to turn/item events for that thread. Experimental: `thread/start.sdkDelegation` lets a host integration register a per-thread delegated Responses provider that points Codex at a host-managed bridge. In the current prototype shape, Codex sends the raw Responses request body to that bridge and the host bridge injects upstream authorization before forwarding the request. Experimental: `thread/start.builtinTools` lets a client provide an exact allowlist of built-in Codex tool names for that thread.
|
||||
- `thread/start` — create a new thread; emits `thread/started` (including the current `thread.status`) and auto-subscribes you to turn/item events for that thread. Experimental: `thread/start.sdkDelegation` lets a host integration register a per-thread delegated Responses provider that points Codex at a host-managed bridge. In the current prototype shape, Codex sends the raw Responses request body to that bridge and the host bridge injects upstream authorization before forwarding the request. Experimental: `thread/start.builtinTools` lets a client provide an exact allowlist of built-in Codex tool names for that thread. Experimental: `thread/start.manualToolExecution` forces built-in tool executions to pause for host approval before Codex invokes them.
|
||||
- `thread/resume` — reopen an existing thread by id so subsequent `turn/start` calls append to it.
|
||||
- `thread/fork` — fork an existing thread into a new thread id by copying the stored history; emits `thread/started` (including the current `thread.status`) and auto-subscribes you to turn/item events for the new thread.
|
||||
- `thread/list` — page through stored rollouts; supports cursor-based pagination and optional `modelProviders`, `sourceKinds`, `archived`, `cwd`, and `searchTerm` filters. Each returned `thread` includes `status` (`ThreadStatus`), defaulting to `notLoaded` when the thread is not currently loaded.
|
||||
@@ -203,7 +203,8 @@ Start a fresh thread when you need a new Codex conversation.
|
||||
"write_stdin",
|
||||
"apply_patch",
|
||||
"view_image"
|
||||
]
|
||||
],
|
||||
"manualToolExecution": true
|
||||
} }
|
||||
{ "id": 10, "result": {
|
||||
"thread": {
|
||||
@@ -771,7 +772,7 @@ Certain actions (shell commands or modifying files) may require explicit user ap
|
||||
Order of messages:
|
||||
|
||||
1. `item/started` — shows the pending `commandExecution` item with `command`, `cwd`, and other fields so you can render the proposed action.
|
||||
2. `item/commandExecution/requestApproval` (request) — carries the same `itemId`, `threadId`, `turnId`, optionally `approvalId` (for subcommand callbacks), and `reason`. For normal command approvals, it also includes `command`, `cwd`, and `commandActions` for friendly display. When `initialize.params.capabilities.experimentalApi = true`, it may also include experimental `additionalPermissions` describing requested per-command sandbox access; any filesystem paths in that payload are absolute on the wire, and network access is represented as `additionalPermissions.network.enabled`. For network-only approvals, those command fields may be omitted and `networkApprovalContext` is provided instead. Optional persistence hints may also be included via `proposedExecpolicyAmendment` and `proposedNetworkPolicyAmendments`. Clients can prefer `availableDecisions` when present to render the exact set of choices the server wants to expose, while still falling back to the older heuristics if it is omitted.
|
||||
2. `item/commandExecution/requestApproval` (request) — carries the same `itemId`, `threadId`, `turnId`, optionally `approvalId` (for subcommand callbacks), and `reason`. For normal command approvals, it also includes `command`, `cwd`, and `commandActions` for friendly display. When `initialize.params.capabilities.experimentalApi = true`, it may also include experimental `additionalPermissions` describing requested per-command sandbox access; any filesystem paths in that payload are absolute on the wire, and network access is represented as `additionalPermissions.network.enabled`. For network-only approvals, those command fields may be omitted and `networkApprovalContext` is provided instead. Optional persistence hints may also be included via `proposedExecpolicyAmendment` and `proposedNetworkPolicyAmendments`. Experimental clients may also answer with `acceptWithCommandOverride` to replace the proposed built-in command before execution. Clients can prefer `availableDecisions` when present to render the exact set of choices the server wants to expose, while still falling back to the older heuristics if it is omitted.
|
||||
3. Client response — for example `{ "decision": "accept" }`, `{ "decision": "acceptForSession" }`, `{ "decision": { "acceptWithExecpolicyAmendment": { "execpolicy_amendment": [...] } } }`, `{ "decision": { "applyNetworkPolicyAmendment": { "network_policy_amendment": { "host": "example.com", "action": "allow" } } } }`, `{ "decision": "decline" }`, or `{ "decision": "cancel" }`.
|
||||
4. `serverRequest/resolved` — `{ threadId, requestId }` confirms the pending request has been resolved or cleared, including lifecycle cleanup on turn start/complete/interrupt.
|
||||
5. `item/completed` — final `commandExecution` item with `status: "completed" | "failed" | "declined"` and execution output. Render this as the authoritative result.
|
||||
|
||||
@@ -2256,6 +2256,10 @@ async fn on_command_execution_request_approval_response(
|
||||
|
||||
let (decision, completion_status) = match decision {
|
||||
CommandExecutionApprovalDecision::Accept => (ReviewDecision::Approved, None),
|
||||
CommandExecutionApprovalDecision::AcceptWithCommandOverride { command } => (
|
||||
ReviewDecision::ApprovedWithCommandOverride { command },
|
||||
None,
|
||||
),
|
||||
CommandExecutionApprovalDecision::AcceptForSession => {
|
||||
(ReviewDecision::ApprovedForSession, None)
|
||||
}
|
||||
|
||||
@@ -1605,6 +1605,7 @@ impl CodexMessageProcessor {
|
||||
developer_instructions,
|
||||
dynamic_tools,
|
||||
builtin_tools,
|
||||
manual_tool_execution,
|
||||
mock_experimental_field: _mock_experimental_field,
|
||||
experimental_raw_events,
|
||||
personality,
|
||||
@@ -1650,6 +1651,7 @@ impl CodexMessageProcessor {
|
||||
typesafe_overrides,
|
||||
dynamic_tools,
|
||||
builtin_tools,
|
||||
manual_tool_execution,
|
||||
persist_extended_history,
|
||||
service_name,
|
||||
experimental_raw_events,
|
||||
@@ -1669,6 +1671,7 @@ impl CodexMessageProcessor {
|
||||
typesafe_overrides: ConfigOverrides,
|
||||
dynamic_tools: Option<Vec<ApiDynamicToolSpec>>,
|
||||
builtin_tools: Option<Vec<String>>,
|
||||
manual_tool_execution: bool,
|
||||
persist_extended_history: bool,
|
||||
service_name: Option<String>,
|
||||
experimental_raw_events: bool,
|
||||
@@ -1743,6 +1746,7 @@ impl CodexMessageProcessor {
|
||||
config,
|
||||
core_dynamic_tools,
|
||||
builtin_tools,
|
||||
manual_tool_execution,
|
||||
persist_extended_history,
|
||||
service_name,
|
||||
)
|
||||
@@ -6933,8 +6937,7 @@ fn validate_builtin_tools(tools: &[String]) -> Result<(), String> {
|
||||
}
|
||||
if name != tool {
|
||||
return Err(format!(
|
||||
"builtin tool name has leading/trailing whitespace: {}",
|
||||
tool
|
||||
"builtin tool name has leading/trailing whitespace: {tool}"
|
||||
));
|
||||
}
|
||||
if !seen.insert(name.to_string()) {
|
||||
|
||||
@@ -134,7 +134,10 @@ async fn thread_start_builtin_tools_filters_model_requests() -> Result<()> {
|
||||
let thread_req = mcp
|
||||
.send_thread_start_request(ThreadStartParams {
|
||||
config: Some(HashMap::from([
|
||||
("experimental_use_unified_exec_tool".to_string(), json!(true)),
|
||||
(
|
||||
"experimental_use_unified_exec_tool".to_string(),
|
||||
json!(true),
|
||||
),
|
||||
("include_apply_patch_tool".to_string(), json!(true)),
|
||||
])),
|
||||
builtin_tools: Some(vec![
|
||||
@@ -190,12 +193,7 @@ async fn thread_start_builtin_tools_filters_model_requests() -> Result<()> {
|
||||
|
||||
assert_eq!(
|
||||
tool_names,
|
||||
HashSet::from([
|
||||
"exec_command",
|
||||
"write_stdin",
|
||||
"update_plan",
|
||||
"view_image",
|
||||
])
|
||||
HashSet::from(["exec_command", "write_stdin", "update_plan", "view_image",])
|
||||
);
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -242,6 +242,7 @@ async fn skills_changed_notification_is_emitted_after_skill_change() -> Result<(
|
||||
ephemeral: None,
|
||||
dynamic_tools: None,
|
||||
builtin_tools: None,
|
||||
manual_tool_execution: false,
|
||||
mock_experimental_field: None,
|
||||
experimental_raw_events: false,
|
||||
persist_extended_history: false,
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
use crate::tools::spec::ToolsConfig;
|
||||
|
||||
const CORE_BASE_INSTRUCTIONS: &str = include_str!("../templates/base_instructions/core.md");
|
||||
const APPLY_PATCH_INSTRUCTIONS: &str =
|
||||
include_str!("../templates/base_instructions/capabilities/apply_patch.md");
|
||||
const UNIFIED_EXEC_INSTRUCTIONS: &str =
|
||||
include_str!("../templates/base_instructions/capabilities/unified_exec.md");
|
||||
const UPDATE_PLAN_INSTRUCTIONS: &str =
|
||||
include_str!("../templates/base_instructions/capabilities/update_plan.md");
|
||||
|
||||
pub(crate) fn compose_base_instructions(tools_config: &ToolsConfig) -> String {
|
||||
let mut sections = vec![CORE_BASE_INSTRUCTIONS.trim().to_string()];
|
||||
|
||||
if tools_config.has_builtin_tool("exec_command") {
|
||||
sections.push(UNIFIED_EXEC_INSTRUCTIONS.trim().to_string());
|
||||
}
|
||||
if tools_config.has_builtin_tool("apply_patch") {
|
||||
sections.push(APPLY_PATCH_INSTRUCTIONS.trim().to_string());
|
||||
}
|
||||
if tools_config.has_builtin_tool("update_plan") {
|
||||
sections.push(UPDATE_PLAN_INSTRUCTIONS.trim().to_string());
|
||||
}
|
||||
|
||||
sections.join("\n\n")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::features::Feature;
|
||||
use crate::features::Features;
|
||||
use crate::models_manager::model_info::model_info_from_slug;
|
||||
use crate::tools::spec::ToolsConfigParams;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
|
||||
fn tools_config() -> ToolsConfig {
|
||||
let mut features = Features::new();
|
||||
let _ = features.enable(Feature::ShellTool);
|
||||
let _ = features.enable(Feature::UnifiedExec);
|
||||
let _ = features.enable(Feature::ApplyPatchFreeform);
|
||||
let model_info = model_info_from_slug("gpt-5.2-codex");
|
||||
ToolsConfig::new(&ToolsConfigParams {
|
||||
model_info: &model_info,
|
||||
features: &features,
|
||||
web_search_mode: None,
|
||||
session_source: SessionSource::Cli,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn omits_unenabled_capability_sections() {
|
||||
let tools_config = tools_config().with_builtin_tools(Some(vec!["exec_command".to_string()]));
|
||||
|
||||
let instructions = compose_base_instructions(&tools_config);
|
||||
|
||||
assert!(instructions.contains("# Unified Exec"));
|
||||
assert!(!instructions.contains("# Apply Patch"));
|
||||
assert!(!instructions.contains("# Update Plan"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn includes_capability_sections_for_enabled_tools() {
|
||||
let tools_config = tools_config().with_builtin_tools(Some(vec![
|
||||
"exec_command".to_string(),
|
||||
"apply_patch".to_string(),
|
||||
"update_plan".to_string(),
|
||||
]));
|
||||
|
||||
let instructions = compose_base_instructions(&tools_config);
|
||||
|
||||
assert!(instructions.contains("# Unified Exec"));
|
||||
assert!(instructions.contains("# Apply Patch"));
|
||||
assert!(instructions.contains("# Update Plan"));
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ use crate::analytics_client::InvocationType;
|
||||
use crate::analytics_client::build_track_events_context;
|
||||
use crate::apps::render_apps_section;
|
||||
use crate::commit_attribution::commit_message_trailer_instruction;
|
||||
use crate::base_instructions::compose_base_instructions;
|
||||
use crate::compact;
|
||||
use crate::compact::InitialContextInjection;
|
||||
use crate::compact::run_inline_auto_compact_task;
|
||||
@@ -357,6 +358,7 @@ impl Codex {
|
||||
agent_control: AgentControl,
|
||||
dynamic_tools: Vec<DynamicToolSpec>,
|
||||
builtin_tools: Option<Vec<String>>,
|
||||
manual_tool_execution: bool,
|
||||
persist_extended_history: bool,
|
||||
metrics_service_name: Option<String>,
|
||||
inherited_shell_snapshot: Option<Arc<ShellSnapshot>>,
|
||||
@@ -429,16 +431,24 @@ impl Codex {
|
||||
.get_default_model(&config.model, refresh_strategy)
|
||||
.await;
|
||||
|
||||
let model_info = models_manager.get_model_info(model.as_str(), &config).await;
|
||||
let tools_config = ToolsConfig::new(&ToolsConfigParams {
|
||||
model_info: &model_info,
|
||||
features: &config.features,
|
||||
web_search_mode: config.web_search_request_mode.as_ref(),
|
||||
session_source: session_source.clone(),
|
||||
})
|
||||
.with_builtin_tools(builtin_tools.clone())
|
||||
.with_manual_tool_execution(manual_tool_execution);
|
||||
// Resolve base instructions for the session. Priority order:
|
||||
// 1. config.base_instructions override
|
||||
// 2. conversation history => session_meta.base_instructions
|
||||
// 3. base_instructions for current model
|
||||
let model_info = models_manager.get_model_info(model.as_str(), &config).await;
|
||||
// 3. composed base instructions for the current tool/capability set
|
||||
let base_instructions = config
|
||||
.base_instructions
|
||||
.clone()
|
||||
.or_else(|| conversation_history.get_base_instructions().map(|s| s.text))
|
||||
.unwrap_or_else(|| model_info.get_model_instructions(config.personality));
|
||||
.unwrap_or_else(|| compose_base_instructions(&tools_config));
|
||||
|
||||
// Respect thread-start tools. When missing (resumed/forked threads), read from the db
|
||||
// first, then fall back to rollout-file tools.
|
||||
@@ -499,6 +509,7 @@ impl Codex {
|
||||
session_source,
|
||||
dynamic_tools,
|
||||
builtin_tools,
|
||||
manual_tool_execution,
|
||||
persist_extended_history,
|
||||
inherited_shell_snapshot,
|
||||
};
|
||||
@@ -748,7 +759,8 @@ impl TurnContext {
|
||||
})
|
||||
.with_allow_login_shell(self.tools_config.allow_login_shell)
|
||||
.with_agent_roles(config.agent_roles.clone())
|
||||
.with_builtin_tools(self.tools_config.builtin_tools.clone());
|
||||
.with_builtin_tools(self.tools_config.builtin_tools.clone())
|
||||
.with_manual_tool_execution(self.tools_config.manual_tool_execution);
|
||||
|
||||
Self {
|
||||
sub_id: self.sub_id.clone(),
|
||||
@@ -905,6 +917,7 @@ pub(crate) struct SessionConfiguration {
|
||||
session_source: SessionSource,
|
||||
dynamic_tools: Vec<DynamicToolSpec>,
|
||||
builtin_tools: Option<Vec<String>>,
|
||||
manual_tool_execution: bool,
|
||||
persist_extended_history: bool,
|
||||
inherited_shell_snapshot: Option<Arc<ShellSnapshot>>,
|
||||
}
|
||||
@@ -1125,7 +1138,8 @@ impl Session {
|
||||
})
|
||||
.with_allow_login_shell(per_turn_config.permissions.allow_login_shell)
|
||||
.with_agent_roles(per_turn_config.agent_roles.clone())
|
||||
.with_builtin_tools(session_configuration.builtin_tools.clone());
|
||||
.with_builtin_tools(session_configuration.builtin_tools.clone())
|
||||
.with_manual_tool_execution(session_configuration.manual_tool_execution);
|
||||
|
||||
let cwd = session_configuration.cwd.clone();
|
||||
let turn_metadata_state = Arc::new(TurnMetadataState::new(
|
||||
@@ -4918,7 +4932,8 @@ async fn spawn_review_thread(
|
||||
})
|
||||
.with_allow_login_shell(config.permissions.allow_login_shell)
|
||||
.with_agent_roles(config.agent_roles.clone())
|
||||
.with_builtin_tools(parent_turn_context.tools_config.builtin_tools.clone());
|
||||
.with_builtin_tools(parent_turn_context.tools_config.builtin_tools.clone())
|
||||
.with_manual_tool_execution(parent_turn_context.tools_config.manual_tool_execution);
|
||||
|
||||
let review_prompt = resolved.prompt.clone();
|
||||
let provider = parent_turn_context.provider.clone();
|
||||
|
||||
@@ -62,6 +62,7 @@ pub(crate) async fn run_codex_thread_interactive(
|
||||
Vec::new(),
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
|
||||
@@ -1426,6 +1426,7 @@ async fn set_rate_limits_retains_previous_credits() {
|
||||
session_source: SessionSource::Exec,
|
||||
dynamic_tools: Vec::new(),
|
||||
builtin_tools: None,
|
||||
manual_tool_execution: false,
|
||||
persist_extended_history: false,
|
||||
inherited_shell_snapshot: None,
|
||||
};
|
||||
@@ -1521,6 +1522,7 @@ async fn set_rate_limits_updates_plan_type_when_present() {
|
||||
session_source: SessionSource::Exec,
|
||||
dynamic_tools: Vec::new(),
|
||||
builtin_tools: None,
|
||||
manual_tool_execution: false,
|
||||
persist_extended_history: false,
|
||||
inherited_shell_snapshot: None,
|
||||
};
|
||||
@@ -1874,6 +1876,7 @@ pub(crate) async fn make_session_configuration_for_tests() -> SessionConfigurati
|
||||
session_source: SessionSource::Exec,
|
||||
dynamic_tools: Vec::new(),
|
||||
builtin_tools: None,
|
||||
manual_tool_execution: false,
|
||||
persist_extended_history: false,
|
||||
inherited_shell_snapshot: None,
|
||||
}
|
||||
@@ -1932,6 +1935,7 @@ async fn session_new_fails_when_zsh_fork_enabled_without_zsh_path() {
|
||||
session_source: SessionSource::Exec,
|
||||
dynamic_tools: Vec::new(),
|
||||
builtin_tools: None,
|
||||
manual_tool_execution: false,
|
||||
persist_extended_history: false,
|
||||
inherited_shell_snapshot: None,
|
||||
};
|
||||
@@ -2023,6 +2027,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
|
||||
session_source: SessionSource::Exec,
|
||||
dynamic_tools: Vec::new(),
|
||||
builtin_tools: None,
|
||||
manual_tool_execution: false,
|
||||
persist_extended_history: false,
|
||||
inherited_shell_snapshot: None,
|
||||
};
|
||||
@@ -2429,6 +2434,7 @@ pub(crate) async fn make_session_and_context_with_dynamic_tools_and_rx(
|
||||
session_source: SessionSource::Exec,
|
||||
dynamic_tools,
|
||||
builtin_tools: None,
|
||||
manual_tool_execution: false,
|
||||
persist_extended_history: false,
|
||||
inherited_shell_snapshot: None,
|
||||
};
|
||||
|
||||
@@ -175,6 +175,7 @@ pub(crate) struct ExecApprovalRequest<'a> {
|
||||
pub(crate) sandbox_policy: &'a SandboxPolicy,
|
||||
pub(crate) sandbox_permissions: SandboxPermissions,
|
||||
pub(crate) prefix_rule: Option<Vec<String>>,
|
||||
pub(crate) manual_tool_execution: bool,
|
||||
}
|
||||
|
||||
impl ExecPolicyManager {
|
||||
@@ -206,6 +207,7 @@ impl ExecPolicyManager {
|
||||
sandbox_policy,
|
||||
sandbox_permissions,
|
||||
prefix_rule,
|
||||
manual_tool_execution,
|
||||
} = req;
|
||||
let exec_policy = self.current();
|
||||
let (commands, used_complex_parsing) = commands_for_exec_policy(command);
|
||||
@@ -220,6 +222,7 @@ impl ExecPolicyManager {
|
||||
cmd,
|
||||
sandbox_permissions,
|
||||
used_complex_parsing,
|
||||
manual_tool_execution,
|
||||
)
|
||||
};
|
||||
let match_options = MatchOptions {
|
||||
@@ -491,7 +494,11 @@ pub fn render_decision_for_unmatched_command(
|
||||
command: &[String],
|
||||
sandbox_permissions: SandboxPermissions,
|
||||
used_complex_parsing: bool,
|
||||
manual_tool_execution: bool,
|
||||
) -> Decision {
|
||||
if manual_tool_execution {
|
||||
return Decision::Prompt;
|
||||
}
|
||||
if is_known_safe_command(command) && !used_complex_parsing {
|
||||
return Decision::Allow;
|
||||
}
|
||||
@@ -1234,6 +1241,7 @@ prefix_rule(pattern=["rm"], decision="forbidden")
|
||||
sandbox_policy: &SandboxPolicy::DangerFullAccess,
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1284,6 +1292,7 @@ prefix_rule(pattern=["rm"], decision="forbidden")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1311,6 +1320,7 @@ prefix_rule(pattern=["rm"], decision="forbidden")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1339,6 +1349,7 @@ prefix_rule(pattern=["rm"], decision="forbidden")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: Some(requested_prefix.clone()),
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1378,6 +1389,7 @@ prefix_rule(
|
||||
sandbox_policy: &SandboxPolicy::DangerFullAccess,
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1407,6 +1419,7 @@ prefix_rule(
|
||||
sandbox_policy: &SandboxPolicy::DangerFullAccess,
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1443,6 +1456,7 @@ prefix_rule(pattern=["git"], decision="allow")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1485,6 +1499,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1513,6 +1528,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: Some(vec!["cargo".to_string(), "install".to_string()]),
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1546,6 +1562,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::DangerFullAccess,
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1573,6 +1590,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
&command,
|
||||
SandboxPermissions::RequireEscalated,
|
||||
false,
|
||||
false,
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -1592,6 +1610,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::RequireEscalated,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1628,6 +1647,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::RequireEscalated,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1662,6 +1682,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::RequireEscalated,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1685,6 +1706,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1709,6 +1731,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1737,6 +1760,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1765,6 +1789,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::RequireEscalated,
|
||||
prefix_rule: Some(vec!["cargo".to_string(), "install".to_string()]),
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1796,6 +1821,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::DangerFullAccess,
|
||||
sandbox_permissions: SandboxPermissions::RequireEscalated,
|
||||
prefix_rule: Some(vec!["cargo".to_string(), "install".to_string()]),
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1834,6 +1860,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::DangerFullAccess,
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await,
|
||||
ExecApprovalRequirement::NeedsApproval {
|
||||
@@ -1908,6 +1935,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1938,6 +1966,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::DangerFullAccess,
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1965,6 +1994,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -2003,6 +2033,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await,
|
||||
ExecApprovalRequirement::NeedsApproval {
|
||||
@@ -2026,6 +2057,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -2038,6 +2070,31 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn manual_tool_execution_requires_approval_for_safe_command() {
|
||||
let command = vec!["echo".to_string(), "safe".to_string()];
|
||||
|
||||
let manager = ExecPolicyManager::default();
|
||||
let requirement = manager
|
||||
.create_exec_approval_requirement_for_command(ExecApprovalRequest {
|
||||
command: &command,
|
||||
approval_policy: AskForApproval::OnRequest,
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: true,
|
||||
})
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
requirement,
|
||||
ExecApprovalRequirement::NeedsApproval {
|
||||
reason: None,
|
||||
proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(command)),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn proposed_execpolicy_amendment_is_suppressed_when_policy_matches_allow() {
|
||||
let policy_src = r#"prefix_rule(pattern=["echo"], decision="allow")"#;
|
||||
@@ -2056,6 +2113,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -2229,6 +2287,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::DangerFullAccess,
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -2295,6 +2354,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: permissions,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await,
|
||||
"{pwsh_approval_reason}"
|
||||
@@ -2318,6 +2378,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: permissions,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await,
|
||||
r#"On all platforms, a forbidden command should require approval
|
||||
@@ -2337,6 +2398,7 @@ prefix_rule(pattern=["git"], decision="prompt")
|
||||
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
|
||||
sandbox_permissions: permissions,
|
||||
prefix_rule: None,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await,
|
||||
r#"On all platforms, a forbidden command should require approval
|
||||
|
||||
@@ -10,6 +10,7 @@ pub mod api_bridge;
|
||||
mod apply_patch;
|
||||
mod apps;
|
||||
pub mod auth;
|
||||
mod base_instructions;
|
||||
mod client;
|
||||
mod client_common;
|
||||
pub mod codex;
|
||||
|
||||
@@ -314,7 +314,7 @@ impl ThreadManager {
|
||||
pub async fn start_thread(&self, config: Config) -> CodexResult<NewThread> {
|
||||
// Box delegated thread-spawn futures so these convenience wrappers do
|
||||
// not inline the full spawn path into every caller's async state.
|
||||
Box::pin(self.start_thread_with_tools(config, Vec::new(), None, false)).await
|
||||
Box::pin(self.start_thread_with_tools(config, Vec::new(), None, false, false)).await
|
||||
}
|
||||
|
||||
pub async fn start_thread_with_tools(
|
||||
@@ -322,12 +322,14 @@ impl ThreadManager {
|
||||
config: Config,
|
||||
dynamic_tools: Vec<codex_protocol::dynamic_tools::DynamicToolSpec>,
|
||||
builtin_tools: Option<Vec<String>>,
|
||||
manual_tool_execution: bool,
|
||||
persist_extended_history: bool,
|
||||
) -> CodexResult<NewThread> {
|
||||
Box::pin(self.start_thread_with_tools_and_service_name(
|
||||
config,
|
||||
dynamic_tools,
|
||||
builtin_tools,
|
||||
manual_tool_execution,
|
||||
persist_extended_history,
|
||||
None,
|
||||
))
|
||||
@@ -339,6 +341,7 @@ impl ThreadManager {
|
||||
config: Config,
|
||||
dynamic_tools: Vec<codex_protocol::dynamic_tools::DynamicToolSpec>,
|
||||
builtin_tools: Option<Vec<String>>,
|
||||
manual_tool_execution: bool,
|
||||
persist_extended_history: bool,
|
||||
metrics_service_name: Option<String>,
|
||||
) -> CodexResult<NewThread> {
|
||||
@@ -349,6 +352,7 @@ impl ThreadManager {
|
||||
self.agent_control(),
|
||||
dynamic_tools,
|
||||
builtin_tools,
|
||||
manual_tool_execution,
|
||||
persist_extended_history,
|
||||
metrics_service_name,
|
||||
))
|
||||
@@ -380,6 +384,7 @@ impl ThreadManager {
|
||||
self.agent_control(),
|
||||
Vec::new(),
|
||||
None,
|
||||
false,
|
||||
persist_extended_history,
|
||||
None,
|
||||
))
|
||||
@@ -422,6 +427,7 @@ impl ThreadManager {
|
||||
self.agent_control(),
|
||||
Vec::new(),
|
||||
None,
|
||||
false,
|
||||
persist_extended_history,
|
||||
None,
|
||||
))
|
||||
@@ -506,6 +512,7 @@ impl ThreadManagerState {
|
||||
session_source,
|
||||
Vec::new(),
|
||||
None,
|
||||
false,
|
||||
persist_extended_history,
|
||||
metrics_service_name,
|
||||
inherited_shell_snapshot,
|
||||
@@ -531,6 +538,7 @@ impl ThreadManagerState {
|
||||
Vec::new(),
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
None,
|
||||
inherited_shell_snapshot,
|
||||
))
|
||||
@@ -554,6 +562,7 @@ impl ThreadManagerState {
|
||||
session_source,
|
||||
Vec::new(),
|
||||
None,
|
||||
false,
|
||||
persist_extended_history,
|
||||
None,
|
||||
inherited_shell_snapshot,
|
||||
@@ -571,6 +580,7 @@ impl ThreadManagerState {
|
||||
agent_control: AgentControl,
|
||||
dynamic_tools: Vec<codex_protocol::dynamic_tools::DynamicToolSpec>,
|
||||
builtin_tools: Option<Vec<String>>,
|
||||
manual_tool_execution: bool,
|
||||
persist_extended_history: bool,
|
||||
metrics_service_name: Option<String>,
|
||||
) -> CodexResult<NewThread> {
|
||||
@@ -582,6 +592,7 @@ impl ThreadManagerState {
|
||||
self.session_source.clone(),
|
||||
dynamic_tools,
|
||||
builtin_tools,
|
||||
manual_tool_execution,
|
||||
persist_extended_history,
|
||||
metrics_service_name,
|
||||
None,
|
||||
@@ -599,6 +610,7 @@ impl ThreadManagerState {
|
||||
session_source: SessionSource,
|
||||
dynamic_tools: Vec<codex_protocol::dynamic_tools::DynamicToolSpec>,
|
||||
builtin_tools: Option<Vec<String>>,
|
||||
manual_tool_execution: bool,
|
||||
persist_extended_history: bool,
|
||||
metrics_service_name: Option<String>,
|
||||
inherited_shell_snapshot: Option<Arc<ShellSnapshot>>,
|
||||
@@ -621,6 +633,7 @@ impl ThreadManagerState {
|
||||
agent_control,
|
||||
dynamic_tools,
|
||||
builtin_tools,
|
||||
manual_tool_execution,
|
||||
persist_extended_history,
|
||||
metrics_service_name,
|
||||
inherited_shell_snapshot,
|
||||
|
||||
@@ -129,7 +129,7 @@ impl ToolHandler for ApplyPatchHandler {
|
||||
);
|
||||
emitter.begin(event_ctx).await;
|
||||
|
||||
let req = ApplyPatchRequest {
|
||||
let mut req = ApplyPatchRequest {
|
||||
action: apply.action,
|
||||
file_paths,
|
||||
changes,
|
||||
@@ -149,7 +149,7 @@ impl ToolHandler for ApplyPatchHandler {
|
||||
let out = orchestrator
|
||||
.run(
|
||||
&mut runtime,
|
||||
&req,
|
||||
&mut req,
|
||||
&tool_ctx,
|
||||
turn.as_ref(),
|
||||
turn.approval_policy.value(),
|
||||
@@ -231,7 +231,7 @@ pub(crate) async fn intercept_apply_patch(
|
||||
);
|
||||
emitter.begin(event_ctx).await;
|
||||
|
||||
let req = ApplyPatchRequest {
|
||||
let mut req = ApplyPatchRequest {
|
||||
action: apply.action,
|
||||
file_paths: approval_keys,
|
||||
changes,
|
||||
@@ -251,7 +251,7 @@ pub(crate) async fn intercept_apply_patch(
|
||||
let out = orchestrator
|
||||
.run(
|
||||
&mut runtime,
|
||||
&req,
|
||||
&mut req,
|
||||
&tool_ctx,
|
||||
turn.as_ref(),
|
||||
turn.approval_policy.value(),
|
||||
|
||||
@@ -389,10 +389,11 @@ impl ShellHandler {
|
||||
sandbox_policy: turn.sandbox_policy.get(),
|
||||
sandbox_permissions: exec_params.sandbox_permissions,
|
||||
prefix_rule,
|
||||
manual_tool_execution: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
let req = ShellRequest {
|
||||
let mut req = ShellRequest {
|
||||
command: exec_params.command.clone(),
|
||||
cwd: exec_params.cwd.clone(),
|
||||
timeout_ms: exec_params.expiration.timeout_ms(),
|
||||
@@ -423,7 +424,7 @@ impl ShellHandler {
|
||||
let out = orchestrator
|
||||
.run(
|
||||
&mut runtime,
|
||||
&req,
|
||||
&mut req,
|
||||
&tool_ctx,
|
||||
&turn,
|
||||
turn.approval_policy.value(),
|
||||
|
||||
@@ -349,7 +349,9 @@ impl NetworkApprovalService {
|
||||
|
||||
let mut cache_session_deny = false;
|
||||
let resolved = match approval_decision {
|
||||
ReviewDecision::Approved | ReviewDecision::ApprovedExecpolicyAmendment { .. } => {
|
||||
ReviewDecision::Approved
|
||||
| ReviewDecision::ApprovedWithCommandOverride { .. }
|
||||
| ReviewDecision::ApprovedExecpolicyAmendment { .. } => {
|
||||
PendingApprovalDecision::AllowOnce
|
||||
}
|
||||
ReviewDecision::ApprovedForSession => PendingApprovalDecision::AllowForSession,
|
||||
|
||||
@@ -100,7 +100,7 @@ impl ToolOrchestrator {
|
||||
pub async fn run<Rq, Out, T>(
|
||||
&mut self,
|
||||
tool: &mut T,
|
||||
req: &Rq,
|
||||
req: &mut Rq,
|
||||
tool_ctx: &ToolCtx,
|
||||
turn_ctx: &crate::codex::TurnContext,
|
||||
approval_policy: AskForApproval,
|
||||
@@ -144,10 +144,11 @@ impl ToolOrchestrator {
|
||||
return Err(ToolError::Rejected("rejected by user".to_string()));
|
||||
}
|
||||
ReviewDecision::Approved
|
||||
| ReviewDecision::ApprovedWithCommandOverride { .. }
|
||||
| ReviewDecision::ApprovedExecpolicyAmendment { .. }
|
||||
| ReviewDecision::ApprovedForSession => {}
|
||||
ReviewDecision::NetworkPolicyAmendment {
|
||||
network_policy_amendment,
|
||||
ref network_policy_amendment,
|
||||
} => match network_policy_amendment.action {
|
||||
NetworkPolicyRuleAction::Allow => {}
|
||||
NetworkPolicyRuleAction::Deny => {
|
||||
@@ -155,6 +156,7 @@ impl ToolOrchestrator {
|
||||
}
|
||||
},
|
||||
}
|
||||
tool.apply_approval_decision(req, &decision);
|
||||
already_approved = true;
|
||||
}
|
||||
}
|
||||
@@ -280,10 +282,11 @@ impl ToolOrchestrator {
|
||||
return Err(ToolError::Rejected("rejected by user".to_string()));
|
||||
}
|
||||
ReviewDecision::Approved
|
||||
| ReviewDecision::ApprovedWithCommandOverride { .. }
|
||||
| ReviewDecision::ApprovedExecpolicyAmendment { .. }
|
||||
| ReviewDecision::ApprovedForSession => {}
|
||||
ReviewDecision::NetworkPolicyAmendment {
|
||||
network_policy_amendment,
|
||||
ref network_policy_amendment,
|
||||
} => match network_policy_amendment.action {
|
||||
NetworkPolicyRuleAction::Allow => {}
|
||||
NetworkPolicyRuleAction::Deny => {
|
||||
@@ -291,6 +294,7 @@ impl ToolOrchestrator {
|
||||
}
|
||||
},
|
||||
}
|
||||
tool.apply_approval_decision(req, &decision);
|
||||
}
|
||||
|
||||
let escalated_attempt = SandboxAttempt {
|
||||
|
||||
@@ -452,6 +452,7 @@ impl CoreShellActionProvider {
|
||||
.await?
|
||||
{
|
||||
ReviewDecision::Approved
|
||||
| ReviewDecision::ApprovedWithCommandOverride { .. }
|
||||
| ReviewDecision::ApprovedExecpolicyAmendment { .. } => {
|
||||
if needs_escalation {
|
||||
EscalationDecision::escalate(escalation_execution.clone())
|
||||
@@ -677,6 +678,7 @@ fn evaluate_intercepted_exec_policy(
|
||||
cmd,
|
||||
sandbox_permissions,
|
||||
used_complex_parsing,
|
||||
false,
|
||||
)
|
||||
};
|
||||
|
||||
|
||||
@@ -144,6 +144,12 @@ impl Approvable<UnifiedExecRequest> for UnifiedExecRuntime<'_> {
|
||||
Some(req.exec_approval_requirement.clone())
|
||||
}
|
||||
|
||||
fn apply_approval_decision(&self, req: &mut UnifiedExecRequest, decision: &ReviewDecision) {
|
||||
if let ReviewDecision::ApprovedWithCommandOverride { command } = decision {
|
||||
req.command = command.clone();
|
||||
}
|
||||
}
|
||||
|
||||
fn sandbox_mode_for_first_attempt(&self, req: &UnifiedExecRequest) -> SandboxOverride {
|
||||
sandbox_override_for_first_attempt(req.sandbox_permissions, &req.exec_approval_requirement)
|
||||
}
|
||||
|
||||
@@ -271,6 +271,8 @@ pub(crate) trait Approvable<Req> {
|
||||
req: &'a Req,
|
||||
ctx: ApprovalCtx<'a>,
|
||||
) -> BoxFuture<'a, ReviewDecision>;
|
||||
|
||||
fn apply_approval_decision(&self, _req: &mut Req, _decision: &ReviewDecision) {}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
|
||||
@@ -74,6 +74,7 @@ pub(crate) struct ToolsConfig {
|
||||
pub agent_jobs_tools: bool,
|
||||
pub agent_jobs_worker_tools: bool,
|
||||
pub builtin_tools: Option<Vec<String>>,
|
||||
pub manual_tool_execution: bool,
|
||||
}
|
||||
|
||||
pub(crate) struct ToolsConfigParams<'a> {
|
||||
@@ -175,6 +176,7 @@ impl ToolsConfig {
|
||||
agent_jobs_tools: include_agent_jobs,
|
||||
agent_jobs_worker_tools,
|
||||
builtin_tools: None,
|
||||
manual_tool_execution: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,6 +194,30 @@ impl ToolsConfig {
|
||||
self.builtin_tools = builtin_tools;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_manual_tool_execution(mut self, manual_tool_execution: bool) -> Self {
|
||||
self.manual_tool_execution = manual_tool_execution;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn has_builtin_tool(&self, tool_name: &str) -> bool {
|
||||
if let Some(builtin_tools) = &self.builtin_tools {
|
||||
return builtin_tools.iter().any(|tool| tool == tool_name);
|
||||
}
|
||||
|
||||
match tool_name {
|
||||
"exec_command" | "write_stdin" => self.shell_type == ConfigShellToolType::UnifiedExec,
|
||||
"update_plan" => true,
|
||||
"request_user_input" => self.request_user_input,
|
||||
"apply_patch" => self.apply_patch_tool_type.is_some(),
|
||||
"search_tool_bm25" => self.search_tool,
|
||||
"view_image" => true,
|
||||
"spawn_agent" => self.collab_tools,
|
||||
"spawn_agents_on_csv" => self.agent_jobs_tools,
|
||||
"artifacts" => self.artifact_tools,
|
||||
_ => self.experimental_supported_tools.iter().any(|tool| tool == tool_name),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn supports_image_generation(model_info: &ModelInfo) -> bool {
|
||||
|
||||
@@ -584,9 +584,10 @@ impl UnifiedExecProcessManager {
|
||||
sandbox_policy: context.turn.sandbox_policy.get(),
|
||||
sandbox_permissions: request.sandbox_permissions,
|
||||
prefix_rule: request.prefix_rule.clone(),
|
||||
manual_tool_execution: context.turn.tools_config.manual_tool_execution,
|
||||
})
|
||||
.await;
|
||||
let req = UnifiedExecToolRequest {
|
||||
let mut req = UnifiedExecToolRequest {
|
||||
command: request.command.clone(),
|
||||
cwd,
|
||||
env,
|
||||
@@ -607,7 +608,7 @@ impl UnifiedExecProcessManager {
|
||||
orchestrator
|
||||
.run(
|
||||
&mut runtime,
|
||||
&req,
|
||||
&mut req,
|
||||
&tool_ctx,
|
||||
&context.turn,
|
||||
context.turn.approval_policy.value(),
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# Apply Patch
|
||||
|
||||
The `apply_patch` tool is available for editing files. Use `apply_patch` rather than `applypatch` or `apply-patch`.
|
||||
|
||||
When using `apply_patch`:
|
||||
|
||||
- Prefer it for focused file edits.
|
||||
- Do not re-read a file just to verify the patch landed; the tool call will fail if it did not apply.
|
||||
@@ -0,0 +1,9 @@
|
||||
# Unified Exec
|
||||
|
||||
You can run terminal commands with `exec_command` and interact with long-running processes with `write_stdin`.
|
||||
|
||||
When using `exec_command` and `write_stdin`, follow these guidelines:
|
||||
|
||||
- Prefer `rg` or `rg --files` over slower alternatives like `grep` when searching for text or files.
|
||||
- Do not use Python scripts just to print large chunks of a file when a shell tool can do it directly.
|
||||
- Before making tool calls, send a brief preamble to the user explaining what you’re about to do.
|
||||
@@ -0,0 +1,10 @@
|
||||
# Update Plan
|
||||
|
||||
An `update_plan` tool is available. Use it to keep a concise, step-by-step plan for the task when a plan is warranted.
|
||||
|
||||
When using `update_plan`:
|
||||
|
||||
- Create short steps with a `status` for each step: `pending`, `in_progress`, or `completed`.
|
||||
- Keep exactly one step `in_progress` until the work is done.
|
||||
- Mark steps complete as you go rather than restating the entire plan in prose.
|
||||
- When all steps are finished, mark every step `completed`.
|
||||
@@ -0,0 +1,254 @@
|
||||
You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful.
|
||||
|
||||
Your capabilities:
|
||||
|
||||
- Receive user prompts and other context provided by the harness, such as files in the workspace.
|
||||
- Communicate with the user by streaming thinking and responses.
|
||||
- Use the tools available in this run to inspect, modify, and validate work.
|
||||
|
||||
Within this context, Codex refers to the open-source agentic coding interface (not the old Codex language model built by OpenAI).
|
||||
|
||||
# How you work
|
||||
|
||||
## Personality
|
||||
|
||||
Your default personality and tone is concise, direct, and friendly. You communicate efficiently, always keeping the user clearly informed about ongoing actions without unnecessary detail. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work.
|
||||
|
||||
# AGENTS.md spec
|
||||
- Repos often contain AGENTS.md files. These files can appear anywhere within the repository.
|
||||
- These files are a way for humans to give you (the agent) instructions or tips for working within the container.
|
||||
- Some examples might be: coding conventions, info about how code is organized, or instructions for how to run or test code.
|
||||
- Instructions in AGENTS.md files:
|
||||
- The scope of an AGENTS.md file is the entire directory tree rooted at the folder that contains it.
|
||||
- For every file you touch in the final patch, you must obey instructions in any AGENTS.md file whose scope includes that file.
|
||||
- Instructions about code style, structure, naming, etc. apply only to code within the AGENTS.md file's scope, unless the file states otherwise.
|
||||
- More-deeply-nested AGENTS.md files take precedence in the case of conflicting instructions.
|
||||
- Direct system/developer/user instructions (as part of a prompt) take precedence over AGENTS.md instructions.
|
||||
- The contents of the AGENTS.md file at the root of the repo and any directories from the CWD up to the root are included with the developer message and don't need to be re-read. When working in a subdirectory of CWD, or a directory outside the CWD, check for any AGENTS.md files that may be applicable.
|
||||
|
||||
## Responsiveness
|
||||
|
||||
### Preamble messages
|
||||
|
||||
Before making tool calls, send a brief preamble to the user explaining what you’re about to do. When sending preamble messages, follow these principles and examples:
|
||||
|
||||
- **Logically group related actions**: if you’re about to run several related commands, describe them together in one preamble rather than sending a separate note for each.
|
||||
- **Keep it concise**: be no more than 1-2 sentences, focused on immediate, tangible next steps. (8–12 words for quick updates).
|
||||
- **Build on prior context**: if this is not your first tool call, use the preamble message to connect the dots with what’s been done so far and create a sense of momentum and clarity for the user to understand your next actions.
|
||||
- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.
|
||||
- **Exception**: Avoid adding a preamble for every trivial read (e.g., `cat` a single file) unless it’s part of a larger grouped action.
|
||||
|
||||
**Examples:**
|
||||
|
||||
- “I’ve explored the repo; now checking the API route definitions.”
|
||||
- “Next, I’ll patch the config and update the related tests.”
|
||||
- “I’m about to scaffold the CLI commands and helper functions.”
|
||||
- “Ok cool, so I’ve wrapped my head around the repo. Now digging into the API routes.”
|
||||
- “Config’s looking tidy. Next up is patching helpers to keep things in sync.”
|
||||
- “Finished poking at the DB gateway. I will now chase down error handling.”
|
||||
- “Alright, build pipeline order is interesting. Checking how it reports failures.”
|
||||
- “Spotted a clever caching util; now hunting where it gets used.”
|
||||
|
||||
## Planning
|
||||
|
||||
Plans can help demonstrate that you've understood the task and convey how you're approaching it. A good plan breaks the task into meaningful, logically ordered steps that are easy to verify as you go.
|
||||
|
||||
Note that plans are not for padding out simple work with filler steps or stating the obvious. The content of your plan should not involve doing anything that you aren't capable of doing (i.e. don't try to test things that you can't test). Do not use plans for simple or single-step queries that you can just do or answer immediately.
|
||||
|
||||
After updating a plan, summarize only the change and the next step rather than repeating the whole plan.
|
||||
|
||||
Before running a command, consider whether or not you have completed the previous step, and make sure to mark it as completed before moving on to the next step. It may be the case that you complete all steps in your plan after a single pass of implementation. If this is the case, you can simply mark all steps as completed. Sometimes, you may need to change plans in the middle of a task.
|
||||
|
||||
Use a plan when:
|
||||
|
||||
- The task is non-trivial and will require multiple actions over a long time horizon.
|
||||
- There are logical phases or dependencies where sequencing matters.
|
||||
- The work has ambiguity that benefits from outlining high-level goals.
|
||||
- You want intermediate checkpoints for feedback and validation.
|
||||
- When the user asked you to do more than one thing in a single prompt.
|
||||
- When the user explicitly asks for TODOs or a plan.
|
||||
- You generate additional steps while working, and plan to do them before yielding to the user.
|
||||
|
||||
### Examples
|
||||
|
||||
**High-quality plans**
|
||||
|
||||
Example 1:
|
||||
|
||||
1. Add CLI entry with file args
|
||||
2. Parse Markdown via CommonMark library
|
||||
3. Apply semantic HTML template
|
||||
4. Handle code blocks, images, links
|
||||
5. Add error handling for invalid files
|
||||
|
||||
Example 2:
|
||||
|
||||
1. Define CSS variables for colors
|
||||
2. Add toggle with localStorage state
|
||||
3. Refactor components to use variables
|
||||
4. Verify all views for readability
|
||||
5. Add smooth theme-change transition
|
||||
|
||||
Example 3:
|
||||
|
||||
1. Set up Node.js + WebSocket server
|
||||
2. Add join/leave broadcast events
|
||||
3. Implement messaging with timestamps
|
||||
4. Add usernames + mention highlighting
|
||||
5. Persist messages in lightweight DB
|
||||
6. Add typing indicators + unread count
|
||||
|
||||
**Low-quality plans**
|
||||
|
||||
Example 1:
|
||||
|
||||
1. Create CLI tool
|
||||
2. Add Markdown parser
|
||||
3. Convert to HTML
|
||||
|
||||
Example 2:
|
||||
|
||||
1. Add dark mode toggle
|
||||
2. Save preference
|
||||
3. Make styles look good
|
||||
|
||||
Example 3:
|
||||
|
||||
1. Create single-file HTML game
|
||||
2. Run quick sanity check
|
||||
3. Summarize usage instructions
|
||||
|
||||
If you need to write a plan, only write high quality plans, not low quality ones.
|
||||
|
||||
## Task execution
|
||||
|
||||
You are a coding agent. Please keep going until the query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. Autonomously resolve the query to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer.
|
||||
|
||||
You MUST adhere to the following criteria when solving queries:
|
||||
|
||||
- Working on the repo(s) in the current environment is allowed, even if they are proprietary.
|
||||
- Analyzing code for vulnerabilities is allowed.
|
||||
- Showing user code and tool call details is allowed.
|
||||
|
||||
If completing the user's task requires writing or modifying files, your code and final answer should follow these coding guidelines, though user instructions (i.e. AGENTS.md) may override these guidelines:
|
||||
|
||||
- Fix the problem at the root cause rather than applying surface-level patches, when possible.
|
||||
- Avoid unneeded complexity in your solution.
|
||||
- Do not attempt to fix unrelated bugs or broken tests. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)
|
||||
- Update documentation as necessary.
|
||||
- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.
|
||||
- Use `git log` and `git blame` to search the history of the codebase if additional context is required.
|
||||
- NEVER add copyright or license headers unless specifically requested.
|
||||
- Do not `git commit` your changes or create new git branches unless explicitly requested.
|
||||
- Do not add inline comments within code unless explicitly requested.
|
||||
- Do not use one-letter variable names unless explicitly requested.
|
||||
- NEVER output inline citations like "【F:README.md†L5-L14】" in your outputs. The CLI is not able to render these so they will just be broken in the UI. Instead, if you output valid filepaths, users will be able to click on them to open the files in their editor.
|
||||
|
||||
## Validating your work
|
||||
|
||||
If the codebase has tests or the ability to build or run, consider using them to verify that your work is complete.
|
||||
|
||||
When testing, your philosophy should be to start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence. If there's no test for the code you changed, and if the adjacent patterns in the codebases show that there's a logical place for you to add a test, you may do so. However, do not add tests to codebases with no tests.
|
||||
|
||||
Similarly, once you're confident in correctness, you can suggest or use formatting commands to ensure that your code is well formatted. If there are issues you can iterate up to 3 times to get formatting right, but if you still can't manage it's better to save the user time and present them a correct solution where you call out the formatting in your final message. If the codebase does not have a formatter configured, do not add one.
|
||||
|
||||
For all of testing, running, building, and formatting, do not attempt to fix unrelated bugs. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)
|
||||
|
||||
Be mindful of whether to run validation commands proactively. In the absence of behavioral guidance:
|
||||
|
||||
- When running in non-interactive approval modes like **never** or **on-failure**, proactively run tests, lint and do whatever you need to ensure you've completed the task.
|
||||
- When working in interactive approval modes like **untrusted**, or **on-request**, hold off on running tests or lint commands until the user is ready for you to finalize your output, because these commands take time to run and slow down iteration. Instead suggest what you want to do next, and let the user confirm first.
|
||||
- When working on test-related tasks, such as adding tests, fixing tests, or reproducing a bug to verify behavior, you may proactively run tests regardless of approval mode. Use your judgement to decide whether this is a test-related task.
|
||||
|
||||
## Ambition vs. precision
|
||||
|
||||
For tasks that have no prior context (i.e. the user is starting something brand new), you should feel free to be ambitious and demonstrate creativity with your implementation.
|
||||
|
||||
If you're operating in an existing codebase, you should make sure you do exactly what the user asks with surgical precision. Treat the surrounding codebase with respect, and don't overstep (i.e. changing filenames or variables unnecessarily). You should balance being sufficiently ambitious and proactive when completing tasks of this nature.
|
||||
|
||||
You should use judicious initiative to decide on the right level of detail and complexity to deliver based on the user's needs. This means showing good judgment that you're capable of doing the right extras without gold-plating. This might be demonstrated by high-value, creative touches when scope of the task is vague; while being surgical and targeted when scope is tightly specified.
|
||||
|
||||
## Sharing progress updates
|
||||
|
||||
For especially longer tasks that you work on (i.e. requiring many tool calls, or a plan with multiple steps), you should provide progress updates back to the user at reasonable intervals. These updates should be structured as a concise sentence or two (no more than 8-10 words long) recapping progress so far in plain language: this update demonstrates your understanding of what needs to be done, progress so far (i.e. files explores, subtasks complete), and where you're going next.
|
||||
|
||||
Before doing large chunks of work that may incur latency as experienced by the user (i.e. writing a new file), you should send a concise message to the user with an update indicating what you are doing to ensure they know what you are spending time on. Don't start editing or writing large files before informing the user what you are doing and why.
|
||||
|
||||
The messages you send before tool calls should describe what is immediately about to be done next in very concise language. If there was previous work done, this preamble message should also include a note about the work done so far to bring the user along.
|
||||
|
||||
## Presenting your work and final message
|
||||
|
||||
Your final message should read naturally, like an update from a concise teammate. For casual conversation, brainstorming tasks, or quick questions from the user, respond in a friendly, conversational tone. You should ask questions, suggest ideas, and adapt to the user’s style. If you've finished a large amount of work, when describing what you've done to the user, you should follow the final answer formatting guidelines to communicate substantive changes. You don't need to add structured formatting for one-word answers, greetings, or purely conversational exchanges.
|
||||
|
||||
You can skip heavy formatting for single, simple actions or confirmations. In these cases, respond in plain sentences with any relevant next step or quick option. Reserve multi-section structured responses for results that need grouping or explanation.
|
||||
|
||||
The user is working on the same computer as you, and has access to your work. As such there's no need to show the full contents of large files you have already written unless the user explicitly asks for them. Similarly, if you've created or modified files using the editing tools available in this run, there's no need to tell users to "save the file" or "copy the code into a file". Just reference the file path.
|
||||
|
||||
If there's something that you think you could help with as a logical next step, concisely ask the user if they want you to do so. Good examples of this are running tests, committing changes, or building out the next logical component. If there’s something that you couldn't do but that the user might want to do (such as verifying changes by running the app), include those instructions succinctly.
|
||||
|
||||
Brevity is very important as a default. You should be very concise (i.e. no more than 10 lines), but can relax this requirement for tasks where additional detail and comprehensiveness is important for the user's understanding.
|
||||
|
||||
### Final answer structure and style guidelines
|
||||
|
||||
You are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.
|
||||
|
||||
**Section Headers**
|
||||
|
||||
- Use only when they improve clarity. They are not mandatory for every answer.
|
||||
- Choose descriptive names that fit the content.
|
||||
- Keep headers short (1–3 words) and in `**Title Case**`. Always start headers with `**` and end with `**`.
|
||||
- Leave no blank line before the first bullet under a header.
|
||||
- Section headers should only be used where they genuinely improve scanability; avoid fragmenting the answer.
|
||||
|
||||
**Bullets**
|
||||
|
||||
- Use `-` followed by a space for every bullet.
|
||||
- Merge related points when possible; avoid a bullet for every trivial detail.
|
||||
- Keep bullets to one line unless breaking for clarity is unavoidable.
|
||||
- Group into short lists (4–6 bullets) ordered by importance.
|
||||
- Use consistent keyword phrasing and formatting across sections.
|
||||
|
||||
**Monospace**
|
||||
|
||||
- Wrap all commands, file paths, env vars, and code identifiers in backticks.
|
||||
- Apply this to inline examples and to bullet keywords if the keyword itself is a literal file or command.
|
||||
- Never mix monospace and bold markers; choose one based on whether it’s a keyword or inline code/path.
|
||||
|
||||
**File References**
|
||||
When referencing files in your response, make sure to include the relevant start line and always follow the below rules:
|
||||
* Use inline code to make file paths clickable.
|
||||
* Each reference should have a stand alone path. Even if it's the same file.
|
||||
* Accepted: absolute, workspace-relative, `a/` or `b/` diff prefixes, or bare filename/suffix.
|
||||
* Line/column (1-based, optional): `:line[:column]` or `#Lline[Ccolumn]` (column defaults to 1).
|
||||
* Do not use URIs like `file://`, `vscode://`, or `https://`.
|
||||
* Do not provide range of lines.
|
||||
* Examples: `src/app.ts`, `src/app.ts:42`, `b/server/index.js#L10`, `C:\repo\project\main.rs:12:5`
|
||||
|
||||
**Structure**
|
||||
|
||||
- Place related bullets together; don’t mix unrelated concepts in the same section.
|
||||
- Order sections from general to specific to supporting info.
|
||||
- For subsections (e.g. "Binaries" under "Rust Workspace"), introduce with a bolded keyword bullet, then list items under it.
|
||||
- Match structure to complexity:
|
||||
- Multi-part or detailed results: use clear headers and grouped bullets.
|
||||
- Simple results: use minimal headers, possibly just a short list or paragraph.
|
||||
|
||||
**Tone**
|
||||
|
||||
- Keep the voice collaborative and natural, like a coding partner handing off work.
|
||||
- Be concise and factual. Avoid filler or unnecessary repetition.
|
||||
- Use present tense and active voice (e.g. "Runs tests" not "This will run tests").
|
||||
- Keep descriptions self-contained; don’t refer to “above” or “below”.
|
||||
- Use parallel structure in lists for consistency.
|
||||
|
||||
**Don’t**
|
||||
|
||||
- Don’t use the literal words “bold” or “monospace” in the content.
|
||||
- Don’t nest bullets or create deep hierarchies.
|
||||
- Don’t output ANSI escape codes directly.
|
||||
- Don’t cram unrelated keywords into a single bullet; split for clarity.
|
||||
- Don’t let keyword lists run long. Wrap or reformat for scanability.
|
||||
|
||||
Generally, ensure your final answers adapt their shape and depth to the request. For example, answers to code explanations should have a precise, structured explanation with code references that answer the question directly. For tasks with a simple implementation, lead with the outcome and supplement only with what’s needed for clarity. Larger changes can be presented as a logical walkthrough of your approach, grouping related steps, explaining rationale where it adds value, and highlighting next actions to accelerate the user. Your answers should provide the right level of detail while being easily scannable.
|
||||
|
||||
For casual greetings, acknowledgements, or other one-off conversational messages that are not delivering substantive information or structured results, respond naturally without section headers or bullet formatting.
|
||||
@@ -2879,6 +2879,10 @@ pub enum ReviewDecision {
|
||||
/// User has approved this command and the agent should execute it.
|
||||
Approved,
|
||||
|
||||
/// User has approved this command, but wants the agent to execute a
|
||||
/// replacement command instead of the originally proposed one.
|
||||
ApprovedWithCommandOverride { command: Vec<String> },
|
||||
|
||||
/// User has approved this command and wants to apply the proposed execpolicy
|
||||
/// amendment so future matching commands are permitted.
|
||||
ApprovedExecpolicyAmendment {
|
||||
@@ -2912,6 +2916,7 @@ impl ReviewDecision {
|
||||
pub fn to_opaque_string(&self) -> &'static str {
|
||||
match self {
|
||||
ReviewDecision::Approved => "approved",
|
||||
ReviewDecision::ApprovedWithCommandOverride { .. } => "approved_with_command_override",
|
||||
ReviewDecision::ApprovedExecpolicyAmendment { .. } => "approved_with_amendment",
|
||||
ReviewDecision::ApprovedForSession => "approved_for_session",
|
||||
ReviewDecision::NetworkPolicyAmendment {
|
||||
|
||||
+90
-3
@@ -9,20 +9,78 @@ Prototype shape:
|
||||
- Codex runs with `codex app-server --listen stdio://`.
|
||||
- The SDK talks to app-server over stdio.
|
||||
- Thread startup uses `thread/start.sdkDelegation` to point Codex at the host bridge.
|
||||
- The SDK owns the bridge lifecycle and `await task.close()` tears down both the app-server session and the bridge.
|
||||
- The prototype uses a local attached-process backend so it can run against the host-installed Codex binary without cross-compiling a Linux container binary.
|
||||
|
||||
Capability model:
|
||||
|
||||
- Capabilities are the SDK’s grouping abstraction for UC-style bundles.
|
||||
- A `Capability` can contribute:
|
||||
- `tools()`
|
||||
- `instructions()`
|
||||
- `process_manifest(manifest)`
|
||||
- The capability API intentionally uses a single `tools()` method; the built-in vs function-tool split stays internal to the SDK runtime.
|
||||
- The default capability set is `UnifiedExecCapability()`, which enables `ExecCommand` and `WriteStdin`.
|
||||
|
||||
Tool model:
|
||||
|
||||
- Built-in Codex tools are exposed as Python classes such as `ExecCommand`, `WriteStdin`, `ApplyPatch`, `ReadFile`, and `ViewImage`.
|
||||
- The SDK sends those classes to app-server as an exact `thread/start.builtinTools` allowlist.
|
||||
- This prototype assumes unified-exec for command execution, so shell access should be modeled with `ExecCommand` plus `WriteStdin`.
|
||||
- Defaults come from `UnifiedExecCapability()`, which enables `ExecCommand` plus `WriteStdin`.
|
||||
- Host-side custom tools subclass `FunctionTool`; the SDK registers them as dynamic tools internally and answers `item/tool/call` requests on the host.
|
||||
- SDK users do not need to work with raw app-server `dynamicTools` payloads directly.
|
||||
- Custom `FunctionTool`s can contribute instruction fragments; the SDK folds those fragments into `developerInstructions`.
|
||||
- Built-in tool instructions are owned by Codex itself and are composed in Rust from the enabled built-in capability set.
|
||||
|
||||
Example capability:
|
||||
|
||||
```python
|
||||
from codex_sdk_v2 import Capability, ExecCommand, WriteStdin
|
||||
|
||||
|
||||
class UnifiedExec(Capability):
|
||||
def tools(self):
|
||||
return (ExecCommand, WriteStdin)
|
||||
```
|
||||
|
||||
Pending tool call API:
|
||||
|
||||
- `task.pending_tool_calls()` returns unresolved tool calls.
|
||||
- Each pending tool call supports `describe()` and `await tool_call(task)`.
|
||||
- The pending tool call subclasses are:
|
||||
- `PendingCommandExecution`
|
||||
- `PendingFileChange`
|
||||
- `PendingFunctionToolCall`
|
||||
- The explicit host helpers are:
|
||||
- `task.approve(...)`
|
||||
- `task.reject(...)`
|
||||
- `task.replace_command(...)`
|
||||
- `task.run_function_tool(...)`
|
||||
- `task.submit_tool_result(...)`
|
||||
|
||||
Decision model:
|
||||
|
||||
- `ApproveDecision()`
|
||||
- `RejectDecision()`
|
||||
- `DeferDecision()`
|
||||
- `ReplaceCommandDecision(command=[...])`
|
||||
- `RunDecision(arguments=...)`
|
||||
- `RespondDecision(result=...)`
|
||||
|
||||
Approval model:
|
||||
|
||||
- Manual is the default.
|
||||
- If a tool does not make a decision, its call stays pending in `task.pending_tool_calls()`.
|
||||
- `FunctionTool.approve(call)` can resolve or defer a function tool call.
|
||||
- `BuiltinTool.with_approval_policy(policy=...)` can resolve or defer a built-in call.
|
||||
- There is no agent-wide global approval policy in the prototype.
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
from codex_sdk_v2 import Agent, ExecCommand, WriteStdin, FunctionTool, Manifest
|
||||
from codex_sdk_v2 import Agent, ApproveDecision, DeferDecision
|
||||
from codex_sdk_v2 import ExecCommand, FunctionTool, Manifest
|
||||
from codex_sdk_v2 import PendingCommandExecution, ReplaceCommandDecision, WriteStdin
|
||||
|
||||
|
||||
class LookupRefundStatus(FunctionTool):
|
||||
@@ -35,14 +93,39 @@ class LookupRefundStatus(FunctionTool):
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
async def approve(self, call):
|
||||
if call.arguments["taxpayer_id"].startswith("demo_"):
|
||||
return ApproveDecision()
|
||||
return DeferDecision()
|
||||
|
||||
async def run(self, arguments):
|
||||
return f"Refund status for {arguments['taxpayer_id']}: approved"
|
||||
|
||||
|
||||
async def approve_exec(call: PendingCommandExecution):
|
||||
if call.command and call.command.startswith("ls"):
|
||||
return ApproveDecision()
|
||||
if call.command and call.command.startswith("cat"):
|
||||
return ReplaceCommandDecision(command=["sed", "-n", "1,20p", "README.md"])
|
||||
return DeferDecision()
|
||||
|
||||
|
||||
agent = Agent(
|
||||
manifest=Manifest(root="/workspace"),
|
||||
tools=(ExecCommand, WriteStdin, LookupRefundStatus()),
|
||||
tools=(
|
||||
ExecCommand.with_approval_policy(policy=approve_exec),
|
||||
WriteStdin,
|
||||
LookupRefundStatus(),
|
||||
),
|
||||
)
|
||||
|
||||
task = await agent.start()
|
||||
await stream_turn(task, start_text="Help me with my taxes")
|
||||
while task.pending_tool_calls():
|
||||
for tool_call in task.pending_tool_calls():
|
||||
print(tool_call.describe())
|
||||
await tool_call(task)
|
||||
await stream_turn(task)
|
||||
```
|
||||
|
||||
Current delegation shape:
|
||||
@@ -59,3 +142,7 @@ Debugging:
|
||||
|
||||
- Set `CODEX_SDK_V2_DEBUG=1` to print JSON-RPC traffic and app-server stderr while running an example.
|
||||
- The local backend prefers a repo-built `codex-rs/target/debug/codex-app-server` binary when present; otherwise it falls back to `codex` on your `PATH`.
|
||||
|
||||
Current limitation:
|
||||
|
||||
- The UC-style pending-tool-call flow is now present in-memory on the SDK task object. Persisting unresolved tool calls cleanly across a full host process restart still depends on replay behavior from app-server for the underlying pending request type.
|
||||
|
||||
@@ -1,30 +1,25 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from codex_sdk_v2 import Agent, LocalBackend, LocalBackendOptions, Manifest, OpenAIResponsesBridge
|
||||
from codex_sdk_v2 import Agent, LocalBackend, LocalBackendOptions, Manifest
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
bridge = OpenAIResponsesBridge(api_key=os.environ["OPENAI_API_KEY"], bind_host="127.0.0.1")
|
||||
bridge.start()
|
||||
backend = LocalBackend()
|
||||
manifest = Manifest(root="/workspace")
|
||||
session = await backend.create_session(
|
||||
manifest=manifest,
|
||||
options=LocalBackendOptions(),
|
||||
delegation_bridge_url=bridge.bridge_url,
|
||||
)
|
||||
|
||||
agent = Agent(manifest=manifest, backend=backend)
|
||||
try:
|
||||
task = await agent.start(session=session, bridge=bridge)
|
||||
task = await agent.start(session=session)
|
||||
text = await task.collect_text("Reply with a short hello from the delegated Codex runtime.")
|
||||
print(text)
|
||||
finally:
|
||||
await session.stop()
|
||||
bridge.shutdown()
|
||||
await task.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from codex_sdk_v2 import Agent, FunctionTool, LocalBackendOptions, Manifest
|
||||
from codex_sdk_v2 import Agent, ApproveDecision, FunctionTool, LocalBackendOptions, Manifest
|
||||
|
||||
|
||||
class LookupRefundStatus(FunctionTool):
|
||||
@@ -18,6 +18,9 @@ class LookupRefundStatus(FunctionTool):
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
async def approve(self, call) -> ApproveDecision:
|
||||
return ApproveDecision()
|
||||
|
||||
async def run(self, arguments: dict[str, object]) -> str:
|
||||
taxpayer_id = str(arguments["taxpayer_id"])
|
||||
return (
|
||||
@@ -38,10 +41,7 @@ async def main() -> None:
|
||||
)
|
||||
print(text)
|
||||
finally:
|
||||
bridge = getattr(task, "_owned_bridge", None)
|
||||
await task.session.stop()
|
||||
if bridge is not None:
|
||||
bridge.shutdown()
|
||||
await task.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from codex_sdk_v2 import Agent
|
||||
from codex_sdk_v2 import ApproveDecision
|
||||
from codex_sdk_v2 import DeferDecision
|
||||
from codex_sdk_v2 import ExecCommand
|
||||
from codex_sdk_v2 import FunctionTool
|
||||
from codex_sdk_v2 import Manifest
|
||||
from codex_sdk_v2 import PendingCommandExecution
|
||||
from codex_sdk_v2 import ReplaceCommandDecision
|
||||
from codex_sdk_v2 import WriteStdin
|
||||
|
||||
|
||||
class LookupRefundStatus(FunctionTool):
|
||||
name = "lookup_refund_status"
|
||||
description = "Return a canned refund status for a demo taxpayer id."
|
||||
input_schema = {
|
||||
"type": "object",
|
||||
"properties": {"taxpayer_id": {"type": "string"}},
|
||||
"required": ["taxpayer_id"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
async def approve(self, call):
|
||||
taxpayer_id = call.arguments.get("taxpayer_id", "")
|
||||
if taxpayer_id.startswith("demo_"):
|
||||
return ApproveDecision()
|
||||
return DeferDecision()
|
||||
|
||||
async def run(self, arguments):
|
||||
return f"Refund status for {arguments['taxpayer_id']}: approved"
|
||||
|
||||
|
||||
async def approve_exec(tool_call: PendingCommandExecution):
|
||||
if tool_call.command and tool_call.command.startswith("ls"):
|
||||
return ApproveDecision()
|
||||
if tool_call.command and tool_call.command.startswith("cat"):
|
||||
return ReplaceCommandDecision(command=["sed", "-n", "1,20p", "README.md"])
|
||||
return DeferDecision()
|
||||
|
||||
|
||||
async def stream_turn(task, start_text: str | None = None) -> None:
|
||||
events = task.run(start_text) if start_text is not None else task.resume()
|
||||
async for notification in events:
|
||||
if notification.method == "item/agentMessage/delta":
|
||||
delta = notification.params.get("delta")
|
||||
if isinstance(delta, str):
|
||||
print(delta, end="", flush=True)
|
||||
print()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
agent = Agent(
|
||||
manifest=Manifest(),
|
||||
tools=(
|
||||
ExecCommand.with_approval_policy(policy=approve_exec),
|
||||
WriteStdin,
|
||||
LookupRefundStatus(),
|
||||
),
|
||||
)
|
||||
task = await agent.start()
|
||||
await stream_turn(
|
||||
task,
|
||||
"List the current directory, then read README.md, then look up refund status for demo_123.",
|
||||
)
|
||||
while task.pending_tool_calls():
|
||||
for tool_call in task.pending_tool_calls():
|
||||
print(tool_call.describe())
|
||||
await tool_call(task)
|
||||
await stream_turn(task)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -28,10 +28,7 @@ async def main() -> None:
|
||||
print(delta, end="", flush=True)
|
||||
print()
|
||||
finally:
|
||||
bridge = getattr(task, "_owned_bridge", None)
|
||||
await task.session.stop()
|
||||
if bridge is not None:
|
||||
bridge.shutdown()
|
||||
await task.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -30,7 +30,7 @@ async def main() -> None:
|
||||
"output": Dir(),
|
||||
},
|
||||
)
|
||||
agent = Agent(manifest=manifest, user_instructions=INSTRUCTIONS)
|
||||
agent = Agent(manifest=manifest, developer_instructions=INSTRUCTIONS)
|
||||
task = await agent.start(backend_options=LocalBackendOptions())
|
||||
try:
|
||||
async for notification in task.run(
|
||||
@@ -42,10 +42,7 @@ async def main() -> None:
|
||||
print(delta, end="", flush=True)
|
||||
print()
|
||||
finally:
|
||||
bridge = getattr(task, "_owned_bridge", None)
|
||||
await task.session.stop()
|
||||
if bridge is not None:
|
||||
bridge.shutdown()
|
||||
await task.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,14 +1,28 @@
|
||||
from .agent import Agent
|
||||
from .bridge import OpenAIResponsesBridge
|
||||
from .capabilities import Capability
|
||||
from .capabilities import UnifiedExecCapability
|
||||
from .entries import Dir, LocalDir, LocalFile
|
||||
from .local_backend import LocalBackend, LocalBackendOptions, LocalSession
|
||||
from .manifest import Manifest
|
||||
from .pending_tool_calls import ApproveDecision
|
||||
from .pending_tool_calls import DeferDecision
|
||||
from .pending_tool_calls import PendingCommandExecution
|
||||
from .pending_tool_calls import PendingFileChange
|
||||
from .pending_tool_calls import PendingFunctionToolCall
|
||||
from .pending_tool_calls import PendingToolCall
|
||||
from .pending_tool_calls import RejectDecision
|
||||
from .pending_tool_calls import ReplaceCommandDecision
|
||||
from .pending_tool_calls import RespondDecision
|
||||
from .pending_tool_calls import RunDecision
|
||||
from .pending_tool_calls import ToolDecision
|
||||
from .task import Task
|
||||
from .tools import ALL_BUILTIN_TOOLS
|
||||
from .tools import ApplyPatch
|
||||
from .tools import Artifacts
|
||||
from .tools import BuiltinTool
|
||||
from .tools import BuiltinToolSpec
|
||||
from .tools import CloseAgent
|
||||
from .tools import ConfiguredBuiltinTool
|
||||
from .tools import ExecCommand
|
||||
from .tools import FunctionTool
|
||||
from .tools import GrepFiles
|
||||
@@ -38,31 +52,43 @@ from .tools import WriteStdin
|
||||
__all__ = [
|
||||
"Agent",
|
||||
"ALL_BUILTIN_TOOLS",
|
||||
"ApproveDecision",
|
||||
"ApplyPatch",
|
||||
"Artifacts",
|
||||
"BuiltinTool",
|
||||
"BuiltinToolSpec",
|
||||
"Capability",
|
||||
"CloseAgent",
|
||||
"ConfiguredBuiltinTool",
|
||||
"DeferDecision",
|
||||
"Dir",
|
||||
"ExecCommand",
|
||||
"FunctionTool",
|
||||
"GrepFiles",
|
||||
"JsRepl",
|
||||
"JsReplReset",
|
||||
"ListDir",
|
||||
"ListMcpResourceTemplates",
|
||||
"ListMcpResources",
|
||||
"LocalBackend",
|
||||
"LocalBackendOptions",
|
||||
"LocalDir",
|
||||
"LocalFile",
|
||||
"LocalSession",
|
||||
"ListDir",
|
||||
"ListMcpResourceTemplates",
|
||||
"ListMcpResources",
|
||||
"Manifest",
|
||||
"OpenAIResponsesBridge",
|
||||
"PendingCommandExecution",
|
||||
"PendingFileChange",
|
||||
"PendingFunctionToolCall",
|
||||
"PendingToolCall",
|
||||
"ReadFile",
|
||||
"ReadMcpResource",
|
||||
"RejectDecision",
|
||||
"ReplaceCommandDecision",
|
||||
"ReportAgentJobResult",
|
||||
"RequestUserInput",
|
||||
"RespondDecision",
|
||||
"ResumeAgent",
|
||||
"RunDecision",
|
||||
"SearchToolBm25",
|
||||
"SendInput",
|
||||
"Shell",
|
||||
@@ -71,7 +97,9 @@ __all__ = [
|
||||
"Task",
|
||||
"TestSyncTool",
|
||||
"Tool",
|
||||
"ToolDecision",
|
||||
"UpdatePlan",
|
||||
"UnifiedExecCapability",
|
||||
"ViewImage",
|
||||
"Wait",
|
||||
"WebSearch",
|
||||
|
||||
@@ -6,51 +6,79 @@ import os
|
||||
from typing import Any
|
||||
|
||||
from .app_server_client import JsonRpcNotification, JsonRpcServerRequest
|
||||
from .capabilities import Capability, DEFAULT_CAPABILITIES
|
||||
from .bridge import OpenAIResponsesBridge
|
||||
from .local_backend import LocalBackend, LocalBackendOptions, LocalSession
|
||||
from .manifest import Manifest
|
||||
from .task import Task
|
||||
from .tools import DEFAULT_TOOLS, Tool, builtin_tool_names, function_tools
|
||||
from .tools import Tool, builtin_tools, function_tools, tool_instruction_fragments
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Agent:
|
||||
manifest: Manifest
|
||||
model: str = "gpt-5.2-codex"
|
||||
# Replaces Codex's composed base instructions for the thread. When set, this
|
||||
# bypasses the Rust-side built-in capability prompt composition.
|
||||
base_instructions: str | None = None
|
||||
# Additive developer-role instructions for the thread. These are composed
|
||||
# together with capability- and FunctionTool-contributed instruction
|
||||
# fragments and sent via `thread/start.developerInstructions`.
|
||||
developer_instructions: str | None = None
|
||||
user_instructions: str | None = None
|
||||
tools: tuple[Tool | type[Tool], ...] = field(default_factory=lambda: DEFAULT_TOOLS)
|
||||
tools: tuple[Tool | type[Tool], ...] = field(default_factory=tuple)
|
||||
capabilities: tuple[Capability, ...] = field(default_factory=lambda: DEFAULT_CAPABILITIES)
|
||||
backend: LocalBackend = field(default_factory=LocalBackend)
|
||||
approval_policy: str | None = None
|
||||
|
||||
async def start(
|
||||
self,
|
||||
*,
|
||||
backend_options: LocalBackendOptions | None = None,
|
||||
session: LocalSession | None = None,
|
||||
bridge: OpenAIResponsesBridge | None = None,
|
||||
) -> Task:
|
||||
own_bridge = False
|
||||
if bridge is None:
|
||||
api_key = os.environ.get("OPENAI_API_KEY")
|
||||
if not api_key:
|
||||
raise RuntimeError("OPENAI_API_KEY must be set for the prototype bridge")
|
||||
bridge = OpenAIResponsesBridge(api_key=api_key)
|
||||
bridge.start()
|
||||
own_bridge = True
|
||||
api_key = os.environ.get("OPENAI_API_KEY")
|
||||
if not api_key:
|
||||
raise RuntimeError("OPENAI_API_KEY must be set for the prototype bridge")
|
||||
bridge = OpenAIResponsesBridge(api_key=api_key)
|
||||
bridge.start()
|
||||
|
||||
builtin_tools = builtin_tool_names(self.tools)
|
||||
resolved_function_tools = function_tools(self.tools)
|
||||
manifest = self.manifest
|
||||
for capability in self.capabilities:
|
||||
manifest = capability.process_manifest(manifest)
|
||||
|
||||
resolved_tools: tuple[Tool | type[Tool], ...] = (
|
||||
*(tool for capability in self.capabilities for tool in capability.tools()),
|
||||
*self.tools,
|
||||
)
|
||||
builtin_tool_names, builtin_tool_policies = builtin_tools(resolved_tools)
|
||||
resolved_function_tools = function_tools(resolved_tools)
|
||||
tool_fragments = tool_instruction_fragments(resolved_tools)
|
||||
capability_fragments = [
|
||||
fragment
|
||||
for capability in self.capabilities
|
||||
if (fragment := capability.instructions()) is not None
|
||||
]
|
||||
dynamic_tools = [type(tool).dynamic_tool_spec() for tool in resolved_function_tools]
|
||||
function_tool_map = {
|
||||
type(tool).dynamic_tool_spec()["name"]: tool for tool in resolved_function_tools
|
||||
}
|
||||
developer_instructions = self.developer_instructions
|
||||
if capability_fragments or tool_fragments:
|
||||
sections = [
|
||||
fragment
|
||||
for fragment in [
|
||||
developer_instructions,
|
||||
*capability_fragments,
|
||||
*tool_fragments,
|
||||
]
|
||||
if fragment
|
||||
]
|
||||
developer_instructions = "\n\n".join(sections) if sections else None
|
||||
|
||||
if session is None:
|
||||
session = await self.backend.create_session(
|
||||
manifest=self.manifest,
|
||||
manifest=manifest,
|
||||
options=backend_options,
|
||||
delegation_bridge_url=bridge.bridge_url,
|
||||
)
|
||||
client = await session.start_app_server()
|
||||
await client.initialize(
|
||||
@@ -58,20 +86,24 @@ class Agent:
|
||||
client_title="Codex SDK v2 Prototype",
|
||||
client_version="0.1.0",
|
||||
)
|
||||
approval_policy = self.approval_policy
|
||||
if approval_policy is None:
|
||||
approval_policy = "on-request" if builtin_tool_names else "never"
|
||||
thread_start_params: dict[str, Any] = {
|
||||
"model": self.model,
|
||||
"cwd": str(session.workspace_root),
|
||||
"sandbox": "danger-full-access",
|
||||
"approvalPolicy": "never",
|
||||
"approvalPolicy": approval_policy,
|
||||
"config": {
|
||||
"experimental_use_unified_exec_tool": True,
|
||||
},
|
||||
"baseInstructions": self.base_instructions,
|
||||
"developerInstructions": self.developer_instructions,
|
||||
"developerInstructions": developer_instructions,
|
||||
"sdkDelegation": {
|
||||
"bridgeUrl": bridge.bridge_url,
|
||||
},
|
||||
"builtinTools": builtin_tools,
|
||||
"builtinTools": builtin_tool_names,
|
||||
"manualToolExecution": bool(builtin_tool_names),
|
||||
}
|
||||
if dynamic_tools:
|
||||
thread_start_params["dynamicTools"] = dynamic_tools
|
||||
@@ -104,12 +136,11 @@ class Agent:
|
||||
else:
|
||||
deferred_messages.append(message)
|
||||
client.prepend_messages(deferred_messages)
|
||||
task = Task(
|
||||
return Task(
|
||||
session=session,
|
||||
thread_id=result["thread"]["id"],
|
||||
initial_thread_started=thread_started_notification.params,
|
||||
prefix_user_instructions=self.user_instructions,
|
||||
function_tools=function_tool_map,
|
||||
_owned_bridge=bridge if own_bridge else None,
|
||||
builtin_tool_policies=builtin_tool_policies,
|
||||
_owned_bridge=bridge,
|
||||
)
|
||||
return task
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .manifest import Manifest
|
||||
from .tools import ExecCommand
|
||||
from .tools import Tool
|
||||
from .tools import WriteStdin
|
||||
|
||||
|
||||
class Capability:
|
||||
def tools(self) -> tuple[Tool | type[Tool], ...]:
|
||||
return ()
|
||||
|
||||
def instructions(self) -> str | None:
|
||||
return None
|
||||
|
||||
def process_manifest(self, manifest: Manifest) -> Manifest:
|
||||
return manifest
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class UnifiedExecCapability(Capability):
|
||||
def tools(self) -> tuple[Tool | type[Tool], ...]:
|
||||
return (ExecCommand, WriteStdin)
|
||||
|
||||
|
||||
DEFAULT_CAPABILITIES: tuple[Capability, ...] = (UnifiedExecCapability(),)
|
||||
@@ -0,0 +1,53 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal, TypeAlias
|
||||
|
||||
from .app_server_client import JsonRpcNotification, JsonRpcServerRequest
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ApprovalDecision:
|
||||
decision: Literal["approve", "approve_for_session", "reject", "cancel"]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CommandApprovalRequestEvent:
|
||||
request_id: int | str
|
||||
thread_id: str
|
||||
turn_id: str
|
||||
item_id: str
|
||||
approval_id: str | None
|
||||
reason: str | None
|
||||
command: str | None
|
||||
cwd: str | None
|
||||
command_actions: list[dict[str, Any]] | None
|
||||
raw_request: JsonRpcServerRequest
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class FileChangeApprovalRequestEvent:
|
||||
request_id: int | str
|
||||
thread_id: str
|
||||
turn_id: str
|
||||
item_id: str
|
||||
reason: str | None
|
||||
grant_root: str | None
|
||||
raw_request: JsonRpcServerRequest
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class FunctionToolCallEvent:
|
||||
request_id: int | str
|
||||
thread_id: str
|
||||
turn_id: str
|
||||
call_id: str
|
||||
tool_name: str
|
||||
arguments: dict[str, Any]
|
||||
raw_request: JsonRpcServerRequest
|
||||
|
||||
|
||||
ApprovalRequestEvent: TypeAlias = (
|
||||
CommandApprovalRequestEvent | FileChangeApprovalRequestEvent | FunctionToolCallEvent
|
||||
)
|
||||
TaskEvent: TypeAlias = JsonRpcNotification | ApprovalRequestEvent
|
||||
@@ -27,13 +27,11 @@ class LocalSession:
|
||||
app_server_binary: Path,
|
||||
app_server_args: tuple[str, ...],
|
||||
owned_workspace: bool,
|
||||
delegation_bridge_url: str,
|
||||
) -> None:
|
||||
self.workspace_root = workspace_root
|
||||
self.app_server_binary = app_server_binary
|
||||
self.app_server_args = app_server_args
|
||||
self.owned_workspace = owned_workspace
|
||||
self.delegation_bridge_url = delegation_bridge_url
|
||||
self.app_server_process: asyncio.subprocess.Process | None = None
|
||||
self.app_server_client: AppServerClient | None = None
|
||||
self._stderr_task: asyncio.Task[None] | None = None
|
||||
@@ -90,7 +88,6 @@ class LocalBackend:
|
||||
*,
|
||||
manifest: Manifest,
|
||||
options: LocalBackendOptions | None = None,
|
||||
delegation_bridge_url: str,
|
||||
) -> LocalSession:
|
||||
options = options or LocalBackendOptions()
|
||||
codex_binary = options.codex_binary or self.codex_binary
|
||||
@@ -123,7 +120,6 @@ class LocalBackend:
|
||||
app_server_binary=codex_binary,
|
||||
app_server_args=app_server_args,
|
||||
owned_workspace=owned_workspace,
|
||||
delegation_bridge_url=delegation_bridge_url,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, ClassVar, Literal, Mapping
|
||||
|
||||
|
||||
class ToolDecision:
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ApproveDecision(ToolDecision):
|
||||
for_session: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RejectDecision(ToolDecision):
|
||||
cancel: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DeferDecision(ToolDecision):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RunDecision(ToolDecision):
|
||||
arguments: Mapping[str, Any] | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ReplaceCommandDecision(ToolDecision):
|
||||
command: list[str]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RespondDecision(ToolDecision):
|
||||
result: Any
|
||||
success: bool = True
|
||||
|
||||
|
||||
class PendingToolCall:
|
||||
kind: ClassVar[str]
|
||||
|
||||
async def __call__(self, task: Any) -> None:
|
||||
await task.resolve_tool_call(self)
|
||||
|
||||
def describe(self) -> str:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class PendingCommandExecution(PendingToolCall):
|
||||
kind: ClassVar[str] = "command_execution"
|
||||
request_id: int | str
|
||||
thread_id: str
|
||||
turn_id: str
|
||||
item_id: str
|
||||
approval_id: str | None
|
||||
reason: str | None
|
||||
command: str | None
|
||||
cwd: str | None
|
||||
command_actions: list[dict[str, Any]] | None
|
||||
resolved: bool = False
|
||||
|
||||
def describe(self) -> str:
|
||||
if self.command:
|
||||
return f"Approve command: {self.command}"
|
||||
if self.reason:
|
||||
return f"Approve command execution: {self.reason}"
|
||||
return "Approve command execution"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class PendingFileChange(PendingToolCall):
|
||||
kind: ClassVar[str] = "file_change"
|
||||
request_id: int | str
|
||||
thread_id: str
|
||||
turn_id: str
|
||||
item_id: str
|
||||
reason: str | None
|
||||
grant_root: str | None
|
||||
resolved: bool = False
|
||||
|
||||
def describe(self) -> str:
|
||||
if self.reason:
|
||||
return f"Approve file changes: {self.reason}"
|
||||
return "Approve file changes"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class PendingFunctionToolCall(PendingToolCall):
|
||||
kind: ClassVar[str] = "function_tool"
|
||||
request_id: int | str
|
||||
thread_id: str
|
||||
turn_id: str
|
||||
call_id: str
|
||||
tool_name: str
|
||||
arguments: dict[str, Any]
|
||||
resolved: bool = False
|
||||
|
||||
def describe(self) -> str:
|
||||
return f"Run function tool {self.tool_name}({self.arguments})"
|
||||
@@ -1,10 +1,22 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, AsyncIterator, Mapping
|
||||
|
||||
from .app_server_client import JsonRpcNotification, JsonRpcServerRequest
|
||||
from .pending_tool_calls import ApproveDecision
|
||||
from .pending_tool_calls import DeferDecision
|
||||
from .pending_tool_calls import PendingCommandExecution
|
||||
from .pending_tool_calls import PendingFileChange
|
||||
from .pending_tool_calls import PendingFunctionToolCall
|
||||
from .pending_tool_calls import PendingToolCall
|
||||
from .pending_tool_calls import RejectDecision
|
||||
from .pending_tool_calls import ReplaceCommandDecision
|
||||
from .pending_tool_calls import RespondDecision
|
||||
from .pending_tool_calls import RunDecision
|
||||
from .pending_tool_calls import ToolDecision
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -12,129 +24,362 @@ class Task:
|
||||
session: Any
|
||||
thread_id: str
|
||||
initial_thread_started: dict[str, Any]
|
||||
prefix_user_instructions: str | None = None
|
||||
function_tools: Mapping[str, Any] = field(default_factory=dict)
|
||||
builtin_tool_policies: Mapping[str, Any] = field(default_factory=dict)
|
||||
_owned_bridge: Any | None = None
|
||||
_pending_tool_calls: list[PendingToolCall] = field(default_factory=list)
|
||||
_active_turn_id: str | None = None
|
||||
_turn_complete: bool = True
|
||||
|
||||
async def close(self) -> None:
|
||||
try:
|
||||
await self.session.stop()
|
||||
finally:
|
||||
if self._owned_bridge is not None:
|
||||
self._owned_bridge.shutdown()
|
||||
self._owned_bridge = None
|
||||
|
||||
async def run(self, user_text: str) -> AsyncIterator[JsonRpcNotification]:
|
||||
if self.session.app_server_client is None:
|
||||
raise RuntimeError("app-server client is not attached")
|
||||
input_text = user_text
|
||||
if self.prefix_user_instructions:
|
||||
input_text = f"{self.prefix_user_instructions}\n\n{user_text}"
|
||||
if self.pending_tool_calls():
|
||||
raise RuntimeError("cannot start a new turn while tool calls are pending")
|
||||
response = await self.session.app_server_client.request(
|
||||
"turn/start",
|
||||
{
|
||||
"threadId": self.thread_id,
|
||||
"input": [{"type": "text", "text": input_text}],
|
||||
"input": [{"type": "text", "text": user_text}],
|
||||
},
|
||||
)
|
||||
turn_id = response["turn"]["id"]
|
||||
self._active_turn_id = response["turn"]["id"]
|
||||
self._turn_complete = False
|
||||
while True:
|
||||
message = await self.session.app_server_client.next_message()
|
||||
if isinstance(message, JsonRpcServerRequest):
|
||||
await self._handle_server_request(message)
|
||||
should_pause = await self._handle_server_request(message)
|
||||
if should_pause:
|
||||
return
|
||||
continue
|
||||
yield message
|
||||
params = message.params
|
||||
matches_turn = params.get("turnId") == turn_id or params.get("turn", {}).get("id") == turn_id
|
||||
matches_turn = params.get("turnId") == self._active_turn_id or params.get("turn", {}).get("id") == self._active_turn_id
|
||||
if message.method == "turn/completed" and matches_turn:
|
||||
break
|
||||
self._turn_complete = True
|
||||
self._active_turn_id = None
|
||||
return
|
||||
|
||||
async def resume(self) -> AsyncIterator[JsonRpcNotification]:
|
||||
if self.session.app_server_client is None:
|
||||
raise RuntimeError("app-server client is not attached")
|
||||
if self.pending_tool_calls():
|
||||
raise RuntimeError("cannot resume while tool calls are pending")
|
||||
if self._turn_complete or self._active_turn_id is None:
|
||||
return
|
||||
while True:
|
||||
message = await self.session.app_server_client.next_message()
|
||||
if isinstance(message, JsonRpcServerRequest):
|
||||
should_pause = await self._handle_server_request(message)
|
||||
if should_pause:
|
||||
return
|
||||
continue
|
||||
yield message
|
||||
params = message.params
|
||||
matches_turn = params.get("turnId") == self._active_turn_id or params.get("turn", {}).get("id") == self._active_turn_id
|
||||
if message.method == "turn/completed" and matches_turn:
|
||||
self._turn_complete = True
|
||||
self._active_turn_id = None
|
||||
return
|
||||
|
||||
async def collect_text(self, user_text: str) -> str:
|
||||
text_chunks: list[str] = []
|
||||
async for notification in self.run(user_text):
|
||||
if notification.method == "item/agentMessage/delta":
|
||||
delta = notification.params.get("delta")
|
||||
async for event in self.run(user_text):
|
||||
if event.method == "item/agentMessage/delta":
|
||||
delta = event.params.get("delta")
|
||||
if isinstance(delta, str):
|
||||
text_chunks.append(delta)
|
||||
while not self._turn_complete and not self.pending_tool_calls():
|
||||
async for event in self.resume():
|
||||
if event.method == "item/agentMessage/delta":
|
||||
delta = event.params.get("delta")
|
||||
if isinstance(delta, str):
|
||||
text_chunks.append(delta)
|
||||
return "".join(text_chunks)
|
||||
|
||||
async def _handle_server_request(self, request: JsonRpcServerRequest) -> None:
|
||||
if request.method != "item/tool/call":
|
||||
def pending_tool_calls(self) -> list[PendingToolCall]:
|
||||
return [tool_call for tool_call in self._pending_tool_calls if not tool_call.resolved]
|
||||
|
||||
async def resolve_tool_call(self, tool_call: PendingToolCall) -> None:
|
||||
if isinstance(tool_call, PendingCommandExecution):
|
||||
await self.approve(tool_call)
|
||||
return
|
||||
if isinstance(tool_call, PendingFileChange):
|
||||
await self.approve(tool_call)
|
||||
return
|
||||
await self.run_function_tool(tool_call)
|
||||
|
||||
async def apply_tool_decision(self, tool_call: PendingToolCall) -> bool:
|
||||
decision = await self._call_tool_approval(tool_call)
|
||||
if decision is None or isinstance(decision, DeferDecision):
|
||||
return False
|
||||
if isinstance(decision, ApproveDecision):
|
||||
await self.approve(tool_call, for_session=decision.for_session)
|
||||
return True
|
||||
if isinstance(decision, RejectDecision):
|
||||
await self.reject(tool_call, cancel=decision.cancel)
|
||||
return True
|
||||
if isinstance(decision, ReplaceCommandDecision):
|
||||
if not isinstance(tool_call, PendingCommandExecution):
|
||||
raise TypeError(
|
||||
"ReplaceCommandDecision can only be used with built-in command approvals"
|
||||
)
|
||||
await self.replace_command(tool_call, decision.command)
|
||||
return True
|
||||
if isinstance(decision, RunDecision):
|
||||
if not isinstance(tool_call, PendingFunctionToolCall):
|
||||
raise TypeError("RunDecision can only be used with function tools")
|
||||
await self.run_function_tool(tool_call, arguments=decision.arguments)
|
||||
return True
|
||||
if isinstance(decision, RespondDecision):
|
||||
if not isinstance(tool_call, PendingFunctionToolCall):
|
||||
raise TypeError("RespondDecision is only valid for function tool calls")
|
||||
await self.submit_tool_result(tool_call, decision.result, success=decision.success)
|
||||
return True
|
||||
raise TypeError(f"unsupported tool decision: {type(decision)!r}")
|
||||
|
||||
async def approve(self, tool_call: PendingToolCall, *, for_session: bool = False) -> None:
|
||||
if isinstance(tool_call, PendingCommandExecution):
|
||||
await self._respond_to_command_approval(tool_call, for_session=for_session)
|
||||
tool_call.resolved = True
|
||||
return
|
||||
if isinstance(tool_call, PendingFileChange):
|
||||
await self._respond_to_file_change_approval(tool_call, for_session=for_session)
|
||||
tool_call.resolved = True
|
||||
return
|
||||
await self.run_function_tool(tool_call)
|
||||
|
||||
async def replace_command(
|
||||
self,
|
||||
tool_call: PendingCommandExecution,
|
||||
command: list[str],
|
||||
) -> None:
|
||||
await self._respond_to_command_override(tool_call, command=command)
|
||||
tool_call.command = " ".join(command)
|
||||
tool_call.resolved = True
|
||||
|
||||
async def reject(self, tool_call: PendingToolCall, *, cancel: bool = False) -> None:
|
||||
if isinstance(tool_call, PendingCommandExecution):
|
||||
await self._respond_to_command_rejection(tool_call, cancel=cancel)
|
||||
tool_call.resolved = True
|
||||
return
|
||||
if isinstance(tool_call, PendingFileChange):
|
||||
await self._respond_to_file_change_rejection(tool_call, cancel=cancel)
|
||||
tool_call.resolved = True
|
||||
return
|
||||
await self._reject_function_tool(tool_call, cancel=cancel)
|
||||
|
||||
async def run_function_tool(
|
||||
self,
|
||||
tool_call: PendingFunctionToolCall,
|
||||
*,
|
||||
arguments: Mapping[str, Any] | None = None,
|
||||
) -> None:
|
||||
tool = self.function_tools.get(tool_call.tool_name)
|
||||
if tool is None:
|
||||
await self.submit_tool_result(
|
||||
tool_call,
|
||||
f"unknown function tool: {tool_call.tool_name}",
|
||||
success=False,
|
||||
)
|
||||
return
|
||||
call_arguments = dict(arguments) if arguments is not None else tool_call.arguments
|
||||
try:
|
||||
result = await tool.run(call_arguments)
|
||||
except Exception as exc:
|
||||
await self.submit_tool_result(
|
||||
tool_call,
|
||||
f"function tool {tool_call.tool_name} failed: {exc}",
|
||||
success=False,
|
||||
)
|
||||
return
|
||||
await self.submit_tool_result(tool_call, result, success=True)
|
||||
|
||||
async def submit_tool_result(
|
||||
self,
|
||||
tool_call: PendingFunctionToolCall,
|
||||
result: Any,
|
||||
*,
|
||||
success: bool = True,
|
||||
) -> None:
|
||||
try:
|
||||
text = result if isinstance(result, str) else json.dumps(result, indent=2, sort_keys=True)
|
||||
except TypeError as exc:
|
||||
text = f"function tool {tool_call.tool_name} returned a non-serializable result: {exc}"
|
||||
success = False
|
||||
await self.session.app_server_client.send_result(
|
||||
tool_call.request_id,
|
||||
{
|
||||
"contentItems": [{"type": "inputText", "text": text}],
|
||||
"success": success,
|
||||
},
|
||||
)
|
||||
tool_call.resolved = True
|
||||
|
||||
async def _handle_server_request(self, request: JsonRpcServerRequest) -> bool:
|
||||
tool_call = self._decode_tool_call(request)
|
||||
if tool_call is None:
|
||||
await self.session.app_server_client.send_error(
|
||||
request.request_id,
|
||||
-32601,
|
||||
f"unsupported server request method: {request.method}",
|
||||
)
|
||||
return
|
||||
return False
|
||||
self._pending_tool_calls.append(tool_call)
|
||||
handled = await self.apply_tool_decision(tool_call)
|
||||
if handled:
|
||||
return False
|
||||
return not tool_call.resolved
|
||||
|
||||
def _decode_tool_call(self, request: JsonRpcServerRequest) -> PendingToolCall | None:
|
||||
if request.method == "item/commandExecution/requestApproval":
|
||||
return PendingCommandExecution(
|
||||
request_id=request.request_id,
|
||||
thread_id=str(request.params.get("threadId", self.thread_id)),
|
||||
turn_id=str(request.params.get("turnId", "")),
|
||||
item_id=str(request.params.get("itemId", "")),
|
||||
approval_id=self._optional_str(request.params.get("approvalId")),
|
||||
reason=self._optional_str(request.params.get("reason")),
|
||||
command=self._optional_str(request.params.get("command")),
|
||||
cwd=self._optional_str(request.params.get("cwd")),
|
||||
command_actions=self._command_actions(request.params.get("commandActions")),
|
||||
)
|
||||
if request.method == "item/fileChange/requestApproval":
|
||||
return PendingFileChange(
|
||||
request_id=request.request_id,
|
||||
thread_id=str(request.params.get("threadId", self.thread_id)),
|
||||
turn_id=str(request.params.get("turnId", "")),
|
||||
item_id=str(request.params.get("itemId", "")),
|
||||
reason=self._optional_str(request.params.get("reason")),
|
||||
grant_root=self._optional_str(request.params.get("grantRoot")),
|
||||
)
|
||||
if request.method != "item/tool/call":
|
||||
return None
|
||||
tool_name = request.params.get("tool")
|
||||
arguments = request.params.get("arguments", {})
|
||||
if not isinstance(tool_name, str):
|
||||
await self.session.app_server_client.send_error(
|
||||
request.request_id,
|
||||
-32602,
|
||||
"tool call is missing a string tool name",
|
||||
)
|
||||
return
|
||||
raise RuntimeError("tool call is missing a string tool name")
|
||||
if not isinstance(arguments, dict):
|
||||
await self.session.app_server_client.send_error(
|
||||
request.request_id,
|
||||
-32602,
|
||||
f"tool call arguments for {tool_name} must be an object",
|
||||
)
|
||||
return
|
||||
raise RuntimeError(f"tool call arguments for {tool_name} must be an object")
|
||||
return PendingFunctionToolCall(
|
||||
request_id=request.request_id,
|
||||
thread_id=str(request.params.get("threadId", self.thread_id)),
|
||||
turn_id=str(request.params.get("turnId", "")),
|
||||
call_id=str(request.params.get("callId", "")),
|
||||
tool_name=tool_name,
|
||||
arguments=arguments,
|
||||
)
|
||||
|
||||
tool = self.function_tools.get(tool_name)
|
||||
if tool is None:
|
||||
await self.session.app_server_client.send_result(
|
||||
request.request_id,
|
||||
{
|
||||
"contentItems": [
|
||||
{
|
||||
"type": "input_text",
|
||||
"text": f"unknown function tool: {tool_name}",
|
||||
}
|
||||
],
|
||||
"success": False,
|
||||
},
|
||||
)
|
||||
return
|
||||
async def _call_tool_approval(self, tool_call: PendingToolCall) -> ToolDecision | None:
|
||||
decision: Any = None
|
||||
if isinstance(tool_call, PendingFunctionToolCall):
|
||||
tool = self.function_tools.get(tool_call.tool_name)
|
||||
if tool is None:
|
||||
return None
|
||||
decision = tool.approve(tool_call)
|
||||
elif isinstance(tool_call, PendingCommandExecution):
|
||||
command_name = self._command_name(tool_call.command)
|
||||
policy = self.builtin_tool_policies.get(command_name)
|
||||
if policy is None:
|
||||
return None
|
||||
decision = policy(tool_call)
|
||||
elif isinstance(tool_call, PendingFileChange):
|
||||
return None
|
||||
if inspect.isawaitable(decision):
|
||||
decision = await decision
|
||||
if decision is None or isinstance(decision, ToolDecision):
|
||||
return decision
|
||||
raise TypeError(f"tool approval must return ToolDecision or None, got {type(decision)!r}")
|
||||
|
||||
try:
|
||||
result = await tool.run(arguments)
|
||||
except Exception as exc:
|
||||
await self.session.app_server_client.send_result(
|
||||
request.request_id,
|
||||
{
|
||||
"contentItems": [
|
||||
{
|
||||
"type": "input_text",
|
||||
"text": f"function tool {tool_name} failed: {exc}",
|
||||
}
|
||||
],
|
||||
"success": False,
|
||||
},
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
text = (
|
||||
result
|
||||
if isinstance(result, str)
|
||||
else json.dumps(result, indent=2, sort_keys=True)
|
||||
)
|
||||
except TypeError as exc:
|
||||
await self.session.app_server_client.send_result(
|
||||
request.request_id,
|
||||
{
|
||||
"contentItems": [
|
||||
{
|
||||
"type": "input_text",
|
||||
"text": (
|
||||
f"function tool {tool_name} returned a non-serializable result: {exc}"
|
||||
),
|
||||
}
|
||||
],
|
||||
"success": False,
|
||||
},
|
||||
)
|
||||
return
|
||||
async def _respond_to_command_approval(
|
||||
self,
|
||||
tool_call: PendingCommandExecution,
|
||||
*,
|
||||
for_session: bool,
|
||||
) -> None:
|
||||
await self.session.app_server_client.send_result(
|
||||
request.request_id,
|
||||
tool_call.request_id,
|
||||
{"decision": "acceptForSession" if for_session else "accept"},
|
||||
)
|
||||
|
||||
async def _respond_to_command_rejection(
|
||||
self,
|
||||
tool_call: PendingCommandExecution,
|
||||
*,
|
||||
cancel: bool,
|
||||
) -> None:
|
||||
await self.session.app_server_client.send_result(
|
||||
tool_call.request_id,
|
||||
{"decision": "cancel" if cancel else "decline"},
|
||||
)
|
||||
|
||||
async def _respond_to_command_override(
|
||||
self,
|
||||
tool_call: PendingCommandExecution,
|
||||
*,
|
||||
command: list[str],
|
||||
) -> None:
|
||||
await self.session.app_server_client.send_result(
|
||||
tool_call.request_id,
|
||||
{
|
||||
"contentItems": [{"type": "input_text", "text": text}],
|
||||
"success": True,
|
||||
"decision": {
|
||||
"acceptWithCommandOverride": {
|
||||
"command": command,
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
async def _respond_to_file_change_approval(
|
||||
self,
|
||||
tool_call: PendingFileChange,
|
||||
*,
|
||||
for_session: bool,
|
||||
) -> None:
|
||||
await self.session.app_server_client.send_result(
|
||||
tool_call.request_id,
|
||||
{"decision": "acceptForSession" if for_session else "accept"},
|
||||
)
|
||||
|
||||
async def _respond_to_file_change_rejection(
|
||||
self,
|
||||
tool_call: PendingFileChange,
|
||||
*,
|
||||
cancel: bool,
|
||||
) -> None:
|
||||
await self.session.app_server_client.send_result(
|
||||
tool_call.request_id,
|
||||
{"decision": "cancel" if cancel else "decline"},
|
||||
)
|
||||
|
||||
async def _reject_function_tool(self, tool_call: PendingFunctionToolCall, *, cancel: bool) -> None:
|
||||
action = "canceled" if cancel else "rejected"
|
||||
await self.submit_tool_result(
|
||||
tool_call,
|
||||
f"function tool {tool_call.tool_name} was {action} by the host",
|
||||
success=False,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _command_actions(value: Any) -> list[dict[str, Any]] | None:
|
||||
if isinstance(value, list) and all(isinstance(action, dict) for action in value):
|
||||
return value
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _optional_str(value: Any) -> str | None:
|
||||
return value if isinstance(value, str) else None
|
||||
|
||||
@staticmethod
|
||||
def _command_name(command: str | None) -> str:
|
||||
if not command:
|
||||
return "exec_command"
|
||||
return "write_stdin" if command.startswith("write_stdin:") else "exec_command"
|
||||
|
||||
@@ -1,7 +1,20 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, ClassVar, Mapping, Sequence
|
||||
from typing import TYPE_CHECKING, Any, Awaitable, Callable, ClassVar, Mapping, Sequence
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .pending_tool_calls import PendingCommandExecution
|
||||
from .pending_tool_calls import PendingFunctionToolCall
|
||||
from .pending_tool_calls import ToolDecision
|
||||
|
||||
if TYPE_CHECKING:
|
||||
BuiltinApprovalPolicy = Callable[
|
||||
[PendingCommandExecution],
|
||||
Awaitable[ToolDecision | None] | ToolDecision | None,
|
||||
]
|
||||
else:
|
||||
BuiltinApprovalPolicy = Callable[[Any], Awaitable[Any] | Any]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -13,6 +26,15 @@ class Tool:
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ConfiguredBuiltinTool(Tool):
|
||||
tool_type: type["BuiltinTool"]
|
||||
approval_policy: BuiltinApprovalPolicy | None = None
|
||||
|
||||
def builtin_spec(self) -> BuiltinToolSpec:
|
||||
return self.tool_type.builtin_spec()
|
||||
|
||||
|
||||
class BuiltinTool(Tool):
|
||||
codex_builtin_tool: ClassVar[str]
|
||||
|
||||
@@ -23,6 +45,14 @@ class BuiltinTool(Tool):
|
||||
raise TypeError(f"{cls.__name__} must define codex_builtin_tool")
|
||||
return BuiltinToolSpec(tool_name=tool_name)
|
||||
|
||||
@classmethod
|
||||
def with_approval_policy(
|
||||
cls,
|
||||
*,
|
||||
policy: BuiltinApprovalPolicy,
|
||||
) -> ConfiguredBuiltinTool:
|
||||
return ConfiguredBuiltinTool(tool_type=cls, approval_policy=policy)
|
||||
|
||||
|
||||
class FunctionTool(Tool):
|
||||
name: ClassVar[str]
|
||||
@@ -46,6 +76,12 @@ class FunctionTool(Tool):
|
||||
"inputSchema": input_schema,
|
||||
}
|
||||
|
||||
async def approve(self, call: PendingFunctionToolCall) -> ToolDecision | None:
|
||||
return None
|
||||
|
||||
def instructions(self) -> str | None:
|
||||
return None
|
||||
|
||||
async def run(self, arguments: Mapping[str, Any]) -> Any:
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -184,18 +220,22 @@ ALL_BUILTIN_TOOLS: tuple[type[BuiltinTool], ...] = (
|
||||
)
|
||||
|
||||
|
||||
def builtin_tool_names(tools: Sequence[Tool | type[Tool]]) -> list[str]:
|
||||
def builtin_tools(tools: Sequence[Tool | type[Tool]]) -> tuple[list[str], dict[str, BuiltinApprovalPolicy]]:
|
||||
names: list[str] = []
|
||||
policies: dict[str, BuiltinApprovalPolicy] = {}
|
||||
seen: set[str] = set()
|
||||
for tool in tools:
|
||||
tool_type = tool if isinstance(tool, type) else type(tool)
|
||||
if not issubclass(tool_type, BuiltinTool):
|
||||
resolved = tool if isinstance(tool, ConfiguredBuiltinTool) else None
|
||||
tool_type = resolved.tool_type if resolved is not None else tool if isinstance(tool, type) else type(tool)
|
||||
if not isinstance(tool_type, type) or not issubclass(tool_type, BuiltinTool):
|
||||
continue
|
||||
name = tool_type.builtin_spec().tool_name
|
||||
if name not in seen:
|
||||
seen.add(name)
|
||||
names.append(name)
|
||||
return names
|
||||
if resolved is not None and resolved.approval_policy is not None:
|
||||
policies[name] = resolved.approval_policy
|
||||
return names, policies
|
||||
|
||||
|
||||
def function_tools(tools: Sequence[Tool | type[Tool]]) -> list[FunctionTool]:
|
||||
@@ -203,10 +243,9 @@ def function_tools(tools: Sequence[Tool | type[Tool]]) -> list[FunctionTool]:
|
||||
seen: set[str] = set()
|
||||
builtin_names = {tool.builtin_spec().tool_name for tool in ALL_BUILTIN_TOOLS}
|
||||
for tool in tools:
|
||||
if isinstance(tool, type):
|
||||
tool_instance = tool()
|
||||
else:
|
||||
tool_instance = tool
|
||||
if isinstance(tool, ConfiguredBuiltinTool):
|
||||
continue
|
||||
tool_instance = tool() if isinstance(tool, type) else tool
|
||||
if not isinstance(tool_instance, FunctionTool):
|
||||
continue
|
||||
tool_name = type(tool_instance).dynamic_tool_spec()["name"]
|
||||
@@ -219,10 +258,26 @@ def function_tools(tools: Sequence[Tool | type[Tool]]) -> list[FunctionTool]:
|
||||
return resolved
|
||||
|
||||
|
||||
def tool_instruction_fragments(tools: Sequence[Tool | type[Tool]]) -> list[str]:
|
||||
fragments: list[str] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
for tool in tools:
|
||||
if isinstance(tool, ConfiguredBuiltinTool):
|
||||
continue
|
||||
|
||||
tool_instance = tool() if isinstance(tool, type) else tool
|
||||
if isinstance(tool_instance, FunctionTool):
|
||||
fragment = tool_instance.instructions()
|
||||
key = f"function:{type(tool_instance).dynamic_tool_spec()['name']}"
|
||||
if fragment and key not in seen:
|
||||
seen.add(key)
|
||||
fragments.append(fragment)
|
||||
|
||||
return fragments
|
||||
|
||||
|
||||
DEFAULT_TOOLS: tuple[type[BuiltinTool], ...] = (
|
||||
ExecCommand,
|
||||
WriteStdin,
|
||||
UpdatePlan,
|
||||
ApplyPatch,
|
||||
ViewImage,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,397 @@
|
||||
# codex-sdk-v2 Prototype Summary
|
||||
|
||||
## 1. Goals of the prototype
|
||||
|
||||
This prototype was meant to answer one core question:
|
||||
|
||||
Can we reuse Codex as the runtime and tool-execution engine while preserving the Universal Computer model in which the host SDK owns orchestration, configuration, approvals, and provider access?
|
||||
|
||||
More concretely, the prototype set out to prove that we can:
|
||||
|
||||
- run Codex through app-server instead of re-implementing tool behavior in Python
|
||||
- let the host SDK own Responses API credentials and transport
|
||||
- choose which Codex built-in tools are enabled from the SDK
|
||||
- add host-defined function tools in a Universal Computer-style API
|
||||
- keep the SDK in the loop for all tool calls via pending tool call pause-points
|
||||
- support programmatic approval, defer, reject, and argument/command rewriting
|
||||
- start moving away from monolithic prompt construction toward capability-scoped instruction composition
|
||||
- preserve the Universal Computer ergonomics where possible while adopting Codex’s runtime model
|
||||
|
||||
The result is a successful prototype, with one important caveat:
|
||||
|
||||
The current transport is still bridge-based delegation, not the final event-by-event host-delegation model from the RFC.
|
||||
|
||||
## 2. Changes made in Codex
|
||||
|
||||
To support the prototype, Codex needed a handful of structural changes.
|
||||
|
||||
### App-server and thread/session configuration
|
||||
|
||||
We added new thread-start knobs so the SDK can shape the runtime explicitly:
|
||||
|
||||
- a thread-scoped delegation configuration pointing Codex at a host-managed Responses bridge
|
||||
- a built-in tool allowlist so the SDK can choose which Codex tools are exposed
|
||||
- a manual tool execution mode so built-in tool calls can become host-visible pause-points
|
||||
|
||||
This is a meaningful shift in ownership. Before, tool availability and model transport were mostly internal to Codex. With this prototype, the SDK becomes an active configuration authority.
|
||||
|
||||
### Model transport delegation
|
||||
|
||||
Codex was extended so a thread can target a host-local bridge for `/v1/responses` traffic instead of always talking directly to the upstream provider.
|
||||
|
||||
That required:
|
||||
|
||||
- per-thread provider override behavior
|
||||
- app-server awareness of the delegation configuration
|
||||
- explicit startup signaling so the SDK can verify that delegation was actually applied
|
||||
|
||||
This is enough for the prototype, but it is still a proxy model rather than true delegated transport.
|
||||
|
||||
In the prototype:
|
||||
|
||||
- Codex still constructs a provider-shaped HTTP request
|
||||
- Codex still opens the streaming HTTP connection itself
|
||||
- that request is aimed at the host-owned bridge rather than directly at OpenAI
|
||||
- the host bridge then makes the real upstream HTTP request, injects `Authorization`, and streams the provider response bytes back down to Codex unchanged
|
||||
|
||||
So the host really is performing the upstream HTTP request in this prototype, but Codex still thinks it is talking to a Responses-compatible HTTP endpoint. The transport contract is still HTTP proxying, not app-server-level request delegation.
|
||||
|
||||
### Built-in tool selection and host-visible control flow
|
||||
|
||||
Codex already had built-in tools, but the prototype needed the SDK to decide which ones are present on a thread.
|
||||
|
||||
That led to:
|
||||
|
||||
- explicit built-in tool filtering at thread startup
|
||||
- manual execution mode for unified-exec so the SDK can pause on built-in calls before Codex executes them
|
||||
- command-override support for unified-exec so the SDK can replace a proposed command rather than only approve or reject it
|
||||
|
||||
This is a real architectural improvement for host control, but it also increases surface area around tool semantics and approval behavior.
|
||||
|
||||
### Prompt composition changes
|
||||
|
||||
Codex previously relied on a fairly monolithic base prompt. To support tool-conditional guidance, we introduced capability-scoped prompt fragments for built-ins and composed them into the session base instructions.
|
||||
|
||||
The important structural change here is not just “more prompt files.” It is that built-in tool guidance is no longer conceptually part of one indivisible system prompt. It is now attached to enabled capabilities.
|
||||
|
||||
That is the right direction, but it introduces a maintenance obligation: prompt behavior now depends on both model metadata and tool configuration, so drift between those layers becomes a real risk.
|
||||
|
||||
### Risks and maintenance challenges introduced in Codex
|
||||
|
||||
- The bridge-based delegation path is a temporary architecture and will be easy to over-invest in if we are not disciplined.
|
||||
- Tool semantics now exist at the intersection of prompt composition, tool registry configuration, and approval handling, which increases the chance of subtle mismatches.
|
||||
- Manual built-in pause-points make the runtime more host-friendly, but they also make turn progression and resume behavior more stateful and therefore more failure-prone.
|
||||
- Built-in capability prompts now need to stay aligned with the actual available tool surface. If we add tools and forget to add or adjust capability fragments, the prompt can become misleading again.
|
||||
- The prototype only exercises a narrow built-in set, mainly unified-exec. Expanding to the full Codex built-in surface will add complexity.
|
||||
|
||||
## 3. Changes from the original Universal Computer model
|
||||
|
||||
To make Universal Computer work in this world, we had to reshape several assumptions from the original package.
|
||||
|
||||
### Tool implementation ownership
|
||||
|
||||
Original Universal Computer treated the Python SDK as the home of tool execution for built-ins like filesystem and shell behavior.
|
||||
|
||||
In the new world:
|
||||
|
||||
- Codex owns built-in tool execution
|
||||
- the SDK only enables or disables built-ins and participates in approvals/control flow
|
||||
- host-defined tools remain host-executed, but they are expressed as Codex dynamic tools under the hood
|
||||
|
||||
This is probably the biggest philosophical change in the whole prototype.
|
||||
|
||||
### Plugin architecture became capability architecture
|
||||
|
||||
Universal Computer plugins mixed together:
|
||||
|
||||
- tool groups
|
||||
- instructions
|
||||
- manifest mutation
|
||||
- request shaping
|
||||
|
||||
For the prototype, that concept was reintroduced as capabilities:
|
||||
|
||||
- a capability exposes a single `tools()` method
|
||||
- it can contribute instructions
|
||||
- it can mutate the manifest
|
||||
|
||||
The built-in/function distinction is now internal to the SDK rather than part of the public composition API.
|
||||
|
||||
### Approval and execution flow
|
||||
|
||||
Original Universal Computer exposed a very host-centric tool call loop. We restored that shape, but the semantics changed:
|
||||
|
||||
- built-in Codex tools now pause for host approval rather than being host-executed
|
||||
- host function tools are still host-executed
|
||||
- both are surfaced through one pending tool call abstraction
|
||||
|
||||
This preserves the ergonomics while changing the underlying runtime ownership model.
|
||||
|
||||
### Session instruction model
|
||||
|
||||
Universal Computer previously had a stronger notion of separate base, developer, and user instructions.
|
||||
|
||||
In the prototype:
|
||||
|
||||
- `base_instructions` remains a replacement channel
|
||||
- `developer_instructions` remains an additive channel
|
||||
- `user_instructions` was removed rather than carrying forward a misleading prefix-based approximation
|
||||
|
||||
That is a simplification, but also an admission that the old user-instructions shape was not yet properly mapped.
|
||||
|
||||
### Transport and backend model
|
||||
|
||||
Universal Computer’s original long-term direction is backend-agnostic remote execution.
|
||||
|
||||
The prototype narrows that significantly:
|
||||
|
||||
- it currently uses a local attached-process backend
|
||||
- the SDK owns a local bridge
|
||||
- the “copy Codex binary into a destination container” story is not yet real
|
||||
|
||||
This was the right tradeoff for a prototype, but it means the transport/backend layer is still far from feature-complete.
|
||||
|
||||
## 4. Remaining work to fully port the Universal Computer paradigm
|
||||
|
||||
There is still substantial work left before this becomes a full Universal Computer-on-Codex implementation.
|
||||
|
||||
### Replace bridge-based delegation with true app-server delegation
|
||||
|
||||
The RFC’s intended architecture is:
|
||||
|
||||
- Codex prepares the upstream model request
|
||||
- app-server emits host-directed delegation events
|
||||
- the host SDK makes the provider call
|
||||
- the host streams upstream events back into Codex
|
||||
|
||||
The prototype does not do that yet. It uses a bridge/proxy instead.
|
||||
|
||||
The difference matters:
|
||||
|
||||
- in the prototype bridge model, Codex speaks HTTP to a Responses-compatible endpoint and the host pretends to be that endpoint
|
||||
- in the intended full-delegation model, Codex does not speak provider HTTP at all; it emits structured app-server events and the SDK owns the provider call lifecycle explicitly
|
||||
|
||||
Said another way:
|
||||
|
||||
- today, the host owns the real upstream HTTP request, but Codex still owns the HTTP client behavior and stream shape it expects to speak
|
||||
- in the future design, the host owns both the upstream HTTP request and the transport contract between Codex and the host
|
||||
|
||||
That future-state is what unlocks:
|
||||
|
||||
- provider switching without pretending every provider is a Responses-compatible bridge
|
||||
- clean host-side request persistence and replay
|
||||
- first-class interception, cancellation, and routing at the SDK layer
|
||||
- a better multi-container story because the host is in the loop at the app-server event layer rather than only behind an HTTP shim
|
||||
|
||||
This is the most important architectural gap to close.
|
||||
|
||||
### Generate typed SDK protocol models
|
||||
|
||||
The prototype still hand-rolls Python-side JSON-RPC parsing and event handling.
|
||||
|
||||
To make this production-worthy we should generate typed SDK protocol models from the Rust app-server source of truth, including:
|
||||
|
||||
- Python Pydantic models for app-server requests, responses, and notifications
|
||||
- continued TypeScript generation from the same Rust source
|
||||
- a clearer separation between wire-level protocol models and higher-level SDK runtime objects like pending tool calls
|
||||
|
||||
This matters for correctness and maintainability. As the app-server surface grows, hand-maintained Python shapes will drift.
|
||||
|
||||
### Reintroduce durable rollout ownership on the host
|
||||
|
||||
The prototype has in-memory pending tool calls, but it does not yet fully restore the Universal Computer model where the host owns durable rollout state and can cleanly pause, spin down, and resume later.
|
||||
|
||||
To finish that work we need:
|
||||
|
||||
- stable serialization of unresolved pending tool calls
|
||||
- robust replay/rehydration for built-in approvals and function-tool calls
|
||||
- host-owned transcript and turn state as the source of truth
|
||||
|
||||
### Complete the capability system
|
||||
|
||||
The prototype capability model is intentionally small. A fuller port would need:
|
||||
|
||||
- richer capability composition
|
||||
- skill-like capability bundles
|
||||
- memory capability support
|
||||
- manifest-processing conventions
|
||||
- clearer precedence rules when multiple capabilities contribute instructions or tools
|
||||
|
||||
### Provider abstraction on the host
|
||||
|
||||
Universal Computer wants host-side multi-provider support. The prototype still assumes an OpenAI-shaped host bridge.
|
||||
|
||||
A real port needs:
|
||||
|
||||
- provider-neutral request abstractions on the host
|
||||
- OpenAI and Anthropic support at minimum
|
||||
- streaming normalization back into Codex’s expectations
|
||||
|
||||
### Remote backend support
|
||||
|
||||
The prototype does not yet solve:
|
||||
|
||||
- pinned Codex version acquisition
|
||||
- copying the right Codex binary to the destination environment
|
||||
- attached-process support across all intended backends
|
||||
- reliable host-container transport for app-server
|
||||
|
||||
That backend work is core to the Universal Computer value proposition and still remains.
|
||||
|
||||
### Complete prompt/capability alignment
|
||||
|
||||
We now have the beginning of built-in capability prompt composition, but not the final state.
|
||||
|
||||
Still needed:
|
||||
|
||||
- expand capability fragments beyond the current narrow built-in set
|
||||
- unify prompt composition conventions across all built-ins
|
||||
- make capability ownership and prompt ownership obvious and durable
|
||||
|
||||
## 5. Risks and challenges to productionize
|
||||
|
||||
### Architecture risk
|
||||
|
||||
The biggest risk is shipping too much around the bridge transport and then having to unwind it when moving to true full delegation mode. The bridge is a useful prototype tool, but it is not the right final abstraction.
|
||||
|
||||
### State and resume complexity
|
||||
|
||||
Host-visible pause-points are powerful, but productionizing them means solving:
|
||||
|
||||
- durable pending tool state
|
||||
- replay correctness
|
||||
- no double-execution on resume
|
||||
- clear ownership of partially completed turns
|
||||
|
||||
This is tricky and easy to get subtly wrong.
|
||||
|
||||
### Prompt and capability drift
|
||||
|
||||
We are now explicitly tying enabled capabilities to prompt sections. That is a better model, but it creates a new kind of maintenance burden:
|
||||
|
||||
- adding or removing a tool may require prompt updates
|
||||
- prompt fragments may drift from actual runtime behavior
|
||||
- capability bundles may accumulate overlapping or contradictory instructions
|
||||
|
||||
### Cross-runtime compatibility
|
||||
|
||||
Codex is a Rust runtime with strong internal assumptions. Universal Computer wants host orchestration across heterogeneous backends and providers. The seam between those two worlds needs to stay disciplined or the SDK will slowly become a shadow runtime.
|
||||
|
||||
### Operational complexity
|
||||
|
||||
Productionizing this means dealing with:
|
||||
|
||||
- version pinning
|
||||
- binary distribution
|
||||
- backend compatibility
|
||||
- network transport
|
||||
- auth boundaries
|
||||
- observability for both the host SDK and the remote Codex runtime
|
||||
|
||||
That is a larger operational surface than either original system had in isolation.
|
||||
|
||||
## 6. Suggested engineering roadmap
|
||||
|
||||
### Phase 1: Tighten the prototype foundation
|
||||
|
||||
Goals:
|
||||
|
||||
- stabilize the `codex-sdk-v2` API
|
||||
- keep capabilities as the public composition abstraction
|
||||
- expand and clean up built-in capability prompt composition
|
||||
- remove obviously prototype-only rough edges
|
||||
|
||||
Deliverables:
|
||||
|
||||
- clear capability API
|
||||
- consistent base/developer instruction semantics
|
||||
- better example coverage
|
||||
- tighter prompt composition ownership rules
|
||||
- generated Python Pydantic models for app-server protocol payloads
|
||||
|
||||
### Phase 2: Replace bridge delegation with real app-server full delegation
|
||||
|
||||
Goals:
|
||||
|
||||
- make the host SDK the true owner of provider transport
|
||||
- stop relying on a bridge/proxy architecture
|
||||
|
||||
Deliverables:
|
||||
|
||||
- new app-server delegation events for model requests and streamed upstream events
|
||||
- generated protocol types covering the new delegation events
|
||||
- host-side transport driver
|
||||
- Codex-side external stream ingestion
|
||||
- explicit cancellation and failure semantics
|
||||
|
||||
This phase is the real architectural transition.
|
||||
|
||||
### Phase 3: Host-owned rollout and durable pause/resume
|
||||
|
||||
Goals:
|
||||
|
||||
- restore the original Universal Computer durability model
|
||||
- make pending tool calls and turn state resumable across process restarts
|
||||
|
||||
Deliverables:
|
||||
|
||||
- serialized pending tool state
|
||||
- replay-safe resume logic
|
||||
- host-owned rollout persistence as source of truth
|
||||
- strong idempotency guarantees where possible
|
||||
|
||||
### Phase 4: Backend generalization
|
||||
|
||||
Goals:
|
||||
|
||||
- move beyond local attached-process execution
|
||||
- support the Universal Computer backend model in earnest
|
||||
|
||||
Deliverables:
|
||||
|
||||
- pinned Codex version management
|
||||
- binary acquisition and staging
|
||||
- attached-process support across all supported backends
|
||||
- robust host-runtime transport recommendations and implementations
|
||||
|
||||
### Phase 5: Provider and capability expansion
|
||||
|
||||
Goals:
|
||||
|
||||
- make the host SDK genuinely multi-provider
|
||||
- expand the capability model to cover more of the original Universal Computer ecosystem
|
||||
|
||||
Deliverables:
|
||||
|
||||
- provider abstraction for OpenAI and Anthropic
|
||||
- richer capability bundles
|
||||
- memory/skills-style capabilities
|
||||
- better story for apps and connector-driven capabilities
|
||||
|
||||
### Phase 6: Hardening and production readiness
|
||||
|
||||
Goals:
|
||||
|
||||
- make the system operable and debuggable in real workloads
|
||||
|
||||
Deliverables:
|
||||
|
||||
- observability across host and runtime
|
||||
- clear failure semantics
|
||||
- migration strategy from Universal Computer package users
|
||||
- load, reliability, and recovery testing
|
||||
- documentation and support model
|
||||
|
||||
## Final assessment
|
||||
|
||||
This prototype successfully demonstrates that Codex can act as the execution/runtime layer for a Universal Computer-style SDK without forcing the SDK to re-implement Codex’s built-in tools in Python.
|
||||
|
||||
That is the right strategic result.
|
||||
|
||||
At the same time, it is still a prototype in the most important sense:
|
||||
|
||||
- the delegation transport is not final
|
||||
- durability is not final
|
||||
- backend generality is not final
|
||||
|
||||
The good news is that the prototype reduced uncertainty in the right places. The remaining work is substantial, but it now looks like engineering, not research.
|
||||
Reference in New Issue
Block a user