mirror of
https://github.com/openai/codex.git
synced 2026-11-16 22:00:36 +00:00
Add automation groundwork
This commit is contained in:
@@ -197,6 +197,8 @@ pub enum Feature {
|
||||
DefaultModeRequestUserInput,
|
||||
/// Enable automatic review for approval prompts.
|
||||
GuardianApproval,
|
||||
/// Enable scheduled automations and heartbeat wakeups.
|
||||
Automations,
|
||||
/// Enable persisted thread goals and automatic goal continuation.
|
||||
Goals,
|
||||
/// Add current context-window metadata to model-visible context.
|
||||
@@ -1147,6 +1149,12 @@ pub const FEATURES: &[FeatureSpec] = &[
|
||||
stage: Stage::Stable,
|
||||
default_enabled: true,
|
||||
},
|
||||
FeatureSpec {
|
||||
id: Feature::Automations,
|
||||
key: "automations",
|
||||
stage: Stage::UnderDevelopment,
|
||||
default_enabled: false,
|
||||
},
|
||||
FeatureSpec {
|
||||
id: Feature::Goals,
|
||||
key: "goals",
|
||||
|
||||
@@ -131,6 +131,13 @@ fn guardian_approval_is_stable_and_enabled_by_default() {
|
||||
assert_eq!(Feature::GuardianApproval.default_enabled(), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automations_is_under_development() {
|
||||
assert_eq!(Feature::Automations.stage(), Stage::UnderDevelopment);
|
||||
assert_eq!(Feature::Automations.default_enabled(), false);
|
||||
assert_eq!(feature_for_key("automations"), Some(Feature::Automations));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_permissions_is_under_development() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -107,6 +107,7 @@ pub const COLLABORATION_MODE_CLOSE_TAG: &str = "</collaboration_mode>";
|
||||
pub const REALTIME_CONVERSATION_OPEN_TAG: &str = "<realtime_conversation>";
|
||||
pub const REALTIME_CONVERSATION_CLOSE_TAG: &str = "</realtime_conversation>";
|
||||
pub const USER_MESSAGE_BEGIN: &str = "## My request for Codex:";
|
||||
pub const AUTOMATION_SESSION_SOURCE_NAME: &str = "automation";
|
||||
|
||||
// TODO(anp): Replace `TurnEnvironmentSelection` with `PathUri` once path URIs carry environment
|
||||
// identifiers.
|
||||
@@ -2688,6 +2689,10 @@ impl fmt::Display for SessionSource {
|
||||
}
|
||||
|
||||
impl SessionSource {
|
||||
pub fn automation() -> Self {
|
||||
Self::Custom(AUTOMATION_SESSION_SOURCE_NAME.to_string())
|
||||
}
|
||||
|
||||
pub fn from_startup_arg(value: &str) -> Result<Self, &'static str> {
|
||||
let trimmed = value.trim();
|
||||
if trimmed.is_empty() {
|
||||
@@ -2709,6 +2714,10 @@ impl SessionSource {
|
||||
matches!(self, SessionSource::Internal(_))
|
||||
}
|
||||
|
||||
pub fn is_automation(&self) -> bool {
|
||||
matches!(self, SessionSource::Custom(value) if value == AUTOMATION_SESSION_SOURCE_NAME)
|
||||
}
|
||||
|
||||
pub fn is_non_root_agent(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE threads
|
||||
ADD COLUMN automation_owner_thread_id TEXT;
|
||||
@@ -0,0 +1,5 @@
|
||||
ALTER TABLE threads
|
||||
ADD COLUMN approvals_reviewer TEXT NOT NULL DEFAULT 'user';
|
||||
|
||||
ALTER TABLE threads
|
||||
ADD COLUMN runtime_workspace_roots_json TEXT;
|
||||
@@ -35,7 +35,11 @@ pub fn rollout_item_affects_thread_metadata(item: &RolloutItem) -> bool {
|
||||
match item {
|
||||
RolloutItem::SessionMeta(_) | RolloutItem::TurnContext(_) => true,
|
||||
RolloutItem::EventMsg(
|
||||
EventMsg::TokenCount(_) | EventMsg::UserMessage(_) | EventMsg::ThreadGoalUpdated(_),
|
||||
EventMsg::SessionConfigured(_)
|
||||
| EventMsg::ThreadSettingsApplied(_)
|
||||
| EventMsg::TokenCount(_)
|
||||
| EventMsg::UserMessage(_)
|
||||
| EventMsg::ThreadGoalUpdated(_),
|
||||
) => true,
|
||||
RolloutItem::EventMsg(_)
|
||||
| RolloutItem::ResponseItem(_)
|
||||
@@ -78,6 +82,13 @@ fn apply_turn_context(metadata: &mut ThreadMetadata, turn_ctx: &TurnContextItem)
|
||||
}
|
||||
metadata.model = Some(turn_ctx.model.clone());
|
||||
metadata.reasoning_effort = turn_ctx.effort.clone();
|
||||
metadata.runtime_workspace_roots = turn_ctx.workspace_roots.as_ref().map(|roots| {
|
||||
roots
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(std::path::PathBuf::from)
|
||||
.collect()
|
||||
});
|
||||
metadata.sandbox_policy =
|
||||
serde_json::to_string(&turn_ctx.permission_profile()).unwrap_or_default();
|
||||
metadata.approval_mode = enum_to_string(&turn_ctx.approval_policy);
|
||||
@@ -109,6 +120,12 @@ fn apply_event_msg(metadata: &mut ThreadMetadata, event: &EventMsg) {
|
||||
set_preview_if_empty(metadata, Some(objective.to_string()));
|
||||
}
|
||||
}
|
||||
EventMsg::SessionConfigured(event) => {
|
||||
metadata.approvals_reviewer = event.approvals_reviewer;
|
||||
}
|
||||
EventMsg::ThreadSettingsApplied(event) => {
|
||||
metadata.approvals_reviewer = event.thread_settings.approvals_reviewer;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -539,6 +556,9 @@ mod tests {
|
||||
preview: None,
|
||||
sandbox_policy: "read-only".to_string(),
|
||||
approval_mode: "on-request".to_string(),
|
||||
approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer::User,
|
||||
runtime_workspace_roots: None,
|
||||
automation_owner_thread_id: None,
|
||||
tokens_used: 1,
|
||||
first_user_message: None,
|
||||
archived_at: None,
|
||||
|
||||
@@ -15,6 +15,7 @@ pub mod log_db;
|
||||
mod migrations;
|
||||
mod model;
|
||||
mod paths;
|
||||
mod persisted_session_source;
|
||||
mod runtime;
|
||||
mod telemetry;
|
||||
|
||||
@@ -45,6 +46,7 @@ pub use model::BackfillStats;
|
||||
pub use model::BackfillStatus;
|
||||
pub use model::DirectionalThreadSpawnEdgeStatus;
|
||||
pub use model::ExtractionOutcome;
|
||||
pub use model::RuntimeThreadMetadataInput;
|
||||
pub use model::SortDirection;
|
||||
pub use model::SortKey;
|
||||
pub use model::Stage1JobClaim;
|
||||
@@ -56,6 +58,9 @@ pub use model::ThreadGoalStatus;
|
||||
pub use model::ThreadMetadata;
|
||||
pub use model::ThreadMetadataBuilder;
|
||||
pub use model::ThreadsPage;
|
||||
pub use model::build_runtime_thread_metadata;
|
||||
pub use persisted_session_source::parse_persisted_session_source;
|
||||
pub use persisted_session_source::persisted_session_source_parent_thread_id;
|
||||
pub use runtime::ExternalAgentConfigImportDetailsRecord;
|
||||
pub use runtime::ExternalAgentConfigImportFailureRecord;
|
||||
pub use runtime::ExternalAgentConfigImportHistoryRecord;
|
||||
|
||||
@@ -29,11 +29,13 @@ pub use thread_goal::ThreadGoalStatus;
|
||||
pub use thread_metadata::Anchor;
|
||||
pub use thread_metadata::BackfillStats;
|
||||
pub use thread_metadata::ExtractionOutcome;
|
||||
pub use thread_metadata::RuntimeThreadMetadataInput;
|
||||
pub use thread_metadata::SortDirection;
|
||||
pub use thread_metadata::SortKey;
|
||||
pub use thread_metadata::ThreadMetadata;
|
||||
pub use thread_metadata::ThreadMetadataBuilder;
|
||||
pub use thread_metadata::ThreadsPage;
|
||||
pub use thread_metadata::build_runtime_thread_metadata;
|
||||
|
||||
pub(crate) use agent_job::AgentJobItemRow;
|
||||
pub(crate) use agent_job::AgentJobRow;
|
||||
|
||||
@@ -2,6 +2,7 @@ use anyhow::Result;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::SandboxPolicy;
|
||||
@@ -11,6 +12,8 @@ use sqlx::Row;
|
||||
use sqlx::sqlite::SqliteRow;
|
||||
use std::path::PathBuf;
|
||||
|
||||
const ARCHIVED_SESSIONS_SUBDIR: &str = "archived_sessions";
|
||||
|
||||
/// The sort key to use when listing threads.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SortKey {
|
||||
@@ -95,6 +98,12 @@ pub struct ThreadMetadata {
|
||||
pub sandbox_policy: String,
|
||||
/// The approval mode (stringified enum).
|
||||
pub approval_mode: String,
|
||||
/// The approval reviewer routing captured for the thread.
|
||||
pub approvals_reviewer: ApprovalsReviewer,
|
||||
/// Effective runtime workspace roots captured for the thread, if known.
|
||||
pub runtime_workspace_roots: Option<Vec<PathBuf>>,
|
||||
/// Owner thread for automation-spawned threads, if any.
|
||||
pub automation_owner_thread_id: Option<ThreadId>,
|
||||
/// The last observed token usage.
|
||||
pub tokens_used: i64,
|
||||
/// First user message observed for this thread, if any.
|
||||
@@ -140,6 +149,10 @@ pub struct ThreadMetadataBuilder {
|
||||
pub sandbox_policy: SandboxPolicy,
|
||||
/// The approval mode.
|
||||
pub approval_mode: AskForApproval,
|
||||
/// The approval reviewer routing.
|
||||
pub approvals_reviewer: ApprovalsReviewer,
|
||||
/// Effective runtime workspace roots, if known.
|
||||
pub runtime_workspace_roots: Option<Vec<PathBuf>>,
|
||||
/// The archive timestamp, if the thread is archived.
|
||||
pub archived_at: Option<DateTime<Utc>>,
|
||||
/// The git commit SHA, if known.
|
||||
@@ -150,6 +163,45 @@ pub struct ThreadMetadataBuilder {
|
||||
pub git_origin_url: Option<String>,
|
||||
}
|
||||
|
||||
/// Fully resolved runtime thread settings used to persist a thread record into sqlite.
|
||||
///
|
||||
/// Callers should populate this from the current live thread/session configuration rather than
|
||||
/// rollout-derived metadata. This keeps state-db materialization logic consistent across core and
|
||||
/// app-server surfaces that need to upsert the current thread.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RuntimeThreadMetadataInput {
|
||||
/// The thread identifier.
|
||||
pub id: ThreadId,
|
||||
/// The absolute rollout path on disk.
|
||||
pub rollout_path: PathBuf,
|
||||
/// Timestamp to record for thread creation/update when first materializing the row.
|
||||
pub created_at: DateTime<Utc>,
|
||||
/// The session source for the running thread.
|
||||
pub session_source: SessionSource,
|
||||
/// Optional analytics source classification for this thread.
|
||||
pub thread_source: Option<ThreadSource>,
|
||||
/// The model provider identifier.
|
||||
pub model_provider_id: String,
|
||||
/// The working directory for the thread.
|
||||
pub cwd: PathBuf,
|
||||
/// Version of the CLI that created the thread.
|
||||
pub cli_version: String,
|
||||
/// The sandbox policy applied to the running thread.
|
||||
pub sandbox_policy: SandboxPolicy,
|
||||
/// The approval mode applied to the running thread.
|
||||
pub approval_mode: AskForApproval,
|
||||
/// The approval reviewer applied to the running thread.
|
||||
pub approvals_reviewer: ApprovalsReviewer,
|
||||
/// Effective runtime workspace roots applied to the running thread.
|
||||
pub runtime_workspace_roots: Vec<PathBuf>,
|
||||
/// Owner thread for automation-spawned threads, if any.
|
||||
pub automation_owner_thread_id: Option<ThreadId>,
|
||||
/// The active model for the running thread.
|
||||
pub model: String,
|
||||
/// The active reasoning effort for the running thread.
|
||||
pub reasoning_effort: Option<ReasoningEffort>,
|
||||
}
|
||||
|
||||
impl ThreadMetadataBuilder {
|
||||
/// Create a new builder with required fields and sensible defaults.
|
||||
pub fn new(
|
||||
@@ -173,6 +225,8 @@ impl ThreadMetadataBuilder {
|
||||
cli_version: None,
|
||||
sandbox_policy: SandboxPolicy::new_read_only_policy(),
|
||||
approval_mode: AskForApproval::OnRequest,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
runtime_workspace_roots: None,
|
||||
archived_at: None,
|
||||
git_sha: None,
|
||||
git_branch: None,
|
||||
@@ -215,6 +269,9 @@ impl ThreadMetadataBuilder {
|
||||
preview: None,
|
||||
sandbox_policy,
|
||||
approval_mode,
|
||||
approvals_reviewer: self.approvals_reviewer,
|
||||
runtime_workspace_roots: self.runtime_workspace_roots.clone(),
|
||||
automation_owner_thread_id: None,
|
||||
tokens_used: 0,
|
||||
first_user_message: None,
|
||||
archived_at: self.archived_at.map(canonicalize_datetime),
|
||||
@@ -225,7 +282,50 @@ impl ThreadMetadataBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_runtime_thread_metadata(input: RuntimeThreadMetadataInput) -> ThreadMetadata {
|
||||
let RuntimeThreadMetadataInput {
|
||||
id,
|
||||
rollout_path,
|
||||
created_at,
|
||||
session_source,
|
||||
thread_source,
|
||||
model_provider_id,
|
||||
cwd,
|
||||
cli_version,
|
||||
sandbox_policy,
|
||||
approval_mode,
|
||||
approvals_reviewer,
|
||||
runtime_workspace_roots,
|
||||
automation_owner_thread_id,
|
||||
model,
|
||||
reasoning_effort,
|
||||
} = input;
|
||||
let mut builder = ThreadMetadataBuilder::new(id, rollout_path, created_at, session_source);
|
||||
builder.thread_source = thread_source;
|
||||
builder.model_provider = Some(model_provider_id.clone());
|
||||
builder.cwd = cwd;
|
||||
builder.cli_version = Some(cli_version);
|
||||
builder.sandbox_policy = sandbox_policy;
|
||||
builder.approval_mode = approval_mode;
|
||||
builder.approvals_reviewer = approvals_reviewer;
|
||||
builder.runtime_workspace_roots =
|
||||
(!runtime_workspace_roots.is_empty()).then_some(runtime_workspace_roots);
|
||||
let mut metadata = builder.build(model_provider_id.as_str());
|
||||
metadata.model = Some(model);
|
||||
metadata.reasoning_effort = reasoning_effort;
|
||||
metadata.automation_owner_thread_id = automation_owner_thread_id;
|
||||
metadata
|
||||
}
|
||||
|
||||
impl ThreadMetadata {
|
||||
pub fn is_archived(&self) -> bool {
|
||||
self.archived_at.is_some()
|
||||
|| self
|
||||
.rollout_path
|
||||
.components()
|
||||
.any(|component| component.as_os_str() == ARCHIVED_SESSIONS_SUBDIR)
|
||||
}
|
||||
|
||||
/// Preserve existing non-null Git fields when rollout-derived metadata is reconciled.
|
||||
pub fn prefer_existing_git_info(&mut self, existing: &Self) {
|
||||
if existing.git_sha.is_some() {
|
||||
@@ -308,6 +408,15 @@ impl ThreadMetadata {
|
||||
if self.approval_mode != other.approval_mode {
|
||||
diffs.push("approval_mode");
|
||||
}
|
||||
if self.approvals_reviewer != other.approvals_reviewer {
|
||||
diffs.push("approvals_reviewer");
|
||||
}
|
||||
if self.runtime_workspace_roots != other.runtime_workspace_roots {
|
||||
diffs.push("runtime_workspace_roots");
|
||||
}
|
||||
if self.automation_owner_thread_id != other.automation_owner_thread_id {
|
||||
diffs.push("automation_owner_thread_id");
|
||||
}
|
||||
if self.tokens_used != other.tokens_used {
|
||||
diffs.push("tokens_used");
|
||||
}
|
||||
@@ -354,6 +463,9 @@ pub(crate) struct ThreadRow {
|
||||
preview: String,
|
||||
sandbox_policy: String,
|
||||
approval_mode: String,
|
||||
approvals_reviewer: String,
|
||||
runtime_workspace_roots_json: Option<String>,
|
||||
automation_owner_thread_id: Option<String>,
|
||||
tokens_used: i64,
|
||||
first_user_message: String,
|
||||
archived_at: Option<i64>,
|
||||
@@ -383,6 +495,9 @@ impl ThreadRow {
|
||||
preview: row.try_get("preview")?,
|
||||
sandbox_policy: row.try_get("sandbox_policy")?,
|
||||
approval_mode: row.try_get("approval_mode")?,
|
||||
approvals_reviewer: row.try_get("approvals_reviewer")?,
|
||||
runtime_workspace_roots_json: row.try_get("runtime_workspace_roots_json")?,
|
||||
automation_owner_thread_id: row.try_get("automation_owner_thread_id")?,
|
||||
tokens_used: row.try_get("tokens_used")?,
|
||||
first_user_message: row.try_get("first_user_message")?,
|
||||
archived_at: row.try_get("archived_at")?,
|
||||
@@ -416,6 +531,9 @@ impl TryFrom<ThreadRow> for ThreadMetadata {
|
||||
preview,
|
||||
sandbox_policy,
|
||||
approval_mode,
|
||||
approvals_reviewer,
|
||||
runtime_workspace_roots_json,
|
||||
automation_owner_thread_id,
|
||||
tokens_used,
|
||||
first_user_message,
|
||||
archived_at,
|
||||
@@ -447,6 +565,13 @@ impl TryFrom<ThreadRow> for ThreadMetadata {
|
||||
preview: (!preview.is_empty()).then_some(preview),
|
||||
sandbox_policy,
|
||||
approval_mode,
|
||||
approvals_reviewer: parse_approvals_reviewer(approvals_reviewer.as_str()),
|
||||
runtime_workspace_roots: runtime_workspace_roots_json
|
||||
.map(parse_runtime_workspace_roots)
|
||||
.transpose()?,
|
||||
automation_owner_thread_id: automation_owner_thread_id
|
||||
.map(|thread_id| ThreadId::from_string(&thread_id))
|
||||
.transpose()?,
|
||||
tokens_used,
|
||||
first_user_message: (!first_user_message.is_empty()).then_some(first_user_message),
|
||||
archived_at: archived_at.map(epoch_seconds_to_datetime).transpose()?,
|
||||
@@ -473,6 +598,15 @@ pub(crate) fn datetime_to_epoch_seconds(dt: DateTime<Utc>) -> i64 {
|
||||
dt.timestamp()
|
||||
}
|
||||
|
||||
fn parse_approvals_reviewer(value: &str) -> ApprovalsReviewer {
|
||||
serde_json::from_value(serde_json::Value::String(value.to_string())).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn parse_runtime_workspace_roots(value: String) -> Result<Vec<PathBuf>> {
|
||||
let roots = serde_json::from_str::<Vec<String>>(value.as_str())?;
|
||||
Ok(roots.into_iter().map(PathBuf::from).collect())
|
||||
}
|
||||
|
||||
pub(crate) fn epoch_millis_to_datetime(value: i64) -> Result<DateTime<Utc>> {
|
||||
// Values older than 2020 if interpreted as milliseconds are legacy second-precision rows.
|
||||
// Convert them in memory so old state DBs keep ordering correctly after new writes use ms.
|
||||
@@ -509,6 +643,7 @@ mod tests {
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::PathBuf;
|
||||
@@ -533,6 +668,9 @@ mod tests {
|
||||
preview: String::new(),
|
||||
sandbox_policy: "read-only".to_string(),
|
||||
approval_mode: "on-request".to_string(),
|
||||
approvals_reviewer: "user".to_string(),
|
||||
runtime_workspace_roots_json: None,
|
||||
automation_owner_thread_id: None,
|
||||
tokens_used: 1,
|
||||
first_user_message: String::new(),
|
||||
archived_at: None,
|
||||
@@ -563,6 +701,9 @@ mod tests {
|
||||
preview: None,
|
||||
sandbox_policy: "read-only".to_string(),
|
||||
approval_mode: "on-request".to_string(),
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
runtime_workspace_roots: None,
|
||||
automation_owner_thread_id: None,
|
||||
tokens_used: 1,
|
||||
first_user_message: None,
|
||||
archived_at: None,
|
||||
@@ -593,4 +734,21 @@ mod tests {
|
||||
expected_thread_metadata(Some(ReasoningEffort::Custom("future".to_string())))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_metadata_is_archived_when_archived_at_is_present() {
|
||||
let mut metadata = expected_thread_metadata(None);
|
||||
metadata.archived_at =
|
||||
Some(DateTime::<Utc>::from_timestamp(1_700_000_200, 0).expect("timestamp"));
|
||||
|
||||
assert_eq!(metadata.is_archived(), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_metadata_is_archived_when_rollout_path_is_archived() {
|
||||
let mut metadata = expected_thread_metadata(None);
|
||||
metadata.rollout_path = PathBuf::from("/tmp/archived_sessions/rollout-123.jsonl");
|
||||
|
||||
assert_eq!(metadata.is_archived(), true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
use serde_json::Value;
|
||||
|
||||
pub fn parse_persisted_session_source(value: &str) -> Option<SessionSource> {
|
||||
let parsed = serde_json::from_str(value)
|
||||
.ok()
|
||||
.or_else(|| serde_json::from_value(Value::String(value.to_string())).ok());
|
||||
match parsed {
|
||||
Some(SessionSource::Unknown) => {
|
||||
parse_legacy_thread_spawn_source(value).or(Some(SessionSource::Unknown))
|
||||
}
|
||||
Some(source) => Some(source),
|
||||
None => parse_legacy_thread_spawn_source(value),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn persisted_session_source_parent_thread_id(value: &str) -> Option<ThreadId> {
|
||||
parse_persisted_session_source(value)?.parent_thread_id()
|
||||
}
|
||||
|
||||
fn parse_legacy_thread_spawn_source(value: &str) -> Option<SessionSource> {
|
||||
let legacy = value
|
||||
.strip_prefix("subagent_thread_spawn_")
|
||||
.or_else(|| value.strip_prefix("thread_spawn_"))?;
|
||||
let (parent_thread_id, depth) = legacy.rsplit_once("_d")?;
|
||||
let parent_thread_id = ThreadId::from_string(parent_thread_id).ok()?;
|
||||
let depth = depth.parse::<i32>().ok()?;
|
||||
Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id,
|
||||
depth,
|
||||
agent_path: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn parses_current_persisted_subagent_thread_spawn_encoding() {
|
||||
let parent_thread_id =
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000123").expect("thread id");
|
||||
let source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id,
|
||||
depth: 1,
|
||||
agent_path: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
});
|
||||
let persisted = serde_json::to_string(&source).expect("serialize session source");
|
||||
|
||||
assert_eq!(parse_persisted_session_source(&persisted), Some(source));
|
||||
assert_eq!(
|
||||
persisted_session_source_parent_thread_id(&persisted),
|
||||
Some(parent_thread_id)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_legacy_display_thread_spawn_encoding() {
|
||||
let parent_thread_id =
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000123").expect("thread id");
|
||||
let legacy = format!("subagent_thread_spawn_{parent_thread_id}_d1");
|
||||
|
||||
assert_eq!(
|
||||
parse_persisted_session_source(&legacy),
|
||||
Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id,
|
||||
depth: 1,
|
||||
agent_path: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
}))
|
||||
);
|
||||
assert_eq!(
|
||||
persisted_session_source_parent_thread_id(&legacy),
|
||||
Some(parent_thread_id)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_builtin_string_variants_written_without_json_quotes() {
|
||||
assert_eq!(
|
||||
parse_persisted_session_source("cli"),
|
||||
Some(SessionSource::Cli)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_persisted_session_source("vscode"),
|
||||
Some(SessionSource::VSCode)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -67,6 +67,7 @@ mod recovery;
|
||||
mod remote_control;
|
||||
#[cfg(test)]
|
||||
mod test_support;
|
||||
mod thread_spawn_lineage;
|
||||
mod threads;
|
||||
|
||||
pub use external_agent_config_imports::ExternalAgentConfigImportDetailsRecord;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::threads::ThreadFilterOptions;
|
||||
use super::threads::push_thread_filters;
|
||||
use super::threads::push_thread_select_columns;
|
||||
use super::*;
|
||||
use crate::SortDirection;
|
||||
use crate::model::Phase2JobClaimOutcome;
|
||||
@@ -168,36 +169,9 @@ WHERE kind = ? AND job_key = ?
|
||||
let idle_cutoff =
|
||||
(Utc::now() - Duration::hours(min_rollout_idle_hours.max(0))).timestamp_millis();
|
||||
|
||||
let mut builder = QueryBuilder::<Sqlite>::new(
|
||||
r#"
|
||||
SELECT
|
||||
threads.id,
|
||||
threads.rollout_path,
|
||||
threads.created_at_ms AS created_at,
|
||||
threads.updated_at_ms AS updated_at,
|
||||
threads.source,
|
||||
threads.thread_source,
|
||||
threads.agent_path,
|
||||
threads.agent_nickname,
|
||||
threads.agent_role,
|
||||
threads.model_provider,
|
||||
threads.model,
|
||||
threads.reasoning_effort,
|
||||
threads.cwd,
|
||||
threads.cli_version,
|
||||
threads.title,
|
||||
threads.preview,
|
||||
threads.sandbox_policy,
|
||||
threads.approval_mode,
|
||||
threads.tokens_used,
|
||||
threads.first_user_message,
|
||||
threads.archived_at,
|
||||
threads.git_sha,
|
||||
threads.git_branch,
|
||||
threads.git_origin_url
|
||||
FROM threads
|
||||
"#,
|
||||
);
|
||||
let mut builder = QueryBuilder::<Sqlite>::new("");
|
||||
push_thread_select_columns(&mut builder);
|
||||
builder.push(" FROM threads");
|
||||
push_thread_filters(
|
||||
&mut builder,
|
||||
ThreadFilterOptions {
|
||||
@@ -538,40 +512,15 @@ WHERE so.thread_id = ? AND so.source_updated_at = ?
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
) -> anyhow::Result<Option<ThreadMetadata>> {
|
||||
let row = sqlx::query(
|
||||
r#"
|
||||
SELECT
|
||||
threads.id,
|
||||
threads.rollout_path,
|
||||
threads.created_at_ms AS created_at,
|
||||
threads.updated_at_ms AS updated_at,
|
||||
threads.source,
|
||||
threads.thread_source,
|
||||
threads.agent_nickname,
|
||||
threads.agent_role,
|
||||
threads.agent_path,
|
||||
threads.model_provider,
|
||||
threads.model,
|
||||
threads.reasoning_effort,
|
||||
threads.cwd,
|
||||
threads.cli_version,
|
||||
threads.title,
|
||||
threads.preview,
|
||||
threads.sandbox_policy,
|
||||
threads.approval_mode,
|
||||
threads.tokens_used,
|
||||
threads.first_user_message,
|
||||
threads.archived_at,
|
||||
threads.git_sha,
|
||||
threads.git_branch,
|
||||
threads.git_origin_url
|
||||
FROM threads
|
||||
WHERE threads.id = ? AND threads.memory_mode = 'enabled'
|
||||
"#,
|
||||
)
|
||||
.bind(thread_id.to_string())
|
||||
.fetch_optional(self.state_pool.as_ref())
|
||||
.await?;
|
||||
let mut builder = QueryBuilder::<Sqlite>::new("");
|
||||
push_thread_select_columns(&mut builder);
|
||||
builder.push(" FROM threads WHERE threads.id = ");
|
||||
builder.push_bind(thread_id.to_string());
|
||||
builder.push(" AND threads.memory_mode = 'enabled'");
|
||||
let row = builder
|
||||
.build()
|
||||
.fetch_optional(self.state_pool.as_ref())
|
||||
.await?;
|
||||
|
||||
row.map(|row| ThreadRow::try_from_row(&row).and_then(ThreadMetadata::try_from))
|
||||
.transpose()
|
||||
|
||||
@@ -5,6 +5,8 @@ use chrono::Utc;
|
||||
#[cfg(test)]
|
||||
use codex_protocol::ThreadId;
|
||||
#[cfg(test)]
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
#[cfg(test)]
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
#[cfg(test)]
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
@@ -61,6 +63,9 @@ pub(super) fn test_thread_metadata(
|
||||
preview: Some("hello".to_string()),
|
||||
sandbox_policy: crate::extract::enum_to_string(&SandboxPolicy::new_read_only_policy()),
|
||||
approval_mode: crate::extract::enum_to_string(&AskForApproval::OnRequest),
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
runtime_workspace_roots: None,
|
||||
automation_owner_thread_id: None,
|
||||
tokens_used: 0,
|
||||
first_user_message: Some("hello".to_string()),
|
||||
archived_at: None,
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
use super::StateRuntime;
|
||||
use codex_protocol::ThreadId;
|
||||
use std::collections::HashSet;
|
||||
|
||||
const MAX_THREAD_SPAWN_LINEAGE_DEPTH: usize = 64;
|
||||
|
||||
impl StateRuntime {
|
||||
/// Find the direct spawned parent of `child_thread_id`, if present.
|
||||
pub async fn get_thread_spawn_parent(
|
||||
&self,
|
||||
child_thread_id: ThreadId,
|
||||
) -> anyhow::Result<Option<ThreadId>> {
|
||||
sqlx::query_scalar::<_, String>(
|
||||
"SELECT parent_thread_id FROM thread_spawn_edges WHERE child_thread_id = ?",
|
||||
)
|
||||
.bind(child_thread_id.to_string())
|
||||
.fetch_optional(self.pool.as_ref())
|
||||
.await?
|
||||
.map(|value| ThreadId::try_from(value).map_err(Into::into))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// Resolve the automation owner for `thread_id`, following persisted thread-spawn lineage.
|
||||
pub async fn automation_owner_thread_id_for_lineage(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
) -> anyhow::Result<Option<ThreadId>> {
|
||||
let mut current_thread_id = thread_id;
|
||||
let mut visited_thread_ids = HashSet::from([thread_id]);
|
||||
|
||||
for _ in 0..MAX_THREAD_SPAWN_LINEAGE_DEPTH {
|
||||
let mut parent_thread_id_from_source = None;
|
||||
if let Some(metadata) = self.get_thread(current_thread_id).await? {
|
||||
if let Some(owner_thread_id) = metadata.automation_owner_thread_id {
|
||||
return Ok(Some(owner_thread_id));
|
||||
}
|
||||
parent_thread_id_from_source =
|
||||
thread_spawn_parent_thread_id_from_source_str(metadata.source.as_str());
|
||||
}
|
||||
|
||||
let Some(parent_thread_id) = self
|
||||
.get_thread_spawn_parent(current_thread_id)
|
||||
.await?
|
||||
.or(parent_thread_id_from_source)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !visited_thread_ids.insert(parent_thread_id) {
|
||||
return Ok(None);
|
||||
}
|
||||
current_thread_id = parent_thread_id;
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(super) async fn upsert_thread_spawn_edge_from_metadata(
|
||||
&self,
|
||||
metadata: &crate::ThreadMetadata,
|
||||
previous_metadata: Option<&crate::ThreadMetadata>,
|
||||
) -> anyhow::Result<()> {
|
||||
if let Some(parent_thread_id) =
|
||||
thread_spawn_parent_thread_id_from_source_str(metadata.source.as_str())
|
||||
{
|
||||
return self
|
||||
.upsert_thread_spawn_edge(
|
||||
parent_thread_id,
|
||||
metadata.id,
|
||||
crate::DirectionalThreadSpawnEdgeStatus::Open,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
if crate::parse_persisted_session_source(metadata.source.as_str())
|
||||
.is_some_and(|session_source| session_source.is_automation())
|
||||
&& let Some(owner_thread_id) = metadata.automation_owner_thread_id
|
||||
{
|
||||
return self
|
||||
.upsert_thread_spawn_edge(
|
||||
owner_thread_id,
|
||||
metadata.id,
|
||||
crate::DirectionalThreadSpawnEdgeStatus::Open,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
if metadata.automation_owner_thread_id.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if previous_metadata.is_some_and(thread_metadata_had_spawn_lineage) {
|
||||
sqlx::query("DELETE FROM thread_spawn_edges WHERE child_thread_id = ?")
|
||||
.bind(metadata.id.to_string())
|
||||
.execute(self.pool.as_ref())
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn thread_metadata_had_spawn_lineage(metadata: &crate::ThreadMetadata) -> bool {
|
||||
metadata.automation_owner_thread_id.is_some()
|
||||
|| thread_spawn_parent_thread_id_from_source_str(metadata.source.as_str()).is_some()
|
||||
|| crate::parse_persisted_session_source(metadata.source.as_str())
|
||||
.is_some_and(|session_source| session_source.is_automation())
|
||||
}
|
||||
|
||||
pub(super) fn thread_spawn_parent_thread_id_from_source_str(source: &str) -> Option<ThreadId> {
|
||||
crate::persisted_session_source_parent_thread_id(source)
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
use super::*;
|
||||
use crate::SortDirection;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
impl StateRuntime {
|
||||
@@ -26,6 +25,9 @@ SELECT
|
||||
threads.preview,
|
||||
threads.sandbox_policy,
|
||||
threads.approval_mode,
|
||||
threads.approvals_reviewer,
|
||||
threads.runtime_workspace_roots_json,
|
||||
threads.automation_owner_thread_id,
|
||||
threads.tokens_used,
|
||||
threads.first_user_message,
|
||||
threads.archived_at,
|
||||
@@ -289,41 +291,6 @@ ORDER BY depth ASC, child_thread_id ASC
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn insert_thread_spawn_edge_if_absent(
|
||||
&self,
|
||||
parent_thread_id: ThreadId,
|
||||
child_thread_id: ThreadId,
|
||||
) -> anyhow::Result<()> {
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO thread_spawn_edges (
|
||||
parent_thread_id,
|
||||
child_thread_id,
|
||||
status
|
||||
) VALUES (?, ?, ?)
|
||||
ON CONFLICT(child_thread_id) DO NOTHING
|
||||
"#,
|
||||
)
|
||||
.bind(parent_thread_id.to_string())
|
||||
.bind(child_thread_id.to_string())
|
||||
.bind(crate::DirectionalThreadSpawnEdgeStatus::Open.as_ref())
|
||||
.execute(self.pool.as_ref())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn insert_thread_spawn_edge_from_source_if_absent(
|
||||
&self,
|
||||
child_thread_id: ThreadId,
|
||||
source: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
let Some(parent_thread_id) = thread_spawn_parent_thread_id_from_source_str(source) else {
|
||||
return Ok(());
|
||||
};
|
||||
self.insert_thread_spawn_edge_if_absent(parent_thread_id, child_thread_id)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Find a rollout path by thread id using the underlying database.
|
||||
pub async fn find_rollout_path_by_id(
|
||||
&self,
|
||||
@@ -499,6 +466,8 @@ ON CONFLICT(child_thread_id) DO NOTHING
|
||||
) -> anyhow::Result<bool> {
|
||||
let updated_at = self.allocate_thread_updated_at(metadata.updated_at)?;
|
||||
let preview = metadata_preview(metadata);
|
||||
let runtime_workspace_roots_json =
|
||||
thread_runtime_workspace_roots_json(metadata.runtime_workspace_roots.as_deref())?;
|
||||
let result = sqlx::query(
|
||||
r#"
|
||||
INSERT INTO threads (
|
||||
@@ -522,6 +491,9 @@ INSERT INTO threads (
|
||||
preview,
|
||||
sandbox_policy,
|
||||
approval_mode,
|
||||
approvals_reviewer,
|
||||
runtime_workspace_roots_json,
|
||||
automation_owner_thread_id,
|
||||
tokens_used,
|
||||
first_user_message,
|
||||
archived,
|
||||
@@ -530,7 +502,7 @@ INSERT INTO threads (
|
||||
git_branch,
|
||||
git_origin_url,
|
||||
memory_mode
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO NOTHING
|
||||
"#,
|
||||
)
|
||||
@@ -564,6 +536,13 @@ ON CONFLICT(id) DO NOTHING
|
||||
.bind(preview)
|
||||
.bind(metadata.sandbox_policy.as_str())
|
||||
.bind(metadata.approval_mode.as_str())
|
||||
.bind(crate::extract::enum_to_string(&metadata.approvals_reviewer))
|
||||
.bind(runtime_workspace_roots_json.as_deref())
|
||||
.bind(
|
||||
metadata
|
||||
.automation_owner_thread_id
|
||||
.map(|thread_id| thread_id.to_string()),
|
||||
)
|
||||
.bind(metadata.tokens_used)
|
||||
.bind(metadata.first_user_message.as_deref().unwrap_or_default())
|
||||
.bind(metadata.archived_at.is_some())
|
||||
@@ -574,7 +553,7 @@ ON CONFLICT(id) DO NOTHING
|
||||
.bind("enabled")
|
||||
.execute(self.pool.as_ref())
|
||||
.await?;
|
||||
self.insert_thread_spawn_edge_from_source_if_absent(metadata.id, metadata.source.as_str())
|
||||
self.upsert_thread_spawn_edge_from_metadata(metadata, /*previous_metadata*/ None)
|
||||
.await?;
|
||||
Ok(result.rows_affected() > 0)
|
||||
}
|
||||
@@ -701,8 +680,11 @@ WHERE id = ?
|
||||
metadata: &crate::ThreadMetadata,
|
||||
creation_memory_mode: Option<&str>,
|
||||
) -> anyhow::Result<()> {
|
||||
let previous_metadata = self.get_thread(metadata.id).await?;
|
||||
let updated_at = self.allocate_thread_updated_at(metadata.updated_at)?;
|
||||
let preview = metadata_preview(metadata);
|
||||
let runtime_workspace_roots_json =
|
||||
thread_runtime_workspace_roots_json(metadata.runtime_workspace_roots.as_deref())?;
|
||||
// Backfill/reconcile callers merge existing git info before upserting, but that
|
||||
// read/modify/write is not atomic. Preserve non-null SQLite git fields here so
|
||||
// an explicit metadata update cannot be lost if a stale rollout upsert lands later.
|
||||
@@ -729,6 +711,9 @@ INSERT INTO threads (
|
||||
preview,
|
||||
sandbox_policy,
|
||||
approval_mode,
|
||||
approvals_reviewer,
|
||||
runtime_workspace_roots_json,
|
||||
automation_owner_thread_id,
|
||||
tokens_used,
|
||||
first_user_message,
|
||||
archived,
|
||||
@@ -737,7 +722,7 @@ INSERT INTO threads (
|
||||
git_branch,
|
||||
git_origin_url,
|
||||
memory_mode
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
rollout_path = excluded.rollout_path,
|
||||
created_at = excluded.created_at,
|
||||
@@ -758,6 +743,9 @@ ON CONFLICT(id) DO UPDATE SET
|
||||
preview = COALESCE(NULLIF(excluded.preview, ''), threads.preview),
|
||||
sandbox_policy = excluded.sandbox_policy,
|
||||
approval_mode = excluded.approval_mode,
|
||||
approvals_reviewer = excluded.approvals_reviewer,
|
||||
runtime_workspace_roots_json = excluded.runtime_workspace_roots_json,
|
||||
automation_owner_thread_id = excluded.automation_owner_thread_id,
|
||||
tokens_used = excluded.tokens_used,
|
||||
first_user_message = excluded.first_user_message,
|
||||
archived = excluded.archived,
|
||||
@@ -797,6 +785,13 @@ ON CONFLICT(id) DO UPDATE SET
|
||||
.bind(preview)
|
||||
.bind(metadata.sandbox_policy.as_str())
|
||||
.bind(metadata.approval_mode.as_str())
|
||||
.bind(crate::extract::enum_to_string(&metadata.approvals_reviewer))
|
||||
.bind(runtime_workspace_roots_json.as_deref())
|
||||
.bind(
|
||||
metadata
|
||||
.automation_owner_thread_id
|
||||
.map(|thread_id| thread_id.to_string()),
|
||||
)
|
||||
.bind(metadata.tokens_used)
|
||||
.bind(metadata.first_user_message.as_deref().unwrap_or_default())
|
||||
.bind(metadata.archived_at.is_some())
|
||||
@@ -807,7 +802,7 @@ ON CONFLICT(id) DO UPDATE SET
|
||||
.bind(creation_memory_mode.unwrap_or("enabled"))
|
||||
.execute(self.pool.as_ref())
|
||||
.await?;
|
||||
self.insert_thread_spawn_edge_from_source_if_absent(metadata.id, metadata.source.as_str())
|
||||
self.upsert_thread_spawn_edge_from_metadata(metadata, previous_metadata.as_ref())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1093,6 +1088,9 @@ SELECT
|
||||
threads.preview,
|
||||
threads.sandbox_policy,
|
||||
threads.approval_mode,
|
||||
threads.approvals_reviewer,
|
||||
threads.runtime_workspace_roots_json,
|
||||
threads.automation_owner_thread_id,
|
||||
threads.tokens_used,
|
||||
threads.first_user_message,
|
||||
threads.archived_at,
|
||||
@@ -1114,12 +1112,6 @@ pub(super) fn extract_memory_mode(items: &[RolloutItem]) -> Option<String> {
|
||||
})
|
||||
}
|
||||
|
||||
fn thread_spawn_parent_thread_id_from_source_str(source: &str) -> Option<ThreadId> {
|
||||
let parsed_source = serde_json::from_str(source)
|
||||
.or_else(|_| serde_json::from_value::<SessionSource>(Value::String(source.to_string())));
|
||||
parsed_source.ok()?.parent_thread_id()
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct ThreadFilterOptions<'a> {
|
||||
pub archived_only: bool,
|
||||
@@ -1259,6 +1251,22 @@ fn metadata_preview(metadata: &crate::ThreadMetadata) -> &str {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn thread_runtime_workspace_roots_json(
|
||||
runtime_workspace_roots: Option<&[PathBuf]>,
|
||||
) -> anyhow::Result<Option<String>> {
|
||||
runtime_workspace_roots
|
||||
.map(|roots| {
|
||||
serde_json::to_string(
|
||||
&roots
|
||||
.iter()
|
||||
.map(|root| root.display().to_string())
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.map_err(Into::into)
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::RolloutItem;
|
||||
use codex_protocol::protocol::ThreadMemoryMode;
|
||||
use codex_rollout::RolloutConfig;
|
||||
use codex_rollout::RolloutRecorder;
|
||||
@@ -32,24 +33,64 @@ pub(super) async fn resume_thread(
|
||||
params: ResumeThreadParams,
|
||||
) -> ThreadStoreResult<()> {
|
||||
store.ensure_live_recorder_absent(params.thread_id).await?;
|
||||
let rollout_path = match (params.rollout_path, params.history) {
|
||||
(Some(rollout_path), _history) => rollout_path,
|
||||
(None, history) => {
|
||||
let recorder_params = match params.rollout_path {
|
||||
Some(rollout_path) => RolloutRecorderParams::resume(rollout_path),
|
||||
None => {
|
||||
let thread = super::read_thread::read_thread(
|
||||
store,
|
||||
ReadThreadParams {
|
||||
thread_id: params.thread_id,
|
||||
include_archived: params.include_archived,
|
||||
include_history: history.is_none(),
|
||||
include_history: params.history.is_none(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
thread
|
||||
let rollout_path = thread
|
||||
.rollout_path
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: format!("thread {} does not have a rollout path", params.thread_id),
|
||||
})?
|
||||
})?;
|
||||
if codex_rollout::existing_rollout_path(rollout_path.as_path())
|
||||
.await
|
||||
.is_some()
|
||||
{
|
||||
RolloutRecorderParams::resume(rollout_path)
|
||||
} else {
|
||||
let session_meta = params
|
||||
.history
|
||||
.as_ref()
|
||||
.and_then(|history| {
|
||||
history.iter().find_map(|item| match item {
|
||||
RolloutItem::SessionMeta(meta_line)
|
||||
if meta_line.meta.id == params.thread_id =>
|
||||
{
|
||||
Some(&meta_line.meta)
|
||||
}
|
||||
RolloutItem::SessionMeta(_)
|
||||
| RolloutItem::ResponseItem(_)
|
||||
| RolloutItem::Compacted(_)
|
||||
| RolloutItem::TurnContext(_)
|
||||
| RolloutItem::EventMsg(_) => None,
|
||||
})
|
||||
})
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"thread {} does not have a rollout path",
|
||||
params.thread_id
|
||||
),
|
||||
})?;
|
||||
RolloutRecorderParams::new(
|
||||
params.thread_id,
|
||||
session_meta.forked_from_id,
|
||||
session_meta.parent_thread_id,
|
||||
session_meta.source.clone(),
|
||||
session_meta.thread_source,
|
||||
session_meta.base_instructions.clone().unwrap_or_default(),
|
||||
session_meta.dynamic_tools.clone().unwrap_or_default(),
|
||||
)
|
||||
.with_multi_agent_version(session_meta.multi_agent_version)
|
||||
}
|
||||
}
|
||||
};
|
||||
let cwd = params
|
||||
@@ -66,7 +107,7 @@ pub(super) async fn resume_thread(
|
||||
model_provider_id: params.metadata.model_provider.clone(),
|
||||
generate_memories: matches!(params.metadata.memory_mode, ThreadMemoryMode::Enabled),
|
||||
};
|
||||
let recorder = RolloutRecorder::new(&config, RolloutRecorderParams::resume(rollout_path))
|
||||
let recorder = RolloutRecorder::new(&config, recorder_params)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to resume local thread recorder: {err}"),
|
||||
|
||||
Reference in New Issue
Block a user