Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(agents): codex support (#6431)
Wolf Mermelstein128689ce5b57
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 9ccfd7516e..dd3c7b4942 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -164,6 +164,8 @@"crates/broadcast","crates/channel_sender","crates/channels",+ "crates/codex_cloud_agents",+ "crates/codex_connection","crates/comms_db_client","crates/connection","crates/connection_gateway_client",@@ -271,6 +273,8 @@"crates/channel_sender","crates/channels","crates/chat",+ "crates/codex_cloud_agents",+ "crates/codex_connection","crates/comms_db_client","crates/connection","crates/connection_gateway_client",@@ -1134,6 +1138,8 @@"crates/calendar_events","crates/channel_sender","crates/channels",+ "crates/codex_cloud_agents",+ "crates/codex_connection","crates/comms_db_client","crates/connection","crates/connection_gateway_client",@@ -1821,6 +1827,141 @@"crates/share_permission_db_utils","crates/workspace-hack"],+ "codex_cloud_agents": [+ "crates/activity",+ "crates/agent",+ "crates/agent_fold",+ "crates/agent_runtime_protocol",+ "crates/agent_session",+ "crates/ai_toolset",+ "crates/ai_usage",+ "crates/attachment",+ "crates/bot_id",+ "crates/bot_token",+ "crates/bots",+ "crates/broadcast",+ "crates/channel_sender",+ "crates/channels",+ "crates/codex_cloud_agents",+ "crates/connection_gateway_client",+ "crates/connection_gateway_models",+ "crates/contacts",+ "crates/cowlike",+ "crates/database_env_vars",+ "crates/document_sub_type",+ "crates/entity_access",+ "crates/entity_access_db_utils",+ "crates/entity_mutation",+ "crates/filter_ast",+ "crates/frecency",+ "crates/genai_telemetry",+ "crates/harness_id",+ "crates/harness_token",+ "crates/invite_email",+ "crates/item_filters",+ "crates/kafka_util",+ "crates/last_online_tracker",+ "crates/macro_auth",+ "crates/macro_authorization",+ "crates/macro_entrypoint",+ "crates/macro_env",+ "crates/macro_env_var",+ "crates/macro_event_broker",+ "crates/macro_event_topics",+ "crates/macro_service_urls",+ "crates/macro_tower_layers",+ "crates/macro_user_id",+ "crates/macro_uuid",+ "crates/mention_utils",+ "crates/model",+ "crates/model-entity",+ "crates/model-error-response",+ "crates/model_file_type",+ "crates/model_notifications",+ "crates/model_owner",+ "crates/model_user",+ "crates/models_bulk_upload",+ "crates/models_entity_access_management",+ "crates/models_pagination",+ "crates/models_permissions",+ "crates/non_empty",+ "crates/notification",+ "crates/notification_state",+ "crates/prompt",+ "crates/rate_limit",+ "crates/remote_env_var",+ "crates/share_permission_db_utils",+ "crates/sqs_worker",+ "crates/workspace-hack"+ ],+ "codex_connection": [+ "crates/activity",+ "crates/agent",+ "crates/agent_fold",+ "crates/agent_runtime_protocol",+ "crates/agent_session",+ "crates/ai_toolset",+ "crates/ai_usage",+ "crates/attachment",+ "crates/bot_id",+ "crates/bot_token",+ "crates/bots",+ "crates/broadcast",+ "crates/channel_sender",+ "crates/channels",+ "crates/codex_cloud_agents",+ "crates/codex_connection",+ "crates/connection_gateway_client",+ "crates/connection_gateway_models",+ "crates/contacts",+ "crates/cowlike",+ "crates/database_env_vars",+ "crates/document_sub_type",+ "crates/entity_access",+ "crates/entity_access_db_utils",+ "crates/entity_mutation",+ "crates/filter_ast",+ "crates/frecency",+ "crates/genai_telemetry",+ "crates/harness_id",+ "crates/harness_token",+ "crates/invite_email",+ "crates/item_filters",+ "crates/kafka_util",+ "crates/last_online_tracker",+ "crates/macro_auth",+ "crates/macro_authorization",+ "crates/macro_entrypoint",+ "crates/macro_env",+ "crates/macro_env_var",+ "crates/macro_event_broker",+ "crates/macro_event_topics",+ "crates/macro_service_urls",+ "crates/macro_tower_layers",+ "crates/macro_user_id",+ "crates/macro_uuid",+ "crates/mention_utils",+ "crates/model",+ "crates/model-entity",+ "crates/model-error-response",+ "crates/model_file_type",+ "crates/model_notifications",+ "crates/model_owner",+ "crates/model_user",+ "crates/models_bulk_upload",+ "crates/models_entity_access_management",+ "crates/models_pagination",+ "crates/models_permissions",+ "crates/non_empty",+ "crates/notification",+ "crates/notification_state",+ "crates/prompt",+ "crates/rate_limit",+ "crates/remote_env_var",+ "crates/share_permission_db_utils",+ "crates/sqs_worker",+ "crates/workspace-hack"+ ],"coding_agent_worker": ["crates/activity","crates/agent",diff --git a/.sqlx/query-00e72d149d1bb8d177d62d204896775d33c18e9aa25ebfe218cd6f39090e7d33.json b/.sqlx/query-00e72d149d1bb8d177d62d204896775d33c18e9aa25ebfe218cd6f39090e7d33.jsonnew file mode 100644index 0000000000..5fc883c53a--- /dev/null+++ b/.sqlx/query-00e72d149d1bb8d177d62d204896775d33c18e9aa25ebfe218cd6f39090e7d33.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT COALESCE(MAX(sequence), 0) AS \"high!\" FROM codex_journal_input WHERE agent_session_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "high!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "00e72d149d1bb8d177d62d204896775d33c18e9aa25ebfe218cd6f39090e7d33"+}diff --git a/.sqlx/query-03c1f300effe353d4fbd0edadb14d47d823a7b30fb531e515758ef72919cd9df.json b/.sqlx/query-03c1f300effe353d4fbd0edadb14d47d823a7b30fb531e515758ef72919cd9df.jsonnew file mode 100644index 0000000000..30b8a29f8c--- /dev/null+++ b/.sqlx/query-03c1f300effe353d4fbd0edadb14d47d823a7b30fb531e515758ef72919cd9df.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM agent_session WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "03c1f300effe353d4fbd0edadb14d47d823a7b30fb531e515758ef72919cd9df"+}diff --git a/.sqlx/query-27ce125b39051e2eb54a13f81e085452fa2ebcac5335aaa63ae7ea227c3e197f.json b/.sqlx/query-27ce125b39051e2eb54a13f81e085452fa2ebcac5335aaa63ae7ea227c3e197f.jsonnew file mode 100644index 0000000000..b06267dda5--- /dev/null+++ b/.sqlx/query-27ce125b39051e2eb54a13f81e085452fa2ebcac5335aaa63ae7ea227c3e197f.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT encrypted_state FROM codex_connections WHERE user_id = $1 FOR UPDATE",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "encrypted_state",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "27ce125b39051e2eb54a13f81e085452fa2ebcac5335aaa63ae7ea227c3e197f"+}diff --git a/.sqlx/query-29220fe53f53b9e4115cdfbfb8e7f33c640455ea42cba85759c8ab49f5c30559.json b/.sqlx/query-29220fe53f53b9e4115cdfbfb8e7f33c640455ea42cba85759c8ab49f5c30559.jsonnew file mode 100644index 0000000000..bd3845876f--- /dev/null+++ b/.sqlx/query-29220fe53f53b9e4115cdfbfb8e7f33c640455ea42cba85759c8ab49f5c30559.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT count(*) AS \"count!\" FROM codex_journal_input",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": []+ },+ "nullable": [+ null+ ]+ },+ "hash": "29220fe53f53b9e4115cdfbfb8e7f33c640455ea42cba85759c8ab49f5c30559"+}diff --git a/.sqlx/query-33fff12cd72c45f5eab2422f59bddd55ba85ed275f71feedd5eeda8727be9a3a.json b/.sqlx/query-33fff12cd72c45f5eab2422f59bddd55ba85ed275f71feedd5eeda8727be9a3a.jsonnew file mode 100644index 0000000000..15ba714357--- /dev/null+++ b/.sqlx/query-33fff12cd72c45f5eab2422f59bddd55ba85ed275f71feedd5eeda8727be9a3a.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE agent_session SET manager_fence = manager_fence + 1, pull_request_url = $2 WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "33fff12cd72c45f5eab2422f59bddd55ba85ed275f71feedd5eeda8727be9a3a"+}diff --git a/.sqlx/query-61e0718ff0d4d5368e872a5bcd4a61f5786fdedc80a8acfb317e85efb74c1a3e.json b/.sqlx/query-61e0718ff0d4d5368e872a5bcd4a61f5786fdedc80a8acfb317e85efb74c1a3e.jsonnew file mode 100644index 0000000000..7b5d1e14d2--- /dev/null+++ b/.sqlx/query-61e0718ff0d4d5368e872a5bcd4a61f5786fdedc80a8acfb317e85efb74c1a3e.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO agent_session (id, manager_replica_id, manager_fence) VALUES ($1, $2, 1)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "61e0718ff0d4d5368e872a5bcd4a61f5786fdedc80a8acfb317e85efb74c1a3e"+}diff --git a/.sqlx/query-7f8df32bcd378cdfce8fd1a1ae4ee44329f9729a9519f0cc6e24069978033724.json b/.sqlx/query-7f8df32bcd378cdfce8fd1a1ae4ee44329f9729a9519f0cc6e24069978033724.jsonnew file mode 100644index 0000000000..e12c519a75--- /dev/null+++ b/.sqlx/query-7f8df32bcd378cdfce8fd1a1ae4ee44329f9729a9519f0cc6e24069978033724.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM codex_journal_input WHERE agent_session_id = $1 AND sequence = 1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "7f8df32bcd378cdfce8fd1a1ae4ee44329f9729a9519f0cc6e24069978033724"+}diff --git a/.sqlx/query-8ef8ecfb0dd0d6202412eabd039fbd963dc937f7fc72174d300f3c49dd873d44.json b/.sqlx/query-8ef8ecfb0dd0d6202412eabd039fbd963dc937f7fc72174d300f3c49dd873d44.jsonnew file mode 100644index 0000000000..9aa194a2bc--- /dev/null+++ b/.sqlx/query-8ef8ecfb0dd0d6202412eabd039fbd963dc937f7fc72174d300f3c49dd873d44.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO codex_journal_input (agent_session_id, sequence, turn_id, input) VALUES ($1, $2, $3, $4)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Int8",+ "Text",+ "Jsonb"+ ]+ },+ "nullable": []+ },+ "hash": "8ef8ecfb0dd0d6202412eabd039fbd963dc937f7fc72174d300f3c49dd873d44"+}diff --git a/.sqlx/query-94d013b1e825cde114d7aaa34a70aa8df67805c659d3e694b1802064542800bf.json b/.sqlx/query-94d013b1e825cde114d7aaa34a70aa8df67805c659d3e694b1802064542800bf.jsonnew file mode 100644index 0000000000..fc0bdcea7c--- /dev/null+++ b/.sqlx/query-94d013b1e825cde114d7aaa34a70aa8df67805c659d3e694b1802064542800bf.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE agent_session SET manager_fence = 2 WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "94d013b1e825cde114d7aaa34a70aa8df67805c659d3e694b1802064542800bf"+}diff --git a/.sqlx/query-a9ce16012ad133f1e310b5899c17523c0cb9741c15e3dab5248c4550eee55f99.json b/.sqlx/query-a9ce16012ad133f1e310b5899c17523c0cb9741c15e3dab5248c4550eee55f99.jsonnew file mode 100644index 0000000000..2a180f41dd--- /dev/null+++ b/.sqlx/query-a9ce16012ad133f1e310b5899c17523c0cb9741c15e3dab5248c4550eee55f99.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO codex_cloud_sessions (agent_session_id, acp_session_id, state) VALUES ($1, $2, $3) ON CONFLICT (agent_session_id) DO UPDATE SET state = EXCLUDED.state",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Jsonb"+ ]+ },+ "nullable": []+ },+ "hash": "a9ce16012ad133f1e310b5899c17523c0cb9741c15e3dab5248c4550eee55f99"+}diff --git a/.sqlx/query-b3ed4f8be05da41404adf810e53d8bd9f7e699126809497e9f50cf3910dc767c.json b/.sqlx/query-b3ed4f8be05da41404adf810e53d8bd9f7e699126809497e9f50cf3910dc767c.jsonnew file mode 100644index 0000000000..e03632aaa9--- /dev/null+++ b/.sqlx/query-b3ed4f8be05da41404adf810e53d8bd9f7e699126809497e9f50cf3910dc767c.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT state FROM codex_cloud_sessions WHERE agent_session_id = $1 AND acp_session_id = $2",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "state",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "b3ed4f8be05da41404adf810e53d8bd9f7e699126809497e9f50cf3910dc767c"+}diff --git a/.sqlx/query-b4b0e0ef222013f018def2ae2e765469b45bb25c99324b452533dabbf4ac2952.json b/.sqlx/query-b4b0e0ef222013f018def2ae2e765469b45bb25c99324b452533dabbf4ac2952.jsonnew file mode 100644index 0000000000..33bd537f50--- /dev/null+++ b/.sqlx/query-b4b0e0ef222013f018def2ae2e765469b45bb25c99324b452533dabbf4ac2952.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "WITH created AS (INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1,$2,$2,$3) RETURNING id) INSERT INTO \"User\" (\"id\", \"email\", \"macro_user_id\") SELECT $4,$2,id FROM created",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "b4b0e0ef222013f018def2ae2e765469b45bb25c99324b452533dabbf4ac2952"+}diff --git a/.sqlx/query-b7f138394db6da7925a2e0b6eb75194f77dec2da14c3e3d82b1d38da675c937c.json b/.sqlx/query-b7f138394db6da7925a2e0b6eb75194f77dec2da14c3e3d82b1d38da675c937c.jsonnew file mode 100644index 0000000000..647bd9ebd3--- /dev/null+++ b/.sqlx/query-b7f138394db6da7925a2e0b6eb75194f77dec2da14c3e3d82b1d38da675c937c.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE codex_connections SET encrypted_state = $2, updated_at = NOW() WHERE user_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Jsonb"+ ]+ },+ "nullable": []+ },+ "hash": "b7f138394db6da7925a2e0b6eb75194f77dec2da14c3e3d82b1d38da675c937c"+}diff --git a/.sqlx/query-c098f82c4c1cd6b8abea223b73bcfd4e3248b52e3f35e63c8b665cc34eef5cb3.json b/.sqlx/query-c098f82c4c1cd6b8abea223b73bcfd4e3248b52e3f35e63c8b665cc34eef5cb3.jsonnew file mode 100644index 0000000000..8a7d12bc2c--- /dev/null+++ b/.sqlx/query-c098f82c4c1cd6b8abea223b73bcfd4e3248b52e3f35e63c8b665cc34eef5cb3.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT sequence, turn_id, input FROM codex_journal_input WHERE agent_session_id = $1 ORDER BY sequence",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "sequence",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "turn_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "input",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true,+ false+ ]+ },+ "hash": "c098f82c4c1cd6b8abea223b73bcfd4e3248b52e3f35e63c8b665cc34eef5cb3"+}diff --git a/.sqlx/query-e1341ead1be484ee3be0587914d7e0de341430b02176d966efa8af976ccdbbc7.json b/.sqlx/query-e1341ead1be484ee3be0587914d7e0de341430b02176d966efa8af976ccdbbc7.jsonnew file mode 100644index 0000000000..0a6d4630a5--- /dev/null+++ b/.sqlx/query-e1341ead1be484ee3be0587914d7e0de341430b02176d966efa8af976ccdbbc7.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT count(*) AS \"count!\" FROM codex_cloud_sessions",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": []+ },+ "nullable": [+ null+ ]+ },+ "hash": "e1341ead1be484ee3be0587914d7e0de341430b02176d966efa8af976ccdbbc7"+}diff --git a/.sqlx/query-e25f0d85e98e8ea21c4451933faf156fa75e1e320b7ec0d9c9e9d73ff09ca3e6.json b/.sqlx/query-e25f0d85e98e8ea21c4451933faf156fa75e1e320b7ec0d9c9e9d73ff09ca3e6.jsonnew file mode 100644index 0000000000..a31c06826f--- /dev/null+++ b/.sqlx/query-e25f0d85e98e8ea21c4451933faf156fa75e1e320b7ec0d9c9e9d73ff09ca3e6.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO codex_connections (user_id) VALUES ($1) ON CONFLICT (user_id) DO NOTHING",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "e25f0d85e98e8ea21c4451933faf156fa75e1e320b7ec0d9c9e9d73ff09ca3e6"+}diff --git a/Cargo.lock b/Cargo.lockindex 28740ad7cb..88b6765416 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -250,12 +250,15 @@ dependencies = ["agent_trigger","ai_usage","anyhow",+ "async-trait","axum","base64 0.22.1","bot_id","channel_sender","channels","chrono",+ "codex_cloud_agents",+ "codex_connection","cursor_api_key","cursor_cloud_agents","dashmap",@@ -294,6 +297,7 @@ dependencies = ["tracing-opentelemetry","url","utoipa",+ "uuid","workspace-hack",]@@ -321,6 +325,8 @@ dependencies = ["bot_id","bots","channels",+ "codex_cloud_agents",+ "codex_connection","connection_gateway_client","contacts","cursor_api_key",@@ -1598,6 +1604,8 @@ dependencies = ["calendar_events","channels","chrono",+ "codex_cloud_agents",+ "codex_connection","comms_db_client","connection_gateway_client","contacts",@@ -3650,6 +3658,55 @@ dependencies = ["thiserror 2.0.18",]+[[package]]+name = "codex_cloud_agents"+version = "0.1.0"+dependencies = [+ "agent-client-protocol",+ "agent_fold",+ "agent_runtime_protocol",+ "agent_session",+ "axum",+ "base64 0.22.1",+ "clap",+ "futures",+ "insta",+ "lazy-regex",+ "reqwest 0.13.4",+ "rootcause",+ "serde",+ "serde_json",+ "sqlx",+ "tempfile",+ "tokio",+ "tokio-util",+ "uuid",+ "workspace-hack",+ "zeroize",+]++[[package]]+name = "codex_connection"+version = "0.1.0"+dependencies = [+ "aes-gcm",+ "async-trait",+ "aws-sdk-kms",+ "chrono",+ "codex_cloud_agents",+ "macro_db_migrator",+ "macro_user_id",+ "rootcause",+ "serde",+ "serde_json",+ "sqlx",+ "thiserror 2.0.18",+ "tokio",+ "uuid",+ "workspace-hack",+ "zeroize",+]+[[package]]name = "coding_agent_worker"version = "0.1.0"@@ -19016,6 +19073,7 @@ dependencies = ["hyper-util","idna","indexmap 2.14.0",+ "insta","ipnet","itertools 0.13.0","lazy_static",diff --git a/Cargo.toml b/Cargo.tomlindex 9a6f537a8b..a613644b7a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -21,6 +21,8 @@ members = ["crates/client/cache-wasm","crates/client/turso-opfs","crates/coding_agent_worker",+ "crates/codex_cloud_agents",+ "crates/codex_connection","crates/collab_surface","crates/complete_graph","crates/cowlike",diff --git a/apps/web/src/features/block-agent/component/ComposeAgentSession.test.tsx b/apps/web/src/features/block-agent/component/ComposeAgentSession.test.tsxindex f4ce8c3b12..077478bb3a 100644--- a/apps/web/src/features/block-agent/component/ComposeAgentSession.test.tsx+++ b/apps/web/src/features/block-agent/component/ComposeAgentSession.test.tsx@@ -1,4 +1,10 @@+const codexAccess = vi.hoisted(() => ({ enabled: true }));+vi.mock('@core/codex/flag', () => ({+ useCodexAgentsAccess: () => () => codexAccess.enabled,+}));+import { MODEL_PRETTYNAME, Model } from '@core/component/AI/constant/model';+import { CODEX_BOT_ID } from '@core/constant/codexAgent';import { CURSOR_BOT_ID } from '@core/constant/cursorAgent';import { agentHarnessServiceClient } from '@service-agent-harness/client';import type { CreateAgentSessionResponse } from '@service-agent-harness/generated/schemas';@@ -20,6 +26,17 @@ const navigation = vi.hoisted(() => ({settings: vi.fn(),navigate: vi.fn(),}));+const codexConnection = vi.hoisted(() => ({+ connected: false,+ environmentId: null as string | null,+}));+vi.mock('@queries/auth/codex', () => ({+ useCodexStatusQuery: () => ({+ isSuccess: true,+ isPlaceholderData: false,+ data: codexConnection,+ }),+}));const cursorConnection = vi.hoisted(() => ({registered: true,isPlaceholderData: false,@@ -117,6 +134,16 @@ vi.mock('@queries/agents/agents', () => ({harness: 'in-memory',default_model: 'anthropic/claude-sonnet-5',},+ {+ bot: {+ id: 'codex-reviewer',+ name: 'Codex Reviewer',+ handle: 'codex-reviewer',+ has_agent: true,+ },+ harness: 'codex-cloud',+ default_model: '',+ },{bot: { id: 'local', name: 'Local', handle: 'local', has_agent: true },harness: 'macrod',@@ -219,6 +246,9 @@ const failure = err([let client: QueryClient;beforeEach(() => {+ codexAccess.enabled = true;+ codexConnection.connected = false;+ codexConnection.environmentId = null;cursorConnection.registered = true;cursorConnection.isPlaceholderData = false;cmd.held = false;@@ -252,6 +282,69 @@ function enterPrompt() {}describe('agent session creation', () => {+ it('hides built-in and saved Codex personas when the rollout is disabled', () => {+ codexAccess.enabled = false;+ codexConnection.connected = true;+ codexConnection.environmentId = 'env-saved';+ mount();+ expect(screen.queryByText('Codex')).toBeNull();+ expect(screen.queryByText('Codex Reviewer')).toBeNull();+ expect(screen.queryByRole('button', { name: /Set up Codex/ })).toBeNull();+ });++ it('opens setup for a custom Codex persona without creating a session', () => {+ mount();+ fireEvent.click(+ screen.getByRole('button', { name: 'Set up Codex Reviewer' })+ );+ expect(navigation.settings).toHaveBeenCalledWith('Harness');+ expect(agentHarnessServiceClient.create).not.toHaveBeenCalled();+ });++ it('opens Codex setup when disconnected', () => {+ mount();+ fireEvent.click(screen.getByRole('button', { name: 'Set up Codex' }));+ expect(navigation.settings).toHaveBeenCalledWith('Harness');+ expect(agentHarnessServiceClient.create).not.toHaveBeenCalled();+ });++ it.each([null, '', ' '])(+ 'requires a saved environment when connected with %s',+ (environmentId) => {+ codexConnection.connected = true;+ codexConnection.environmentId = environmentId;+ mount();+ expect(+ screen.queryByRole('radio', { name: /^Codex @codex$/ })+ ).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Set up Codex' }));+ expect(navigation.settings).toHaveBeenCalledWith('Harness');+ expect(agentHarnessServiceClient.create).not.toHaveBeenCalled();+ fireEvent.click(+ screen.getByRole('button', { name: 'Set up Codex Reviewer' })+ );+ expect(agentHarnessServiceClient.create).not.toHaveBeenCalled();+ }+ );++ it.each(['environment-1'])(+ 'starts connected Codex with environment %s without a model override',+ async (environmentId) => {+ codexConnection.connected = true;+ codexConnection.environmentId = environmentId;+ mount();+ fireEvent.click(screen.getByRole('radio', { name: /^Codex @codex$/ }));+ expect(+ screen.queryByRole('button', { name: 'Model override' })+ ).toBeNull();+ hotkeys.enter();+ await waitFor(() =>+ expect(agentHarnessServiceClient.create).toHaveBeenCalledWith({+ botId: CODEX_BOT_ID,+ })+ );+ }+ );it('autofocuses the prompt when the composer opens', async () => {mount();const prompt = screen.getByRole('textbox', { name: 'Task for the agent' });diff --git a/apps/web/src/features/block-agent/component/ComposeAgentSession.tsx b/apps/web/src/features/block-agent/component/ComposeAgentSession.tsxindex b72edfde99..6fdf7f28dd 100644--- a/apps/web/src/features/block-agent/component/ComposeAgentSession.tsx+++ b/apps/web/src/features/block-agent/component/ComposeAgentSession.tsx@@ -3,8 +3,14 @@ import {useCanAutofocusSplitContent,useSplitPanelOrThrow,} from '@components/app/split-layout/layoutUtils';+import { useCodexAgentsAccess } from '@core/codex/flag';import { MODEL_PRETTYNAME, Model } from '@core/component/AI/constant/model';import { toast } from '@core/component/Toast/Toast';+import {+ CODEX_BOT_HANDLE,+ CODEX_BOT_ID,+ CODEX_BOT_NAME,+} from '@core/constant/codexAgent';import {CURSOR_BOT_HANDLE,CURSOR_BOT_ID,@@ -30,6 +36,7 @@ import {} from '@queries/agent-session/mutations';import { useAgentsQuery } from '@queries/agents/agents';import { useAgentModelsQuery } from '@queries/agents/models';+import { useCodexStatusQuery } from '@queries/auth/codex';import {useCursorApiKeyStatusQuery,useCursorModelsQuery,@@ -99,6 +106,13 @@ function ComposeAgentSessionContent(props: ComposeAgentSessionProps) {const navigate = useNavigate();const agentsQuery = useAgentsQuery();const cursorStatus = useCursorApiKeyStatusQuery();+ const canUseCodex = useCodexAgentsAccess();+ const codexStatus = useCodexStatusQuery(canUseCodex);+ const codexReady = () =>+ canUseCodex() &&+ codexStatus.isSuccess &&+ codexStatus.data.connected &&+ !!codexStatus.data.environmentId?.trim();const cursorConnected = () =>cursorStatus.isSuccess ? cursorStatus.data.registered : false;const cursorNeedsConnection = () =>@@ -134,52 +148,83 @@ function ComposeAgentSessionContent(props: ComposeAgentSessionProps) {// First-party agents lead, then saved personas the caller can start —// their own, team-shared, and selected-channel personas they can `@`.- const personas = createMemo<PersonaOption[]>(() => [- {- id: MACRO_PERSONA_ID,- name: MACRO_AGENT_NAME,- handle: MACRO_AGENT_HANDLE,- harness: 'in-memory',- defaultModel: macroDefaults.isSuccess- ? (macroDefaults.data.currentModel ?? undefined)- : undefined,- },- {- id: CURSOR_BOT_ID,- botId: CURSOR_BOT_ID,- name: CURSOR_BOT_NAME,- handle: CURSOR_BOT_HANDLE,- harness: 'cursor',- defaultModel: cursorStatus.isSuccess- ? (cursorStatus.data.defaultModelId ??- (cursorDefaults.isSuccess- ? (cursorDefaults.data.currentModel ?? undefined)- : undefined))- : undefined,- unavailableReason: cursorConnected()- ? undefined- : 'Connect Cursor in Settings → Harness',- connectLabel: cursorNeedsConnection() ? 'Connect Cursor' : undefined,- },- ...(agentsQuery.isSuccess ? agentsQuery.data : [])- // Only runtimes Macro provisions can be started from here; a persona on- // a registered macrod daemon opens its own sessions.- .filter((agent) => isManagedHarness(agent.harness))- .map((agent) => ({- id: agent.bot.id,- botId: agent.bot.id,- name: agent.bot.name,- handle: agent.bot.handle,- description: agent.bot.description ?? undefined,- avatarUrl: agent.bot.avatar_url ?? undefined,- harness: agent.harness,- defaultModel: agent.default_model,- ownerId:- agent.bot.owner?.type === 'user'- ? agent.bot.owner.user_id- : (agent.bot.created_by ?? undefined),- })),- ]);+ const personas = createMemo<PersonaOption[]>(() =>+ (+ [+ {+ id: MACRO_PERSONA_ID,+ name: MACRO_AGENT_NAME,+ handle: MACRO_AGENT_HANDLE,+ harness: 'in-memory',+ defaultModel: macroDefaults.isSuccess+ ? (macroDefaults.data.currentModel ?? undefined)+ : undefined,+ },+ {+ id: CURSOR_BOT_ID,+ botId: CURSOR_BOT_ID,+ name: CURSOR_BOT_NAME,+ handle: CURSOR_BOT_HANDLE,+ harness: 'cursor',+ defaultModel: cursorStatus.isSuccess+ ? (cursorStatus.data.defaultModelId ??+ (cursorDefaults.isSuccess+ ? (cursorDefaults.data.currentModel ?? undefined)+ : undefined))+ : undefined,+ unavailableReason: cursorConnected()+ ? undefined+ : 'Connect Cursor in Settings → Harness',+ connectLabel: cursorNeedsConnection() ? 'Connect Cursor' : undefined,+ },+ {+ id: CODEX_BOT_ID,+ botId: CODEX_BOT_ID,+ name: CODEX_BOT_NAME,+ handle: CODEX_BOT_HANDLE,+ harness: 'codex-cloud',+ unavailableReason: codexReady()+ ? undefined+ : 'Connect ChatGPT, then choose and save an environment in Settings → Harness',+ connectLabel:+ codexStatus.isSuccess &&+ !codexStatus.isPlaceholderData &&+ !codexReady()+ ? 'Set up Codex'+ : undefined,+ },+ ...(agentsQuery.isSuccess ? agentsQuery.data : [])+ // Only runtimes Macro provisions can be started from here; a persona on+ // a registered macrod daemon opens its own sessions.+ .filter((agent) => isManagedHarness(agent.harness))+ .map((agent) => ({+ id: agent.bot.id,+ botId: agent.bot.id,+ name: agent.bot.name,+ handle: agent.bot.handle,+ description: agent.bot.description ?? undefined,+ avatarUrl: agent.bot.avatar_url ?? undefined,+ harness: agent.harness,+ unavailableReason:+ agent.harness === 'codex-cloud' && !codexReady()+ ? 'Connect ChatGPT, then choose and save an environment in Settings → Harness'+ : undefined,+ connectLabel:+ agent.harness === 'codex-cloud' &&+ codexStatus.isSuccess &&+ !codexStatus.isPlaceholderData &&+ !codexReady()+ ? `Set up ${agent.bot.name}`+ : undefined,+ defaultModel: agent.default_model,+ ownerId:+ agent.bot.owner?.type === 'user'+ ? agent.bot.owner.user_id+ : (agent.bot.created_by ?? undefined),+ })),+ ] satisfies PersonaOption[]+ ).filter((persona) => persona.harness !== 'codex-cloud' || canUseCodex())+ );const selectedPersona = () =>personas().find((persona) => persona.id === personaId()) ?? personas()[0];const runtimeDescription = () => {@@ -192,6 +237,7 @@ function ComposeAgentSessionContent(props: ComposeAgentSessionProps) {);};const availableModels = (): ModelOption[] => {+ if (selectedPersona()?.harness === 'codex-cloud') return [];if (selectedPersona()?.harness === 'cursor') {return cursorModels.isSuccess? cursorModels.data.models.map((model) => ({@@ -206,6 +252,7 @@ function ComposeAgentSessionContent(props: ComposeAgentSessionProps) {const modelShortlist = () =>shortlistModelOptions(selectedPersona(), availableModels());const modelsForPersona = (persona: PersonaOption): ModelOption[] => {+ if (persona.harness === 'codex-cloud') return [];const defaults =persona.harness === 'cursor' ? cursorDefaults : macroDefaults;const models =@@ -234,7 +281,7 @@ function ComposeAgentSessionContent(props: ComposeAgentSessionProps) {const connectPersona = (id: string) => {if (submitting() || sessionId()) return;const persona = personas().find((item) => item.id === id);- if (persona?.harness !== 'cursor' || !persona.connectLabel) return;+ if (!persona?.connectLabel) return;close();openSettings('Harness');};@@ -448,20 +495,22 @@ function ComposeAgentSessionContent(props: ComposeAgentSessionProps) {<div class="mt-auto flex shrink-0 items-center justify-between gap-2 px-4 pt-1 pb-3"><div class="m-px flex min-h-7 min-w-0 flex-wrap items-center gap-2 text-sm">- <Suspense>- <ModelPicker- persona={selectedPersona()}- available={modelsForPersona(selectedPersona())}- shortlist={modelShortlist()}- value={modelOverride()}- loading={- selectedPersona()?.harness === 'cursor' &&- cursorModels.isPending- }- disabled={submitting() || !!sessionId()}- onSelect={setModelOverride}- />- </Suspense>+ <Show when={selectedPersona()?.harness !== 'codex-cloud'}>+ <Suspense>+ <ModelPicker+ persona={selectedPersona()}+ available={modelsForPersona(selectedPersona())}+ shortlist={modelShortlist()}+ value={modelOverride()}+ loading={+ selectedPersona()?.harness === 'cursor' &&+ cursorModels.isPending+ }+ disabled={submitting() || !!sessionId()}+ onSelect={setModelOverride}+ />+ </Suspense>+ </Show></div><SessionStartTogglediff --git a/apps/web/src/features/block-agent/component/compose-agent-session-options.ts b/apps/web/src/features/block-agent/component/compose-agent-session-options.tsindex aedd916f5e..a0d7290668 100644--- a/apps/web/src/features/block-agent/component/compose-agent-session-options.ts+++ b/apps/web/src/features/block-agent/component/compose-agent-session-options.ts@@ -39,7 +39,10 @@ export const MAX_FEATURED_MODELS = 5;*/export function isManagedHarness(harness: string): boolean {return (- harness === 'in-memory' || harness === 'macro-inmem' || harness === 'cursor'+ harness === 'in-memory' ||+ harness === 'macro-inmem' ||+ harness === 'cursor' ||+ harness === 'codex-cloud');}@@ -73,6 +76,8 @@ export function agentRuntimeDescription(if (persona.harness === 'cursor') {return 'Bring in Cursor for some heavier coding work';}+ if (persona.harness === 'codex-cloud')+ return 'Runs in your selected Codex cloud environment';if (persona.harness === 'macrod') {return `Do work locally using ${persona.name}${ownerName ? ` owned by ${ownerName}` : ''}`;}@@ -91,6 +96,8 @@ export function harnessDisplayName(harness: string): string {return 'Macro';case 'cursor':return 'Cursor';+ case 'codex-cloud':+ return 'Codex';default:return harness;}diff --git a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx b/apps/web/src/features/block-agent/context/AgentSessionContext.tsxindex aec4228a43..ef63bbc245 100644--- a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx+++ b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx@@ -1,3 +1,4 @@+import { isCodexBotId } from '@core/constant/codexAgent';/*** Block-level state for the agent block, following the chat block's* `ChatInputProvider`/`useChatInputContext` convention: the provider owns the@@ -187,7 +188,7 @@ export function AgentSessionProvider(The poll component gates on `isSuccess` so it should not suspend;this boundary is the backstop if a read of `query.data` ever does. */}<Suspense fallback={null}>- <CursorExternalUrlPoll+ <CloudExternalUrlPollsessionId={sessionId}session={feed.session}applySnapshot={feed.applySnapshot}@@ -228,7 +229,7 @@ export function AgentSessionProvider(* the feed's snapshot. Lives in its own Suspense so the rest of the block* stays mounted while this query's first fetch is in flight.*/-function CursorExternalUrlPoll(props: {+function CloudExternalUrlPoll(props: {sessionId: Accessor<string | undefined>;session: Accessor<AgentSessionResponse | undefined>;applySnapshot: (session: AgentSessionResponse) => void;@@ -239,7 +240,9 @@ function CursorExternalUrlPoll(props: {const id = props.sessionId();const session = props.session();if (!id || !session || session.external?.url) return undefined;- return isCursorBotId(session.botId) ? id : undefined;+ return isCursorBotId(session.botId) || isCodexBotId(session.botId)+ ? id+ : undefined;});createEffect(() => {// `query.data` suspends while pending and throws once it errorsdiff --git a/apps/web/src/features/channel/Input/ChannelInput.tsx b/apps/web/src/features/channel/Input/ChannelInput.tsxindex d05920c3e6..7f4b246961 100644--- a/apps/web/src/features/channel/Input/ChannelInput.tsx+++ b/apps/web/src/features/channel/Input/ChannelInput.tsx@@ -1,3 +1,4 @@+import { useCodexAgentsAccess } from '@core/codex/flag';import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { DragInsertIndicator } from '@core/component/LexicalMarkdown/component/misc/DragInsertIndicator';@@ -11,6 +12,7 @@ import {insertDocumentMentionAtDragCoordinates,updateDragInsertPreviewFromCoordinates,} from '@core/component/LexicalMarkdown/utils/dragInsertUtils';+import { isCodexBotId } from '@core/constant/codexAgent';import { isCursorBotId } from '@core/constant/cursorAgent';import {enableChatV3Agents,@@ -28,6 +30,7 @@ import {uploadFile,} from '@core/util/upload';import type { EntityData } from '@entity';+import { useCodexStatusQuery } from '@queries/auth/codex';import { useCursorApiKeyStatusQuery } from '@queries/auth/cursor-api-key';import { CollapsedInput, ComposerSurface } from '@ui';import { $getRoot } from 'lexical';@@ -40,6 +43,7 @@ import {Switch,} from 'solid-js';import {+ codexMentionUser,cursorMentionUser,isMacroAiId,isMacroCoderId,@@ -268,6 +272,8 @@ export function ChannelInput(props: ChannelInputProps) {const canUseCursor = useCursorAgentsAccess();const cursorApiKey = useCursorApiKeyStatusQuery();+ const canUseCodex = useCodexAgentsAccess();+ const codexStatus = useCodexStatusQuery(canUseCodex);// Macro AI and Macro Coder (flag-gated) are mentionable in every channel,// and any bot added to the channel is mentionable too. All are surfaced@@ -276,10 +282,19 @@ export function ChannelInput(props: ChannelInputProps) {const mentionUsers: Accessor<IUser[]> = () => {const cursorEnabled =canUseCursor() && (cursorApiKey.data?.registered ?? false);+ const codexEnabled =+ canUseCodex() &&+ codexStatus.isSuccess &&+ codexStatus.data.connected &&+ !!codexStatus.data.environmentId?.trim();const base = [...(props.participants?.() ?? []),...(props.bots?.() ?? []),- ].filter((user) => cursorEnabled || !isCursorBotId(user.id));+ ].filter(+ (user) =>+ (cursorEnabled || !isCursorBotId(user.id)) &&+ (codexEnabled || !isCodexBotId(user.id))+ );if (isFeatureEnabled(enableChatV3Agents) &&!base.some((user) => isMacroCoderId(user.id))@@ -300,6 +315,9 @@ export function ChannelInput(props: ChannelInputProps) {) {base.unshift(cursorMentionUser());}+ if (codexEnabled && !base.some((user) => isCodexBotId(user.id))) {+ base.unshift(codexMentionUser());+ }if (!base.some((user) => isMacroAiId(user.id))) {base.unshift(macroAiMentionUser());}diff --git a/apps/web/src/features/channel/Input/tests/input-slots.test.tsx b/apps/web/src/features/channel/Input/tests/input-slots.test.tsxindex 835daa8108..893d2073da 100644--- a/apps/web/src/features/channel/Input/tests/input-slots.test.tsx+++ b/apps/web/src/features/channel/Input/tests/input-slots.test.tsx@@ -40,6 +40,10 @@ vi.mock('@core/cursor/flag', () => ({useCursorAgentsAccess: () => () => true,}));+vi.mock('@core/codex/flag', () => ({+ useCodexAgentsAccess: () => () => false,+}));+// Several service clients in StaticMarkdown's import graph build websocket// connections at module scope, which jsdom cannot do. Stub the builder so// every module-scope socket is inert.diff --git a/apps/web/src/features/channel/Input/tests/task-mode.test.tsx b/apps/web/src/features/channel/Input/tests/task-mode.test.tsxindex 3b364a75d2..fde5436b44 100644--- a/apps/web/src/features/channel/Input/tests/task-mode.test.tsx+++ b/apps/web/src/features/channel/Input/tests/task-mode.test.tsx@@ -33,6 +33,10 @@ vi.mock('@core/cursor/flag', () => ({useCursorAgentsAccess: () => () => true,}));+vi.mock('@core/codex/flag', () => ({+ useCodexAgentsAccess: () => () => false,+}));+// Several service clients in StaticMarkdown's import graph build websocket// connections at module scope, which jsdom cannot do. Stub the builder so// every module-scope socket is inert.diff --git a/apps/web/src/features/channel/macroAi.ts b/apps/web/src/features/channel/macroAi.tsindex d57725e839..44a807bb97 100644--- a/apps/web/src/features/channel/macroAi.ts+++ b/apps/web/src/features/channel/macroAi.ts@@ -1,3 +1,7 @@+import {+ CODEX_BOT_NAME,+ CODEX_BOT_PRINCIPAL_ID,+} from '@core/constant/codexAgent';import {CURSOR_BOT_NAME,CURSOR_BOT_PRINCIPAL_ID,@@ -81,3 +85,12 @@ export function cursorMentionUser(): IUser {email: CURSOR_BOT_NAME,};}++/** Codex as a bot mention, using the canonical principal identifier. */+export function codexMentionUser(): IUser {+ return {+ id: CODEX_BOT_PRINCIPAL_ID,+ name: CODEX_BOT_NAME,+ email: CODEX_BOT_NAME,+ };+}diff --git a/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts b/apps/web/src/features/channel/use-channel-bot-mention-users.test.tsindex 3fa4af7bfd..11775770c6 100644--- a/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts+++ b/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts@@ -1,7 +1,39 @@+const codexAccess = vi.hoisted(() => ({ enabled: true }));+vi.mock('@core/codex/flag', () => ({+ useCodexAgentsAccess: () => () => codexAccess.enabled,+}));+import type { Agent } from '@service-storage/generated/schemas/agent';import type { Bot } from '@service-storage/generated/schemas/bot';-import { describe, expect, it } from 'vitest';-import { availableBotMentionUsers } from './use-channel-bot-mention-users';+import { createRoot } from 'solid-js';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import {+ availableBotMentionUsers,+ useChannelBotMentionUsers,+} from './use-channel-bot-mention-users';++const readiness = vi.hoisted(() => ({+ connected: true,+ environmentId: null as string | null,+}));+vi.mock('@queries/auth/codex', () => ({+ useCodexStatusQuery: () => ({ isSuccess: true, data: readiness }),+}));+vi.mock('@queries/auth/cursor-api-key', () => ({+ useCursorApiKeyStatusQuery: () => ({+ isSuccess: true,+ data: { registered: false },+ }),+}));+vi.mock('@queries/channel/channel-bots', () => ({+ useChannelBotsQuery: () => ({ isSuccess: true, data: [] }),+}));+vi.mock('@queries/agents/agents', () => ({+ useAgentsQuery: () => ({+ isSuccess: true,+ data: [agent('codex-agent', 'Codex', 'all', 'codex-cloud')],+ }),+}));const timestamp = '2026-08-27T12:00:00Z';@@ -36,6 +68,49 @@ function agent(}describe('availableBotMentionUsers', () => {+ beforeEach(() => {+ codexAccess.enabled = true;+ });+ it('hides connected Codex agents when the rollout is disabled', () => {+ codexAccess.enabled = false;+ readiness.environmentId = 'env-saved';+ createRoot((dispose) => {+ expect(useChannelBotMentionUsers(() => 'channel-1')()).toEqual([]);+ dispose();+ });+ });+ it.each([null, '', ' ', 'env-saved'])(+ 'gates the real mention query on saved environment %s',+ (environmentId) => {+ readiness.environmentId = environmentId;+ createRoot((dispose) => {+ const users = useChannelBotMentionUsers(() => 'channel-1');+ expect(users().map((user) => user.id)).toEqual(+ environmentId === 'env-saved' ? ['bot|codex-agent'] : []+ );+ dispose();+ });+ }+ );+ it('hides installed Codex personas when access is disabled', () => {+ const codex = agent('codex-agent', 'Codex', 'selected', 'codex-cloud');+ expect(+ availableBotMentionUsers(+ [codex.bot, bot('other', 'Other')],+ [codex],+ false,+ false+ ).map((user) => user.id)+ ).toEqual(['bot|other']);+ expect(+ availableBotMentionUsers([codex.bot], [codex], false, true)+ ).toHaveLength(1);+ });+ it('only offers Codex agents after connection and environment readiness', () => {+ const codex = agent('codex-agent', 'Codex', 'all', 'codex-cloud');+ expect(availableBotMentionUsers([], [codex], false, false)).toEqual([]);+ expect(availableBotMentionUsers([], [codex], false, true)).toHaveLength(1);+ });it('adds all-channel agents without adding selected agents from other channels', () => {expect(availableBotMentionUsers(diff --git a/apps/web/src/features/channel/use-channel-bot-mention-users.ts b/apps/web/src/features/channel/use-channel-bot-mention-users.tsindex 9d358c4c79..94bd634821 100644--- a/apps/web/src/features/channel/use-channel-bot-mention-users.ts+++ b/apps/web/src/features/channel/use-channel-bot-mention-users.ts@@ -1,5 +1,8 @@+import { useCodexAgentsAccess } from '@core/codex/flag';+import { isCodexBotId } from '@core/constant/codexAgent';import type { IUser } from '@core/user/types';import { useAgentsQuery } from '@queries/agents/agents';+import { useCodexStatusQuery } from '@queries/auth/codex';import { useCursorApiKeyStatusQuery } from '@queries/auth/cursor-api-key';import { useChannelBotsQuery } from '@queries/channel/channel-bots';import type { Agent } from '@service-storage/generated/schemas/agent';@@ -19,17 +22,29 @@ function mentionUser(bot: Bot): IUser {export function availableBotMentionUsers(channelBots: readonly Bot[],agents: readonly Agent[],- cursorConnected: boolean+ cursorConnected: boolean,+ codexConnected = false): IUser[] {const globalAgents = agents.filter((agent) =>agent.channel_scope === 'all' &&agent.bot.has_agent &&- (agent.harness !== 'cursor' || cursorConnected)+ (agent.harness !== 'cursor' || cursorConnected) &&+ (agent.harness !== 'codex-cloud' || codexConnected)+ );+ const codexBotIds = new Set(+ agents+ .filter((agent) => agent.harness === 'codex-cloud')+ .map((agent) => agent.bot.id));const seen = new Set<string>();return [...channelBots, ...globalAgents.map((agent) => agent.bot)]+ .filter(+ (bot) =>+ codexConnected ||+ (!isCodexBotId(`bot|${bot.id}`) && !codexBotIds.has(bot.id))+ ).map(mentionUser).filter((user) => {if (seen.has(user.id)) return false;@@ -51,12 +66,18 @@ export function useChannelBotMentionUsers(const channelBots = useChannelBotsQuery(channelId);const agents = useAgentsQuery();const cursorStatus = useCursorApiKeyStatusQuery();+ const canUseCodex = useCodexAgentsAccess();+ const codexStatus = useCodexStatusQuery(canUseCodex);return createMemo(() =>availableBotMentionUsers(- channelBots.data ?? [],- agents.data ?? [],- cursorStatus.data?.registered ?? false+ channelBots.isSuccess ? channelBots.data : [],+ agents.isSuccess ? agents.data : [],+ cursorStatus.isSuccess ? cursorStatus.data.registered : false,+ canUseCodex() &&+ codexStatus.isSuccess &&+ codexStatus.data.connected &&+ !!codexStatus.data.environmentId?.trim()));}diff --git a/apps/web/src/features/settings/Harness.test.tsx b/apps/web/src/features/settings/Harness.test.tsxindex 4fbd6d08f2..f03246a396 100644--- a/apps/web/src/features/settings/Harness.test.tsx+++ b/apps/web/src/features/settings/Harness.test.tsx@@ -1,3 +1,8 @@+const codexAccess = vi.hoisted(() => ({ enabled: true }));+vi.mock('@core/codex/flag', () => ({+ useCodexAgentsAccess: () => () => codexAccess.enabled,+}));+/*** @vitest-environment jsdom*/@@ -20,6 +25,10 @@ import { Suspense } from 'solid-js';import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { Harness } from './Harness';+vi.mock('./codex/views/CodexHarness', () => ({+ CodexHarness: () => <div data-testid="codex-harness" />,+}));+const mocks = vi.hoisted(() => ({status: {isSuccess: true,@@ -157,6 +166,7 @@ beforeAll(() => {});beforeEach(() => {+ codexAccess.enabled = true;vi.clearAllMocks();mocks.status.data = {registered: false,@@ -183,6 +193,15 @@ beforeEach(() => {});describe('Harness', () => {+ it.each([false, true])(+ 'gates Codex settings on rollout access %s',+ (enabled) => {+ codexAccess.enabled = enabled;+ render(() => <Harness />);+ expect(screen.queryByTestId('codex-harness') !== null).toBe(enabled);+ }+ );+it.each(['success', 'error'] as const)('keeps settings visible while Cursor models load and after %s',async (outcome) => {diff --git a/apps/web/src/features/settings/Harness.tsx b/apps/web/src/features/settings/Harness.tsxindex 7420c5758f..045b5b9c82 100644--- a/apps/web/src/features/settings/Harness.tsx+++ b/apps/web/src/features/settings/Harness.tsx@@ -1,3 +1,4 @@+import { useCodexAgentsAccess } from '@core/codex/flag';import { ModelCatalogPicker } from '@core/component/AI/component/input/ModelCatalogPicker';import { isLargeModelCatalog } from '@core/component/AI/component/input/modelCatalog';import { toast } from '@core/component/Toast/Toast';@@ -20,9 +21,10 @@ import {import type { Harness as RegisteredHarness } from '@service-storage/client';import { useSearchParams } from '@solidjs/router';import { Button, Dialog, Panel } from '@ui';-import { createSignal, For, type JSX, onMount, Show } from 'solid-js';+import { createSignal, For, onMount, Show } from 'solid-js';+import { CodexHarness } from './codex/views/CodexHarness';import { HarnessPairingDialog } from './HarnessPairingDialog';-import { ConnectAction, StatusDot } from './integration-ui';+import { ConnectAction, HarnessIcon, StatusDot } from './integration-ui';import { SettingsCard, SettingsPage } from './primitives';const BYOA_DOCS_URL = 'https://docs.macro.com/AI/bring-your-own';@@ -40,6 +42,7 @@ function lastConnectedText(harness: RegisteredHarness): string {/** Settings UI for choosing and configuring the available agent harnesses. */export function Harness() {+ const canUseCodex = useCodexAgentsAccess();const [cursorApiKey, setCursorApiKey] = createSignal('');const cursorStatus = useCursorApiKeyStatusQuery();const saveCursorApiKey = useSaveCursorApiKey();@@ -359,6 +362,10 @@ export function Harness() {</div></section>+ <Show when={canUseCodex()}>+ <CodexHarness />+ </Show>+<section class="flex gap-4 px-6 py-5"><HarnessIcon><TerminalWindowIcon />@@ -534,11 +541,3 @@ function HarnessRemoveDialog(props: {</Dialog>);}--function HarnessIcon(props: { children: JSX.Element }) {- return (- <div class="flex size-9 shrink-0 items-center justify-center rounded-lg bg-ink/4 text-ink-muted [&_svg]:size-5">- {props.children}- </div>- );-}diff --git a/apps/web/src/features/settings/codex/components/CodexConnection.test.tsx b/apps/web/src/features/settings/codex/components/CodexConnection.test.tsxnew file mode 100644index 0000000000..0afe46b28d--- /dev/null+++ b/apps/web/src/features/settings/codex/components/CodexConnection.test.tsx@@ -0,0 +1,239 @@+import { fireEvent, render, screen } from '@solidjs/testing-library';+import { createSignal } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';+import { CodexConnection } from './CodexConnection';++vi.mock('@ui', () => ({+ Button: (+ props: import('solid-js').JSX.ButtonHTMLAttributes<HTMLButtonElement>+ ) => <button {...props} />,+}));+const base = () => ({+ connection: undefined,+ login: undefined,+ environments: [],+ environmentsLoading: false,+ environmentsError: false,+ loading: false,+ pending: false,+ error: undefined,+ onConnect: vi.fn(),+ onCancel: vi.fn(),+ onDisconnect: vi.fn(),+ onRetryEnvironments: vi.fn(),+ onSave: vi.fn(),+});+const login = {+ userCode: 'ABCD-EFGH',+ verificationUrl: 'https://auth.openai.com/codex/device',+ expiresAt: '2026-09-16T12:00:00Z',+};++describe('Codex connection', () => {+ it('identifies a connection by account when email is unavailable', () => {+ render(() => (+ <CodexConnection+ {...base()}+ connection={{+ connected: true,+ email: null,+ accountId: 'example-account',+ environmentId: null,+ }}+ />+ ));+ expect(screen.getByText('example-account')).toBeTruthy();+ expect(screen.getByRole('link', { name: 'Open Codex' })).toBeTruthy();+ });++ it('cannot save without selecting an environment when environment loading fails', () => {+ const props = base();+ render(() => (+ <CodexConnection+ {...props}+ connection={{+ connected: true,+ environmentId: 'env-old',+ }}+ environmentsError+ />+ ));+ fireEvent.change(screen.getByLabelText('Cloud environment'), {+ target: { value: '' },+ });+ expect(screen.queryByLabelText('Branch')).toBeNull();+ expect(screen.getByRole('alert').textContent).toBe(+ 'Could not load environments.'+ );+ fireEvent.click(+ screen.getByRole('button', { name: 'Save Codex settings' })+ );+ expect(props.onSave).not.toHaveBeenCalled();+ expect(+ screen+ .getByRole('button', { name: 'Save Codex settings' })+ .hasAttribute('disabled')+ ).toBe(true);+ });++ it('requires an environment and offers no automatic or branch selection', () => {+ render(() => (+ <CodexConnection+ {...base()}+ connection={{ connected: true, environmentId: null }}+ environmentsLoading+ />+ ));+ expect(screen.getByRole('status').textContent).toBe(+ 'Loading environments…'+ );+ expect(screen.queryByLabelText('Branch')).toBeNull();+ expect(+ screen.getByRole('option', { name: 'Choose an environment' })+ ).toBeTruthy();+ });++ it('starts device sign-in without requesting a token', () => {+ const props = base();+ render(() => <CodexConnection {...props} />);+ fireEvent.click(+ screen.getByRole('button', { name: 'Connect with ChatGPT' })+ );+ expect(props.onConnect).toHaveBeenCalledOnce();+ expect(screen.queryByRole('textbox')).toBeNull();+ });+ it('shows the code, official link and cancel while waiting', () => {+ const props = base();+ render(() => (+ <CodexConnection {...props} login={{ ...login, status: 'pending' }} />+ ));+ expect(screen.getByText('ABCD-EFGH')).toBeTruthy();+ expect(+ screen+ .getByRole('link', { name: 'Continue to ChatGPT' })+ .getAttribute('href')+ ).toBe(login.verificationUrl);+ fireEvent.click(screen.getByRole('button', { name: 'Cancel sign-in' }));+ expect(props.onCancel).toHaveBeenCalledOnce();+ });+ it.each(['expired', 'failed'] as const)(+ 'allows a fresh login after %s',+ (status) => {+ render(() => (+ <CodexConnection {...base()} login={{ ...login, status }} />+ ));+ expect(+ screen.getByRole('button', { name: 'Connect with ChatGPT' })+ ).toBeTruthy();+ expect(+ screen.queryByRole('link', { name: 'Continue to ChatGPT' })+ ).toBeNull();+ }+ );+ it('saves only the selected environment and always describes the main branch', () => {+ const props = base();+ render(() => (+ <CodexConnection+ {...props}+ connection={{+ connected: true,+ email: null,+ environmentId: null,+ }}+ environments={[+ {+ id: 'env-1',+ label: 'Example repo',+ repositories: [+ {+ fullName: 'example/repo',+ cloneUrl: 'https://github.com/example/repo.git',+ defaultBranch: 'develop',+ },+ ],+ },+ ]}+ />+ ));+ expect(+ screen+ .getByRole('button', { name: 'Save Codex settings' })+ .hasAttribute('disabled')+ ).toBe(true);+ expect(screen.queryByLabelText('Branch')).toBeNull();+ fireEvent.change(screen.getByLabelText('Cloud environment'), {+ target: { value: 'env-1' },+ });+ expect(screen.queryByLabelText('Branch')).toBeNull();+ expect(+ screen.getByText(/New sessions always start from the main branch/)+ ).toBeTruthy();+ fireEvent.click(+ screen.getByRole('button', { name: 'Save Codex settings' })+ );+ expect(props.onSave).toHaveBeenCalledWith({+ environmentId: 'env-1',+ });+ fireEvent.click(screen.getByRole('button', { name: 'Disconnect ChatGPT' }));+ expect(props.onDisconnect).toHaveBeenCalledOnce();+ });+ it('keeps server errors visible and prevents duplicate pending actions', () => {+ render(() => (+ <CodexConnection {...base()} error="Could not start sign-in" pending />+ ));+ expect(screen.getByRole('alert').textContent).toBe(+ 'Could not start sign-in'+ );+ expect(+ screen+ .getByRole('button', { name: 'Connect with ChatGPT' })+ .hasAttribute('disabled')+ ).toBe(true);+ });++ it('marks selections unsaved until the server confirms them and preserves failed edits', () => {+ const props = base();+ const [connection, setConnection] = createSignal({+ connected: true,+ environmentId: null as string | null,+ });+ const [error, setError] = createSignal<string>();+ render(() => (+ <CodexConnection+ {...props}+ connection={connection()}+ error={error()}+ environments={[+ {+ id: 'env-1',+ repositories: [+ {+ fullName: 'example/repo',+ cloneUrl: 'https://github.com/example/repo.git',+ defaultBranch: 'main',+ },+ ],+ },+ ]}+ />+ ));+ const save = screen.getByRole('button', { name: 'Save Codex settings' });+ expect(save.hasAttribute('disabled')).toBe(true);+ fireEvent.change(screen.getByLabelText('Cloud environment'), {+ target: { value: 'env-1' },+ });+ expect(screen.getByRole('status').textContent).toContain('Unsaved changes');+ expect(save.hasAttribute('disabled')).toBe(false);+ fireEvent.click(save);+ setError('Could not save Codex settings.');+ expect(screen.getByRole('status').textContent).toContain('Unsaved changes');+ expect(save.hasAttribute('disabled')).toBe(false);+ expect(+ (screen.getByLabelText('Cloud environment') as HTMLSelectElement).value+ ).toBe('env-1');+ setError(undefined);+ setConnection({ connected: true, environmentId: 'env-1' });+ expect(screen.queryByRole('status')).toBeNull();+ expect(save.hasAttribute('disabled')).toBe(true);+ });+});diff --git a/apps/web/src/features/settings/codex/components/CodexConnection.tsx b/apps/web/src/features/settings/codex/components/CodexConnection.tsxnew file mode 100644index 0000000000..a2ed528c08--- /dev/null+++ b/apps/web/src/features/settings/codex/components/CodexConnection.tsx@@ -0,0 +1,283 @@+import OpenAiIcon from '@core/component/AI/assets/openai.svg';+import ArrowUpRightIcon from '@phosphor/arrow-up-right.svg';+import { Button } from '@ui';+import { createSignal, For, Show } from 'solid-js';+import { HarnessIcon } from '../../integration-ui';+import type { CodexConnectionDisplay, CodexLoginDisplay } from '../core/types';++export function CodexConnection(props: {+ connection: CodexConnectionDisplay | undefined;+ login: CodexLoginDisplay | undefined;+ environments: {+ id: string;+ label?: string | null;+ repositories: {+ fullName: string;+ cloneUrl: string;+ defaultBranch: string;+ }[];+ }[];+ environmentsLoading: boolean;+ environmentsError: boolean;+ loading: boolean;+ pending: boolean;+ error: string | undefined;+ onConnect: () => void;+ onCancel: () => void;+ onDisconnect: () => void;+ onRetryEnvironments: () => void;+ onSave: (config: { environmentId: string }) => void;+}) {+ const [environment, setEnvironment] = createSignal<string>();+ const selectedEnvironment = () =>+ environment() ?? props.connection?.environmentId ?? '';+ const hasChanges = () =>+ selectedEnvironment() !== (props.connection?.environmentId ?? '');+ const connected = () => props.connection?.connected === true;+ const loginPending = () => props.login?.status === 'pending';+ return (+ <section class="flex gap-4 px-6 py-5" aria-label="Codex connection">+ <HarnessIcon>+ <OpenAiIcon />+ </HarnessIcon>+ <div class="min-w-0 flex-1">+ <div class="flex items-center gap-2">+ <h2 class="text-sm font-medium text-ink">Codex</h2>+ <Show when={connected()}>+ <span class="rounded-full bg-success-bg px-2 py-0.5 text-[11px] font-medium text-success">+ Connected+ </span>+ </Show>+ </div>+ <p class="mt-1 text-sm text-ink-muted">+ Use your ChatGPT account to run Codex cloud sessions in Macro.+ </p>+ <Show when={props.error}>+ <p role="alert" class="mt-3 text-sm text-negative">+ {props.error}+ </p>+ </Show>+ <Show+ when={!props.loading}+ fallback={+ <p class="mt-4 text-xs text-ink-muted">Loading Codex connection…</p>+ }+ >+ <Show+ when={connected()}+ fallback={+ <div class="mt-4 flex flex-col items-start gap-3">+ <Show+ when={loginPending()}+ fallback={+ <>+ <Show when={props.login?.status === 'expired'}>+ <p role="status" class="text-sm text-ink-muted">+ This sign-in code expired. Start again to get a new+ code.+ </p>+ </Show>+ <Show when={props.login?.status === 'failed'}>+ <p role="alert" class="text-sm text-negative">+ ChatGPT sign-in failed. Please try again.+ </p>+ </Show>+ <Button+ type="button"+ variant="outline"+ size="sm"+ depth={3}+ class="gap-2"+ disabled={props.pending}+ onClick={props.onConnect}+ >+ <OpenAiIcon class="size-4" aria-hidden="true" />+ Connect with ChatGPT+ </Button>+ <p class="text-xs text-ink-extra-muted">+ You'll finish sign-in on ChatGPT.+ </p>+ </>+ }+ >+ <p class="text-sm text-ink">+ Open ChatGPT and enter this code to connect your account.+ </p>+ <code class="ph-no-capture select-all rounded-md border border-edge-muted bg-input px-4 py-2.5 text-lg font-medium tracking-widest text-ink">+ {props.login?.userCode}+ </code>+ <a+ class="inline-flex items-center gap-1 text-sm text-ink-muted hover:text-ink"+ href={props.login?.verificationUrl}+ target="_blank"+ rel="noopener noreferrer"+ >+ Continue to ChatGPT+ <ArrowUpRightIcon class="size-3.5" aria-hidden="true" />+ </a>+ <p role="status" class="text-xs text-ink-muted">+ Waiting for sign-in… Code expires{' '}+ {props.login+ ? new Date(props.login.expiresAt).toLocaleTimeString()+ : ''}+ .+ </p>+ <Button+ type="button"+ variant="outline"+ size="sm"+ depth={3}+ disabled={props.pending}+ onClick={props.onCancel}+ >+ Cancel sign-in+ </Button>+ </Show>+ </div>+ }+ >+ <Show when={props.connection?.email ?? props.connection?.accountId}>+ <p class="mt-1 text-xs text-ink-extra-muted break-all">+ {props.connection?.email ?? props.connection?.accountId}+ </p>+ </Show>+ <div class="mt-4 flex flex-col gap-3">+ <label+ class="flex flex-col gap-1.5 text-xs text-ink"+ for="codex-environment"+ >+ Cloud environment+ <select+ id="codex-environment"+ class="settings-input w-full max-w-sm"+ value={selectedEnvironment()}+ disabled={props.environmentsLoading || props.pending}+ onChange={(event) => {+ setEnvironment(event.currentTarget.value);+ }}+ >+ <option value="" disabled selected={!selectedEnvironment()}>+ Choose an environment+ </option>+ <For each={props.environments}>+ {(item) => (+ <option+ value={item.id}+ selected={selectedEnvironment() === item.id}+ >+ {item.label ?? item.id}+ {item.repositories.length+ ? ` — ${item.repositories.map((repo) => repo.fullName).join(', ')}`+ : ''}+ </option>+ )}+ </For>+ </select>+ </label>+ <p class="text-xs text-ink-extra-muted">+ Choose and save an environment before using @codex. New sessions+ always start from the main branch.+ </p>+ <Show when={props.environmentsLoading}>+ <p role="status" class="text-xs text-ink-muted">+ Loading environments…+ </p>+ </Show>+ <Show when={props.environmentsError}>+ <div class="flex items-center gap-2">+ <p role="alert" class="text-sm text-negative">+ Could not load environments.+ </p>+ <a+ href="https://chatgpt.com/codex"+ target="_blank"+ rel="noopener noreferrer"+ class="text-sm text-accent underline"+ >+ Open Codex+ </a>+ <Button+ size="sm"+ variant="outline"+ onClick={props.onRetryEnvironments}+ >+ Retry environments+ </Button>+ </div>+ </Show>+ <Show+ when={+ !props.environmentsLoading &&+ !props.environmentsError &&+ props.environments.length === 0+ }+ >+ <p class="text-xs text-ink-extra-muted">+ Create a cloud environment in Codex, then retry.+ <a+ href="https://chatgpt.com/codex"+ target="_blank"+ rel="noopener noreferrer"+ class="ml-1 text-accent underline"+ >+ Open Codex+ </a>+ </p>+ <Button+ size="sm"+ variant="outline"+ onClick={props.onRetryEnvironments}+ >+ Retry environments+ </Button>+ </Show>+ <Show when={hasChanges()}>+ <p role="status" class="text-xs text-ink-muted">+ Unsaved changes. Save before starting a new @codex session.+ </p>+ </Show>+ <div class="flex gap-2">+ <Button+ type="button"+ variant="outline"+ size="sm"+ depth={3}+ disabled={+ props.pending || !hasChanges() || !selectedEnvironment()+ }+ onClick={() =>+ props.onSave({+ environmentId: selectedEnvironment(),+ })+ }+ >+ Save Codex settings+ </Button>+ </div>+ </div>+ <div class="mt-4 flex flex-wrap items-center justify-between gap-3">+ <p class="flex-1 basis-56 text-xs text-ink-extra-muted">+ Existing cloud sessions keep running after disconnecting.+ </p>+ <Button+ type="button"+ variant="danger"+ size="sm"+ depth={3}+ class="shrink-0"+ aria-label="Disconnect ChatGPT"+ disabled={props.pending}+ onClick={() => {+ setEnvironment(undefined);+ props.onDisconnect();+ }}+ >+ Disconnect+ </Button>+ </div>+ </Show>+ </Show>+ </div>+ </section>+ );+}diff --git a/apps/web/src/features/settings/codex/core/types.ts b/apps/web/src/features/settings/codex/core/types.tsnew file mode 100644index 0000000000..f6c9497605--- /dev/null+++ b/apps/web/src/features/settings/codex/core/types.ts@@ -0,0 +1,12 @@+export type CodexLoginDisplay = {+ userCode: string;+ verificationUrl: string;+ expiresAt: string;+ status: 'pending' | 'connected' | 'expired' | 'failed';+};+export type CodexConnectionDisplay = {+ connected: boolean;+ email?: string | null;+ accountId?: string | null;+ environmentId?: string | null;+};diff --git a/apps/web/src/features/settings/codex/views/CodexHarness.tsx b/apps/web/src/features/settings/codex/views/CodexHarness.tsxnew file mode 100644index 0000000000..bdfffedb41--- /dev/null+++ b/apps/web/src/features/settings/codex/views/CodexHarness.tsx@@ -0,0 +1,124 @@+import { toast } from '@core/component/Toast/Toast';+import {+ useBeginCodexLogin,+ useCancelCodexLogin,+ useCodexEnvironmentsQuery,+ useCodexLoginQuery,+ useCodexStatusQuery,+ useConfigureCodex,+ useDisconnectCodex,+} from '@queries/auth/codex';+import { createSignal, Show, Suspense } from 'solid-js';+import { CodexConnection } from '../components/CodexConnection';++export function CodexHarness() {+ return (+ <Suspense>+ <CodexHarnessContent />+ </Suspense>+ );+}+function CodexHarnessContent() {+ const connection = useCodexStatusQuery();+ const begin = useBeginCodexLogin();+ const cancel = useCancelCodexLogin();+ const disconnect = useDisconnectCodex();+ const configure = useConfigureCodex();+ const [attempt, setAttempt] =+ createSignal<Awaited<ReturnType<typeof begin.mutateAsync>>>();+ const [error, setError] = createSignal<string>();+ const status = useCodexLoginQuery(attempt);+ const connected = () => connection.isSuccess && connection.data.connected;+ const environments = useCodexEnvironmentsQuery(connected);+ const startLogin = async () => {+ setError(undefined);+ try {+ setAttempt(await begin.mutateAsync());+ } catch {+ setError('Could not start ChatGPT sign-in. Please try again.');+ }+ };+ const cancelLogin = async () => {+ const current = attempt();+ if (!current) return;+ setError(undefined);+ try {+ await cancel.mutateAsync(current.attemptId);+ setAttempt(undefined);+ } catch {+ setError('Could not cancel sign-in. Please try again.');+ }+ };+ const disconnectAccount = async () => {+ setError(undefined);+ try {+ await disconnect.mutateAsync();+ setAttempt(undefined);+ toast.success('ChatGPT disconnected');+ } catch {+ setError('Could not disconnect ChatGPT. Please try again.');+ }+ };+ const save = async (config: { environmentId: string }) => {+ setError(undefined);+ try {+ await configure.mutateAsync(config);+ toast.success('Codex settings saved');+ } catch {+ setError(+ 'Could not save Codex settings. Check the environment, then retry.'+ );+ }+ };+ return (+ <Show+ when={+ connection.isSuccess && connection.data.connected+ ? (connection.data.accountId ?? 'connected')+ : 'disconnected'+ }+ keyed+ >+ {(_account) => (+ <CodexConnection+ connection={+ connection.isSuccess && !connection.isPlaceholderData+ ? connection.data+ : undefined+ }+ loading={connection.isPending || connection.isPlaceholderData}+ login={+ attempt()+ ? {+ ...attempt()!,+ status: status.isSuccess ? status.data.status : 'pending',+ }+ : undefined+ }+ environments={environments.isSuccess ? environments.data : []}+ environmentsLoading={environments.isPending}+ environmentsError={environments.isError}+ pending={+ begin.isPending ||+ cancel.isPending ||+ disconnect.isPending ||+ configure.isPending+ }+ error={+ error() ??+ (connection.isError+ ? 'Could not load your Codex connection. Refresh to retry.'+ : status.isError+ ? 'Could not check sign-in. Cancel and try again.'+ : undefined)+ }+ onConnect={() => void startLogin()}+ onCancel={() => void cancelLogin()}+ onDisconnect={() => void disconnectAccount()}+ onRetryEnvironments={() => void environments.refetch()}+ onSave={(config) => void save(config)}+ />+ )}+ </Show>+ );+}diff --git a/apps/web/src/features/settings/integration-ui.tsx b/apps/web/src/features/settings/integration-ui.tsxindex 735d5761a1..7c580a9bec 100644--- a/apps/web/src/features/settings/integration-ui.tsx+++ b/apps/web/src/features/settings/integration-ui.tsx@@ -1,7 +1,18 @@import ArrowUpRightIcon from '@phosphor/arrow-up-right.svg';import SpinnerIcon from '@phosphor/spinner-gap.svg';import { cn } from '@ui';-import { Show } from 'solid-js';+import { type JSX, Show } from 'solid-js';++export function HarnessIcon(props: { children: JSX.Element }) {+ return (+ <div+ aria-hidden="true"+ class="flex size-9 shrink-0 items-center justify-center rounded-lg bg-ink/4 text-ink-muted [&_svg]:size-5"+ >+ {props.children}+ </div>+ );+}/** Shared bits for the Connected accounts integration cards: the trailingdiff --git a/apps/web/src/lib/core/codex/flag.test.ts b/apps/web/src/lib/core/codex/flag.test.tsnew file mode 100644index 0000000000..0c241df488--- /dev/null+++ b/apps/web/src/lib/core/codex/flag.test.ts@@ -0,0 +1,38 @@+import { createRoot, createSignal } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';+import { useCodexAgentsAccess } from './flag';++const flags = vi.hoisted(() => ({+ agents: (): boolean => false,+ codex: (): boolean => false,+}));+vi.mock('@core/constant/featureFlags', () => ({+ enableChatV3Agents: { key: 'enable-chat-v3-agents' },+ enableCodexAgents: { key: 'enable-codex-agents' },+}));+vi.mock('@app/lib/analytics/posthog', () => ({+ useFeatureFlag: (flag: { key: string }) => () => ({+ enabled:+ flag.key === 'enable-chat-v3-agents' ? flags.agents() : flags.codex(),+ }),+}));++describe('Codex access', () => {+ it('requires both rollouts and responds to flag changes', () => {+ createRoot((dispose) => {+ const [agents, setAgents] = createSignal(false);+ const [codex, setCodex] = createSignal(false);+ flags.agents = agents;+ flags.codex = codex;+ const access = useCodexAgentsAccess();+ expect(access()).toBe(false);+ setCodex(true);+ expect(access()).toBe(false);+ setAgents(true);+ expect(access()).toBe(true);+ setCodex(false);+ expect(access()).toBe(false);+ dispose();+ });+ });+});diff --git a/apps/web/src/lib/core/codex/flag.ts b/apps/web/src/lib/core/codex/flag.tsnew file mode 100644index 0000000000..b77cd16358--- /dev/null+++ b/apps/web/src/lib/core/codex/flag.ts@@ -0,0 +1,13 @@+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import {+ enableChatV3Agents,+ enableCodexAgents,+} from '@core/constant/featureFlags';+import type { Accessor } from 'solid-js';++/** Codex surfaces require both the agent rollout and the Codex rollout. */+export function useCodexAgentsAccess(): Accessor<boolean> {+ const agents = useFeatureFlag(enableChatV3Agents);+ const codex = useFeatureFlag(enableCodexAgents);+ return () => agents().enabled && codex().enabled;+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.tsxindex aa4cd4d8e1..a9a1661a57 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipPullRequest.tsx@@ -11,9 +11,8 @@ import { type Component, createMemo, Show } from 'solid-js';/*** The pull request a session opened, in the chip's header: our GitHub PR* entity once the webhook has synced it, a plain link to GitHub until then.- * Cursor reports the url the moment the PR exists, which is usually a few- * seconds before the entity does; connection gateway supplies the saved entity- * and subsequent status changes.+ * Cloud runtimes can report the URL before the GitHub webhook entity exists.+ * Connection gateway supplies the saved entity and subsequent status changes.*/export const MagicChipPullRequest: Component<{ url: string }> = (props) => {const reference = createMemo(() => parseGithubPrUrl(props.url));diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsxindex bf8fe5cbaa..36922cf668 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx@@ -177,24 +177,27 @@ describe('MagicChipView', () => {expect(label?.textContent).toContain('Thinking');});- it('places the pull request in the header once the session opened one', () => {- const { container } = render(() => (- <MagicChipView- agentSessionId="session-1"- presentation={{ kind: 'settled', markdown: 'Opened a PR.' }}- header={{- agent: 'Cursor Agent',- pullRequestUrl: 'https://github.com/macro-inc/macro/pull/6303',- }}- />- ));- const link = header(container)?.querySelector(- '[data-testid="chip-pull-request"]'- );- expect(link?.getAttribute('href')).toBe(- 'https://github.com/macro-inc/macro/pull/6303'- );- });+ it.each(['Cursor Agent', 'Codex Agent'])(+ 'places the pull request in the %s header once the session opened one',+ (agent) => {+ const { container } = render(() => (+ <MagicChipView+ agentSessionId="session-1"+ presentation={{ kind: 'settled', markdown: 'Opened a PR.' }}+ header={{+ agent,+ pullRequestUrl: 'https://github.com/macro-inc/macro/pull/6303',+ }}+ />+ ));+ const link = header(container)?.querySelector(+ '[data-testid="chip-pull-request"]'+ );+ expect(link?.getAttribute('href')).toBe(+ 'https://github.com/macro-inc/macro/pull/6303'+ );+ }+ );it('keeps the same answer height once the answer streams in', () => {const { container } = render(() => (diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.tsindex ce04671a9d..89eaa07e3c 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts@@ -128,61 +128,71 @@ describe('createMagicChipModel', () => {serviceClient.control.mockResolvedValue({ isErr: () => false });});- it('reloads the session PR on gateway updates and reconnect without folding it', async () => {- const snapshot = (pullRequestUrl: string | null) => ({- isOk: () => true,- isErr: () => false,- value: {- status: { kind: 'disconnected' },- harness: 'cursor',- model: '',- canEdit: true,- pullRequestUrl,- },- });- const first = 'https://github.com/org/repo/pull/1';- const second = 'https://github.com/org/repo/pull/2';- serviceClient.get.mockResolvedValue(snapshot(null));- let model!: ReturnType<typeof createMagicChipModel>;- let sibling!: ReturnType<typeof createMagicChipModel>;- const dispose = createRoot((dispose) => {- model = createModel(props);- sibling = createModel(props);- return dispose;- });- await settle();- expect(model.header()?.pullRequestUrl).toBeUndefined();- expect(serviceClient.get).toHaveBeenCalledTimes(1);-- let resolveStale!: (value: ReturnType<typeof snapshot>) => void;- serviceClient.get.mockReturnValueOnce(- new Promise((resolve) => {- resolveStale = resolve;- })- );- void handleAgentSessionUpdated({ agentSessionId: 'session' });- await settle();- serviceClient.get.mockResolvedValue(snapshot(first));- await handleAgentSessionUpdated({ agentSessionId: 'session' });- await settle();- expect(model.header()?.pullRequestUrl).toBe(first);- resolveStale(snapshot(null));- await settle();- expect(model.header()?.pullRequestUrl).toBe(first);-- sessionFold.acquireAgentSessionFold.mock.calls[0]![0].onReplace([]);- expect(model.header()?.pullRequestUrl).toBe(first);- serviceClient.get.mockResolvedValue(snapshot(second));- await invalidateAgentSessionMetadata();- await settle();- expect(model.header()?.pullRequestUrl).toBe(second);- expect(sibling.header()?.pullRequestUrl).toBe(second);- dispose();- const calls = serviceClient.get.mock.calls.length;- await handleAgentSessionUpdated({ agentSessionId: 'session' });- await invalidateAgentSessionMetadata();- expect(serviceClient.get).toHaveBeenCalledTimes(calls);- });+ it.each(['cursor', 'codex-cloud'])(+ 'reloads the completed %s session PR on gateway updates and reconnect without folding it',+ async (harness) => {+ const snapshot = (pullRequestUrl: string | null) => ({+ isOk: () => true,+ isErr: () => false,+ value: {+ status: { kind: 'disconnected' },+ harness,+ model: '',+ canEdit: true,+ pullRequestUrl,+ },+ });+ const first = 'https://github.com/org/repo/pull/1';+ const second = 'https://github.com/org/repo/pull/2';+ serviceClient.get.mockResolvedValue(snapshot(null));+ let model!: ReturnType<typeof createMagicChipModel>;+ let sibling!: ReturnType<typeof createMagicChipModel>;+ const dispose = createRoot((dispose) => {+ model = createModel(props);+ sibling = createModel(props);+ return dispose;+ });+ await settle();+ expect(model.header()?.pullRequestUrl).toBeUndefined();+ expect(serviceClient.get).toHaveBeenCalledTimes(1);++ let resolveStale!: (value: ReturnType<typeof snapshot>) => void;+ serviceClient.get.mockReturnValueOnce(+ new Promise((resolve) => {+ resolveStale = resolve;+ })+ );+ void handleAgentSessionUpdated({ agentSessionId: 'session' });+ await settle();+ serviceClient.get.mockResolvedValue(snapshot(first));+ await handleAgentSessionUpdated({ agentSessionId: 'session' });+ await settle();+ expect(model.header()?.pullRequestUrl).toBe(first);+ expect(model.header()?.agent).toBe(+ harness === 'codex-cloud' ? 'Codex Agent' : 'Cursor Agent'+ );+ await handleAgentSessionUpdated({ agentSessionId: 'session' });+ await settle();+ expect(model.header()?.pullRequestUrl).toBe(first);+ expect(sibling.header()?.pullRequestUrl).toBe(first);+ resolveStale(snapshot(null));+ await settle();+ expect(model.header()?.pullRequestUrl).toBe(first);++ sessionFold.acquireAgentSessionFold.mock.calls[0]![0].onReplace([]);+ expect(model.header()?.pullRequestUrl).toBe(first);+ serviceClient.get.mockResolvedValue(snapshot(second));+ await invalidateAgentSessionMetadata();+ await settle();+ expect(model.header()?.pullRequestUrl).toBe(second);+ expect(sibling.header()?.pullRequestUrl).toBe(second);+ dispose();+ const calls = serviceClient.get.mock.calls.length;+ await handleAgentSessionUpdated({ agentSessionId: 'session' });+ await invalidateAgentSessionMetadata();+ expect(serviceClient.get).toHaveBeenCalledTimes(calls);+ }+ );it('restarts an initial pending snapshot when registration arrives', async () => {const snapshot = (pullRequestUrl: string | null) => ({diff --git a/apps/web/src/lib/core/constant/codexAgent.ts b/apps/web/src/lib/core/constant/codexAgent.tsnew file mode 100644index 0000000000..9d33cb302b--- /dev/null+++ b/apps/web/src/lib/core/constant/codexAgent.ts@@ -0,0 +1,8 @@+/** First-party Codex identity, matching the backend bot_id registry. */+export const CODEX_BOT_ID = '00000000-0000-0000-0000-00000000c0de';+export const CODEX_BOT_PRINCIPAL_ID = `bot|${CODEX_BOT_ID}`;+export const CODEX_BOT_NAME = 'Codex';+export const CODEX_BOT_HANDLE = 'codex';+export function isCodexBotId(id: string): boolean {+ return id === CODEX_BOT_ID || id === CODEX_BOT_PRINCIPAL_ID;+}diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex a0dc422f19..d14b46ed7a 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -675,6 +675,13 @@ export const enableCursorAgents = defineFlag({default: onInDev,});+// Codex cloud agent mentions, composer choices, and harness settings also+// require enableChatV3Agents. Override with VITE_ENABLE_CODEX_AGENTS.+export const enableCodexAgents = defineFlag({+ key: 'enable-codex-agents',+ env: 'ENABLE_CODEX_AGENTS',+});+// The Recent view: the touched-by-me feed (everything the viewer mutated,// newest own-touch first). Gates the view (the route redirects to the inbox// when off) and its sidebar entry. PostHog-gated with a dev-mode default;diff --git a/apps/web/src/lib/queries/auth/codex.ts b/apps/web/src/lib/queries/auth/codex.tsnew file mode 100644index 0000000000..97a76197f2--- /dev/null+++ b/apps/web/src/lib/queries/auth/codex.ts@@ -0,0 +1,80 @@+import { throwOnErr } from '@core/util/result';+import { queryClient } from '@queries/client';+import {+ type CodexConfig,+ type CodexLogin,+ codexClient,+} from '@service-auth/codex';+import { useMutation, useQuery } from '@tanstack/solid-query';+import { authKeys } from './keys';++const invalidateConnection = async () => {+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: authKeys.codexStatus.queryKey }),+ queryClient.invalidateQueries({+ queryKey: authKeys.codexEnvironments.queryKey,+ }),+ ]);+};+export function useCodexStatusQuery(enabled: () => boolean = () => true) {+ return useQuery(() => ({+ queryKey: authKeys.codexStatus.queryKey,+ enabled: enabled(),+ queryFn: () => throwOnErr(codexClient.status),+ placeholderData: {+ connected: false,+ email: null,+ accountId: null,+ environmentId: null,+ },+ }));+}+export function useCodexLoginQuery(attempt: () => CodexLogin | undefined) {+ return useQuery(() => ({+ queryKey: authKeys.codexLogin(attempt()?.attemptId ?? '').queryKey,+ enabled: !!attempt(),+ queryFn: async () => {+ const login = attempt();+ if (!login) throw new Error('No active Codex login');+ const result = await throwOnErr(() => codexClient.poll(login.attemptId));+ if (result.status === 'connected') await invalidateConnection();+ return result;+ },+ retry: false,+ refetchInterval: (query) =>+ query.state.data && query.state.data.status !== 'pending'+ ? false+ : Math.max(1, attempt()?.pollIntervalSeconds ?? 5) * 1000,+ refetchIntervalInBackground: true,+ }));+}+export function useCodexEnvironmentsQuery(enabled: () => boolean) {+ return useQuery(() => ({+ queryKey: authKeys.codexEnvironments.queryKey,+ enabled: enabled(),+ queryFn: () => throwOnErr(codexClient.environments),+ }));+}+export function useBeginCodexLogin() {+ return useMutation(() => ({+ mutationFn: () => throwOnErr(codexClient.login),+ }));+}+export function useCancelCodexLogin() {+ return useMutation(() => ({+ mutationFn: (id: string) => throwOnErr(() => codexClient.cancel(id)),+ }));+}+export function useDisconnectCodex() {+ return useMutation(() => ({+ mutationFn: () => throwOnErr(codexClient.disconnect),+ onSuccess: invalidateConnection,+ }));+}+export function useConfigureCodex() {+ return useMutation(() => ({+ mutationFn: (config: CodexConfig) =>+ throwOnErr(() => codexClient.configure(config)),+ onSuccess: invalidateConnection,+ }));+}diff --git a/apps/web/src/lib/queries/auth/keys.ts b/apps/web/src/lib/queries/auth/keys.tsindex 55658c78d2..64ac727974 100644--- a/apps/web/src/lib/queries/auth/keys.ts+++ b/apps/web/src/lib/queries/auth/keys.ts@@ -1,6 +1,9 @@import { createQueryKeys } from '@lukemorales/query-key-factory';export const authKeys = createQueryKeys('auth', {+ codexStatus: null,+ codexEnvironments: null,+ codexLogin: (attemptId: string) => ({ queryKey: [attemptId] }),cursorApiKeyStatus: null,cursorModels: null,githubLinkStatus: null,diff --git a/apps/web/src/lib/queries/bots/first-party-bot-name.ts b/apps/web/src/lib/queries/bots/first-party-bot-name.tsindex ecf9cd8748..f5252206af 100644--- a/apps/web/src/lib/queries/bots/first-party-bot-name.ts+++ b/apps/web/src/lib/queries/bots/first-party-bot-name.ts@@ -1,3 +1,4 @@+import { CODEX_BOT_NAME, isCodexBotId } from '@core/constant/codexAgent';import { CURSOR_BOT_NAME, isCursorBotId } from '@core/constant/cursorAgent';import { isMacroAgentId, MACRO_AGENT_NAME } from '@core/constant/macroAgent';import { isMacroCoderId, MACRO_CODER_NAME } from '@core/constant/macroCoder';@@ -12,6 +13,7 @@ export function firstPartyBotName(id: string): string | undefined {if (isMacroAgentId(id)) return MACRO_AGENT_NAME;if (isMacroCoderId(id)) return MACRO_CODER_NAME;if (isMacroNewId(id)) return MACRO_NEW_NAME;+ if (isCodexBotId(id)) return CODEX_BOT_NAME;if (isCursorBotId(id)) return CURSOR_BOT_NAME;if (isMacroSystemId(id)) return MACRO_SYSTEM_NAME;return undefined;diff --git a/apps/web/src/lib/service-clients/service-auth/codex.ts b/apps/web/src/lib/service-clients/service-auth/codex.tsnew file mode 100644index 0000000000..cc1b3e9735--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/codex.ts@@ -0,0 +1,39 @@+import { SERVER_HOSTS } from '@core/constant/servers';+import { fetchWithToken } from '@core/util/fetchWithToken';++import type {+ CodexConfigRequest,+ CodexConnectionStatus,+ CodexEnvironment,+ CodexLoginPoll,+ CodexLoginStart,+} from './generated/schemas';++export type {+ CodexConfigRequest as CodexConfig,+ CodexLoginStart as CodexLogin,+} from './generated/schemas';++const base = `${SERVER_HOSTS['auth-service']}/codex`;++/** The browser only receives device-flow display data; OAuth tokens stay server-side. */+export const codexClient = {+ status: () => fetchWithToken<CodexConnectionStatus>(base),+ login: () =>+ fetchWithToken<CodexLoginStart>(`${base}/login`, { method: 'POST' }),+ poll: (id: string) =>+ fetchWithToken<CodexLoginPoll>(`${base}/login/${encodeURIComponent(id)}`),+ cancel: (id: string) =>+ fetchWithToken(`${base}/login/${encodeURIComponent(id)}`, {+ method: 'DELETE',+ }),+ disconnect: () => fetchWithToken(base, { method: 'DELETE' }),+ environments: () =>+ fetchWithToken<CodexEnvironment[]>(`${base}/environments`),+ configure: (config: CodexConfigRequest) =>+ fetchWithToken<CodexConnectionStatus>(`${base}/config`, {+ method: 'PUT',+ body: JSON.stringify(config),+ headers: { 'Content-Type': 'application/json' },+ }),+};diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.tsindex d8ccf80f0c..d25cc65550 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts@@ -6,6 +6,11 @@*/import type {AppleLoginRequest,+ CodexConfigRequest,+ CodexConnectionStatus,+ CodexEnvironment,+ CodexLoginPoll,+ CodexLoginStart,CreateAccountMergeRequest,CreateCheckoutSessionV2Request,CreateInProgressLinkResponse,@@ -73,6 +78,247 @@ import type {UserTokensResponse,} from './schemas';+export type getCodexConnectionResponse200 = {+ data: CodexConnectionStatus;+ status: 200;+};++export type getCodexConnectionResponseSuccess =+ getCodexConnectionResponse200 & {+ headers: Headers;+ };++export type getCodexConnectionResponse = getCodexConnectionResponseSuccess;++export const getGetCodexConnectionUrl = () => {+ return `/codex`;+};++export const getCodexConnection = async (+ options?: RequestInit+): Promise<getCodexConnectionResponse> => {+ const res = await fetch(getGetCodexConnectionUrl(), {+ ...options,+ method: 'GET',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: getCodexConnectionResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as getCodexConnectionResponse;+};++export type disconnectCodexResponse204 = {+ data: void;+ status: 204;+};++export type disconnectCodexResponseSuccess = disconnectCodexResponse204 & {+ headers: Headers;+};++export type disconnectCodexResponse = disconnectCodexResponseSuccess;++export const getDisconnectCodexUrl = () => {+ return `/codex`;+};++export const disconnectCodex = async (+ options?: RequestInit+): Promise<disconnectCodexResponse> => {+ const res = await fetch(getDisconnectCodexUrl(), {+ ...options,+ method: 'DELETE',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: disconnectCodexResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as disconnectCodexResponse;+};++export type configureCodexResponse200 = {+ data: CodexConnectionStatus;+ status: 200;+};++export type configureCodexResponseSuccess = configureCodexResponse200 & {+ headers: Headers;+};++export type configureCodexResponse = configureCodexResponseSuccess;++export const getConfigureCodexUrl = () => {+ return `/codex/config`;+};++export const configureCodex = async (+ codexConfigRequest: CodexConfigRequest,+ options?: RequestInit+): Promise<configureCodexResponse> => {+ const res = await fetch(getConfigureCodexUrl(), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(codexConfigRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: configureCodexResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as configureCodexResponse;+};++export type listCodexEnvironmentsResponse200 = {+ data: CodexEnvironment[];+ status: 200;+};++export type listCodexEnvironmentsResponseSuccess =+ listCodexEnvironmentsResponse200 & {+ headers: Headers;+ };++export type listCodexEnvironmentsResponse =+ listCodexEnvironmentsResponseSuccess;++export const getListCodexEnvironmentsUrl = () => {+ return `/codex/environments`;+};++export const listCodexEnvironments = async (+ options?: RequestInit+): Promise<listCodexEnvironmentsResponse> => {+ const res = await fetch(getListCodexEnvironmentsUrl(), {+ ...options,+ method: 'GET',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: listCodexEnvironmentsResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as listCodexEnvironmentsResponse;+};++export type startCodexLoginResponse200 = {+ data: CodexLoginStart;+ status: 200;+};++export type startCodexLoginResponseSuccess = startCodexLoginResponse200 & {+ headers: Headers;+};++export type startCodexLoginResponse = startCodexLoginResponseSuccess;++export const getStartCodexLoginUrl = () => {+ return `/codex/login`;+};++export const startCodexLogin = async (+ options?: RequestInit+): Promise<startCodexLoginResponse> => {+ const res = await fetch(getStartCodexLoginUrl(), {+ ...options,+ method: 'POST',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: startCodexLoginResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as startCodexLoginResponse;+};++export type pollCodexLoginResponse200 = {+ data: CodexLoginPoll;+ status: 200;+};++export type pollCodexLoginResponseSuccess = pollCodexLoginResponse200 & {+ headers: Headers;+};++export type pollCodexLoginResponse = pollCodexLoginResponseSuccess;++export const getPollCodexLoginUrl = (attemptId: string) => {+ return `/codex/login/${attemptId}`;+};++export const pollCodexLogin = async (+ attemptId: string,+ options?: RequestInit+): Promise<pollCodexLoginResponse> => {+ const res = await fetch(getPollCodexLoginUrl(attemptId), {+ ...options,+ method: 'GET',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: pollCodexLoginResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as pollCodexLoginResponse;+};++export type cancelCodexLoginResponse204 = {+ data: void;+ status: 204;+};++export type cancelCodexLoginResponseSuccess = cancelCodexLoginResponse204 & {+ headers: Headers;+};++export type cancelCodexLoginResponse = cancelCodexLoginResponseSuccess;++export const getCancelCodexLoginUrl = (attemptId: string) => {+ return `/codex/login/${attemptId}`;+};++export const cancelCodexLogin = async (+ attemptId: string,+ options?: RequestInit+): Promise<cancelCodexLoginResponse> => {+ const res = await fetch(getCancelCodexLoginUrl(attemptId), {+ ...options,+ method: 'DELETE',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: cancelCodexLoginResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as cancelCodexLoginResponse;+};+/*** Never returns the key, or any part of it. There is no screen that needs one,and a masked key still leaks its length and alphabet.diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexConfigRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexConfigRequest.tsnew file mode 100644index 0000000000..abcdc52185--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexConfigRequest.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Explicit remote environment for future Codex sessions.+ */+export interface CodexConfigRequest {+ /** An environment currently visible to this account. */+ environmentId: string;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexConnectionStatus.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexConnectionStatus.tsnew file mode 100644index 0000000000..7770a1a60e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexConnectionStatus.ts@@ -0,0 +1,23 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { CodexConnectionStatusAccountId } from './codexConnectionStatusAccountId';+import type { CodexConnectionStatusEmail } from './codexConnectionStatusEmail';+import type { CodexConnectionStatusEnvironmentId } from './codexConnectionStatusEnvironmentId';++/**+ * Safe connection metadata; no secret or masked token is returned.+ */+export interface CodexConnectionStatus {+ /** Connected provider account identifier. */+ accountId?: CodexConnectionStatusAccountId;+ /** Whether the user has completed provider authorization. */+ connected: boolean;+ /** Reserved until provider-verified email metadata is available. */+ email?: CodexConnectionStatusEmail;+ /** Explicitly selected remote environment. */+ environmentId?: CodexConnectionStatusEnvironmentId;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexConnectionStatusAccountId.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexConnectionStatusAccountId.tsnew file mode 100644index 0000000000..0ed48c4aa3--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexConnectionStatusAccountId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Connected provider account identifier.+ */+export type CodexConnectionStatusAccountId = string | null;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexConnectionStatusEmail.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexConnectionStatusEmail.tsnew file mode 100644index 0000000000..1728419bce--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexConnectionStatusEmail.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Reserved until provider-verified email metadata is available.+ */+export type CodexConnectionStatusEmail = string | null;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexConnectionStatusEnvironmentId.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexConnectionStatusEnvironmentId.tsnew file mode 100644index 0000000000..f94bf79f02--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexConnectionStatusEnvironmentId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Explicitly selected remote environment.+ */+export type CodexConnectionStatusEnvironmentId = string | null;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexEnvironment.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexEnvironment.tsnew file mode 100644index 0000000000..7fc8145223--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexEnvironment.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { CodexEnvironmentLabel } from './codexEnvironmentLabel';+import type { CodexEnvironmentRepository } from './codexEnvironmentRepository';++/**+ * A cloud environment visible to the connected provider account.+ */+export interface CodexEnvironment {+ /** Provider environment identity. */+ id: string;+ /** Human-readable provider label. */+ label?: CodexEnvironmentLabel;+ /** Ordered safe repository identities from Codex. */+ repositories: CodexEnvironmentRepository[];+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexEnvironmentLabel.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexEnvironmentLabel.tsnew file mode 100644index 0000000000..8d647e3d37--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexEnvironmentLabel.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Human-readable provider label.+ */+export type CodexEnvironmentLabel = string | null;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexEnvironmentRepository.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexEnvironmentRepository.tsnew file mode 100644index 0000000000..758dbda681--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexEnvironmentRepository.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Safe repository metadata available to the connected Codex account.+ */+export interface CodexEnvironmentRepository {+ /** Credential-free HTTPS clone URL. */+ cloneUrl: string;+ /** Provider default branch. */+ defaultBranch: string;+ /** Owner/repository identity. */+ fullName: string;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexLoginPoll.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexLoginPoll.tsnew file mode 100644index 0000000000..bd1fe141e9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexLoginPoll.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { CodexLoginState } from './codexLoginState';++/**+ * Outcome of polling one attempt.+ */+export interface CodexLoginPoll {+ /** Current attempt state. */+ status: CodexLoginState;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexLoginStart.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexLoginStart.tsnew file mode 100644index 0000000000..9ad6ca2246--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexLoginStart.ts@@ -0,0 +1,25 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Expiring browser authorization instructions.+ */+export interface CodexLoginStart {+ /** Owner-bound attempt UUID. */+ attemptId: string;+ /** UTC attempt deadline. */+ expiresAt: string;+ /**+ * Minimum browser polling interval.+ * @minimum 0+ */+ pollIntervalSeconds: number;+ /** Short expiring user code, not an API credential. */+ userCode: string;+ /** Official provider verification URL. */+ verificationUrl: string;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexLoginState.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexLoginState.tsnew file mode 100644index 0000000000..e11bb1f73d--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/codexLoginState.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Device authorization state visible to its initiating user.+ */+export type CodexLoginState =+ (typeof CodexLoginState)[keyof typeof CodexLoginState];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const CodexLoginState = {+ pending: 'pending',+ connected: 'connected',+ expired: 'expired',+ failed: 'failed',+} as const;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.tsindex 7733234f6c..dfcc1cf7c8 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts@@ -11,6 +11,17 @@ export * from './checkoutSessionMetadata';export * from './checkoutSessionMetadataFbc';export * from './checkoutSessionMetadataFbp';export * from './checkoutSessionMetadataGaClientId';+export * from './codexConfigRequest';+export * from './codexConnectionStatus';+export * from './codexConnectionStatusAccountId';+export * from './codexConnectionStatusEmail';+export * from './codexConnectionStatusEnvironmentId';+export * from './codexEnvironment';+export * from './codexEnvironmentLabel';+export * from './codexEnvironmentRepository';+export * from './codexLoginPoll';+export * from './codexLoginStart';+export * from './codexLoginState';export * from './createAccountMergeRequest';export * from './createCheckoutSessionV2Request';export * from './createCheckoutSessionV2RequestDiscount';diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.jsonindex 20a615dc5d..97a7d9e24f 100644--- a/apps/web/src/lib/service-clients/service-auth/openapi.json+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json@@ -10,6 +10,149 @@"version": "0.1.0"},"paths": {+ "/codex": {+ "get": {+ "tags": ["crate::api::codex"],+ "operationId": "get_codex_connection",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodexConnectionStatus"+ }+ }+ }+ }+ }+ },+ "delete": {+ "tags": ["crate::api::codex"],+ "operationId": "disconnect_codex",+ "responses": {+ "204": {+ "description": ""+ }+ }+ }+ },+ "/codex/config": {+ "put": {+ "tags": ["crate::api::codex"],+ "operationId": "configure_codex",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodexConfigRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodexConnectionStatus"+ }+ }+ }+ }+ }+ }+ },+ "/codex/environments": {+ "get": {+ "tags": ["crate::api::codex"],+ "operationId": "list_codex_environments",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CodexEnvironment"+ }+ }+ }+ }+ }+ }+ }+ },+ "/codex/login": {+ "post": {+ "tags": ["crate::api::codex"],+ "operationId": "start_codex_login",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodexLoginStart"+ }+ }+ }+ }+ }+ }+ },+ "/codex/login/{attempt_id}": {+ "get": {+ "tags": ["crate::api::codex"],+ "operationId": "poll_codex_login",+ "parameters": [+ {+ "name": "attempt_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodexLoginPoll"+ }+ }+ }+ }+ }+ },+ "delete": {+ "tags": ["crate::api::codex"],+ "operationId": "cancel_codex_login",+ "parameters": [+ {+ "name": "attempt_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "204": {+ "description": ""+ }+ }+ }+ },"/cursor-api-key": {"get": {"tags": ["crate::api::cursor_api_key::get_cursor_api_key"],@@ -3832,6 +3975,135 @@}}},+ "CodexConfigRequest": {+ "type": "object",+ "description": "Explicit remote environment for future Codex sessions.",+ "required": ["environmentId"],+ "properties": {+ "environmentId": {+ "type": "string",+ "description": "An environment currently visible to this account."+ }+ },+ "additionalProperties": false+ },+ "CodexConnectionStatus": {+ "type": "object",+ "description": "Safe connection metadata; no secret or masked token is returned.",+ "required": ["connected"],+ "properties": {+ "accountId": {+ "type": ["string", "null"],+ "description": "Connected provider account identifier."+ },+ "connected": {+ "type": "boolean",+ "description": "Whether the user has completed provider authorization."+ },+ "email": {+ "type": ["string", "null"],+ "description": "Reserved until provider-verified email metadata is available."+ },+ "environmentId": {+ "type": ["string", "null"],+ "description": "Explicitly selected remote environment."+ }+ }+ },+ "CodexEnvironment": {+ "type": "object",+ "description": "A cloud environment visible to the connected provider account.",+ "required": ["id", "repositories"],+ "properties": {+ "id": {+ "type": "string",+ "description": "Provider environment identity."+ },+ "label": {+ "type": ["string", "null"],+ "description": "Human-readable provider label."+ },+ "repositories": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CodexEnvironmentRepository"+ },+ "description": "Ordered safe repository identities from Codex."+ }+ }+ },+ "CodexEnvironmentRepository": {+ "type": "object",+ "description": "Safe repository metadata available to the connected Codex account.",+ "required": ["fullName", "cloneUrl", "defaultBranch"],+ "properties": {+ "cloneUrl": {+ "type": "string",+ "description": "Credential-free HTTPS clone URL."+ },+ "defaultBranch": {+ "type": "string",+ "description": "Provider default branch."+ },+ "fullName": {+ "type": "string",+ "description": "Owner/repository identity."+ }+ }+ },+ "CodexLoginPoll": {+ "type": "object",+ "description": "Outcome of polling one attempt.",+ "required": ["status"],+ "properties": {+ "status": {+ "$ref": "#/components/schemas/CodexLoginState",+ "description": "Current attempt state."+ }+ }+ },+ "CodexLoginStart": {+ "type": "object",+ "description": "Expiring browser authorization instructions.",+ "required": [+ "attemptId",+ "verificationUrl",+ "userCode",+ "expiresAt",+ "pollIntervalSeconds"+ ],+ "properties": {+ "attemptId": {+ "type": "string",+ "format": "uuid",+ "description": "Owner-bound attempt UUID."+ },+ "expiresAt": {+ "type": "string",+ "format": "date-time",+ "description": "UTC attempt deadline."+ },+ "pollIntervalSeconds": {+ "type": "integer",+ "format": "int64",+ "description": "Minimum browser polling interval.",+ "minimum": 0+ },+ "userCode": {+ "type": "string",+ "description": "Short expiring user code, not an API credential."+ },+ "verificationUrl": {+ "type": "string",+ "description": "Official provider verification URL."+ }+ }+ },+ "CodexLoginState": {+ "type": "string",+ "description": "Device authorization state visible to its initiating user.",+ "enum": ["pending", "connected", "expired", "failed"]+ },"CreateAccountMergeRequest": {"type": "object","required": ["email"],diff --git a/crates/agent_harness/Cargo.toml b/crates/agent_harness/Cargo.tomlindex 1e86cc3876..ba42d0510f 100644--- a/crates/agent_harness/Cargo.toml+++ b/crates/agent_harness/Cargo.toml@@ -5,6 +5,9 @@ publish = falseversion = "0.1.0"[dependencies]+async-trait = { workspace = true }+codex_cloud_agents = { path = "../codex_cloud_agents", features = ["postgres"] }+codex_connection = { path = "../codex_connection" }agent = { path = "../agent" }agent-client-protocol = { workspace = true }# The session-token claim shape and its signing, so the harness and the proxy@@ -73,6 +76,7 @@ utoipa = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]+uuid = { workspace = true }agent_fold = { path = "../agent_fold", features = ["test-utils"] }agent_session = { path = "../agent_session", features = ["test-utils"] }bot_id = { path = "../bot_id", features = ["test-utils"] }diff --git a/crates/agent_harness/src/domain/codex.rs b/crates/agent_harness/src/domain/codex.rsnew file mode 100644index 0000000000..823f37c24b--- /dev/null+++ b/crates/agent_harness/src/domain/codex.rs@@ -0,0 +1,214 @@+//! Per-owner Codex authorization and provider mapping for hosted conversations.+use agent_session::domain::{+ model::{AgentSessionId, ExternalSession},+ ports::{AgentSessionRepo, ExternalSessionRepo},+};+use codex_cloud_agents::domain::cloud::{+ CloudConversation, CloudEventStream, CloudId, CreatedTask, Launch, TaskSnapshot, TurnId,+};+use codex_cloud_agents::domain::runtime::{CloudRuntime, CloudTarget, RuntimeIdentity};+use codex_cloud_agents::domain::{Credentials, OAuth};+use codex_connection::domain::ConnectionService;+use macro_user_id::user_id::MacroUserIdStr;+use std::sync::Arc;++fn repository_identity(value: &str) -> Result<String, rootcause::Report> {+ let parsed = url::Url::parse(value).map_err(|_| {+ rootcause::report!(+ "invalid Codex repository metadata; select an environment in Harness settings"+ )+ })?;+ if parsed.scheme() != "https"+ || parsed.host_str().is_none()+ || !parsed.username().is_empty()+ || parsed.password().is_some()+ || parsed.query().is_some()+ || parsed.fragment().is_some()+ {+ return Err(rootcause::report!(+ "invalid Codex repository metadata; select an environment in Harness settings"+ ));+ }+ let path = parsed.path().trim_end_matches('/');+ let path = path.strip_suffix(".git").unwrap_or(path);+ if parsed.host_str() == Some("github.com") {+ Ok(format!("https://github.com{}", path.to_ascii_lowercase()))+ } else {+ let mut canonical = parsed.clone();+ canonical.set_path(path);+ Ok(canonical.to_string())+ }+}++/// Provider slug persisted with Codex external session mappings.+pub const CODEX_PROVIDER: &str = "codex-cloud";+/// A cloud client bound to the session owner's original connection generation.+pub struct CodexRuntime<P, S, H = S> {+ /// Shared transport, containing no owner credentials.+ pub provider: Arc<P>,+ /// Connection lifecycle service, consulted before every provider operation.+ pub connections: Arc<dyn ConnectionService>,+ /// Session owner whose authorization pays for cloud work.+ pub owner: MacroUserIdStr<'static>,+ /// Immutable original connection/account identity.+ pub binding: RuntimeIdentity,+ /// Macro session receiving the external task mapping.+ pub session: AgentSessionId,+ /// Owning session persistence port.+ pub sessions: S,+ /// Owning session port for recording the configured repository.+ pub session_repository: H,+ /// Shared owner-authorized session PR publication service.+ pub pull_requests: Option<Arc<dyn agent_session::domain::pull_request::SessionPullRequests>>,+ /// Immutable ownership claim activated before this attachment can publish metadata.+ pub claim: Arc<std::sync::OnceLock<agent_session::domain::model::SessionClaim>>,+}+impl<P, S, H> CodexRuntime<P, S, H> {+ async fn connection(+ &self,+ ) -> Result<codex_connection::domain::ResolvedConnection, rootcause::Report> {+ let resolved = self.connections.resolve(self.owner.as_ref()).await?;+ if resolved.connection_id.to_string() != self.binding.connection_id+ || resolved.credentials.account_id != self.binding.account_id+ {+ return Err(rootcause::report!(+ "this session belongs to a previous Codex connection; start a new session after reconnecting"+ ));+ }+ Ok(resolved)+ }+ async fn credentials(&self) -> Result<Credentials, rootcause::Report> {+ Ok(self.connection().await?.credentials)+ }+}+impl<P: OAuth + CloudConversation, S: ExternalSessionRepo, H: AgentSessionRepo> CloudRuntime+ for CodexRuntime<P, S, H>+{+ async fn identity(&self) -> Result<RuntimeIdentity, rootcause::Report> {+ self.credentials().await?;+ Ok(self.binding.clone())+ }+ async fn resolve_target(+ &self,+ _: &str,+ _: Option<&CloudTarget>,+ ) -> Result<CloudTarget, rootcause::Report> {+ let resolved = self.connection().await?;+ let id = resolved.environment_id.ok_or_else(|| {+ rootcause::report!(+ "select and save a Codex environment in Harness settings before sending a prompt"+ )+ })?;+ let environments = self.provider.environments(&resolved.credentials).await?;+ let environment = environments.iter().find(|environment| environment.id == id.as_str())+ .ok_or_else(||rootcause::report!("the configured Codex environment is unavailable; select and save an environment in Harness settings"))?;+ let target = CloudTarget {+ environment: CloudId::new(environment.id.clone())?,+ branch: "main".into(),+ repository_url: environment+ .repositories+ .first()+ .map(|repository| repository_identity(&repository.clone_url))+ .transpose()?,+ };+ target.validate()?;+ // Do not pin a target after the owner disconnects or reconnects.+ self.credentials().await?;+ self.session_repository+ .set_repo_url(self.session, target.repository_url.clone())+ .await+ .map_err(|error| {+ rootcause::report!("could not record the selected Codex repository: {error}")+ })?;+ Ok(target)+ }+ async fn report_pull_request(&self, url: &str) -> Result<(), rootcause::Report> {+ self.credentials().await?;+ if let Some(service) = &self.pull_requests {+ service+ .set_pull_request(+ self.session,+ &self.owner,+ url,+ Some(+ *self.claim.get().ok_or_else(|| {+ rootcause::report!("Codex attachment is not activated")+ })?,+ ),+ )+ .await+ .map_err(|error| {+ rootcause::report!("could not publish Codex pull request: {error}")+ })?;+ }+ Ok(())+ }+ async fn launch(&self, request: &Launch) -> Result<CreatedTask, rootcause::Report> {+ request.validate()?;+ let auth = self.credentials().await?;+ if !self+ .provider+ .environments(&auth)+ .await?+ .iter()+ .any(|env| env.id == request.environment.as_str())+ {+ return Err(rootcause::report!(+ "the selected Codex environment is no longer available to this account"+ ));+ }+ let receipt = self.provider.create(&auth, request).await?;+ self.sessions+ .upsert(+ self.session,+ ExternalSession {+ provider: CODEX_PROVIDER.into(),+ external_id: receipt.task_id.as_str().into(),+ external_name: None,+ external_url: Some(receipt.url.clone()),+ last_run_id: receipt+ .assistant_turn_id+ .as_ref()+ .map(|turn| turn.as_str().into()),+ },+ )+ .await+ .map_err(|e| rootcause::report!("could not record Codex task mapping: {e}"))?;+ Ok(receipt)+ }+ async fn snapshot(&self, task: &CloudId) -> Result<TaskSnapshot, rootcause::Report> {+ self.provider+ .snapshot(&self.credentials().await?, task)+ .await+ }+ async fn follow_up(+ &self,+ task: &CloudId,+ turn: &TurnId,+ prompt: &str,+ ) -> Result<CreatedTask, rootcause::Report> {+ self.provider+ .follow_up(&self.credentials().await?, task, turn, prompt)+ .await+ }+ async fn cancel(&self, task: &CloudId) -> Result<(), rootcause::Report> {+ self.provider.cancel(&self.credentials().await?, task).await+ }+ async fn turn(&self, task: &CloudId, turn: &TurnId) -> Result<TaskSnapshot, rootcause::Report> {+ self.provider+ .turn(&self.credentials().await?, task, turn)+ .await+ }+ async fn stream(+ &self,+ task: &CloudId,+ turn: &TurnId,+ ) -> Result<CloudEventStream, rootcause::Report> {+ self.provider+ .stream(&self.credentials().await?, task, turn)+ .await+ }+}++#[cfg(test)]+mod test;diff --git a/crates/agent_harness/src/domain/codex/test.rs b/crates/agent_harness/src/domain/codex/test.rsnew file mode 100644index 0000000000..dccd8a5303--- /dev/null+++ b/crates/agent_harness/src/domain/codex/test.rs@@ -0,0 +1,330 @@+use super::*;+use codex_cloud_agents::domain::cloud::{CloudTasks, TurnSnapshot};+use codex_cloud_agents::domain::{DeviceLogin, Environment, LoginPoll, Secret};+use codex_connection::domain::{+ ConnectionError, ConnectionStatus, LoginStatus, ResolvedConnection, StartedLogin,+};+use std::{collections::HashMap, sync::Mutex};++#[derive(Default)]+struct Connections(+ Mutex<HashMap<String, (String, String)>>,+ Mutex<Option<Option<String>>>,+);+#[async_trait::async_trait]+impl ConnectionService for Connections {+ async fn resolve(&self, owner: &str) -> Result<ResolvedConnection, ConnectionError> {+ let rows = self.0.lock().unwrap();+ let (connection, account) = rows.get(owner).ok_or(ConnectionError::NotConnected)?;+ let environment = self+ .1+ .lock()+ .unwrap()+ .clone()+ .unwrap_or(Some("env_owner".into()));+ Ok(ResolvedConnection {+ connection_id: connection.parse().unwrap(),+ credentials: Credentials {+ version: 1,+ access_token: Secret::new(account.clone()).unwrap(),+ refresh_token: Secret::new("refresh".into()).unwrap(),+ expires_at: u64::MAX,+ account_id: account.clone(),+ },+ environment_id: environment.map(|id| CloudId::new(id).unwrap()),+ })+ }+ async fn status(&self, _: &str) -> Result<ConnectionStatus, ConnectionError> {+ unimplemented!()+ }+ async fn start_login(&self, _: &str) -> Result<StartedLogin, ConnectionError> {+ unimplemented!()+ }+ async fn poll_login(&self, _: &str, _: uuid::Uuid) -> Result<LoginStatus, ConnectionError> {+ unimplemented!()+ }+ async fn cancel_login(&self, _: &str, _: uuid::Uuid) -> Result<(), ConnectionError> {+ unimplemented!()+ }+ async fn disconnect(&self, owner: &str) -> Result<(), ConnectionError> {+ self.0.lock().unwrap().remove(owner);+ Ok(())+ }+ async fn environments(&self, _: &str) -> Result<Vec<Environment>, ConnectionError> {+ unimplemented!()+ }+ async fn configure(&self, _: &str, _: &str) -> Result<ConnectionStatus, ConnectionError> {+ unimplemented!()+ }+}+#[derive(Default, Clone)]+struct Sessions(Arc<Mutex<HashMap<AgentSessionId, ExternalSession>>>);+impl ExternalSessionRepo for Sessions {+ async fn upsert(+ &self,+ id: AgentSessionId,+ external: ExternalSession,+ ) -> agent_session::domain::error::Result<()> {+ self.0.lock().unwrap().insert(id, external);+ Ok(())+ }+ async fn get(+ &self,+ id: AgentSessionId,+ ) -> agent_session::domain::error::Result<Option<ExternalSession>> {+ Ok(self.0.lock().unwrap().get(&id).cloned())+ }+ async fn delete(&self, id: AgentSessionId) -> agent_session::domain::error::Result<()> {+ self.0.lock().unwrap().remove(&id);+ Ok(())+ }+}+#[derive(Default)]+struct Provider(+ Mutex<Vec<String>>,+ Mutex<Option<Vec<Environment>>>,+ Mutex<Vec<(String, String, String)>>,+);+impl OAuth for Provider {+ async fn begin(&self) -> Result<DeviceLogin, rootcause::Report> {+ unimplemented!()+ }+ async fn poll(&self, _: &DeviceLogin) -> Result<LoginPoll, rootcause::Report> {+ unimplemented!()+ }+ async fn refresh(&self, _: &Credentials) -> Result<Credentials, rootcause::Report> {+ unimplemented!()+ }+ async fn environments(&self, _: &Credentials) -> Result<Vec<Environment>, rootcause::Report> {+ if let Some(environments) = self.1.lock().unwrap().clone() {+ return Ok(environments);+ }+ Ok(vec![Environment {+ id: "env_owner".into(),+ label: None,+ repositories: vec![],+ }])+ }+}+impl CloudTasks for Provider {+ async fn create(+ &self,+ auth: &Credentials,+ request: &Launch,+ ) -> Result<CreatedTask, rootcause::Report> {+ self.2.lock().unwrap().push((+ request.environment.as_str().into(),+ request.branch.clone(),+ request.prompt.clone(),+ ));+ self.0.lock().unwrap().push(auth.account_id.clone());+ Ok(CreatedTask {+ task_id: CloudId::new("task_owner".into())?,+ assistant_turn_id: Some(TurnId::new("turn_owner".into())?),+ url: "https://chatgpt.com/codex/tasks/task_owner".into(),+ })+ }+ async fn snapshot(+ &self,+ _: &Credentials,+ task: &CloudId,+ ) -> Result<TaskSnapshot, rootcause::Report> {+ Ok(TaskSnapshot {+ task_id: task.clone(),+ native: None,+ pull_requests: vec![],+ title: None,+ assistant_status: Some("completed".into()),+ turns: Vec::<TurnSnapshot>::new(),+ })+ }+}+impl CloudConversation for Provider {+ async fn follow_up(+ &self,+ auth: &Credentials,+ task: &CloudId,+ _: &TurnId,+ _: &str,+ ) -> Result<CreatedTask, rootcause::Report> {+ self.0+ .lock()+ .unwrap()+ .push(format!("followup:{}", auth.account_id));+ Ok(CreatedTask {+ task_id: task.clone(),+ assistant_turn_id: Some(TurnId::new("turn_owner".into())?),+ url: "https://chatgpt.com/codex/tasks/task_owner".into(),+ })+ }+ async fn cancel(&self, auth: &Credentials, _: &CloudId) -> Result<(), rootcause::Report> {+ self.0+ .lock()+ .unwrap()+ .push(format!("cancel:{}", auth.account_id));+ Ok(())+ }+ async fn turn(+ &self,+ auth: &Credentials,+ task: &CloudId,+ _: &TurnId,+ ) -> Result<TaskSnapshot, rootcause::Report> {+ self.snapshot(auth, task).await+ }+ async fn stream(+ &self,+ _: &Credentials,+ _: &CloudId,+ _: &TurnId,+ ) -> Result<CloudEventStream, rootcause::Report> {+ Ok(Box::pin(futures::stream::empty()))+ }+}+fn runtime(+ owner: &str,+ connections: Arc<Connections>,+ provider: Arc<Provider>,+) -> CodexRuntime<Provider, Sessions, agent_session::testing::InMemoryAgentSessionRepo> {+ let connection = uuid::Uuid::now_v7().to_string();+ connections+ .0+ .lock()+ .unwrap()+ .insert(owner.into(), (connection.clone(), owner.into()));+ CodexRuntime {+ provider,+ connections,+ owner: MacroUserIdStr::try_from(owner.to_owned()).unwrap(),+ binding: RuntimeIdentity {+ connection_id: connection,+ account_id: owner.into(),+ },+ session: AgentSessionId::new(),+ sessions: Sessions::default(),+ session_repository: agent_session::testing::InMemoryAgentSessionRepo::default(),+ pull_requests: None,+ claim: Arc::new(std::sync::OnceLock::new()),+ }+}+fn launch() -> Launch {+ Launch {+ environment: CloudId::new("env_owner".into()).unwrap(),+ branch: "main".into(),+ prompt: "inspect".into(),+ }+}+#[tokio::test]+async fn owners_use_only_their_credentials_and_record_mapping_before_return() {+ let connections = Arc::new(Connections::default());+ let provider = Arc::new(Provider::default());+ let a = runtime("macro|[email protected]", connections.clone(), provider.clone());+ let b = runtime("macro|[email protected]", connections, provider.clone());+ a.launch(&launch()).await.unwrap();+ b.launch(&launch()).await.unwrap();+ assert_eq!(+ *provider.0.lock().unwrap(),+ ["macro|[email protected]", "macro|[email protected]"]+ );+ assert_eq!(+ a.sessions.get(a.session).await.unwrap().unwrap().provider,+ CODEX_PROVIDER+ );+}+#[tokio::test]+async fn disconnect_and_reconnect_cannot_retarget_existing_session() {+ let connections = Arc::new(Connections::default());+ let provider = Arc::new(Provider::default());+ let old = runtime("macro|[email protected]", connections.clone(), provider.clone());+ connections.disconnect(old.owner.as_ref()).await.unwrap();+ assert!(old.launch(&launch()).await.is_err());+ let _new = runtime(old.owner.as_ref(), connections, provider.clone());+ assert!(+ old.cancel(&CloudId::new("task_owner".into()).unwrap())+ .await+ .is_err()+ );+ assert!(provider.0.lock().unwrap().is_empty());+}+#[tokio::test]+async fn launch_rechecks_environment_visibility() {+ let connections = Arc::new(Connections::default());+ let provider = Arc::new(Provider::default());+ let runtime = runtime("macro|[email protected]", connections, provider.clone());+ let mut request = launch();+ request.environment = CloudId::new("env_foreign".into()).unwrap();+ assert!(runtime.launch(&request).await.is_err());+ assert!(provider.0.lock().unwrap().is_empty());+}++mod selection;++#[derive(Default)]+struct PullRequests(+ Mutex<+ Vec<(+ AgentSessionId,+ String,+ String,+ agent_session::domain::model::SessionClaim,+ )>,+ >,+);+impl agent_session::domain::pull_request::SessionPullRequests for PullRequests {+ fn set_pull_request<'a>(+ &'a self,+ session: AgentSessionId,+ owner: &'a MacroUserIdStr<'static>,+ url: &'a str,+ claim: Option<agent_session::domain::model::SessionClaim>,+ ) -> std::pin::Pin<+ Box<dyn Future<Output = agent_session::domain::error::Result<String>> + Send + 'a>,+ > {+ Box::pin(async move {+ self.0.lock().unwrap().push((+ session,+ owner.to_string(),+ url.to_owned(),+ claim.expect("Codex publication requires the activated fence"),+ ));+ Ok(url.into())+ })+ }+}+#[tokio::test]+async fn pr_publication_passes_the_activated_claim_and_rejects_disconnected_owner() {+ use agent_session::domain::model::{ManagerFence, ReplicaId, SessionClaim};+ let connections = Arc::new(Connections::default());+ let mut runtime = runtime(+ "macro|[email protected]",+ connections.clone(),+ Arc::new(Provider::default()),+ );+ let reporter = Arc::new(PullRequests::default());+ runtime.pull_requests = Some(reporter.clone());+ let url = "https://github.com/org/repo/pull/42";+ assert!(runtime.report_pull_request(url).await.is_err());+ assert!(reporter.0.lock().unwrap().is_empty());+ let claim = SessionClaim {+ session: runtime.session,+ replica: ReplicaId::from_uuid(uuid::Uuid::from_u128(2)),+ fence: ManagerFence(7),+ };+ runtime.claim.set(claim).unwrap();+ runtime.report_pull_request(url).await.unwrap();+ {+ let calls = reporter.0.lock().unwrap();+ assert_eq!(calls[0].0, runtime.session);+ assert_eq!(calls[0].1, runtime.owner.as_ref());+ assert_eq!(calls[0].2, url);+ assert_eq!(calls[0].3.session, claim.session);+ assert_eq!(calls[0].3.replica, claim.replica);+ assert_eq!(calls[0].3.fence, claim.fence);+ }+ connections+ .disconnect(runtime.owner.as_ref())+ .await+ .unwrap();+ assert!(runtime.report_pull_request(url).await.is_err());+ assert_eq!(reporter.0.lock().unwrap().len(), 1);+}diff --git a/crates/agent_harness/src/domain/codex/test/selection.rs b/crates/agent_harness/src/domain/codex/test/selection.rsnew file mode 100644index 0000000000..40dc205107--- /dev/null+++ b/crates/agent_harness/src/domain/codex/test/selection.rs@@ -0,0 +1,161 @@+use super::*;+use codex_cloud_agents::domain::EnvironmentRepository;+use codex_cloud_agents::domain::acp_session::{+ Outcome, SessionService, SessionSink, SessionStore, StoredSession,+};+use codex_cloud_agents::domain::cloud::CloudEvent;+use codex_cloud_agents::domain::journal::{JournalEntry, JournalInput};++#[derive(Default, Clone)]+struct Journal(+ Arc<Mutex<HashMap<String, StoredSession>>>,+ Arc<Mutex<HashMap<String, Vec<JournalEntry>>>>,+);+impl SessionStore for Journal {+ async fn load(&self, id: &str) -> Result<Option<StoredSession>, rootcause::Report> {+ Ok(self.0.lock().unwrap().get(id).cloned())+ }+ async fn save(&self, id: &str, state: &StoredSession) -> Result<(), rootcause::Report> {+ self.0.lock().unwrap().insert(id.into(), state.clone());+ Ok(())+ }+ async fn read(&self, id: &str) -> Result<Vec<JournalEntry>, rootcause::Report> {+ Ok(self.1.lock().unwrap().get(id).cloned().unwrap_or_default())+ }+ async fn append(+ &self,+ id: &str,+ expected: i64,+ turn: Option<&TurnId>,+ input: &JournalInput,+ ) -> Result<JournalEntry, rootcause::Report> {+ let mut journals = self.1.lock().unwrap();+ let entries = journals.entry(id.into()).or_default();+ assert_eq!(entries.len() as i64, expected);+ let entry = JournalEntry {+ sequence: expected + 1,+ turn: turn.cloned(),+ input: input.clone(),+ };+ entries.push(entry.clone());+ Ok(entry)+ }+ async fn validate(&self) -> Result<(), rootcause::Report> {+ Ok(())+ }+}+struct Sink;+impl SessionSink for Sink {+ fn emit(&self, _: &CloudEvent) -> Result<(), rootcause::Report> {+ Ok(())+ }+}++fn text() -> Vec<agent_client_protocol::schema::v1::ContentBlock> {+ vec![agent_client_protocol::schema::v1::ContentBlock::Text(+ agent_client_protocol::schema::v1::TextContent::new("fix the org/repo login button"),+ )]+}+fn configured_runtime() -> (+ Arc<CodexRuntime<Provider, Sessions, agent_session::testing::InMemoryAgentSessionRepo>>,+ Arc<Connections>,+ Arc<Provider>,+) {+ let connections = Arc::new(Connections::default());+ *connections.1.lock().unwrap() = Some(None);+ let provider = Arc::new(Provider::default());+ *provider.1.lock().unwrap() = Some(vec![Environment {+ id: "env_a".into(),+ label: None,+ repositories: vec![EnvironmentRepository {+ full_name: "org/repo".into(),+ clone_url: "https://github.com/Org/Repo.git".into(),+ default_branch: "develop".into(),+ }],+ }]);+ let runtime = runtime(+ "macro|[email protected]",+ connections.clone(),+ provider.clone(),+ );+ let mut current = agent_session::testing::test_agent_session(runtime.session);+ current.owner_id = runtime.owner.clone();+ runtime.session_repository.insert_session(current);+ (Arc::new(runtime), connections, provider)+}++#[tokio::test]+async fn explicit_configuration_is_required_even_when_prompt_names_available_repository() {+ let (runtime, connections, provider) = configured_runtime();+ let journal = Journal::default();+ let service = SessionService::new(runtime, journal.clone(), None);+ let id = service.new_session().await.unwrap();+ let error = service.prompt(&id, text(), &Sink).await.err().unwrap();+ assert!(+ error+ .to_string()+ .contains("select and save a Codex environment")+ );+ let state = journal.load(&id).await.unwrap().unwrap();+ assert!(state.target.is_none());+ assert!(!state.uncertain_write);+ assert_eq!(journal.read(&id).await.unwrap().len(), 1);+ assert!(provider.2.lock().unwrap().is_empty());+ *connections.1.lock().unwrap() = Some(Some("env_a".into()));+ assert!(matches!(+ service.prompt(&id, text(), &Sink).await.unwrap(),+ Outcome::Completed+ ));+ assert_eq!(provider.2.lock().unwrap()[0].0, "env_a");+ assert_eq!(provider.2.lock().unwrap()[0].1, "main");+}++#[tokio::test]+async fn configured_target_remains_pinned_across_settings_changes_and_restart() {+ let (runtime, connections, provider) = configured_runtime();+ *connections.1.lock().unwrap() = Some(Some("env_a".into()));+ let journal = Journal::default();+ let service = SessionService::new(runtime.clone(), journal.clone(), None);+ let id = service.new_session().await.unwrap();+ service.prompt(&id, text(), &Sink).await.unwrap();+ let pinned = journal.load(&id).await.unwrap().unwrap().target.unwrap();+ assert_eq!(pinned.environment.as_str(), "env_a");+ assert_eq!(pinned.branch, "main");+ assert_eq!(+ runtime+ .session_repository+ .get(runtime.session)+ .await+ .unwrap()+ .repo_url+ .as_deref(),+ Some("https://github.com/org/repo")+ );+ *connections.1.lock().unwrap() = Some(Some("other_environment".into()));+ drop(service);+ SessionService::new(runtime, journal.clone(), None)+ .prompt(&id, text(), &Sink)+ .await+ .unwrap();+ assert_eq!(+ journal.load(&id).await.unwrap().unwrap().target.unwrap(),+ pinned+ );+ assert_eq!(provider.2.lock().unwrap().len(), 1);+}++#[test]+fn repository_identity_only_casefolds_github_and_strips_one_git_suffix() {+ assert_eq!(+ repository_identity("https://GitHub.com/ORG/Repo.git").unwrap(),+ "https://github.com/org/repo"+ );+ assert_eq!(+ repository_identity("https://github.com/org/repo.git.git").unwrap(),+ "https://github.com/org/repo.git"+ );+ assert_eq!(+ repository_identity("https://git.example.com/Org/Repo.git").unwrap(),+ "https://git.example.com/Org/Repo"+ );+}diff --git a/crates/agent_harness/src/domain/mod.rs b/crates/agent_harness/src/domain/mod.rsindex 0d51730b49..3f0d2d41d9 100644--- a/crates/agent_harness/src/domain/mod.rs+++ b/crates/agent_harness/src/domain/mod.rs@@ -16,3 +16,6 @@ pub mod sandbox;pub mod service;/// Policy for turning broker trigger events into harness work.pub mod trigger_router;++/// Per-owner hosted Codex runtime authorization.+pub mod codex;diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rsindex f32b32c11f..07297c3a97 100644--- a/crates/agent_harness/src/domain/model.rs+++ b/crates/agent_harness/src/domain/model.rs@@ -64,6 +64,8 @@ pub enum AgentKind {SandboxedCoder,/// A Cursor cloud agent, served over an in-process ACP pipe.Cursor,+ /// A per-owner Codex cloud conversation served over ACP.+ CodexCloud,/// The in-process (in-memory) "macro(new)" bot, served by `agent_inmem`.InMemory,/// The bot's operator hosts the runtime and dials the gateway; no@@ -79,6 +81,8 @@ impl AgentKind {Self::SandboxedCoder} else if bot == bot_id::CURSOR_BOT_ID {Self::Cursor+ } else if bot == bot_id::CODEX_BOT_ID {+ Self::CodexCloud} else if bot == bot_id::MACRO_NEW_BOT_ID {Self::InMemory} else {@@ -91,6 +95,7 @@ impl AgentKind {pub fn from_harness(harness: &str) -> Self {match harness {"cursor" => Self::Cursor,+ "codex-cloud" => Self::CodexCloud,"in-memory" | "macro-inmem" => Self::InMemory,// Registered macrod harnesses are the deliberate external case:// the agent's `harness_id` names whose daemon serves it.diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rsindex 1d6ba9e8fe..ab43060729 100644--- a/crates/agent_harness/src/domain/service/open.rs+++ b/crates/agent_harness/src/domain/service/open.rs@@ -116,7 +116,7 @@ whererequest: agent_session::domain::ports::OpenManagedSession,) -> agent_session::domain::error::Result<AgentSession> {let managed_defaults = self.inner.defaults.managed();- let (bot_id, model, harness, instructions, mcp_servers) = match request.profile {+ let (bot_id, model, harness, instructions, mut mcp_servers) = match request.profile {Some(SelectedManagedPersona {bot_id,profile: Some(profile),@@ -150,6 +150,12 @@ whereAgentMcpServers::OwnerConnections,),};+ let kind = AgentKind::for_session(bot_id, &harness);+ if kind == AgentKind::CodexCloud {+ mcp_servers = AgentMcpServers::Selected {+ servers: Vec::new(),+ };+ }let defaults = self.inner.defaults.for_bot(bot_id);let sandbox_size = self.inner@@ -177,7 +183,7 @@ whereoriginating_message_id: None,model,harness,- repo_url: Some(defaults.repo_url.clone()),+ repo_url: (kind != AgentKind::CodexCloud).then(|| defaults.repo_url.clone()),// Managed sandboxes run in the path baked into their image.workspace: agent_session::MANAGED_CONTAINER_WORKSPACE.to_owned(),sandbox_size,@@ -188,7 +194,11 @@ where.await?;self.inner.publish_opened(&session).await;- let mcp_servers = egress.sandbox.acp_servers();+ let mcp_servers = if kind == AgentKind::CodexCloud {+ Vec::new()+ } else {+ egress.sandbox.acp_servers()+ };let container = match self.inner.containers@@ -344,7 +354,7 @@ whereoriginating_message_id: Some(origin.message_id),model: runtime.model.clone(),harness: runtime.harness.clone(),- repo_url: Some(repo_url.clone()),+ repo_url: (runtime.kind != AgentKind::CodexCloud).then(|| repo_url.clone()),// Managed sandboxes run in the path baked into their image.workspace: agent_session::MANAGED_CONTAINER_WORKSPACE.to_owned(),sandbox_size,@@ -361,7 +371,11 @@ where.await?;self.publish_opened(&session).await;- let mcp_servers = egress.sandbox.acp_servers();+ let mcp_servers = if runtime.kind == AgentKind::CodexCloud {+ Vec::new()+ } else {+ egress.sandbox.acp_servers()+ };let container = match self.containers.spawn(SpawnContainer {diff --git a/crates/agent_harness/src/domain/service/queue.rs b/crates/agent_harness/src/domain/service/queue.rsindex c95c398515..72d4fd572d 100644--- a/crates/agent_harness/src/domain/service/queue.rs+++ b/crates/agent_harness/src/domain/service/queue.rs@@ -215,8 +215,7 @@ wherecommand: HarnessCommand,) -> Result<CommandOutcome> {let span = tracing::Span::current();- // Open never routes: it is what creates the session row this routing- // would read, and a fresh id has no manager to defer to.+ // Open creates the row and has no existing manager to route through.if matches!(command, HarnessCommand::Open(_)) {span.record("agent.session.management", "open");span.record("agent.command.forwarded", false);diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rsindex c82409b11a..c8250e134e 100644--- a/crates/agent_harness/src/domain/service/test.rs+++ b/crates/agent_harness/src/domain/service/test.rs@@ -353,12 +353,21 @@ fn harness_with_mentions(prompt_composer,EgressProvisionerMock::new(),NoPeers,- SessionDefaults {+ HarnessDefaults::new(SessionDefaults {bot_id: BotId::TEST_A,model: "claude".to_owned(),harness: "opencode".to_owned(),repo_url: "https://github.com/macro-inc/macro".to_owned(),- },+ })+ .with_bot(+ bot_id::CODEX_BOT_ID,+ SessionDefaults {+ bot_id: bot_id::CODEX_BOT_ID,+ model: String::new(),+ harness: "codex-cloud".into(),+ repo_url: String::new(),+ },+ ),lifecycle.clone(),crate::domain::pending::PendingCommands::new(),mentions,@@ -2848,3 +2857,99 @@ mod lifecycle_events {assert_eq!(events.len(), 5, "nothing follows deleted: {events:#?}");}}++#[tokio::test]+async fn codex_named_session_provisions_egress_without_advertising_mcp() {+ let (service, repo, containers, _, _) = harness();+ let open = service.open_managed_session(OpenManagedSession {+ owner: sender(),+ instructions: None,+ prompt: Some("inspect".into()),+ profile: Some(agent_session::domain::ports::SelectedManagedPersona {+ bot_id: bot_id::CODEX_BOT_ID,+ profile: None,+ }),+ });+ let drive = async {+ while containers.spawned() == 0 {+ tokio::task::yield_now().await;+ }+ let container = containers.container(session_of(&containers)).unwrap();+ complete_handshake(&container).await;+ container+ };+ let (opened, container) = tokio::join!(open, drive);+ let session = opened.unwrap();+ assert_eq!(service.inner.egress.provisioned().len(), 1);+ assert_eq!(+ repo.find_by_egress_token_hash("test-token-hash")+ .await+ .unwrap()+ .unwrap()+ .id,+ session.id+ );+ assert_eq!(session.harness, "codex-cloud");+ assert!(session.repo_url.is_none());+ assert_eq!(+ repo.get(session.id).await.unwrap().mcp_servers,+ AgentMcpServers::Selected {+ servers: Vec::new()+ }+ );+ let requests = container.agent().received_requests();+ let ClientRequest::NewSessionRequest(request) = &requests[1] else {+ panic!("expected session/new")+ };+ assert!(request.mcp_servers.is_empty());+}++#[tokio::test]+async fn codex_channel_mention_provisions_egress_without_advertising_mcp() {+ let (service, repo, containers, announcer, _) = harness();+ let mut command = open_command();+ command.bot_id = bot_id::CODEX_BOT_ID;+ command.runtime = AgentRuntimeConfig {+ kind: AgentKind::CodexCloud,+ model: String::new(),+ harness: "codex-cloud".into(),+ instructions: String::new(),+ mcp_servers: AgentMcpServers::Selected {+ servers: Vec::new(),+ },+ };+ command.origin.content = "@codex inspect the repository".into();+ let id = AgentSessionId::new();+ let open = service.execute(id, HarnessCommand::Open(command));+ let drive = async {+ while containers.spawned() == 0 {+ tokio::task::yield_now().await;+ }+ let container = containers.container(session_of(&containers)).unwrap();+ complete_handshake(&container).await;+ container+ };+ let (opened, container) = tokio::join!(open, drive);+ opened.unwrap();+ let stored = repo.get(id).await.unwrap();+ assert_eq!(stored.bot_id, bot_id::CODEX_BOT_ID);+ assert_eq!(service.inner.egress.provisioned().len(), 1);+ assert_eq!(+ repo.find_by_egress_token_hash("test-token-hash")+ .await+ .unwrap()+ .unwrap()+ .id,+ id+ );+ assert_eq!(stored.harness, "codex-cloud");+ assert!(stored.repo_url.is_none());+ assert_eq!(announcer.announced()[0].bot_id, bot_id::CODEX_BOT_ID);+ let requests = container.agent().received_requests();+ let ClientRequest::NewSessionRequest(request) = &requests[1] else {+ panic!("expected session/new")+ };+ assert!(request.mcp_servers.is_empty());+}++mod reopen;diff --git a/crates/agent_harness/src/domain/service/test/reopen.rs b/crates/agent_harness/src/domain/service/test/reopen.rsnew file mode 100644index 0000000000..5237aff407--- /dev/null+++ b/crates/agent_harness/src/domain/service/test/reopen.rs@@ -0,0 +1,77 @@+use super::*;++async fn codex_session(+ repo: &InMemoryAgentSessionRepo,+ containers: &MockContainerManager,+) -> AgentSessionId {+ let id = AgentSessionId::new();+ agent_session::domain::ports::AgentSessionRepo::create(+ repo,+ CreateAgentSessionParams {+ id,+ owner_id: sender(),+ bot_id: bot_id::CODEX_BOT_ID,+ thread_id: None,+ originating_message_id: None,+ model: "codex".into(),+ harness: "codex-cloud".into(),+ repo_url: Some("https://github.com/owner/repo".into()),+ workspace: String::new(),+ sandbox_size: SandboxSize::Default,+ instructions: None,+ mcp_servers: Default::default(),+ egress_token_hash: None,+ },+ )+ .await+ .unwrap();+ repo.set_acp_session_id(id, SessionId::new("acp-test"))+ .await+ .unwrap();+ containers+ .spawn(SpawnContainer {+ session_id: id,+ kind: AgentKind::CodexCloud,+ size: SandboxSize::Default,+ egress: crate::testing::helpers::egress::test_egress(),+ })+ .await+ .unwrap();+ id+}++#[tokio::test]+async fn codex_delivery_loads_saved_session_before_prompting() {+ let (service, repo, containers, _, _) = harness();+ let id = codex_session(&repo, &containers).await;+ let delivery = service.execute(id, HarnessCommand::Deliver(forward_message("continue")));+ let drive = async {+ while containers.resumed() == 0 {+ tokio::task::yield_now().await;+ }+ let container = containers.container(id).unwrap();+ let agent = container.agent();+ container.sends_ready();+ agent.wait_for_requests(1).await;+ agent.completes_initialize(+ InitializeResponse::new(PROTOCOL_VERSION)+ .agent_capabilities(AgentCapabilities::new().load_session(true)),+ );+ agent.wait_for_requests(2).await;+ assert!(matches!(+ &agent.received_requests()[1],+ ClientRequest::LoadSessionRequest(request) if request.session_id.to_string() == "acp-test"+ ));+ agent.loads_session(agent_client_protocol::schema::v1::LoadSessionResponse::new());+ agent.wait_for_requests(3).await;+ assert_eq!(prompts(&agent).len(), 1);+ };+ tokio::time::timeout(std::time::Duration::from_secs(5), async {+ let (result, ()) = tokio::join!(delivery, drive);+ result.unwrap();+ })+ .await+ .unwrap();+ assert_eq!(containers.resumed(), 1);+ assert_eq!(containers.spawned(), 1, "delivery reuses the saved session");+}diff --git a/crates/agent_harness/src/inbound/kafka/test.rs b/crates/agent_harness/src/inbound/kafka/test.rsindex 251ed0fcbb..b2f4d566e6 100644--- a/crates/agent_harness/src/inbound/kafka/test.rs+++ b/crates/agent_harness/src/inbound/kafka/test.rs@@ -21,6 +21,7 @@ fn runtime(kind: AgentKind) -> Option<AgentRuntimeConfig> {model: "configured-model".to_owned(),harness: match kind {AgentKind::Cursor => "cursor",+ AgentKind::CodexCloud => "codex-cloud",AgentKind::InMemory => "in-memory",AgentKind::SandboxedCoder => "opencode",AgentKind::External => "byoa",diff --git a/crates/agent_harness/src/outbound/cursor/pipe.rs b/crates/agent_harness/src/outbound/acp_pipe.rssimilarity index 100%rename from crates/agent_harness/src/outbound/cursor/pipe.rsrename to crates/agent_harness/src/outbound/acp_pipe.rsdiff --git a/crates/agent_harness/src/outbound/cursor/pipe/test.rs b/crates/agent_harness/src/outbound/acp_pipe/test.rssimilarity index 100%rename from crates/agent_harness/src/outbound/cursor/pipe/test.rsrename to crates/agent_harness/src/outbound/acp_pipe/test.rsdiff --git a/crates/agent_harness/src/outbound/agent_prompt_composer.rs b/crates/agent_harness/src/outbound/agent_prompt_composer.rsindex 0ae72dfea9..cfc8916c00 100644--- a/crates/agent_harness/src/outbound/agent_prompt_composer.rs+++ b/crates/agent_harness/src/outbound/agent_prompt_composer.rs@@ -41,3 +41,6 @@ impl AgentPromptComposer for LexicalAgentPromptComposer {.map_err(|error| HarnessError::PromptComposition(rootcause::report!(error).into()))}}++#[cfg(test)]+mod test;diff --git a/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs b/crates/agent_harness/src/outbound/agent_prompt_composer/test.rsnew file mode 100644index 0000000000..f43162ffb7--- /dev/null+++ b/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs@@ -0,0 +1,24 @@+use super::*;+use axum::{Json, Router, routing::post};++#[tokio::test]+async fn composition_preserves_lexical_output_without_tool_instructions() {+ let app = Router::new().route(+ "/agent-context",+ post(|| async { Json(serde_json::json!({ "markdown": "Sanitized prompt and context" })) }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let composer = LexicalAgentPromptComposer::new(LexicalClient::new(+ "test".into(),+ format!("http://{address}"),+ ));++ for messages in [None, Some([].as_slice())] {+ let prompt = composer.compose("Raw prompt", messages).await.unwrap();+ assert_eq!(prompt, "Sanitized prompt and context");+ assert!(!prompt.contains("set_pull_request"));+ }+ server.abort();+}diff --git a/crates/agent_harness/src/outbound/codex.rs b/crates/agent_harness/src/outbound/codex.rsnew file mode 100644index 0000000000..cb95ba1234--- /dev/null+++ b/crates/agent_harness/src/outbound/codex.rs@@ -0,0 +1,173 @@+//! Hosts per-owner Codex ACP conversations with PostgreSQL ownership fencing.+use super::acp_pipe::PipeTransport;+use crate::domain::{+ codex::{CODEX_PROVIDER, CodexRuntime},+ error::{HarnessError, Result},+ model::SpawnContainer,+ ports::ContainerManager,+ sandbox::SandboxResizeEffect,+};+use agent_session::domain::{+ connection::{AttachmentActivation, RuntimeAttachment},+ model::{AgentSessionId, SandboxSize},+ ports::{AgentSessionRepo, ExternalSessionRepo},+};+use codex_cloud_agents::domain::{+ OAuth,+ acp_session::{SessionService, SessionStore},+ cloud::CloudConversation,+ runtime::RuntimeIdentity,+};+use codex_connection::domain::ConnectionService;+use std::sync::Arc;++/// Provisions an ACP attachment; cloud execution begins only with a prompt.+pub struct CodexContainerManager<P, S, J> {+ provider: Arc<P>,+ connections: Option<Arc<dyn ConnectionService>>,+ sessions: S,+ pull_requests: Option<Arc<dyn agent_session::domain::pull_request::SessionPullRequests>>,+ journal: Arc<dyn Fn(AgentSessionId) -> (J, AttachmentActivation) + Send + Sync>,+}+impl<P, S: Clone, J> Clone for CodexContainerManager<P, S, J> {+ fn clone(&self) -> Self {+ Self {+ provider: self.provider.clone(),+ connections: self.connections.clone(),+ sessions: self.sessions.clone(),+ pull_requests: self.pull_requests.clone(),+ journal: self.journal.clone(),+ }+ }+}+impl<+ P: OAuth + CloudConversation + 'static,+ S: AgentSessionRepo + ExternalSessionRepo + Clone + 'static,+ J: SessionStore + 'static,+> CodexContainerManager<P, S, J>+{+ /// Compose owner connection and cloud ports with the process's durable session claim.+ pub fn new(+ provider: Arc<P>,+ connections: Option<Arc<dyn ConnectionService>>,+ sessions: S,+ journal: Arc<dyn Fn(AgentSessionId) -> (J, AttachmentActivation) + Send + Sync>,+ ) -> Self {+ Self {+ provider,+ connections,+ sessions,+ pull_requests: None,+ journal,+ }+ }+ /// Publish verified Codex PRs through the same session operation as other runtimes.+ pub fn with_pull_requests(+ mut self,+ service: Arc<dyn agent_session::domain::pull_request::SessionPullRequests>,+ ) -> Self {+ self.pull_requests = Some(service);+ self+ }+ async fn attach(&self, id: AgentSessionId) -> Result<RuntimeAttachment<PipeTransport>> {+ let row = AgentSessionRepo::get(&self.sessions, id).await?;+ let connections = self.connections.clone().ok_or_else(|| {+ HarnessError::Container(+ "Codex connection encryption is not configured on this deployment".into(),+ )+ })?;+ let resolved = connections+ .resolve(row.owner_id.as_ref())+ .await+ .map_err(|e| HarnessError::Container(e.to_string()))?;+ let claim = Arc::new(std::sync::OnceLock::new());+ let runtime = Arc::new(CodexRuntime {+ provider: self.provider.clone(),+ connections,+ owner: row.owner_id.clone(),+ binding: RuntimeIdentity {+ connection_id: resolved.connection_id.to_string(),+ account_id: resolved.credentials.account_id.clone(),+ },+ session: id,+ sessions: self.sessions.clone(),+ session_repository: self.sessions.clone(),+ pull_requests: self.pull_requests.clone(),+ claim: claim.clone(),+ });+ let (journal, activate) = (self.journal)(id);+ let activate: AttachmentActivation = Box::new(move |ownership| {+ activate(ownership)?;+ claim.set(ownership).map_err(|_| {+ agent_runtime_protocol::domain::ports::TransportError::Client(+ "Codex attachment already activated".into(),+ )+ .into()+ })+ });+ let service = Arc::new(+ SessionService::new(runtime, journal, None).with_session_id(id.as_uuid().to_string()),+ );+ let (ours, theirs) = tokio::io::duplex(64 * 1024);+ let (reader, writer) = tokio::io::split(theirs);+ let closed = tokio_util::sync::CancellationToken::new();+ let on_close = closed.clone();+ let (reload_tx, reload_rx) = tokio::sync::mpsc::unbounded_channel();+ tokio::spawn(async move {+ if let Err(error) =+ codex_cloud_agents::inbound::acp::serve(service, reader, writer, Some(reload_tx))+ .await+ {+ tracing::warn!(%id,error=%error,"Codex ACP transport closed");+ }+ on_close.cancel();+ });+ Ok(RuntimeAttachment::solo(PipeTransport::connect_recoverable(+ ours,+ || {},+ closed.clone(),+ Some(reload_rx),+ ))+ .with_closed(closed)+ .on_activate(activate))+ }+}+impl<+ P: OAuth + CloudConversation + 'static,+ S: AgentSessionRepo + ExternalSessionRepo + Clone + 'static,+ J: SessionStore + 'static,+> ContainerManager for CodexContainerManager<P, S, J>+{+ type Transport = PipeTransport;+ async fn spawn(&self, command: SpawnContainer) -> Result<RuntimeAttachment<PipeTransport>> {+ self.attach(command.session_id).await+ }+ async fn resume(&self, session: AgentSessionId) -> Result<RuntimeAttachment<PipeTransport>> {+ self.attach(session).await+ }+ async fn session_token(&self, _session: AgentSessionId) -> Result<Option<String>> {+ Ok(None)+ }+ async fn teardown(&self, session: AgentSessionId) -> Result<()> {+ let Some(external) = ExternalSessionRepo::get(&self.sessions, session).await? else {+ return Ok(());+ };+ if external.provider != CODEX_PROVIDER {+ return Err(HarnessError::Container(+ "Codex session has a foreign provider mapping".into(),+ ));+ }+ // Teardown removes only Macro's mapping. Remote work is cancelled through+ // the explicit authorized session/cancel operation; deletion does not imply stop.+ ExternalSessionRepo::delete(&self.sessions, session).await?;+ Ok(())+ }+ fn resize_effect(&self, _from: SandboxSize, _to: SandboxSize) -> SandboxResizeEffect {+ SandboxResizeEffect::Unsupported+ }+ async fn resize(&self, _session: AgentSessionId, _size: SandboxSize) -> Result<()> {+ Err(HarnessError::Container(+ "Codex cloud compute cannot be resized from Macro".into(),+ ))+ }+}diff --git a/crates/agent_harness/src/outbound/cursor/mod.rs b/crates/agent_harness/src/outbound/cursor/mod.rsindex 62c5152945..4e64808d36 100644--- a/crates/agent_harness/src/outbound/cursor/mod.rs+++ b/crates/agent_harness/src/outbound/cursor/mod.rs@@ -2,7 +2,7 @@pub mod keys;pub mod manager;-pub mod pipe;+pub use crate::outbound::acp_pipe as pipe;mod pull_request;pub mod repository_chooser;diff --git a/crates/agent_harness/src/outbound/cursor/pull_request.rs b/crates/agent_harness/src/outbound/cursor/pull_request.rsindex a8effc5529..bd18526659 100644--- a/crates/agent_harness/src/outbound/cursor/pull_request.rs+++ b/crates/agent_harness/src/outbound/cursor/pull_request.rs@@ -21,7 +21,7 @@ impl PullRequestReporter for CursorPullRequestReporter {) -> Pin<Box<dyn Future<Output = Result<(), rootcause::Report>> + Send + 'a>> {Box::pin(async move {self.service- .set_pull_request(self.session, &self.owner, url)+ .set_pull_request(self.session, &self.owner, url, None).await.map(|_| ()).map_err(|error| rootcause::report!(error).into())diff --git a/crates/agent_harness/src/outbound/mod.rs b/crates/agent_harness/src/outbound/mod.rsindex 6434741c5d..0c48201206 100644--- a/crates/agent_harness/src/outbound/mod.rs+++ b/crates/agent_harness/src/outbound/mod.rs@@ -19,3 +19,8 @@ pub(crate) mod provision;pub mod routing;pub mod runtime_registry;pub mod sidecar;++/// Provider-neutral in-process ACP transport.+pub mod acp_pipe;+/// Per-owner Codex cloud runtime.+pub mod codex;diff --git a/crates/agent_harness/src/outbound/routing.rs b/crates/agent_harness/src/outbound/routing.rsindex 0eae018737..992931ca3c 100644--- a/crates/agent_harness/src/outbound/routing.rs+++ b/crates/agent_harness/src/outbound/routing.rs@@ -28,37 +28,45 @@ mod test;/// Dispatches each session to the provider its bot is served by.#[derive(Clone)]-pub struct RoutedContainerManager<Sandbox, Cursor, Sessions> {+pub struct RoutedContainerManager<Sandbox, Cursor, Codex, Sessions> {sandbox: Sandbox,cursor: Cursor,+ codex: Codex,sessions: Sessions,}-impl<Sandbox, Cursor, Sessions> RoutedContainerManager<Sandbox, Cursor, Sessions> {+impl<Sandbox, Cursor, Codex, Sessions> RoutedContainerManager<Sandbox, Cursor, Codex, Sessions> {/// Wire the router over its providers.- pub fn new(sandbox: Sandbox, cursor: Cursor, sessions: Sessions) -> Self {+ pub fn new(sandbox: Sandbox, cursor: Cursor, codex: Codex, sessions: Sessions) -> Self {Self {sandbox,cursor,+ codex,sessions,}}}-impl<Sandbox, Cursor, Sessions> ContainerManager- for RoutedContainerManager<Sandbox, Cursor, Sessions>+impl<Sandbox, Cursor, Codex, Sessions> ContainerManager+ for RoutedContainerManager<Sandbox, Cursor, Codex, Sessions>whereSandbox: ContainerManager,Cursor: ContainerManager,+ Codex: ContainerManager,Sessions: AgentSessionRepo + Clone,{- type Transport = RoutedTransport<Sandbox::Transport, Cursor::Transport>;+ type Transport = RoutedTransport<Sandbox::Transport, Cursor::Transport, Codex::Transport>;async fn spawn(&self,command: SpawnContainer,) -> Result<agent_session::domain::connection::RuntimeAttachment<Self::Transport>> {match command.kind {+ AgentKind::CodexCloud => Ok(self+ .codex+ .spawn(command)+ .await?+ .map_transport(RoutedTransport::Codex)),AgentKind::Cursor => Ok(self.cursor.spawn(command)@@ -79,6 +87,11 @@ where) -> Result<agent_session::domain::connection::RuntimeAttachment<Self::Transport>> {let row = self.sessions.get(session).await?;match AgentKind::for_session(row.bot_id, &row.harness) {+ AgentKind::CodexCloud => Ok(self+ .codex+ .resume(session)+ .await?+ .map_transport(RoutedTransport::Codex)),AgentKind::Cursor => Ok(self.cursor.resume(session)@@ -96,6 +109,7 @@ whereasync fn session_token(&self, session: AgentSessionId) -> Result<Option<String>> {let row = self.sessions.get(session).await?;match AgentKind::for_session(row.bot_id, &row.harness) {+ AgentKind::CodexCloud => self.codex.session_token(session).await,AgentKind::Cursor => self.cursor.session_token(session).await,AgentKind::SandboxedCoder | AgentKind::InMemory => {self.sandbox.session_token(session).await@@ -107,6 +121,7 @@ whereasync fn teardown(&self, session: AgentSessionId) -> Result<()> {let row = self.sessions.get(session).await?;match AgentKind::for_session(row.bot_id, &row.harness) {+ AgentKind::CodexCloud => self.codex.teardown(session).await,AgentKind::Cursor => self.cursor.teardown(session).await,AgentKind::SandboxedCoder | AgentKind::InMemory => self.sandbox.teardown(session).await,AgentKind::External => Err(external_is_unroutable()),@@ -124,6 +139,9 @@ wherelet row = self.sessions.get(session).await?;match AgentKind::for_session(row.bot_id, &row.harness) {AgentKind::SandboxedCoder => self.sandbox.resize(session, size).await,+ AgentKind::CodexCloud => Err(HarnessError::Container(+ "a codex session has no sandbox to resize".to_owned(),+ )),AgentKind::Cursor => Err(HarnessError::Container("a cursor session has no sandbox to resize".to_owned(),)),@@ -144,37 +162,44 @@ fn external_is_unroutable() -> HarnessError {}/// A transport that is one provider's or the other's, decided per session.-pub enum RoutedTransport<Sandbox, Cursor> {+pub enum RoutedTransport<Sandbox, Cursor, Codex> {/// A sandbox-provider transport.Sandbox(Sandbox),/// A Cursor-provider transport.Cursor(Cursor),+ /// A Codex cloud provider transport half.+ Codex(Codex),}/// The sending half of a [`RoutedTransport`].-pub enum RoutedSender<Sandbox, Cursor> {+pub enum RoutedSender<Sandbox, Cursor, Codex> {/// A sandbox-provider sender.Sandbox(Sandbox),/// A Cursor-provider sender.Cursor(Cursor),+ /// A Codex cloud provider transport half.+ Codex(Codex),}/// The receiving half of a [`RoutedTransport`].-pub enum RoutedReceiver<Sandbox, Cursor> {+pub enum RoutedReceiver<Sandbox, Cursor, Codex> {/// A sandbox-provider receiver.Sandbox(Sandbox),/// A Cursor-provider receiver.Cursor(Cursor),+ /// A Codex cloud provider transport half.+ Codex(Codex),}-impl<Sandbox, Cursor> Transport<ToRuntimeMessage, ToServerMessage>- for RoutedTransport<Sandbox, Cursor>+impl<Sandbox, Cursor, Codex> Transport<ToRuntimeMessage, ToServerMessage>+ for RoutedTransport<Sandbox, Cursor, Codex>whereSandbox: Transport<ToRuntimeMessage, ToServerMessage>,Cursor: Transport<ToRuntimeMessage, ToServerMessage>,+ Codex: Transport<ToRuntimeMessage, ToServerMessage>,{- type Sender = RoutedSender<Sandbox::Sender, Cursor::Sender>;- type Receiver = RoutedReceiver<Sandbox::Receiver, Cursor::Receiver>;+ type Sender = RoutedSender<Sandbox::Sender, Cursor::Sender, Codex::Sender>;+ type Receiver = RoutedReceiver<Sandbox::Receiver, Cursor::Receiver, Codex::Receiver>;fn split(self) -> (Self::Sender, Self::Receiver) {match self {@@ -185,6 +210,10 @@ whereRoutedReceiver::Sandbox(receiver),)}+ Self::Codex(transport) => {+ let (sender, receiver) = transport.split();+ (RoutedSender::Codex(sender), RoutedReceiver::Codex(receiver))+ }Self::Cursor(transport) => {let (sender, receiver) = transport.split();(@@ -196,28 +225,34 @@ where}}-impl<Sandbox, Cursor> TransportSender<ToRuntimeMessage> for RoutedSender<Sandbox, Cursor>+impl<Sandbox, Cursor, Codex> TransportSender<ToRuntimeMessage>+ for RoutedSender<Sandbox, Cursor, Codex>whereSandbox: TransportSender<ToRuntimeMessage>,Cursor: TransportSender<ToRuntimeMessage>,+ Codex: TransportSender<ToRuntimeMessage>,{async fn send(&self, message: ToRuntimeMessage) -> std::result::Result<(), TransportError> {match self {Self::Sandbox(sender) => sender.send(message).await,Self::Cursor(sender) => sender.send(message).await,+ Self::Codex(sender) => sender.send(message).await,}}}-impl<Sandbox, Cursor> TransportReceiver<ToServerMessage> for RoutedReceiver<Sandbox, Cursor>+impl<Sandbox, Cursor, Codex> TransportReceiver<ToServerMessage>+ for RoutedReceiver<Sandbox, Cursor, Codex>whereSandbox: TransportReceiver<ToServerMessage>,Cursor: TransportReceiver<ToServerMessage>,+ Codex: TransportReceiver<ToServerMessage>,{async fn recv(&mut self) -> std::result::Result<Option<ToServerMessage>, TransportError> {match self {Self::Sandbox(receiver) => receiver.recv().await,Self::Cursor(receiver) => receiver.recv().await,+ Self::Codex(receiver) => receiver.recv().await,}}}diff --git a/crates/agent_harness/src/outbound/routing/test.rs b/crates/agent_harness/src/outbound/routing/test.rsindex 45f7ca94b3..e869383a18 100644--- a/crates/agent_harness/src/outbound/routing/test.rs+++ b/crates/agent_harness/src/outbound/routing/test.rs@@ -244,6 +244,7 @@ async fn the_cursor_bot_routes_to_cursor_and_everything_else_to_the_sandbox() {let router = RoutedContainerManager::new(sandbox.clone(),cursor.clone(),+ TaggedManager::new("codex"),FixedBotSessions(bot_id::CURSOR_BOT_ID),);@@ -270,6 +271,7 @@ async fn resume_and_teardown_route_by_the_stored_bot() {let router = RoutedContainerManager::new(sandbox.clone(),cursor.clone(),+ TaggedManager::new("codex"),FixedBotSessions(bot_id::CURSOR_BOT_ID),);@@ -287,6 +289,7 @@ async fn a_database_backed_cursor_agent_routes_by_its_stored_harness() {let router = RoutedContainerManager::new(sandbox.clone(),cursor.clone(),+ TaggedManager::new("codex"),FixedBotSessions(BotId::TEST_A),);@@ -300,3 +303,41 @@ async fn a_database_backed_cursor_agent_routes_by_its_stored_harness() {);assert!(sandbox.calls().is_empty());}++#[tokio::test]+async fn codex_routes_all_lifecycle_operations_and_rejects_resize() {+ let sandbox = TaggedManager::new("sandbox");+ let cursor = TaggedManager::new("cursor");+ let codex = TaggedManager::new("codex");+ let router = RoutedContainerManager::new(+ sandbox.clone(),+ cursor.clone(),+ codex.clone(),+ FixedBotSessions(bot_id::CODEX_BOT_ID),+ );+ router+ .spawn(spawn_for(AgentKind::CodexCloud))+ .await+ .unwrap()+ .map_transport(|transport| assert!(matches!(transport, RoutedTransport::Codex(_))));+ let session = AgentSessionId::new();+ router.resume(session).await.unwrap();+ router.session_token(session).await.unwrap();+ router.teardown(session).await.unwrap();+ assert!(router.resize(session, SandboxSize::Default).await.is_err());+ assert_eq!(+ codex.calls(),+ [+ "codex:spawn",+ "codex:resume",+ "codex:session_token",+ "codex:teardown"+ ]+ );+ assert!(sandbox.calls().is_empty());+ assert!(cursor.calls().is_empty());+ assert_eq!(+ AgentKind::from_harness("codex-cloud"),+ AgentKind::CodexCloud+ );+}diff --git a/crates/agent_harness/src/testing/helpers/agent.rs b/crates/agent_harness/src/testing/helpers/agent.rsindex 3fed915fd3..c9518d0afa 100644--- a/crates/agent_harness/src/testing/helpers/agent.rs+++ b/crates/agent_harness/src/testing/helpers/agent.rs@@ -121,6 +121,16 @@ impl FakeAgent {self.sends_reply(id, response);}+ /// Answer the `session/load` this agent received.+ pub fn loads_session(&self, response: agent_client_protocol::schema::v1::LoadSessionResponse) {+ let id = self+ .lock_progress()+ .opening+ .clone()+ .expect("the harness has not sent session/load");+ self.sends_reply(id, response);+ }+/// Wait for and complete the next `session/prompt` request.pub async fn completes_prompt(&self) {let mut received = self.received.subscribe();diff --git a/crates/agent_session/src/domain/pull_request.rs b/crates/agent_session/src/domain/pull_request.rsindex 7797164ba1..b0bf30972c 100644--- a/crates/agent_session/src/domain/pull_request.rs+++ b/crates/agent_session/src/domain/pull_request.rs@@ -5,7 +5,7 @@ use std::pin::Pin;use macro_user_id::user_id::MacroUserIdStr;use super::error::{AgentSessionError, Result};-use super::model::AgentSessionId;+use super::model::{AgentSessionId, SessionClaim};use super::ports::{AgentSessionRealtime, AgentSessionRepo};use tracing::Instrument;@@ -20,17 +20,20 @@ pub trait SessionPullRequests: Send + Sync {session: AgentSessionId,owner: &'a MacroUserIdStr<'static>,url: &'a str,+ claim: Option<SessionClaim>,) -> Pin<Box<dyn Future<Output = Result<String>> + Send + 'a>>;}/// Persist the session's current PR independently of conversation history.pub trait SessionPullRequestRepo: Send + Sync {/// Update only if the current URL differs; return whether the row changed.+ /// A supplied claim must match atomically with the write, even for an unchanged URL.fn record_pull_request(&self,session: AgentSessionId,owner: &MacroUserIdStr<'static>,url: &str,+ claim: Option<SessionClaim>,) -> impl Future<Output = Result<bool>> + Send;}@@ -57,6 +60,7 @@ wheresession: AgentSessionId,owner: &'a MacroUserIdStr<'static>,url: &'a str,+ claim: Option<SessionClaim>,) -> Pin<Box<dyn Future<Output = Result<String>> + Send + 'a>> {let span = tracing::info_span!("agent.session.set_pull_request",@@ -71,7 +75,10 @@ wherereturn Err(AgentSessionError::Forbidden);}let url = canonical_url(url)?;- let changed = self.repo.record_pull_request(session, owner, &url).await?;+ let changed = self+ .repo+ .record_pull_request(session, owner, &url, claim)+ .await?;tracing::Span::current().record("outcome", if changed { "updated" } else { "unchanged" });if changed {diff --git a/crates/agent_session/src/domain/pull_request/test.rs b/crates/agent_session/src/domain/pull_request/test.rsindex ba6483b966..e63437b9b2 100644--- a/crates/agent_session/src/domain/pull_request/test.rs+++ b/crates/agent_session/src/domain/pull_request/test.rs@@ -39,16 +39,18 @@ async fn persists_and_publishes_once_and_rejects_another_owner() {let url = "https://github.com/org/repo/pull/123";let other = MacroUserIdStr::try_from_email("[email protected]").unwrap();assert!(matches!(- service.set_pull_request(session.id, &other, url).await,+ service+ .set_pull_request(session.id, &other, url, None)+ .await,Err(AgentSessionError::Forbidden)));assert!(repo.list_by_session(session.id).await.unwrap().is_empty());service- .set_pull_request(session.id, &session.owner_id, url)+ .set_pull_request(session.id, &session.owner_id, url, None).await.unwrap();service- .set_pull_request(session.id, &session.owner_id, url)+ .set_pull_request(session.id, &session.owner_id, url, None).await.unwrap();assert!(repo.list_by_session(session.id).await.unwrap().is_empty());@@ -66,6 +68,7 @@ async fn persists_and_publishes_once_and_rejects_another_owner() {session.id,&session.owner_id,"https://github.com/org/repo/pull/124",+ None,).await.unwrap();@@ -89,7 +92,7 @@ async fn gateway_failure_does_not_undo_the_persisted_link() {let service = SessionPullRequestService::new(repo.clone(), RecordingRealtime::down());let url = "https://github.com/org/repo/pull/123";service- .set_pull_request(session.id, &session.owner_id, url)+ .set_pull_request(session.id, &session.owner_id, url, None).await.unwrap();assert_eq!(@@ -101,3 +104,41 @@ async fn gateway_failure_does_not_undo_the_persisted_link() {Some(url));}++#[tokio::test]+async fn superseded_claim_cannot_publish_even_an_unchanged_url() {+ use crate::domain::model::ClaimOutcome;+ use crate::domain::model::ReplicaId;+ use crate::domain::ports::SessionOwnership;+ let repo = InMemoryAgentSessionRepo::new();+ let session = test_agent_session(AgentSessionId::new());+ repo.insert_session(session.clone());+ let replica = ReplicaId::mint();+ let ClaimOutcome::Claimed(old) = repo.claim(session.id, replica).await.unwrap() else {+ panic!("claim")+ };+ let ClaimOutcome::Claimed(current) = repo.claim(session.id, replica).await.unwrap() else {+ panic!("reclaim")+ };+ let realtime = RecordingRealtime::new();+ let service = SessionPullRequestService::new(repo.clone(), realtime.clone());+ let current_url = "https://github.com/org/repo/pull/2";+ service+ .set_pull_request(session.id, &session.owner_id, current_url, Some(current))+ .await+ .unwrap();+ for url in ["https://github.com/org/repo/pull/1", current_url] {+ assert!(+ matches!(service.set_pull_request(session.id, &session.owner_id, url, Some(old)).await, Err(AgentSessionError::FencedOut(id)) if id == session.id)+ );+ }+ assert_eq!(+ repo.get(session.id)+ .await+ .unwrap()+ .pull_request_url+ .as_deref(),+ Some(current_url)+ );+ assert_eq!(realtime.updated(), [session.id]);+}diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rsindex c7d08fda25..ad5fb382ab 100644--- a/crates/agent_session/src/inbound/axum_router/test.rs+++ b/crates/agent_session/src/inbound/axum_router/test.rs@@ -789,3 +789,5 @@ async fn an_external_open_carries_its_instructions() {Some(INSTRUCTIONS));}++mod read;diff --git a/crates/agent_session/src/inbound/axum_router/test/read.rs b/crates/agent_session/src/inbound/axum_router/test/read.rsnew file mode 100644index 0000000000..e5e116b25c--- /dev/null+++ b/crates/agent_session/src/inbound/axum_router/test/read.rs@@ -0,0 +1,87 @@+use super::*;+use crate::domain::model::{CreateAgentSessionParams, ReplicaId, SandboxSize};+use crate::domain::ports::{+ AgentSessionRepo, NoOpAgentSessionNameGenerator, NoOpRealtime, NoOpTurnObserver,+ NoopLifecyclePublisher,+};+use crate::domain::service::AgentSessionServiceImpl;+use crate::testing::InMemoryAgentSessionRepo;+async fn view_router() -> Router {+ let repo = InMemoryAgentSessionRepo::new();+ repo.create(CreateAgentSessionParams {+ id: AgentSessionId::TEST_A,+ owner_id: MacroUserIdStr::try_from(OWNER.to_owned()).unwrap(),+ bot_id: BotId::TEST_A,+ thread_id: None,+ originating_message_id: None,+ model: "codex".into(),+ harness: "codex-cloud".into(),+ repo_url: None,+ workspace: String::new(),+ sandbox_size: SandboxSize::Default,+ instructions: None,+ mcp_servers: Default::default(),+ egress_token_hash: None,+ })+ .await+ .unwrap();+ let auth = MacroAuthorizationServiceImpl::new(+ FakeJwtValidator,+ InternalAuthConfig {+ api_key: "test-internal-key".into(),+ default_user_id: None,+ },+ SelfBotAuthorizer,+ NoUserApiKeyAuthorizer,+ );+ agent_session_read_router(AgentSessionRouterState::new(+ AgentSessionServiceImpl::new(+ repo.clone(),+ agent_fold::domain::service::FoldedMessageService::new(repo),+ NoOpRealtime,+ NoOpAgentSessionNameGenerator,+ Arc::new(NoOpTurnObserver),+ Arc::new(NoopLifecyclePublisher),+ ReplicaId::mint(),+ ),+ Arc::new(entity_access::domain::ports::NoOpEntityAccessService),+ MacroAuthorizationState::new(Arc::new(auth)),+ ))+}+#[tokio::test]+async fn unauthorized_view_cannot_read_saved_session() {+ let response = view_router()+ .await+ .oneshot(+ Request::builder()+ .uri(format!("/{}", AgentSessionId::TEST_A))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);+}+#[tokio::test]+async fn detached_session_returns_saved_metadata() {+ let response = view_router()+ .await+ .oneshot(+ Request::builder()+ .uri(format!("/{}", AgentSessionId::TEST_A))+ .header(+ macro_authorization::INTERNAL_API_KEY_HEADER,+ "test-internal-key",+ )+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ let body = axum::body::to_bytes(response.into_body(), 8192)+ .await+ .unwrap();+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(value["id"], AgentSessionId::TEST_A.to_string());+}diff --git a/crates/agent_session/src/inbound/toolset/set_pull_request.rs b/crates/agent_session/src/inbound/toolset/set_pull_request.rsindex e4ade6296e..8361a21230 100644--- a/crates/agent_session/src/inbound/toolset/set_pull_request.rs+++ b/crates/agent_session/src/inbound/toolset/set_pull_request.rs@@ -42,7 +42,7 @@ impl AsyncTool<SessionToolContext> for SetPullRequest {) -> ToolResult<String> {context.service- .set_pull_request(context.session, &request.user_id, &self.url)+ .set_pull_request(context.session, &request.user_id, &self.url, None).await.map_err(|error| ToolCallError {description: error.to_string(),diff --git a/crates/agent_session/src/outbound/postgres/pull_request.rs b/crates/agent_session/src/outbound/postgres/pull_request.rsindex 739b44f5eb..0a919bb86c 100644--- a/crates/agent_session/src/outbound/postgres/pull_request.rs+++ b/crates/agent_session/src/outbound/postgres/pull_request.rs@@ -8,14 +8,40 @@ impl crate::domain::pull_request::SessionPullRequestRepo for PgAgentSessionReposession: AgentSessionId,owner: &MacroUserIdStr<'static>,url: &str,+ claim: Option<SessionClaim>,) -> Result<bool> {+ let mut transaction = self.pool.begin().await.map_err(anyhow::Error::from)?;+ if let Some(claim) = claim {+ if claim.session != session {+ return Err(AgentSessionError::FencedOut(session));+ }+ // Takeover changes this same row, so the claim stays valid through commit.+ let locked = sqlx::query_scalar!(+ r#"+ SELECT id+ FROM agent_session+ WHERE id = $1 AND manager_replica_id = $2 AND manager_fence = $3+ FOR UPDATE+ "#,+ session.as_uuid(),+ claim.replica.as_uuid(),+ claim.fence.0,+ )+ .fetch_optional(&mut *transaction)+ .await+ .map_err(anyhow::Error::from)?;+ if locked.is_none() {+ return Err(AgentSessionError::FencedOut(session));+ }+ }let result = sqlx::query!("UPDATE agent_session SET pull_request_url = $3, modified_at = clock_timestamp() WHERE id = $1 AND owner_id = $2 AND pull_request_url IS DISTINCT FROM $3",session.as_uuid(), owner.as_ref(), url,)- .execute(&self.pool)+ .execute(&mut *transaction).await.map_err(anyhow::Error::from)?;+ transaction.commit().await.map_err(anyhow::Error::from)?;Ok(result.rows_affected() == 1)}}diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rsindex 8530ba0c95..e20201d9d8 100644--- a/crates/agent_session/src/outbound/postgres/test.rs+++ b/crates/agent_session/src/outbound/postgres/test.rs@@ -1835,8 +1835,8 @@ async fn pull_request_is_atomic_and_survives_history_selection(pool: PgPool) {let session = create_session(&repo, new_session(bot, None, None)).await;let url = "https://github.com/org/repo/pull/123";let (first, second) = tokio::join!(- repo.record_pull_request(session.id, &session.owner_id, url),- repo.record_pull_request(session.id, &session.owner_id, url),+ repo.record_pull_request(session.id, &session.owner_id, url, None),+ repo.record_pull_request(session.id, &session.owner_id, url, None),);assert_eq!(usize::from(first.unwrap()) + usize::from(second.unwrap()),@@ -1878,7 +1878,7 @@ async fn pull_request_is_atomic_and_survives_history_selection(pool: PgPool) {);assert!(!repo- .record_pull_request(session.id, &session.owner_id, url)+ .record_pull_request(session.id, &session.owner_id, url, None).await.unwrap());@@ -1918,3 +1918,71 @@ async fn rotating_a_session_credential_revokes_the_previous_one(pool: PgPool) {session.id);}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn pull_request_waiting_on_takeover_cannot_overwrite_successor(pool: PgPool) {+ use crate::domain::pull_request::SessionPullRequestRepo;+ let repo = PgAgentSessionRepo::new(pool.clone());+ let bot = create_test_bot(&pool).await;+ let session = create_session(&repo, new_session(bot, None, None)).await;+ let ClaimOutcome::Claimed(old) = repo.claim(session.id, ReplicaId::mint()).await.unwrap()+ else {+ panic!("claim")+ };+ let original_url = "https://github.com/org/repo/pull/1";+ assert!(+ repo.record_pull_request(session.id, &session.owner_id, original_url, Some(old))+ .await+ .unwrap()+ );+ assert!(+ !repo+ .record_pull_request(session.id, &session.owner_id, original_url, Some(old))+ .await+ .unwrap()+ );+ // A takeover holds the same row lock as PR publication until commit.+ let mut takeover = pool.begin().await.unwrap();+ sqlx::query!("UPDATE agent_session SET manager_fence = manager_fence + 1, pull_request_url = $2 WHERE id = $1", session.id.as_uuid(), "https://github.com/org/repo/pull/2")+ .execute(&mut *takeover).await.unwrap();+ let stale_repo = repo.clone();+ let owner = session.owner_id.clone();+ let mut stale = tokio::spawn(async move {+ stale_repo+ .record_pull_request(+ session.id,+ &owner,+ "https://github.com/org/repo/pull/1",+ Some(old),+ )+ .await+ });+ assert!(+ tokio::time::timeout(std::time::Duration::from_millis(50), &mut stale)+ .await+ .is_err(),+ "publication must wait for the locked ownership row"+ );+ takeover.commit().await.unwrap();+ assert!(+ matches!(stale.await.unwrap(), Err(AgentSessionError::FencedOut(id)) if id == session.id)+ );+ assert_eq!(+ AgentSessionRepo::get(&repo, session.id)+ .await+ .unwrap()+ .pull_request_url+ .as_deref(),+ Some("https://github.com/org/repo/pull/2")+ );+ assert!(matches!(+ repo.record_pull_request(+ session.id,+ &session.owner_id,+ "https://github.com/org/repo/pull/2",+ Some(old)+ )+ .await,+ Err(AgentSessionError::FencedOut(_))+ ));+}diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rsindex c56e1f78d5..02ecb5fda0 100644--- a/crates/agent_session/src/testing.rs+++ b/crates/agent_session/src/testing.rs@@ -855,7 +855,18 @@ impl crate::domain::pull_request::SessionPullRequestRepo for InMemoryAgentSessiosession: AgentSessionId,owner: &MacroUserIdStr<'static>,url: &str,+ claim: Option<SessionClaim>,) -> Result<bool> {+ // Keep the claim lock through the mutation, matching the PostgreSQL row lock.+ let leases = self.leases.lock().unwrap();+ if let Some(claim) = claim+ && (claim.session != session+ || !leases.get(&session).is_some_and(|(replica, fence)| {+ *replica == Some(claim.replica) && *fence == claim.fence.0+ }))+ {+ return Err(AgentSessionError::FencedOut(session));+ }let mut sessions = self.sessions.lock().unwrap();let stored = sessions.get_mut(&session)diff --git a/crates/bot_id/src/lib.rs b/crates/bot_id/src/lib.rsindex 1a8d5ded17..3aad6e6592 100644--- a/crates/bot_id/src/lib.rs+++ b/crates/bot_id/src/lib.rs@@ -115,6 +115,13 @@ pub const CURSOR_HANDLE: &str = "cursor";/// Display name for the "Cursor" system bot.pub const CURSOR_NAME: &str = "Cursor";+/// Stable identity for the per-owner Codex cloud agent.+pub const CODEX_BOT_ID: BotId = BotId::new_from_uuid(Uuid::from_u128(0xc0de));+/// Mention handle for Codex.+pub const CODEX_HANDLE: &str = "codex";+/// Display name for Codex.+pub const CODEX_NAME: &str = "Codex";+/// Stable handle for the autonomous Macro platform principal.pub const MACRO_SYSTEM_HANDLE: &str = "macro-system";@@ -166,6 +173,12 @@ pub const SYSTEM_BOTS: &[SystemBot] = &[handle: CURSOR_HANDLE,has_agent: true,},+ SystemBot {+ id: CODEX_BOT_ID,+ name: CODEX_NAME,+ handle: CODEX_HANDLE,+ has_agent: true,+ },// Posts as itself for autonomous platform operations, but nothing mentions// it and it opens no sessions.SystemBot {diff --git a/crates/codex_cloud_agents/Cargo.toml b/crates/codex_cloud_agents/Cargo.tomlnew file mode 100644index 0000000000..fe998c66a3--- /dev/null+++ b/crates/codex_cloud_agents/Cargo.toml@@ -0,0 +1,38 @@+[package]+name = "codex_cloud_agents"+version = "0.1.0"+edition = "2024"+publish = false++[features]+postgres = ["dep:agent_session", "dep:sqlx"]++[[bin]]+name = "codex-cloud-probe"+path = "src/main.rs"++[dependencies]+agent_runtime_protocol = { path = "../agent_runtime_protocol" }+agent_session = { path = "../agent_session", optional = true }+sqlx = { workspace = true, optional = true }+agent-client-protocol = { workspace = true }+base64 = { workspace = true }+clap = { workspace = true }+futures = { workspace = true }+lazy-regex = { workspace = true }+reqwest = { workspace = true, features = ["stream"] }+rootcause = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+tempfile = { workspace = true }+tokio = { workspace = true, features = ["signal", "time", "io-std", "io-util", "sync"] }+tokio-util = { workspace = true, features = ["compat"] }+uuid = { workspace = true }+zeroize = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+agent_fold = { path = "../agent_fold", default-features = false }+axum = { workspace = true }+insta = { version = "1.48.0", features = ["json"] }+tokio = { workspace = true, features = ["net", "test-util"] }diff --git a/crates/codex_cloud_agents/src/bin/codex_acp.rs b/crates/codex_cloud_agents/src/bin/codex_acp.rsnew file mode 100644index 0000000000..bfd674ec7d--- /dev/null+++ b/crates/codex_cloud_agents/src/bin/codex_acp.rs@@ -0,0 +1,222 @@+//! Zed stdio ACP composition root using the dedicated direct-OAuth state.+use clap::Parser;+use codex_cloud_agents::domain::acp_session::{SessionStore, StoredSession};+use codex_cloud_agents::domain::cloud::TurnId;+use codex_cloud_agents::domain::journal::{JournalEntry, JournalInput};+use serde::{Deserialize, Serialize};+use std::{+ io::{Read as _, Write as _},+ path::{Path, PathBuf},+};++use codex_cloud_agents::domain::{Probe, acp_session::SessionService, cloud::CloudId};+use codex_cloud_agents::outbound::openai::OpenAi;+#[path = "../credentials.rs"]+mod credentials;+use credentials::JsonStore;+use std::process::ExitCode;+use std::sync::Arc;++#[derive(Parser)]+#[command(version, about = "Run Codex cloud sessions over stdio ACP")]+struct Args {+ /// Private directory used by codex-cloud-probe login.+ #[arg(long)]+ state_dir: PathBuf,+ /// Codex cloud environment ID.+ #[arg(long)]+ environment: String,+ /// Repository branch to start cloud sessions from.+ #[arg(long)]+ branch: String,+}++#[tokio::main]+async fn main() -> ExitCode {+ match run(Args::parse()).await {+ Ok(()) => ExitCode::SUCCESS,+ Err(error) => {+ eprintln!("codex_acp: {error}");+ ExitCode::FAILURE+ }+ }+}+async fn run(args: Args) -> Result<(), rootcause::Report> {+ let root = &args.state_dir;+ let store = JsonStore::open(root)?;+ let probe = Arc::new(Probe::new(OpenAi::new()?, store));+ if probe.status()?.is_none() {+ return Err(rootcause::report!(+ "run codex-cloud-probe --state-dir <same directory> login before starting codex_acp"+ ));+ }+ eprintln!(+ "codex_acp: cloud environment {} on branch {}; tools run remotely",+ args.environment, args.branch+ );+ let service = Arc::new(SessionService::new(+ probe,+ JsonSessionStore::open(root)?,+ Some(codex_cloud_agents::domain::runtime::CloudTarget {+ environment: CloudId::new(args.environment)?,+ branch: args.branch,+ repository_url: None,+ }),+ ));+ codex_cloud_agents::inbound::acp::serve(service, tokio::io::stdin(), tokio::io::stdout(), None)+ .await+ .map_err(|e| rootcause::report!("ACP transport: {e}"))+}++// Demo-only session journal; production sessions use PostgreSQL.+/// File journal under the explicitly configured private state directory.+struct JsonSessionStore {+ directory: PathBuf,+ gate: tokio::sync::Mutex<()>,+}+#[derive(Serialize, Deserialize)]+struct DemoJournal {+ state: StoredSession,+ inputs: Vec<JournalEntry>,+}+impl JsonSessionStore {+ /// Create the journal directory under a previously validated private state root.+ fn open(root: &Path) -> Result<Self, rootcause::Report> {+ let directory = root.join("sessions");+ if !directory.exists() {+ use std::os::unix::fs::DirBuilderExt as _;+ std::fs::DirBuilder::new().mode(0o700).create(&directory)?;+ }+ let metadata = std::fs::symlink_metadata(&directory)?;+ use std::os::unix::fs::PermissionsExt as _;+ if !metadata.is_dir()+ || metadata.file_type().is_symlink()+ || metadata.permissions().mode() & 0o077 != 0+ {+ return Err(rootcause::report!(+ "session directory must be private and not a symlink"+ ));+ }+ Ok(Self {+ directory,+ gate: tokio::sync::Mutex::new(()),+ })+ }+ fn path(&self, id: &str) -> Result<PathBuf, rootcause::Report> {+ let parsed = uuid::Uuid::parse_str(id)+ .map_err(|_| rootcause::report!("invalid session identifier"))?;+ if parsed.to_string() != id {+ return Err(rootcause::report!("noncanonical session identifier"));+ }+ Ok(self.directory.join(format!("{id}.json")))+ }+ fn read_file(&self, id: &str) -> Result<Option<DemoJournal>, rootcause::Report> {+ let path = self.path(id)?;+ let metadata = match std::fs::symlink_metadata(&path) {+ Ok(metadata) => metadata,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(error) => return Err(error.into()),+ };+ use std::os::unix::fs::PermissionsExt as _;+ if !metadata.is_file()+ || metadata.file_type().is_symlink()+ || metadata.permissions().mode() & 0o077 != 0+ {+ return Err(rootcause::report!(+ "session journal must be a private regular file"+ ));+ }+ const MAX_JOURNAL_BYTES: u64 = 64 * 1024 * 1024;+ let mut bytes = Vec::new();+ std::fs::File::open(path)?+ .take(MAX_JOURNAL_BYTES + 1)+ .read_to_end(&mut bytes)?;+ if bytes.len() as u64 > MAX_JOURNAL_BYTES {+ return Err(rootcause::report!("session journal exceeds size limit"));+ }+ let journal: DemoJournal = serde_json::from_slice(&bytes)+ .map_err(|_| rootcause::report!("invalid demo journal"))?;+ if journal+ .inputs+ .iter()+ .enumerate()+ .any(|(index, entry)| entry.sequence != index as i64 + 1)+ {+ return Err(rootcause::report!("incomplete demo journal"));+ }+ Ok(Some(journal))+ }+ fn write_file(&self, id: &str, journal: &DemoJournal) -> Result<(), rootcause::Report> {+ let path = self.path(id)?;+ let mut temporary = tempfile::NamedTempFile::new_in(&self.directory)?;+ let bytes = serde_json::to_vec(journal)?;+ if bytes.len() > 64 * 1024 * 1024 {+ return Err(rootcause::report!(+ "session journal exceeds size limit; local observation stopped"+ ));+ }+ temporary.write_all(&bytes)?;+ temporary.flush()?;+ temporary.as_file().sync_all()?;+ temporary+ .persist(path)+ .map_err(|_| rootcause::report!("could not persist session journal"))?;+ std::fs::File::open(&self.directory)?.sync_all()?;+ Ok(())+ }+}+impl SessionStore for JsonSessionStore {+ async fn load(&self, id: &str) -> Result<Option<StoredSession>, rootcause::Report> {+ let _gate = self.gate.lock().await;+ Ok(self.read_file(id)?.map(|journal| journal.state))+ }+ async fn save(&self, id: &str, state: &StoredSession) -> Result<(), rootcause::Report> {+ let _gate = self.gate.lock().await;+ let mut journal = self.read_file(id)?.unwrap_or_else(|| DemoJournal {+ state: StoredSession::default(),+ inputs: Vec::new(),+ });+ journal.state = state.clone();+ self.write_file(id, &journal)+ }+ async fn read(&self, id: &str) -> Result<Vec<JournalEntry>, rootcause::Report> {+ let _gate = self.gate.lock().await;+ Ok(self+ .read_file(id)?+ .map(|journal| journal.inputs)+ .unwrap_or_default())+ }+ async fn append(+ &self,+ id: &str,+ expected: i64,+ turn: Option<&TurnId>,+ input: &JournalInput,+ ) -> Result<JournalEntry, rootcause::Report> {+ let _gate = self.gate.lock().await;+ let mut journal = self+ .read_file(id)?+ .ok_or_else(|| rootcause::report!("unknown demo session"))?;+ let high = journal.inputs.last().map_or(0, |entry| entry.sequence);+ if high != expected {+ return Err(rootcause::report!("demo journal sequence changed"));+ }+ let entry = JournalEntry {+ sequence: high+ .checked_add(1)+ .ok_or_else(|| rootcause::report!("demo journal sequence overflow"))?,+ turn: turn.cloned(),+ input: input.clone(),+ };+ journal.inputs.push(entry.clone());+ self.write_file(id, &journal)?;+ Ok(entry)+ }+ async fn validate(&self) -> Result<(), rootcause::Report> {+ Ok(())+ }+}++#[cfg(test)]+#[path = "codex_acp/test.rs"]+mod test;diff --git a/crates/codex_cloud_agents/src/bin/codex_acp/test.rs b/crates/codex_cloud_agents/src/bin/codex_acp/test.rsnew file mode 100644index 0000000000..8d299b2e9d--- /dev/null+++ b/crates/codex_cloud_agents/src/bin/codex_acp/test.rs@@ -0,0 +1,113 @@+use super::*;+use std::os::unix::fs::PermissionsExt as _;+#[tokio::test]+async fn atomic_private_roundtrip_and_path_validation() {+ let root = tempfile::tempdir().unwrap();+ let store = JsonSessionStore::open(root.path()).unwrap();+ let id = uuid::Uuid::now_v7().to_string();+ let mut state = StoredSession {+ task: Some("task_1".into()),+ ..StoredSession::default()+ };+ store.save(&id, &state).await.unwrap();+ store+ .append(&id, 0, None, &JournalInput::HistoryComplete)+ .await+ .unwrap();+ assert_eq!(+ store.load(&id).await.unwrap().unwrap().task,+ Some("task_1".into())+ );+ assert_eq!(+ std::fs::metadata(store.path(&id).unwrap())+ .unwrap()+ .permissions()+ .mode()+ & 0o077,+ 0+ );+ state.uncertain_write = true;+ store.save(&id, &state).await.unwrap();+ assert!(store.load(&id).await.unwrap().unwrap().uncertain_write);+ assert_eq!(+ store.read(&id).await.unwrap().len(),+ 1,+ "metadata saves retain native history"+ );+ assert!(+ store+ .append(&id, 0, None, &JournalInput::HistoryComplete)+ .await+ .is_err()+ );+ assert!(store.load("../../credentials").await.is_err());+ std::fs::write(store.path(&id).unwrap(), b"{ secret broken json").unwrap();+ let error = store.load(&id).await.err().unwrap().to_string();+ assert!(!error.contains("secret"));+}++#[tokio::test]+async fn missing_input_journal_is_rejected() {+ let root = tempfile::tempdir().unwrap();+ let store = JsonSessionStore::open(root.path()).unwrap();+ let id = uuid::Uuid::now_v7().to_string();+ store.save(&id, &StoredSession::default()).await.unwrap();+ std::fs::write(+ store.path(&id).unwrap(),+ serde_json::to_vec(&StoredSession::default()).unwrap(),+ )+ .unwrap();+ assert!(+ store+ .load(&id)+ .await+ .err()+ .unwrap()+ .to_string()+ .contains("invalid demo journal")+ );+}+#[tokio::test]+async fn rejects_symlink_and_public_journals() {+ let root = tempfile::tempdir().unwrap();+ let store = JsonSessionStore::open(root.path()).unwrap();+ let id = uuid::Uuid::now_v7().to_string();+ store.save(&id, &StoredSession::default()).await.unwrap();+ let path = store.path(&id).unwrap();+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();+ assert!(store.load(&id).await.is_err());+ std::fs::remove_file(&path).unwrap();+ std::os::unix::fs::symlink(root.path().join("credentials.json"), &path).unwrap();+ assert!(store.load(&id).await.is_err());+}++#[test]+fn cli_requires_explicit_state_environment_and_branch() {+ use clap::CommandFactory as _;+ Args::command().debug_assert();+ let invocation = [+ "codex_acp",+ "--state-dir",+ "/tmp/probe",+ "--environment",+ "env-test",+ "--branch",+ "test-branch",+ ];+ let args = Args::try_parse_from(invocation).unwrap();+ assert_eq!(args.state_dir, PathBuf::from("/tmp/probe"));+ assert_eq!(args.environment, "env-test");+ assert_eq!(args.branch, "test-branch");+ for missing in [1, 3, 5] {+ let incomplete: Vec<_> = invocation+ .iter()+ .enumerate()+ .filter(|(index, _)| *index != missing && *index != missing + 1)+ .map(|(_, value)| *value)+ .collect();+ assert_eq!(+ Args::try_parse_from(incomplete).err().unwrap().kind(),+ clap::error::ErrorKind::MissingRequiredArgument+ );+ }+}diff --git a/crates/codex_cloud_agents/src/credentials.rs b/crates/codex_cloud_agents/src/credentials.rsnew file mode 100644index 0000000000..ac2457b0e2--- /dev/null+++ b/crates/codex_cloud_agents/src/credentials.rs@@ -0,0 +1,151 @@+//! Private JSON credential file with atomic writes and a command-lifetime lock.++use codex_cloud_agents::domain::{CredentialStore, Credentials};+use std::fs::{File, OpenOptions};+use std::io::{Read as _, Write as _};+use std::path::{Path, PathBuf};++#[cfg(test)]+#[path = "credentials/test.rs"]+mod test;++const AUTH_FILE: &str = "credentials.json";+const MAX_FILE: u64 = 1024 * 1024;++/// Single-user local store. The file lock prevents competing refresh writers.+pub struct JsonStore {+ directory: PathBuf,+ lock: File,+}++impl JsonStore {+ /// Open an explicit private directory, refusing symlinks and broad permissions.+ /// Unix only: this probe does not claim Windows ACL protection.+ pub fn open(directory: &Path) -> Result<Self, rootcause::Report> {+ if !directory.is_absolute() {+ return Err(rootcause::report!("--state-dir must be an absolute path"));+ }+ private_directory(directory)?;+ let lock_path = directory.join(".lock");+ if lock_path.exists() || lock_path.is_symlink() {+ check_private(&lock_path, false)?;+ }+ let mut options = OpenOptions::new();+ options.read(true).write(true).create(true).truncate(false);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt as _;+ options.mode(0o600);+ }+ let lock = options.open(lock_path)?;+ lock.try_lock().map_err(|_| {+ rootcause::report!("another probe command is using this state directory")+ })?;+ Ok(Self {+ directory: directory.to_owned(),+ lock,+ })+ }+}++impl Drop for JsonStore {+ fn drop(&mut self) {+ // Closing only this descriptor does not release a flock while a forked+ // child or duplicated descriptor retains the same open-file description.+ // Explicit unlock ends the store's ownership before File closes below.+ let _ = self.lock.unlock();+ }+}++impl CredentialStore for JsonStore {+ fn load(&self) -> Result<Option<Credentials>, rootcause::Report> {+ let path = self.directory.join(AUTH_FILE);+ match std::fs::symlink_metadata(&path) {+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(error) => return Err(error.into()),+ Ok(_) => check_private(&path, false)?,+ }+ let mut bytes = zeroize::Zeroizing::new(Vec::new());+ File::open(path)?+ .take(MAX_FILE + 1)+ .read_to_end(&mut bytes)?;+ if bytes.len() as u64 > MAX_FILE {+ return Err(rootcause::report!("credential file exceeds 1 MiB limit"));+ }+ let credentials: Credentials = serde_json::from_slice(&bytes)+ .map_err(|_| rootcause::report!("invalid credential JSON (contents withheld)"))?;+ credentials.validate()?;+ Ok(Some(credentials))+ }++ fn save(&self, credentials: &Credentials) -> Result<(), rootcause::Report> {+ credentials.validate()?;+ let path = self.directory.join(AUTH_FILE);+ if path.exists() || path.is_symlink() {+ check_private(&path, false)?;+ }+ let mut temporary = tempfile::NamedTempFile::new_in(&self.directory)?;+ let bytes = zeroize::Zeroizing::new(serde_json::to_vec_pretty(credentials)?);+ temporary.write_all(&bytes)?;+ temporary.write_all(b"\n")?;+ temporary.as_file().sync_all()?;+ temporary+ .persist(&path)+ .map_err(|_| rootcause::report!("could not atomically save credentials"))?;+ File::open(&self.directory)?.sync_all()?;+ Ok(())+ }++ fn clear(&self) -> Result<(), rootcause::Report> {+ let path = self.directory.join(AUTH_FILE);+ if path.exists() || path.is_symlink() {+ check_private(&path, false)?;+ std::fs::remove_file(path)?;+ File::open(&self.directory)?.sync_all()?;+ }+ Ok(())+ }+}++fn private_directory(path: &Path) -> Result<(), rootcause::Report> {+ #[cfg(unix)]+ {+ use std::os::unix::fs::DirBuilderExt as _;+ if !path.exists() && !path.is_symlink() {+ std::fs::DirBuilder::new()+ .recursive(true)+ .mode(0o700)+ .create(path)?;+ }+ check_private(path, true)+ }+ #[cfg(not(unix))]+ {+ let _ = path;+ Err(rootcause::report!(+ "private JSON storage currently requires Unix"+ ))+ }+}++fn check_private(path: &Path, directory: bool) -> Result<(), rootcause::Report> {+ let metadata = std::fs::symlink_metadata(path)?;+ if metadata.file_type().is_symlink()+ || (directory && !metadata.is_dir())+ || (!directory && !metadata.is_file())+ {+ return Err(rootcause::report!(+ "state path must be a regular private directory/file, not a symlink"+ ));+ }+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt as _;+ if metadata.permissions().mode() & 0o077 != 0 {+ return Err(rootcause::report!(+ "state permissions are too broad; directory needs 0700 and files 0600"+ ));+ }+ }+ Ok(())+}diff --git a/crates/codex_cloud_agents/src/credentials/test.rs b/crates/codex_cloud_agents/src/credentials/test.rsnew file mode 100644index 0000000000..2ad95a2144--- /dev/null+++ b/crates/codex_cloud_agents/src/credentials/test.rs@@ -0,0 +1,110 @@+use super::*;+use codex_cloud_agents::domain::Secret;+use std::os::unix::fs::{PermissionsExt as _, symlink};++fn credentials() -> Credentials {+ Credentials {+ version: 1,+ access_token: Secret::new("test-access".to_owned()).unwrap(),+ refresh_token: Secret::new("test-refresh".to_owned()).unwrap(),+ expires_at: 12345,+ account_id: "account-test".to_owned(),+ }+}++#[test]+fn json_round_trip_private_permissions_atomic_replace_and_logout() {+ let root = tempfile::tempdir().unwrap();+ let directory = root.path().join("state");+ let store = JsonStore::open(&directory).unwrap();+ assert!(store.load().unwrap().is_none());+ store.save(&credentials()).unwrap();+ let saved = store.load().unwrap().unwrap();+ assert_eq!(saved.refresh_token.expose(), "test-refresh");+ assert_eq!(+ std::fs::metadata(&directory).unwrap().permissions().mode() & 0o777,+ 0o700+ );+ assert_eq!(+ std::fs::metadata(directory.join(AUTH_FILE))+ .unwrap()+ .permissions()+ .mode()+ & 0o777,+ 0o600+ );+ let mut next = credentials();+ next.refresh_token = Secret::new("rotated".to_owned()).unwrap();+ store.save(&next).unwrap();+ assert_eq!(+ store.load().unwrap().unwrap().refresh_token.expose(),+ "rotated"+ );+ assert_eq!(std::fs::read_dir(&directory).unwrap().count(), 2);+ store.clear().unwrap();+ store.clear().unwrap();+ assert!(store.load().unwrap().is_none());+}++#[test]+fn lock_excludes_second_command_and_releases_on_drop() {+ let root = tempfile::tempdir().unwrap();+ let directory = root.path().join("state");+ let first = JsonStore::open(&directory).unwrap();+ assert!(JsonStore::open(&directory).is_err());+ drop(first);+ JsonStore::open(&directory).expect("dropping the first store releases its lock immediately");+}++#[test]+fn refuses_symlink_and_public_directory_without_chmodding_it() {+ let root = tempfile::tempdir().unwrap();+ let public = root.path().join("public");+ std::fs::create_dir(&public).unwrap();+ std::fs::set_permissions(&public, std::fs::Permissions::from_mode(0o755)).unwrap();+ assert!(JsonStore::open(&public).is_err());+ assert_eq!(+ std::fs::metadata(&public).unwrap().permissions().mode() & 0o777,+ 0o755+ );+ let link = root.path().join("link");+ symlink(&public, &link).unwrap();+ assert!(JsonStore::open(&link).is_err());+}++#[test]+fn refuses_credential_symlink_and_withholds_corrupt_file_contents() {+ let root = tempfile::tempdir().unwrap();+ let directory = root.path().join("state");+ let store = JsonStore::open(&directory).unwrap();+ let path = directory.join(AUTH_FILE);+ symlink(root.path().join("missing"), &path).unwrap();+ assert!(store.load().is_err());+ assert!(store.save(&credentials()).is_err());+ std::fs::remove_file(&path).unwrap();+ store.save(&credentials()).unwrap();+ std::fs::write(&path, "secret-marker invalid JSON").unwrap();+ let error = store.load().err().unwrap().to_string();+ assert!(!error.contains("secret-marker"));+}++#[test]+fn drop_releases_lock_even_while_a_duplicate_descriptor_survives() {+ let root = tempfile::tempdir().unwrap();+ let directory = root.path().join("state");+ let first = JsonStore::open(&directory).unwrap();+ // A clone shares the open-file description just as fork inheritance does,+ // reproducing the lifetime race without forking a multithreaded test process.+ let inherited = first.lock.try_clone().unwrap();+ assert!(JsonStore::open(&directory).is_err());+ drop(first);+ let second =+ JsonStore::open(&directory).expect("store drop unlocks despite the surviving duplicate");+ drop(inherited);+ assert!(+ JsonStore::open(&directory).is_err(),+ "the old descriptor must not release the new owner's lock"+ );+ drop(second);+ JsonStore::open(&directory).expect("the second owner releases its lock");+}diff --git a/crates/codex_cloud_agents/src/domain.rs b/crates/codex_cloud_agents/src/domain.rsnew file mode 100644index 0000000000..08a1c74487--- /dev/null+++ b/crates/codex_cloud_agents/src/domain.rs@@ -0,0 +1,244 @@+//! Device-login lifecycle independent of HTTP and filesystem implementation.++use serde::{Deserialize, Serialize};+use std::time::{Duration, SystemTime, UNIX_EPOCH};+use zeroize::Zeroize;++#[cfg(test)]+mod test;++/// Durable cloud conversation orchestration for ACP clients.+pub mod acp_session;+/// Cloud task commands and observations used by the feasibility probe.+pub mod cloud;+/// Native append-only inputs and deterministic replay.+pub mod journal;++/// An opaque secret. It deliberately has no Debug or Display implementation.+#[derive(Serialize, Deserialize)]+#[serde(transparent)]+pub struct Secret(String);++impl Secret {+ /// Validate an opaque token without including its value in errors.+ pub fn new(value: String) -> Result<Self, rootcause::Report> {+ if value.is_empty() || value.len() > 128 * 1024 || value.chars().any(char::is_control) {+ return Err(rootcause::report!("invalid credential value"));+ }+ Ok(Self(value))+ }++ /// Expose only at the provider or persistence boundary.+ pub fn expose(&self) -> &str {+ &self.0+ }+}++impl Drop for Secret {+ fn drop(&mut self) {+ self.0.zeroize();+ }+}++/// ChatGPT OAuth credentials, kept private by the chosen credential adapter.+#[derive(Serialize, Deserialize)]+pub struct Credentials {+ /// Format version, checked on load.+ pub version: u8,+ /// Bearer credential.+ pub access_token: Secret,+ /// Rotating refresh credential.+ pub refresh_token: Secret,+ /// Unix seconds at which the access token expires.+ pub expires_at: u64,+ /// Account identifier extracted from the trusted token exchange response.+ /// This metadata is not independent JWT identity verification.+ pub account_id: String,+}++impl Credentials {+ /// Reject malformed credential state before provider use.+ pub fn validate(&self) -> Result<(), rootcause::Report> {+ if self.version != 1+ || self.expires_at == 0+ || self.account_id.is_empty()+ || self.account_id.len() > 256+ || !self+ .account_id+ .bytes()+ .all(|c| c.is_ascii_alphanumeric() || b"-_".contains(&c))+ || self.access_token.expose().is_empty()+ || self.refresh_token.expose().is_empty()+ || self.access_token.expose().chars().any(char::is_control)+ || self.refresh_token.expose().chars().any(char::is_control)+ {+ return Err(rootcause::report!(+ "invalid stored credentials; log in again"+ ));+ }+ Ok(())+ }+}++/// Pending device login. Never log this structure as a whole.+pub struct DeviceLogin {+ /// URL shown to the account holder.+ pub verification_url: String,+ /// Short one-time code shown to the account holder.+ pub user_code: String,+ /// Private handle used for polling.+ pub device_auth_id: Secret,+ /// Minimum delay between polling requests.+ pub interval: Duration,+ /// Maximum local waiting period.+ pub timeout: Duration,+}++/// Result of a single device poll.+pub enum LoginPoll {+ /// OpenAI has not completed the browser verification.+ Pending,+ /// Tokens have been exchanged successfully.+ Complete(Credentials),+}++/// Provider operations needed for this first feasibility milestone.+pub trait OAuth: Send + Sync {+ /// Begin a fresh device authorization.+ fn begin(&self) -> impl Future<Output = Result<DeviceLogin, rootcause::Report>> + Send;+ /// Poll once and exchange an authorization code when available.+ fn poll(+ &self,+ login: &DeviceLogin,+ ) -> impl Future<Output = Result<LoginPoll, rootcause::Report>> + Send;+ /// Rotate an expired access credential.+ fn refresh(+ &self,+ current: &Credentials,+ ) -> impl Future<Output = Result<Credentials, rootcause::Report>> + Send;+ /// Read safe environment metadata using this account.+ fn environments(+ &self,+ credentials: &Credentials,+ ) -> impl Future<Output = Result<Vec<Environment>, rootcause::Report>> + Send;+}++/// Safe subset of a cloud environment; never prints setup scripts or secrets.+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]+pub struct Environment {+ /// Provider identifier.+ pub id: String,+ /// Human-readable label, if present.+ pub label: Option<String>,+ /// Ordered, validated repositories; empty when complete metadata is unavailable.+ pub repositories: Vec<EnvironmentRepository>,+}++/// Repository identity projected from provider metadata, never from an environment label.+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]+pub struct EnvironmentRepository {+ /// Provider owner/repository name.+ pub full_name: String,+ /// HTTPS clone URL without credentials, query, or fragment.+ pub clone_url: String,+ /// Provider default branch.+ pub default_branch: String,+}++/// Local persistence, exclusively locked by its composition root for a command.+pub trait CredentialStore {+ /// Load the probe's credentials only.+ fn load(&self) -> Result<Option<Credentials>, rootcause::Report>;+ /// Atomically replace credentials.+ fn save(&self, credentials: &Credentials) -> Result<(), rootcause::Report>;+ /// Delete only this probe's saved credentials.+ fn clear(&self) -> Result<(), rootcause::Report>;+}++/// Orchestrates login and refresh while preserving account binding.+pub struct Probe<Provider, Store> {+ provider: Provider,+ store: Store,+ refresh_lock: tokio::sync::Mutex<()>,+}++impl<Provider: OAuth, Store: CredentialStore> Probe<Provider, Store> {+ /// Compose independently testable provider and storage adapters.+ pub fn new(provider: Provider, store: Store) -> Self {+ Self {+ provider,+ store,+ refresh_lock: tokio::sync::Mutex::new(()),+ }+ }++ /// Start a fresh login without overwriting an existing connection.+ pub async fn begin_login(&self) -> Result<DeviceLogin, rootcause::Report> {+ if self.store.load()?.is_some() {+ return Err(rootcause::report!(+ "already connected; run logout before switching accounts"+ ));+ }+ self.provider.begin().await+ }++ /// Await verification, then persist once. Dropping the future cancels local waiting.+ pub async fn finish_login(&self, login: &DeviceLogin) -> Result<(), rootcause::Report> {+ let wait = async {+ loop {+ match self.provider.poll(login).await? {+ LoginPoll::Complete(credentials) => {+ credentials.validate()?;+ return self.store.save(&credentials);+ }+ LoginPoll::Pending => tokio::time::sleep(login.interval).await,+ }+ }+ };+ tokio::time::timeout(login.timeout, wait)+ .await+ .map_err(|_| rootcause::report!("device login expired; run login again"))?+ }++ /// Inspect local state; no network request or token refresh.+ pub fn status(&self) -> Result<Option<Credentials>, rootcause::Report> {+ self.store.load()+ }++ /// Forget local credentials; does not revoke or cancel anything at OpenAI.+ pub fn logout(&self) -> Result<(), rootcause::Report> {+ self.store.clear()+ }++ /// Query cloud environments, refreshing expiring credentials once beforehand.+ pub async fn environments(&self, now: u64) -> Result<Vec<Environment>, rootcause::Report> {+ let credentials = self.credentials(now).await?;+ self.provider.environments(&credentials).await+ }++ async fn credentials(&self, now: u64) -> Result<Credentials, rootcause::Report> {+ let _refresh_guard = self.refresh_lock.lock().await;+ let mut credentials = self+ .store+ .load()?+ .ok_or_else(|| rootcause::report!("not connected; run login first"))?;+ if credentials.expires_at <= now.saturating_add(60) {+ let refreshed = self.provider.refresh(&credentials).await?;+ refreshed.validate()?;+ if refreshed.account_id != credentials.account_id {+ return Err(rootcause::report!("refresh changed account; log in again"));+ }+ self.store.save(&refreshed)?;+ credentials = refreshed;+ }+ Ok(credentials)+ }+}++/// Current Unix seconds for the CLI composition root.+pub fn unix_now() -> Result<u64, rootcause::Report> {+ Ok(SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs())+}++/// Authenticated cloud operation port for local and hosted runtimes.+pub mod runtime;diff --git a/crates/codex_cloud_agents/src/domain/acp_session.rs b/crates/codex_cloud_agents/src/domain/acp_session.rsnew file mode 100644index 0000000000..7db1d5c627--- /dev/null+++ b/crates/codex_cloud_agents/src/domain/acp_session.rs@@ -0,0 +1,751 @@+//! Serial cloud conversations, durable launch receipts, and provider-grounded completion.+use super::cloud::{CloudEvent, CloudId, Launch, NativeRecord, TurnId};+use super::journal::{JournalEntry, JournalInput, ReplayMachine};+use super::runtime::{CloudRuntime, CloudTarget};+mod metadata;+use futures::StreamExt as _;+use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use std::sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+};+use std::time::Duration;+use tokio::sync::Mutex;++/// Durable conversation state. Pending writes are never retried automatically.+#[derive(Clone, Default, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct StoredSession {+ /// Account binding prevents replay after switching OAuth accounts.+ pub account_id: String,+ /// Connection generation pinned for hosted account reconnects.+ pub connection_id: String,+ /// Destination pinned before the first cloud submission; absent until selection succeeds.+ pub target: Option<CloudTarget>,+ /// The single remote task backing this conversation.+ pub task: Option<String>,+ /// Latest assistant turn used as the parent for continuation.+ pub turn: Option<String>,+ /// A write began without a durably recorded receipt.+ pub uncertain_write: bool,+}+/// Persistence boundary for conversation identity and replay.+pub trait SessionStore: Send + Sync {+ /// Read a previously created session.+ fn load(+ &self,+ id: &str,+ ) -> impl Future<Output = Result<Option<StoredSession>, rootcause::Report>> + Send;+ /// Atomically checkpoint a session before acknowledging provider writes.+ fn save(+ &self,+ id: &str,+ state: &StoredSession,+ ) -> impl Future<Output = Result<(), rootcause::Report>> + Send;+ /// Read the complete ordered native input journal.+ fn read(+ &self,+ id: &str,+ ) -> impl Future<Output = Result<Vec<JournalEntry>, rootcause::Report>> + Send;+ /// Append only if the expected sequence and attachment fence still match.+ fn append(+ &self,+ id: &str,+ expected: i64,+ turn: Option<&TurnId>,+ input: &JournalInput,+ ) -> impl Future<Output = Result<JournalEntry, rootcause::Report>> + Send;+ /// Verify this attachment still owns its management generation before provider calls.+ fn validate(&self) -> impl Future<Output = Result<(), rootcause::Report>> + Send;+}+/// Session event delivery implemented by the inbound connection.+pub trait SessionSink: Send + Sync {+ /// Queue one ordered event; errors stop local observation.+ fn emit(&self, event: &CloudEvent) -> Result<(), rootcause::Report>;+ /// Request a transactional replacement after silently captured recovery output.+ /// Return true when the host must load before another prompt may run.+ fn recovered(&self) -> Result<bool, rootcause::Report> {+ Ok(false)+ }+}+struct Discard;+impl SessionSink for Discard {+ fn emit(&self, _: &CloudEvent) -> Result<(), rootcause::Report> {+ Ok(())+ }+}+/// Verified provider terminal outcome.+pub enum Outcome {+ /// Provider completed successfully.+ Completed,+ /// Provider explicitly reports cancellation.+ Cancelled,+}+struct Session {+ state: Mutex<StoredSession>,+ machine: Mutex<ReplayMachine>,+ turn_lock: Arc<tokio::sync::Mutex<()>>,+ recovery_gate: std::sync::Mutex<bool>,+ cancel: AtomicBool,+ reload_pending: AtomicBool,+ changed: tokio::sync::Notify,+ metadata_lock: Mutex<()>,+ published_pr: Mutex<Option<String>>,+}+/// Exclusive recovery reservation retained across the ACP load response.+pub struct Recovery {+ session: Arc<Session>,+ guard: Option<tokio::sync::OwnedMutexGuard<()>>,+}+impl Drop for Recovery {+ fn drop(&mut self) {+ let mut recovering = self+ .session+ .recovery_gate+ .lock()+ .expect("recovery gate poisoned");+ drop(self.guard.take());+ *recovering = false;+ self.session.changed.notify_waiters();+ }+}+/// Owns serial turns while cancellation remains independently runnable.+pub struct SessionService<R, J> {+ probe: Arc<R>,+ fixed_session: Option<String>,++ journal: J,+ explicit_target: Option<CloudTarget>,+ sessions: Mutex<HashMap<String, Arc<Session>>>,+ metadata_changed: tokio::sync::Notify,+}+impl<R: CloudRuntime, J: SessionStore> SessionService<R, J> {+ /// Compose cloud and persistence ports with an explicit remote target.+ pub fn new(probe: Arc<R>, journal: J, explicit_target: Option<CloudTarget>) -> Self {+ Self {+ probe,+ fixed_session: None,+ journal,+ explicit_target,+ sessions: Mutex::new(HashMap::new()),+ metadata_changed: tokio::sync::Notify::new(),+ }+ }+ /// Pin ACP identity to the host session so a lost new-session response cannot orphan a launch.+ pub fn with_session_id(mut self, id: String) -> Self {+ self.fixed_session = Some(id);+ self+ }+ /// Create a local session without starting cloud execution.+ pub async fn new_session(&self) -> Result<String, rootcause::Report> {+ let id = self+ .fixed_session+ .clone()+ .unwrap_or_else(|| uuid::Uuid::now_v7().to_string());+ if self.journal.load(&id).await?.is_some() {+ self.session(&id).await?;+ self.metadata_changed.notify_one();+ return Ok(id);+ }+ let auth = self.probe.identity().await?;+ self.journal+ .save(+ &id,+ &StoredSession {+ account_id: auth.account_id,+ connection_id: auth.connection_id,+ ..StoredSession::default()+ },+ )+ .await?;+ self.journal+ .append(&id, 0, None, &JournalInput::HistoryComplete)+ .await?;+ self.session(&id).await?;+ self.metadata_changed.notify_one();+ Ok(id)+ }+ async fn session(&self, id: &str) -> Result<Arc<Session>, rootcause::Report> {+ self.journal.validate().await?;+ let current_identity = self.probe.identity().await?;+ let mut sessions = self.sessions.lock().await;+ if let Some(session) = sessions.get(id) {+ let state = session.state.lock().await;+ if state.account_id != current_identity.account_id+ || state.connection_id != current_identity.connection_id+ {+ return Err(rootcause::report!(+ "saved session belongs to a different account or connection"+ ));+ }+ return Ok(session.clone());+ }+ let state = self+ .journal+ .load(id)+ .await?+ .ok_or_else(|| rootcause::report!("unknown session"))?;+ if (state.task.is_some() || state.turn.is_some()) && state.target.is_none() {+ return Err(rootcause::report!("saved cloud task has no pinned target"));+ }+ let auth = self.probe.identity().await?;+ if state.account_id != auth.account_id || state.connection_id != auth.connection_id {+ return Err(rootcause::report!(+ "saved session belongs to a different account or remote target"+ ));+ }+ let entries = self.journal.read(id).await?;+ if entries.is_empty() {+ return Err(rootcause::report!(+ "native journal has no complete history boundary"+ ));+ }+ let mut machine = ReplayMachine::default();+ for entry in &entries {+ machine.push(entry)?;+ }+ machine.finish();+ let session = Arc::new(Session {+ machine: Mutex::new(machine),+ state: Mutex::new(state),+ turn_lock: Arc::new(tokio::sync::Mutex::new(())),+ recovery_gate: std::sync::Mutex::new(false),+ cancel: AtomicBool::new(false),+ reload_pending: AtomicBool::new(false),+ changed: tokio::sync::Notify::new(),+ metadata_lock: Mutex::new(()),+ published_pr: Mutex::new(None),+ });+ sessions.insert(id.to_owned(), session.clone());+ Ok(session)+ }+ /// Replay the durable conversation without launching or continuing work.+ pub async fn replay(&self, id: &str, sink: &impl SessionSink) -> Result<(), rootcause::Report> {+ let session = self.session(id).await?;+ let _guard = session+ .turn_lock+ .try_lock()+ .map_err(|_| rootcause::report!("session is busy"))?;+ self.replay_entries(id, sink).await+ }+ async fn replay_entries(+ &self,+ id: &str,+ sink: &impl SessionSink,+ ) -> Result<(), rootcause::Report> {+ let session = self.session(id).await?;+ let state = session.state.lock().await.clone();+ let entries = self.journal.read(id).await?;+ if entries.is_empty() {+ return Err(rootcause::report!(+ "native journal has no complete history boundary"+ ));+ }+ // Associations can arrive after a later prompt. Rebuild their tool activity+ // beside the originating turn rather than attributing it to that later turn.+ let mut catalog = ReplayMachine::default();+ for entry in &entries {+ catalog.push(entry)?;+ }+ let mut machine = ReplayMachine::default();+ let mut current_turn = None;+ let emit = |event: CloudEvent, turn: &mut Option<String>| {+ if event.method == "session/turn_complete"+ && let Some(turn) = turn.as_deref()+ && let Some(pr) = metadata::pull_request_event(&catalog, &state, turn)+ {+ sink.emit(&pr)?;+ }+ if event.method == "user/message" {+ *turn = None;+ }+ sink.emit(&event)+ };+ for entry in &entries {+ if let JournalInput::PromptAccepted { turn, .. } = &entry.input {+ current_turn = turn.clone();+ }+ for event in machine.push(entry)? {+ emit(event, &mut current_turn)?;+ }+ }+ for event in machine.finish() {+ emit(event, &mut current_turn)?;+ }+ Ok(())+ }++ async fn finish_events(+ &self,+ session: &Session,+ sink: &impl SessionSink,+ ) -> Result<(), rootcause::Report> {+ let state = session.state.lock().await.clone();+ let mut machine = session.machine.lock().await;+ for event in machine.finish() {+ if event.method == "session/turn_complete"+ && let Some(turn) = state.turn.as_deref()+ && let Some(pr) = metadata::pull_request_event(&machine, &state, turn)+ {+ sink.emit(&pr)?;+ }+ sink.emit(&event)?;+ }+ Ok(())+ }+ async fn record(+ &self,+ id: &str,+ session: &Session,+ input: JournalInput,+ sink: &impl SessionSink,+ ) -> Result<Vec<CloudEvent>, rootcause::Report> {+ let turn = match &input {+ JournalInput::PromptAccepted { turn, .. } => turn.clone(),+ _ => session.state.lock().await.turn.clone(),+ }+ .map(TurnId::new)+ .transpose()?;+ let mut machine = session.machine.lock().await;+ machine.ensure_appendable(&input)?;+ let entry = self+ .journal+ .append(id, machine.sequence(), turn.as_ref(), &input)+ .await?;+ let events = machine.push(&entry)?;+ if matches!(&input, JournalInput::Poll {snapshot,..} if !snapshot.pull_requests.is_empty())+ {+ self.metadata_changed.notify_one();+ }+ for event in &events {+ sink.emit(event)?;+ }+ Ok(events)+ }+ async fn observe_event(+ &self,+ id: &str,+ session: &Session,+ task: &CloudId,+ record: NativeRecord,+ sink: &impl SessionSink,+ ) -> Result<(), rootcause::Report> {+ let events = self+ .record(id, session, JournalInput::Native(record), sink)+ .await?;+ if events.iter().any(|event| {+ event.method.contains("requestApproval")+ || event.method.contains("requestUserInput")+ || event.method.contains("elicitation")+ }) {+ self.journal.validate().await?;+ self.probe.cancel(task).await?;+ return Err(rootcause::report!(+ "cloud turn requested interactive input or approval unsupported by this adapter; remote cancellation requested"+ ));+ }+ Ok(())+ }+ /// Signal and perform remote cancellation without waiting for the turn lock.+ pub async fn cancel(&self, id: &str) -> Result<(), rootcause::Report> {+ self.journal.validate().await?;+ let session = self.session(id).await?;+ self.record(id, &session, JournalInput::CancellationRequested, &Discard)+ .await?;+ session.cancel.store(true, Ordering::SeqCst);+ session.changed.notify_waiters();+ let task = session.state.lock().await.task.clone();+ if let Some(task) = task {+ self.probe.cancel(&CloudId::new(task)?).await?;+ }+ Ok(())+ }+ /// Preserve the client's original text blocks in the native input journal.+ pub async fn prompt(+ &self,+ id: &str,+ blocks: Vec<agent_client_protocol::schema::v1::ContentBlock>,+ sink: &impl SessionSink,+ ) -> Result<Outcome, rootcause::Report> {+ let prompt = blocks+ .iter()+ .map(|block| match block {+ agent_client_protocol::schema::v1::ContentBlock::Text(text) => {+ Ok(text.text.as_str())+ }+ _ => Err(rootcause::report!("only text prompt blocks are supported")),+ })+ .collect::<Result<Vec<_>, _>>()?+ .join("\n");+ self.journal.validate().await?;+ if prompt.trim().is_empty() || prompt.len() > 64 * 1024 {+ return Err(rootcause::report!(+ "provide a nonempty prompt (maximum 64 KiB)"+ ));+ }+ let session = self.session(id).await?;+ let _guard = loop {+ let changed = session.changed.notified();+ tokio::pin!(changed);+ changed.as_mut().enable();+ if session.reload_pending.load(Ordering::SeqCst) {+ changed.await;+ continue;+ }+ // Classify the held lock atomically with recovery reservation/drop.+ let immediate =+ {+ let recovering = session+ .recovery_gate+ .lock()+ .expect("recovery gate poisoned");+ if *recovering {+ None+ } else {+ Some(session.turn_lock.try_lock().map_err(|_| {+ rootcause::report!("session already has a running prompt")+ })?)+ }+ };+ let guard = match immediate {+ Some(guard) => guard,+ None => session.turn_lock.lock().await,+ };+ if !session.reload_pending.load(Ordering::SeqCst) {+ break guard;+ }+ drop(guard);+ };+ self.journal.validate().await?;+ session.cancel.store(false, Ordering::SeqCst);+ let previous = session.state.lock().await.clone();+ if previous.uncertain_write {+ return Err(rootcause::report!(+ "previous submission has an uncertain outcome; inspect cloud tasks before starting another session"+ ));+ }+ if let Some(task) = &previous.task {+ let mut snapshot = self.probe.snapshot(&CloudId::new(task.clone())?).await?;+ let native = snapshot.native.take();+ self.record(+ id,+ &session,+ JournalInput::Poll {+ snapshot: snapshot.clone(),+ native,+ },+ sink,+ )+ .await?;+ if let Some(current) = snapshot+ .turns+ .iter()+ .find(|turn| turn.source == "current_assistant_turn")+ .and_then(|turn| turn.id.as_ref())+ && previous.turn.as_ref() != Some(current)+ {+ return Err(rootcause::report!(+ "cloud conversation advanced outside this session; refusing to branch from an older turn"+ ));+ }+ if !snapshot.terminal() {+ return Err(rootcause::report!(+ "existing cloud task is still running or has unknown status; cancel it or wait before continuing"+ ));+ }+ }+ let target = match previous.target {+ Some(target) => target,+ None => {+ let selecting = self+ .probe+ .resolve_target(&prompt, self.explicit_target.as_ref());+ tokio::pin!(selecting);+ let target = loop {+ let changed = session.changed.notified();+ tokio::pin!(changed);+ changed.as_mut().enable();+ if session.cancel.load(Ordering::SeqCst) {+ return Ok(Outcome::Cancelled);+ }+ tokio::select! {+ result = &mut selecting => {+ if session.cancel.load(Ordering::SeqCst) { return Ok(Outcome::Cancelled); }+ break result?;+ }+ _ = changed => {}+ }+ };+ target.validate()?;+ self.journal.validate().await?;+ if session.cancel.load(Ordering::SeqCst) {+ return Ok(Outcome::Cancelled);+ }+ let mut state = session.state.lock().await;+ let mut updated = state.clone();+ updated.target = Some(target.clone());+ self.journal.save(id, &updated).await?;+ *state = updated;+ target+ }+ };+ if session.cancel.load(Ordering::SeqCst) {+ return Ok(Outcome::Cancelled);+ }+ let request = Launch {+ environment: target.environment,+ branch: target.branch,+ prompt,+ };+ self.record(id, &session, JournalInput::Prompt(blocks), sink)+ .await?;+ {+ let mut state = session.state.lock().await;+ let mut updated = state.clone();+ updated.uncertain_write = true;+ self.journal.save(id, &updated).await?;+ *state = updated;+ }+ let receipt = match (&previous.task, &previous.turn) {+ (Some(task), Some(turn)) => {+ self.probe+ .follow_up(+ &CloudId::new(task.clone())?,+ &TurnId::new(turn.clone())?,+ &request.prompt,+ )+ .await+ }+ (None, None) => self.probe.launch(&request).await,+ _ => {+ return Err(rootcause::report!(+ "saved task has no assistant turn; inspect it before continuing"+ ));+ }+ };+ let receipt = match receipt {+ Ok(receipt) => receipt,+ Err(error) => {+ let message = error.format_current_context().to_string();+ self.record(id, &session, JournalInput::SubmissionError(message), sink)+ .await?;+ return Err(error);+ }+ };+ self.record(+ id,+ &session,+ JournalInput::PromptAccepted {+ task: receipt.task_id.as_str().to_owned(),+ turn: receipt+ .assistant_turn_id+ .as_ref()+ .map(|turn| turn.as_str().to_owned()),+ },+ sink,+ )+ .await?;+ let task = receipt.task_id;+ {+ let mut state = session.state.lock().await;+ let mut updated = state.clone();+ updated.task = Some(task.as_str().to_owned());+ updated.turn = receipt+ .assistant_turn_id+ .as_ref()+ .map(|turn| turn.as_str().to_owned());+ updated.uncertain_write = updated.turn.is_none();+ self.journal.save(id, &updated).await?;+ *state = updated;+ }+ let turn = receipt.assistant_turn_id.ok_or_else(|| {+ rootcause::report!(+ "provider created task without assistant turn; submission will not be retried"+ )+ })?;+ if session.cancel.load(Ordering::SeqCst) {+ self.probe.cancel(&task).await?;+ }+ let outcome = self.observe(id, session.clone(), task, turn, sink).await;+ self.finish_events(&session, sink).await?;+ outcome+ }+ async fn reserve_recovery(&self, id: &str) -> Result<Recovery, rootcause::Report> {+ self.journal.validate().await?;+ let session = self.session(id).await?;+ let guard = loop {+ let changed = session.changed.notified();+ tokio::pin!(changed);+ changed.as_mut().enable();+ let guard = {+ let mut recovering = session+ .recovery_gate+ .lock()+ .expect("recovery gate poisoned");+ if *recovering {+ None+ } else {+ let guard = session+ .turn_lock+ .clone()+ .try_lock_owned()+ .map_err(|_| rootcause::report!("session is busy"))?;+ *recovering = true;+ Some(guard)+ }+ };+ if let Some(guard) = guard {+ break guard;+ }+ changed.await;+ };+ let recovery = Recovery {+ session,+ guard: Some(guard),+ };+ if recovery.session.state.lock().await.uncertain_write {+ return Err(rootcause::report!(+ "previous submission has an uncertain outcome; inspect cloud tasks before continuing"+ ));+ }+ Ok(recovery)+ }+ /// Replay and reserve the old turn before the client can send a new prompt.+ pub async fn prepare_recovery(+ &self,+ id: &str,+ sink: &impl SessionSink,+ ) -> Result<Recovery, rootcause::Report> {+ let recovery = self.reserve_recovery(id).await?;+ self.replay_entries(id, sink).await?;+ self.metadata_changed.notify_one();+ recovery+ .session+ .reload_pending+ .store(false, Ordering::SeqCst);+ recovery.session.changed.notify_waiters();+ Ok(recovery)+ }+ /// Reattach observation to a durably recorded turn, never creating provider work.+ pub async fn resume_observation(+ &self,+ id: &str,+ sink: &impl SessionSink,+ ) -> Result<Option<Outcome>, rootcause::Report> {+ let recovery = self.reserve_recovery(id).await?;+ self.finish_recovery(id, recovery, sink).await+ }+ /// Observe the reserved turn while follow-up prompts wait for its verified outcome.+ pub async fn finish_recovery(+ &self,+ id: &str,+ recovery: Recovery,+ sink: &impl SessionSink,+ ) -> Result<Option<Outcome>, rootcause::Report> {+ let session = recovery.session.clone();+ let state = session.state.lock().await.clone();+ if state.uncertain_write {+ return Err(rootcause::report!(+ "previous submission has an uncertain outcome; inspect cloud tasks before continuing"+ ));+ }+ let (Some(task), Some(turn)) = (state.task, state.turn) else {+ return Ok(None);+ };+ self.record(id, &session, JournalInput::RecoveryStarted, sink)+ .await?;+ let outcome = self+ .observe(+ id,+ session.clone(),+ CloudId::new(task)?,+ TurnId::new(turn)?,+ sink,+ )+ .await+ .map(Some);+ self.finish_events(&session, sink).await?;+ if sink.recovered()? {+ session.reload_pending.store(true, Ordering::SeqCst);+ }+ drop(recovery);+ outcome+ }+ async fn observe(+ &self,+ id: &str,+ session: Arc<Session>,+ task: CloudId,+ turn: TurnId,+ sink: &impl SessionSink,+ ) -> Result<Outcome, rootcause::Report> {+ let mut stream = match self.probe.stream(&task, &turn).await {+ Ok(stream) => Some(stream),+ Err(error) => {+ let message = error.format_current_context().to_string();+ self.record(id, &session, JournalInput::TransportError(message), sink)+ .await?;+ None+ }+ };+ let mut reconnects = 0_u8;+ let mut interval = tokio::time::interval(Duration::from_secs(5));+ loop {+ tokio::select! {+ event = async { match &mut stream { Some(stream) => stream.next().await, None => std::future::pending().await } } => {+ match event {+ Some(Ok(event)) => {+ self.observe_event(id, &session, &task, event, sink).await?;+ }+ Some(Err(error)) => { let message = error.format_current_context().to_string(); self.record(id, &session, JournalInput::TransportError(message), sink).await?; stream = None; }+ None => { self.record(id, &session, JournalInput::TransportError("stream ended".into()), sink).await?; stream = None; }+ }+ }+ _ = interval.tick() => {+ self.journal.validate().await?;+ let mut snapshot = self.probe.turn(&task, &turn).await?;+ let native = snapshot.native.take();+ self.record(id, &session, JournalInput::Poll { snapshot: snapshot.clone(), native }, sink).await?;+ match snapshot.assistant_status.as_deref() {+ Some("completed") => {+ // A terminal snapshot can race queued SSE records; drain available+ // history before reconciling the authoritative final message.+ if let Some(active) = &mut stream {+ let drain = async {+ while let Some(Ok(event)) = active.next().await {+ self.observe_event(id, &session, &task, event, sink).await?;+ }+ Ok::<(), rootcause::Report>(())+ };+ if let Ok(result) = tokio::time::timeout(Duration::from_secs(2), drain).await { result?; }+ }+ // The completed replay can expose records absent from the live+ // stream. Stable outer IDs suppress records already journaled.+ if let Ok(mut replay) = self.probe.stream(&task, &turn).await {+ let drain = async {+ while let Some(Ok(event)) = replay.next().await { self.observe_event(id, &session, &task, event, sink).await?; }+ Ok::<(), rootcause::Report>(())+ };+ if let Ok(result) = tokio::time::timeout(Duration::from_secs(2), drain).await { result?; }+ }+ self.record(id, &session, JournalInput::Terminal("completed".into()), sink).await?;+ return Ok(Outcome::Completed);+ }+ Some("cancelled") => { self.record(id, &session, JournalInput::Terminal("cancelled".into()), sink).await?; return Ok(Outcome::Cancelled); },+ Some("failed") => { self.record(id, &session, JournalInput::Terminal("failed".into()), sink).await?; return Err(rootcause::report!("cloud assistant turn failed")); },+ _ => {+ if stream.is_none() && reconnects < 3 {+ reconnects += 1;+ stream = self.probe.stream(&task, &turn).await.ok();+ }+ }+ }+ }+ }+ }+ }+}++#[cfg(test)]+mod test;diff --git a/crates/codex_cloud_agents/src/domain/acp_session/metadata.rs b/crates/codex_cloud_agents/src/domain/acp_session/metadata.rsnew file mode 100644index 0000000000..c1cb2adf23--- /dev/null+++ b/crates/codex_cloud_agents/src/domain/acp_session/metadata.rs@@ -0,0 +1,192 @@+//! Metadata refresh consumes provider facts without replaying assistant output.+use super::*;+use crate::domain::cloud::ExternalPullRequest;++fn repository(url: &str) -> Option<String> {+ let path = url.strip_prefix("https://github.com/")?;+ let mut parts = path.split('/');+ let owner = parts.next()?;+ let repo = parts.next()?;+ if owner.is_empty() || repo.is_empty() {+ return None;+ }+ Some(format!("{owner}/{repo}").to_ascii_lowercase())+}+#[derive(Clone, Debug, PartialEq, Eq)]+struct Selected {+ turn: String,+ url: String,+}+fn select(+ accepted: &[String],+ target: &CloudTarget,+ prs: &[ExternalPullRequest],+) -> Option<Selected> {+ let repo = repository(target.repository_url.as_deref()?)?;+ accepted.iter().rev().find_map(|turn| {+ prs.iter()+ .rev()+ .find(|pr| {+ pr.assistant_turn_id.as_str() == turn+ && repository(&pr.url).as_deref() == Some(repo.as_str())+ })+ .map(|pr| Selected {+ turn: turn.clone(),+ url: pr.url.clone(),+ })+ })+}++/// A provider association is an observed link, not evidence that our adapter created a PR.+pub(super) fn pull_request_event(+ machine: &ReplayMachine,+ state: &StoredSession,+ turn: &str,+) -> Option<CloudEvent> {+ let task = state.task.as_deref()?;+ let target = state.target.as_ref()?;+ if !machine+ .accepted(task)+ .iter()+ .any(|accepted| accepted == turn)+ {+ return None;+ }+ let selected = select(&[turn.to_owned()], target, &machine.pull_requests(task))?;+ Some(CloudEvent {+ id: format!("codex-pr:{}:{}", selected.turn, selected.url),+ method: "adapter/pull_request".into(),+ params: serde_json::json!({+ "url": selected.url,+ "assistantTurnId": selected.turn,+ "source": "codex_cloud_metadata",+ }),+ })+}+impl<R: CloudRuntime, J: SessionStore> SessionService<R, J> {+ /// Wait for a newly attached session or foreground metadata observation.+ pub async fn metadata_changed(&self) {+ self.metadata_changed.notified().await;+ }+ /// Refresh attached sessions' task metadata without launching work or replaying history.+ /// Fence and identity checks precede provider reads; the attachment retries failures with backoff.+ pub async fn refresh_metadata(&self) -> Result<Vec<String>, rootcause::Report> {+ let mut changed = Vec::new();+ let sessions: Vec<_> = self+ .sessions+ .lock()+ .await+ .iter()+ .map(|(id, session)| (id.clone(), session.clone()))+ .collect();+ if sessions.is_empty() {+ return Ok(changed);+ }+ self.journal.validate().await?;+ for (id, session) in sessions {+ self.session(&id).await?;+ let Ok(_guard) = session.metadata_lock.try_lock() else {+ continue;+ };+ let state = session.state.lock().await.clone();+ let (Some(task), Some(target)) = (state.task, state.target) else {+ continue;+ };+ let task = CloudId::new(task)?;+ let (accepted, known, sequence) = {+ let machine = session.machine.lock().await;+ (+ machine.accepted(task.as_str()),+ machine.pull_requests(task.as_str()),+ machine.sequence(),+ )+ };+ let prior = select(&accepted, &target, &known);+ let read_error = match self.probe.snapshot(&task).await {+ Ok(mut snapshot) => {+ if session.machine.lock().await.sequence() != sequence {+ continue;+ }+ if snapshot.task_id != task {+ eprintln!("codex_acp: PR metadata returned a different task");+ continue;+ }+ let mut candidates = known;+ candidates.extend(snapshot.pull_requests.iter().rev().cloned());+ if select(&accepted, &target, &candidates) != prior {+ let native = snapshot.native.take();+ // Record before host publication; unchanged evidence needs no new row.+ self.record_metadata_if_current(+ &id,+ &session,+ sequence,+ JournalInput::Metadata { snapshot, native },+ )+ .await?;+ }+ None+ }+ Err(error) => Some(error),+ };+ if self.publish_recorded_pr(&session).await? {+ changed.push(id);+ }+ if let Some(error) = read_error {+ return Err(error);+ }+ }+ Ok(changed)+ }+ async fn record_metadata_if_current(+ &self,+ id: &str,+ session: &Session,+ expected: i64,+ input: JournalInput,+ ) -> Result<bool, rootcause::Report> {+ let turn = session+ .state+ .lock()+ .await+ .turn+ .clone()+ .map(TurnId::new)+ .transpose()?;+ let mut machine = session.machine.lock().await;+ if machine.sequence() != expected {+ return Ok(false);+ }+ machine.ensure_appendable(&input)?;+ let entry = self+ .journal+ .append(id, expected, turn.as_ref(), &input)+ .await?;+ machine.push(&entry)?;+ Ok(true)+ }+ async fn publish_recorded_pr(&self, session: &Session) -> Result<bool, rootcause::Report> {+ let state = session.state.lock().await.clone();+ let (Some(task), Some(target)) = (state.task, state.target) else {+ return Ok(false);+ };+ let selected = {+ let machine = session.machine.lock().await;+ select(+ &machine.accepted(&task),+ &target,+ &machine.pull_requests(&task),+ )+ };+ let Some(Selected { url, .. }) = selected else {+ return Ok(false);+ };+ let mut published = session.published_pr.lock().await;+ if published.as_ref() == Some(&url) {+ return Ok(false);+ }+ self.journal.validate().await?;+ self.probe.report_pull_request(&url).await?;+ *published = Some(url);+ Ok(true)+ }+}diff --git a/crates/codex_cloud_agents/src/domain/acp_session/test.rs b/crates/codex_cloud_agents/src/domain/acp_session/test.rsnew file mode 100644index 0000000000..8aec670d55--- /dev/null+++ b/crates/codex_cloud_agents/src/domain/acp_session/test.rs@@ -0,0 +1,756 @@+use super::*;+fn text(value: &str) -> Vec<agent_client_protocol::schema::v1::ContentBlock> {+ vec![agent_client_protocol::schema::v1::ContentBlock::Text(+ agent_client_protocol::schema::v1::TextContent::new(value),+ )]+}+use crate::domain::cloud::CloudConversation;+use crate::domain::cloud::{CloudEventStream, CloudTasks, CreatedTask, TaskSnapshot, TurnSnapshot};+use crate::domain::{CredentialStore, OAuth, Probe};+use crate::domain::{Credentials, DeviceLogin, Environment, LoginPoll, Secret};+use std::sync::Mutex;+use std::sync::atomic::AtomicUsize;++#[derive(Default, Clone)]+struct Journal(+ Arc<Mutex<HashMap<String, StoredSession>>>,+ Arc<Mutex<HashMap<String, Vec<JournalEntry>>>>,+);+impl SessionStore for Journal {+ async fn load(&self, id: &str) -> Result<Option<StoredSession>, rootcause::Report> {+ Ok(self.0.lock().unwrap().get(id).cloned())+ }+ async fn save(&self, id: &str, state: &StoredSession) -> Result<(), rootcause::Report> {+ self.0.lock().unwrap().insert(id.to_owned(), state.clone());+ Ok(())+ }+ async fn read(&self, id: &str) -> std::result::Result<Vec<JournalEntry>, rootcause::Report> {+ Ok(self.1.lock().unwrap().get(id).cloned().unwrap_or_default())+ }+ async fn append(+ &self,+ id: &str,+ expected: i64,+ turn: Option<&TurnId>,+ input: &JournalInput,+ ) -> std::result::Result<JournalEntry, rootcause::Report> {+ let mut journals = self.1.lock().unwrap();+ let entries = journals.entry(id.to_owned()).or_default();+ if entries.len() as i64 != expected {+ return Err(rootcause::report!("stale sequence"));+ }+ let entry = JournalEntry {+ sequence: expected + 1,+ turn: turn.cloned(),+ input: input.clone(),+ };+ entries.push(entry.clone());+ Ok(entry)+ }+ async fn validate(&self) -> Result<(), rootcause::Report> {+ Ok(())+ }+}+struct Auth;+impl CredentialStore for Auth {+ fn load(&self) -> Result<Option<Credentials>, rootcause::Report> {+ Ok(Some(Credentials {+ version: 1,+ access_token: Secret::new("test-access".into())?,+ refresh_token: Secret::new("test-refresh".into())?,+ expires_at: u64::MAX,+ account_id: "test-account".into(),+ }))+ }+ fn save(&self, _: &Credentials) -> Result<(), rootcause::Report> {+ Ok(())+ }+ fn clear(&self) -> Result<(), rootcause::Report> {+ Ok(())+ }+}+#[derive(Default)]+struct Sink(Mutex<Vec<CloudEvent>>);+impl SessionSink for Sink {+ fn emit(&self, event: &CloudEvent) -> Result<(), rootcause::Report> {+ self.0.lock().unwrap().push(event.clone());+ Ok(())+ }+}+#[derive(Default)]+struct State {+ creates: AtomicUsize,+ followups: AtomicUsize,+ allow_follow_up: bool,+ streams: AtomicUsize,+ running: AtomicBool,+ cancels: AtomicUsize,+ entered: tokio::sync::Notify,+ release: tokio::sync::Notify,+ ambiguous: bool,+ paused: bool,+ native: Option<Vec<NativeRecord>>,+}+struct Provider(Arc<State>);+impl OAuth for Provider {+ async fn begin(&self) -> Result<DeviceLogin, rootcause::Report> {+ Err(rootcause::report!("unused"))+ }+ async fn poll(&self, _: &DeviceLogin) -> Result<LoginPoll, rootcause::Report> {+ Err(rootcause::report!("unused"))+ }+ async fn refresh(&self, _: &Credentials) -> Result<Credentials, rootcause::Report> {+ Err(rootcause::report!("unused"))+ }+ async fn environments(&self, _: &Credentials) -> Result<Vec<Environment>, rootcause::Report> {+ Ok(vec![Environment {+ id: "env_test".into(),+ label: None,+ repositories: vec![],+ }])+ }+}+fn snapshot(turn: &str, status: &str) -> TaskSnapshot {+ TaskSnapshot {+ native: None,+ pull_requests: vec![],+ task_id: CloudId::new("task_test".into()).unwrap(),+ title: None,+ assistant_status: Some(status.into()),+ turns: vec![TurnSnapshot {+ source: "current_assistant_turn".into(),+ id: Some(turn.into()),+ messages: vec![],+ output_types: vec![],+ has_diff: false,+ }],+ }+}+impl CloudTasks for Provider {+ async fn create(&self, _: &Credentials, _: &Launch) -> Result<CreatedTask, rootcause::Report> {+ self.0.creates.fetch_add(1, Ordering::SeqCst);+ self.0.entered.notify_one();+ if self.0.paused {+ self.0.release.notified().await;+ }+ if self.0.ambiguous {+ return Err(rootcause::report!("acceptance unknown"));+ }+ Ok(CreatedTask {+ task_id: CloudId::new("task_test".into())?,+ assistant_turn_id: Some(TurnId::new("turn_new".into())?),+ url: "https://example.test/task".into(),+ })+ }+ async fn snapshot(+ &self,+ _: &Credentials,+ _: &CloudId,+ ) -> Result<TaskSnapshot, rootcause::Report> {+ Ok(snapshot(+ if self.0.allow_follow_up {+ "turn_new"+ } else {+ "turn_external"+ },+ "completed",+ ))+ }+}+impl CloudConversation for Provider {+ async fn follow_up(+ &self,+ _: &Credentials,+ _: &CloudId,+ _: &TurnId,+ _: &str,+ ) -> Result<CreatedTask, rootcause::Report> {+ assert!(self.0.allow_follow_up, "unexpected follow-up");+ self.0.followups.fetch_add(1, Ordering::SeqCst);+ Ok(CreatedTask {+ task_id: CloudId::new("task_test".into())?,+ assistant_turn_id: Some(TurnId::new("turn_follow".into())?),+ url: "https://example.test/task".into(),+ })+ }+ async fn cancel(&self, _: &Credentials, _: &CloudId) -> Result<(), rootcause::Report> {+ self.0.cancels.fetch_add(1, Ordering::SeqCst);+ self.0.running.store(false, Ordering::SeqCst);+ Ok(())+ }+ async fn turn(+ &self,+ _: &Credentials,+ _: &CloudId,+ _: &TurnId,+ ) -> Result<TaskSnapshot, rootcause::Report> {+ Ok(snapshot(+ "turn_new",+ if self.0.allow_follow_up {+ "completed"+ } else if self.0.running.load(Ordering::SeqCst) {+ "in_progress"+ } else {+ "cancelled"+ },+ ))+ }+ async fn stream(+ &self,+ _: &Credentials,+ _: &CloudId,+ _: &TurnId,+ ) -> Result<CloudEventStream, rootcause::Report> {+ self.0.streams.fetch_add(1, Ordering::SeqCst);+ if let Some(records) = &self.0.native {+ return Ok(Box::pin(futures::stream::iter(+ records.clone().into_iter().map(Ok),+ )));+ }+ Ok(Box::pin(futures::stream::empty()))+ }+}+fn service(state: Arc<State>, journal: Journal) -> SessionService<Probe<Provider, Auth>, Journal> {+ SessionService::new(+ Arc::new(Probe::new(Provider(state), Auth)),+ journal,+ Some(crate::domain::runtime::CloudTarget {+ environment: CloudId::new("env_test".into()).unwrap(),+ branch: "main".into(),+ repository_url: None,+ }),+ )+}+#[tokio::test]+async fn ambiguous_submission_is_checkpointed_and_never_retried() {+ let state = Arc::new(State {+ ambiguous: true,+ ..Default::default()+ });+ let journal = Journal::default();+ let service = service(state.clone(), journal.clone());+ let id = service.new_session().await.unwrap();+ let sink = Sink::default();+ assert!(service.prompt(&id, text("hello"), &sink).await.is_err());+ assert!(journal.load(&id).await.unwrap().unwrap().uncertain_write);+ assert!(service.prompt(&id, text("retry"), &sink).await.is_err());+ assert_eq!(state.creates.load(Ordering::SeqCst), 1);+}+#[tokio::test]+async fn concurrent_prompt_is_rejected_and_cancel_during_create_reaches_remote_receipt() {+ let state = Arc::new(State {+ paused: true,+ ..Default::default()+ });+ let service = service(state.clone(), Journal::default());+ let id = service.new_session().await.unwrap();+ let sink = Sink::default();+ let prompt = service.prompt(&id, text("hello"), &sink);+ tokio::pin!(prompt);+ tokio::select! {+ _ = &mut prompt => panic!("creation should pause"),+ _ = state.entered.notified() => {}+ }+ assert!(service.prompt(&id, text("parallel"), &sink).await.is_err());+ service.cancel(&id).await.unwrap();+ assert_eq!(state.cancels.load(Ordering::SeqCst), 0);+ state.release.notify_one();+ assert!(matches!(prompt.await.unwrap(), Outcome::Cancelled));+ assert_eq!(state.creates.load(Ordering::SeqCst), 1);+ assert_eq!(state.cancels.load(Ordering::SeqCst), 1);+}+#[tokio::test]+async fn stale_parent_refuses_provider_follow_up() {+ let state = Arc::new(State::default());+ let journal = Journal::default();+ let id = uuid::Uuid::now_v7().to_string();+ journal+ .save(+ &id,+ &StoredSession {+ account_id: "test-account".into(),+ connection_id: "test-account".into(),+ target: Some(crate::domain::runtime::CloudTarget {+ environment: CloudId::new("env_test".into()).unwrap(),+ branch: "main".into(),+ repository_url: None,+ }),+ task: Some("task_test".into()),+ turn: Some("turn_old".into()),+ ..Default::default()+ },+ )+ .await+ .unwrap();+ journal+ .append(&id, 0, None, &JournalInput::HistoryComplete)+ .await+ .unwrap();+ let service = service(state.clone(), journal);+ let error = service+ .prompt(&id, text("hello"), &Sink::default())+ .await+ .err()+ .unwrap();+ assert!(error.to_string().contains("advanced outside"));+ assert_eq!(state.creates.load(Ordering::SeqCst), 0);+}++struct FailingReceiptJournal(Journal);+impl SessionStore for FailingReceiptJournal {+ async fn load(&self, id: &str) -> Result<Option<StoredSession>, rootcause::Report> {+ self.0.load(id).await+ }+ async fn save(&self, id: &str, state: &StoredSession) -> Result<(), rootcause::Report> {+ if state.task.is_some() {+ return Err(rootcause::report!("injected receipt disk failure"));+ }+ self.0.save(id, state).await+ }+ async fn read(&self, id: &str) -> Result<Vec<JournalEntry>, rootcause::Report> {+ self.validate().await?;+ self.0.read(id).await+ }+ async fn append(+ &self,+ id: &str,+ expected: i64,+ turn: Option<&TurnId>,+ input: &JournalInput,+ ) -> Result<JournalEntry, rootcause::Report> {+ self.validate().await?;+ self.0.append(id, expected, turn, input).await+ }+ async fn validate(&self) -> Result<(), rootcause::Report> {+ Ok(())+ }+}+#[tokio::test]+async fn receipt_persistence_failure_keeps_session_uncertain_in_memory_and_on_disk() {+ let state = Arc::new(State::default());+ let journal = Journal::default();+ let service = SessionService::new(+ Arc::new(Probe::new(Provider(state.clone()), Auth)),+ FailingReceiptJournal(journal.clone()),+ Some(crate::domain::runtime::CloudTarget {+ environment: CloudId::new("env_test".into()).unwrap(),+ branch: "main".into(),+ repository_url: None,+ }),+ );+ let id = service.new_session().await.unwrap();+ let sink = Sink::default();+ assert!(service.prompt(&id, text("hello"), &sink).await.is_err());+ assert!(journal.load(&id).await.unwrap().unwrap().uncertain_write);+ assert!(service.prompt(&id, text("retry"), &sink).await.is_err());+ assert_eq!(state.creates.load(Ordering::SeqCst), 1);+}+#[tokio::test]+async fn loading_session_from_another_account_rejects_replay_before_emitting_content() {+ let journal = Journal::default();+ let id = uuid::Uuid::now_v7().to_string();+ journal+ .save(+ &id,+ &StoredSession {+ account_id: "another-account".into(),+ target: Some(crate::domain::runtime::CloudTarget {+ environment: CloudId::new("env_test".into()).unwrap(),+ branch: "main".into(),+ repository_url: None,+ }),+ ..Default::default()+ },+ )+ .await+ .unwrap();+ let service = service(Arc::new(State::default()), journal);+ let sink = Sink::default();+ assert!(service.replay(&id, &sink).await.is_err());+ assert!(sink.0.lock().unwrap().is_empty());+}++#[tokio::test]+async fn restart_reattaches_saved_turn_without_launching_again() {+ let provider = Arc::new(State::default());+ let journal = Journal::default();+ let original = service(provider.clone(), journal.clone());+ let id = original.new_session().await.unwrap();+ original+ .prompt(&id, text("first"), &Sink::default())+ .await+ .unwrap();+ drop(original);+ let restarted = service(provider.clone(), journal);+ restarted.replay(&id, &Sink::default()).await.unwrap();+ assert!(matches!(+ restarted+ .resume_observation(&id, &Sink::default())+ .await+ .unwrap(),+ Some(Outcome::Cancelled)+ ));+ assert_eq!(provider.creates.load(Ordering::SeqCst), 1);+}+#[tokio::test]+async fn deterministic_host_identity_recovers_new_session_response_loss() {+ let provider = Arc::new(State::default());+ let journal = Journal::default();+ let id = uuid::Uuid::now_v7().to_string();+ let original = service(provider.clone(), journal.clone()).with_session_id(id.clone());+ assert_eq!(original.new_session().await.unwrap(), id);+ original+ .prompt(&id, text("first"), &Sink::default())+ .await+ .unwrap();+ let restarted = service(provider.clone(), journal).with_session_id(id.clone());+ assert_eq!(restarted.new_session().await.unwrap(), id);+ assert_eq!(provider.creates.load(Ordering::SeqCst), 1);+}++#[tokio::test(start_paused = true)]+async fn restarted_running_turn_observes_and_cancels_without_creation() {+ let provider = Arc::new(State::default());+ provider.running.store(true, Ordering::SeqCst);+ let journal = Journal::default();+ let original = service(provider.clone(), journal.clone());+ let id = original.new_session().await.unwrap();+ let mut stored = journal.load(&id).await.unwrap().unwrap();+ stored.target = Some(CloudTarget {+ environment: CloudId::new("env_test".into()).unwrap(),+ branch: "main".into(),+ repository_url: None,+ });+ stored.task = Some("task_test".into());+ stored.turn = Some("turn_new".into());+ journal.save(&id, &stored).await.unwrap();+ drop(original);+ let restarted = Arc::new(service(provider.clone(), journal));+ let observing = {+ let restarted = restarted.clone();+ let id = id.clone();+ tokio::spawn(async move { restarted.resume_observation(&id, &Sink::default()).await })+ };+ while provider.streams.load(Ordering::SeqCst) == 0 {+ tokio::task::yield_now().await;+ }+ assert!(!observing.is_finished());+ restarted.cancel(&id).await.unwrap();+ tokio::time::advance(Duration::from_secs(5)).await;+ assert!(matches!(+ observing.await.unwrap().unwrap(),+ Some(Outcome::Cancelled)+ ));+ assert_eq!(provider.creates.load(Ordering::SeqCst), 0);+ assert_eq!(provider.cancels.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn prompt_immediately_after_load_waits_for_recovery_then_follows_same_task() {+ let provider = Arc::new(State {+ allow_follow_up: true,+ ..State::default()+ });+ let journal = Journal::default();+ let original = service(provider.clone(), journal.clone());+ let id = original.new_session().await.unwrap();+ original+ .prompt(&id, text("first"), &Sink::default())+ .await+ .unwrap();+ drop(original);+ let restarted = Arc::new(service(provider.clone(), journal));+ let recovery = restarted+ .prepare_recovery(&id, &Sink::default())+ .await+ .unwrap();+ let followup = {+ let restarted = restarted.clone();+ let id = id.clone();+ tokio::spawn(async move {+ restarted+ .prompt(&id, text("continue"), &Sink::default())+ .await+ })+ };+ tokio::task::yield_now().await;+ assert!(!followup.is_finished());+ restarted+ .finish_recovery(&id, recovery, &Sink::default())+ .await+ .unwrap();+ assert!(matches!(+ followup.await.unwrap().unwrap(),+ Outcome::Completed+ ));+ assert_eq!(provider.creates.load(Ordering::SeqCst), 1);+ assert_eq!(provider.followups.load(Ordering::SeqCst), 1);+}++#[derive(Clone)]+struct FencedJournal {+ inner: Journal,+ fenced: Arc<AtomicBool>,+}+impl SessionStore for FencedJournal {+ async fn load(&self, id: &str) -> Result<Option<StoredSession>, rootcause::Report> {+ self.inner.load(id).await+ }+ async fn save(&self, id: &str, state: &StoredSession) -> Result<(), rootcause::Report> {+ self.validate().await?;+ self.inner.save(id, state).await+ }+ async fn read(&self, id: &str) -> Result<Vec<JournalEntry>, rootcause::Report> {+ self.validate().await?;+ self.inner.read(id).await+ }+ async fn append(+ &self,+ id: &str,+ expected: i64,+ turn: Option<&TurnId>,+ input: &JournalInput,+ ) -> Result<JournalEntry, rootcause::Report> {+ self.validate().await?;+ self.inner.append(id, expected, turn, input).await+ }+ async fn validate(&self) -> Result<(), rootcause::Report> {+ if self.fenced.load(Ordering::SeqCst) {+ Err(rootcause::report!("fenced out"))+ } else {+ Ok(())+ }+ }+}+#[tokio::test]+async fn prompt_waiting_for_recovery_revalidates_fence_before_provider_work() {+ let provider = Arc::new(State {+ allow_follow_up: true,+ ..State::default()+ });+ let fenced = Arc::new(AtomicBool::new(false));+ let service = Arc::new(SessionService::new(+ Arc::new(Probe::new(Provider(provider.clone()), Auth)),+ FencedJournal {+ inner: Journal::default(),+ fenced: fenced.clone(),+ },+ Some(crate::domain::runtime::CloudTarget {+ environment: CloudId::new("env_test".into()).unwrap(),+ branch: "main".into(),+ repository_url: None,+ }),+ ));+ let id = service.new_session().await.unwrap();+ let recovery = service+ .prepare_recovery(&id, &Sink::default())+ .await+ .unwrap();+ let waiting = {+ let service = service.clone();+ tokio::spawn(async move { service.prompt(&id, text("first"), &Sink::default()).await })+ };+ tokio::task::yield_now().await;+ assert!(!waiting.is_finished());+ fenced.store(true, Ordering::SeqCst);+ drop(recovery);+ let result = waiting.await.unwrap();+ assert!(result.err().unwrap().to_string().contains("fenced out"));+ assert_eq!(provider.creates.load(Ordering::SeqCst), 0);+ assert_eq!(provider.followups.load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn malformed_native_input_is_durable_before_decode_failure() {+ let journal = Journal::default();+ let provider = Arc::new(State {+ running: AtomicBool::new(true),+ native: Some(vec![NativeRecord {+ event: "future".into(),+ id: None,+ data: "not json".into(),+ }]),+ ..State::default()+ });+ let service = service(provider.clone(), journal.clone());+ let id = service.new_session().await.unwrap();+ let sink = Sink::default();+ assert!(service.prompt(&id, text("hello"), &sink).await.is_err());+ let entries = journal.read(&id).await.unwrap();+ assert!(entries.iter().any(+ |entry| matches!(&entry.input, JournalInput::Native(record) if record.data == "not json")+ ));+ assert!(entries.iter().any(|entry| matches!(&entry.input, JournalInput::PromptAccepted {task,..} if task == "task_test")));+ assert_eq!(provider.creates.load(Ordering::SeqCst), 1);+ assert_eq!(sink.0.lock().unwrap().len(), 1);+ service.cancel(&id).await.unwrap();+ assert_eq!(provider.cancels.load(Ordering::SeqCst), 1);+}++struct FailingNativeJournal(Journal);+impl SessionStore for FailingNativeJournal {+ async fn load(&self, id: &str) -> Result<Option<StoredSession>, rootcause::Report> {+ self.0.load(id).await+ }+ async fn save(&self, id: &str, state: &StoredSession) -> Result<(), rootcause::Report> {+ self.0.save(id, state).await+ }+ async fn read(&self, id: &str) -> Result<Vec<JournalEntry>, rootcause::Report> {+ self.0.read(id).await+ }+ async fn append(+ &self,+ id: &str,+ expected: i64,+ turn: Option<&TurnId>,+ input: &JournalInput,+ ) -> Result<JournalEntry, rootcause::Report> {+ if matches!(input, JournalInput::Native(_)) {+ return Err(rootcause::report!("injected append failure"));+ }+ self.0.append(id, expected, turn, input).await+ }+ async fn validate(&self) -> Result<(), rootcause::Report> {+ Ok(())+ }+}+#[tokio::test]+async fn failed_native_append_never_delivers_unpersisted_provider_output() {+ let journal = Journal::default();+ let provider = Arc::new(State {+ running: AtomicBool::new(true),+ native: Some(vec![NativeRecord::from_event(CloudEvent {+ id: "private-output".into(),+ method: "item/agentMessage/delta".into(),+ params: serde_json::json!({"delta":"must not escape"}),+ })]),+ ..State::default()+ });+ let service = SessionService::new(+ Arc::new(Probe::new(Provider(provider.clone()), Auth)),+ FailingNativeJournal(journal.clone()),+ Some(crate::domain::runtime::CloudTarget {+ environment: CloudId::new("env_test".into()).unwrap(),+ branch: "main".into(),+ repository_url: None,+ }),+ );+ let id = service.new_session().await.unwrap();+ let sink = Sink::default();+ assert!(service.prompt(&id, text("hello"), &sink).await.is_err());+ assert_eq!(sink.0.lock().unwrap().len(), 1);+ assert!(+ !journal+ .read(&id)+ .await+ .unwrap()+ .iter()+ .any(|entry| matches!(entry.input, JournalInput::Native(_)))+ );+ assert_eq!(provider.creates.load(Ordering::SeqCst), 1);+}++#[derive(Default)]+struct HostedRecoverySink(AtomicBool);+impl SessionSink for HostedRecoverySink {+ fn emit(&self, _: &CloudEvent) -> Result<(), rootcause::Report> {+ self.0.store(true, Ordering::SeqCst);+ Ok(())+ }+ fn recovered(&self) -> Result<bool, rootcause::Report> {+ Ok(self.0.load(Ordering::SeqCst))+ }+}+#[tokio::test]+async fn recovered_history_requires_successful_replacement_before_followup_dispatch() {+ let provider = Arc::new(State {+ allow_follow_up: true,+ ..State::default()+ });+ let journal = Journal::default();+ let initial = service(provider.clone(), journal.clone());+ let id = initial.new_session().await.unwrap();+ let mut stored = journal.load(&id).await.unwrap().unwrap();+ stored.target = Some(CloudTarget {+ environment: CloudId::new("env_test".into()).unwrap(),+ branch: "main".into(),+ repository_url: None,+ });+ stored.task = Some("task_test".into());+ stored.turn = Some("turn_new".into());+ journal.save(&id, &stored).await.unwrap();+ drop(initial);+ let service = Arc::new(service(provider.clone(), journal));+ let recovery = service+ .prepare_recovery(&id, &Sink::default())+ .await+ .unwrap();+ service+ .finish_recovery(&id, recovery, &HostedRecoverySink::default())+ .await+ .unwrap();+ let waiting = {+ let service = service.clone();+ let id = id.clone();+ tokio::spawn(async move {+ service+ .prompt(&id, text("continue"), &Sink::default())+ .await+ })+ };+ tokio::task::yield_now().await;+ assert!(!waiting.is_finished());+ assert_eq!(provider.followups.load(Ordering::SeqCst), 0);+ let replacement = service+ .prepare_recovery(&id, &Sink::default())+ .await+ .unwrap();+ tokio::task::yield_now().await;+ assert_eq!(provider.followups.load(Ordering::SeqCst), 0);+ service+ .finish_recovery(&id, replacement, &Sink::default())+ .await+ .unwrap();+ assert!(matches!(+ waiting.await.unwrap().unwrap(),+ Outcome::Completed+ ));+ assert_eq!(provider.followups.load(Ordering::SeqCst), 1);+ assert_eq!(provider.creates.load(Ordering::SeqCst), 0);+}++#[test]+fn old_session_target_layout_is_rejected() {+ let old = serde_json::json!({"account_id":"account","connection_id":"connection","environment":"old","branch":"main","task":null,"turn":null,"uncertain_write":false});+ assert!(serde_json::from_value::<StoredSession>(old).is_err());+ assert!(+ serde_json::from_value::<StoredSession>(+ serde_json::to_value(StoredSession::default()).unwrap()+ )+ .is_ok()+ );+}++#[tokio::test]+async fn saved_task_without_target_is_rejected_instead_of_selecting_a_new_one() {+ let journal = Journal::default();+ let provider = Arc::new(State::default());+ let first = service(provider.clone(), journal.clone());+ let id = first.new_session().await.unwrap();+ let mut stored = journal.load(&id).await.unwrap().unwrap();+ stored.task = Some("task_test".into());+ stored.turn = Some("turn_new".into());+ journal.save(&id, &stored).await.unwrap();+ drop(first);+ let restarted = service(provider.clone(), journal);+ let error = restarted+ .prompt(&id, text("continue"), &Sink::default())+ .await+ .err()+ .unwrap();+ assert!(error.to_string().contains("no pinned target"));+ assert_eq!(provider.creates.load(Ordering::SeqCst), 0);+ assert_eq!(provider.followups.load(Ordering::SeqCst), 0);+}++mod metadata_test;diff --git a/crates/codex_cloud_agents/src/domain/acp_session/test/metadata_test.rs b/crates/codex_cloud_agents/src/domain/acp_session/test/metadata_test.rsnew file mode 100644index 0000000000..dd0fcaa6bc--- /dev/null+++ b/crates/codex_cloud_agents/src/domain/acp_session/test/metadata_test.rs@@ -0,0 +1,366 @@+use super::*;+use crate::domain::cloud::ExternalPullRequest;+use crate::domain::runtime::{CloudRuntime, RuntimeIdentity};++struct Runtime {+ prs: Mutex<Vec<ExternalPullRequest>>,+ reports: Mutex<Vec<String>>,+ failed: AtomicBool,+ foreign: AtomicBool,+ reads: AtomicUsize,+ journal: Journal,+ hold: AtomicBool,+ entered: tokio::sync::Notify,+ release: tokio::sync::Notify,+}+impl CloudRuntime for Runtime {+ async fn identity(&self) -> Result<RuntimeIdentity, rootcause::Report> {+ let account = if self.foreign.load(Ordering::SeqCst) {+ "foreign"+ } else {+ "test-account"+ };+ Ok(RuntimeIdentity {+ account_id: account.into(),+ connection_id: account.into(),+ })+ }+ async fn resolve_target(+ &self,+ _: &str,+ _: Option<&CloudTarget>,+ ) -> Result<CloudTarget, rootcause::Report> {+ panic!("metadata never selects a new target")+ }+ async fn launch(&self, _: &Launch) -> Result<CreatedTask, rootcause::Report> {+ panic!("metadata never creates cloud work")+ }+ async fn follow_up(+ &self,+ _: &CloudId,+ _: &TurnId,+ _: &str,+ ) -> Result<CreatedTask, rootcause::Report> {+ panic!("metadata never continues cloud work")+ }+ async fn cancel(&self, _: &CloudId) -> Result<(), rootcause::Report> {+ panic!("metadata never cancels cloud work")+ }+ async fn turn(&self, _: &CloudId, _: &TurnId) -> Result<TaskSnapshot, rootcause::Report> {+ panic!("metadata uses task details")+ }+ async fn stream(&self, _: &CloudId, _: &TurnId) -> Result<CloudEventStream, rootcause::Report> {+ panic!("metadata never replays SSE")+ }+ async fn snapshot(&self, task: &CloudId) -> Result<TaskSnapshot, rootcause::Report> {+ self.reads.fetch_add(1, Ordering::SeqCst);+ let prs = self.prs.lock().unwrap().clone();+ if self.hold.load(Ordering::SeqCst) {+ self.entered.notify_one();+ self.release.notified().await;+ }+ Ok(TaskSnapshot {+ task_id: task.clone(),+ native: None,+ title: None,+ assistant_status: Some("completed".into()),+ turns: vec![],+ pull_requests: prs,+ })+ }+ async fn report_pull_request(&self, url: &str) -> Result<(), rootcause::Report> {+ // A host must never receive PR metadata before its source evidence is durable.+ let found = self+ .journal+ .1+ .lock()+ .unwrap()+ .values()+ .flatten()+ .any(|entry| serde_json::to_string(&entry.input).unwrap().contains(url));+ assert!(found, "publication precedes native journal evidence");+ self.reports.lock().unwrap().push(url.into());+ if self.failed.load(Ordering::SeqCst) {+ return Err(rootcause::report!("injected PR persistence failure"));+ }+ Ok(())+ }+}+fn pr(turn: &str, repo: &str, number: u32) -> ExternalPullRequest {+ ExternalPullRequest {+ assistant_turn_id: TurnId::new(turn.into()).unwrap(),+ url: format!("https://github.com/{repo}/pull/{number}"),+ }+}+async fn fixture() -> (String, Journal, Arc<Runtime>) {+ let id = uuid::Uuid::now_v7().to_string();+ let journal = Journal::default();+ journal+ .save(+ &id,+ &StoredSession {+ account_id: "test-account".into(),+ connection_id: "test-account".into(),+ target: Some(CloudTarget {+ environment: CloudId::new("env_test".into()).unwrap(),+ branch: "main".into(),+ repository_url: Some("https://github.com/org/repo".into()),+ }),+ task: Some("task_test".into()),+ turn: Some("turn_new".into()),+ uncertain_write: false,+ },+ )+ .await+ .unwrap();+ journal+ .append(&id, 0, None, &JournalInput::HistoryComplete)+ .await+ .unwrap();+ journal+ .append(&id, 1, None, &JournalInput::Prompt(text("original")))+ .await+ .unwrap();+ journal+ .append(+ &id,+ 2,+ None,+ &JournalInput::PromptAccepted {+ task: "task_test".into(),+ turn: Some("turn_old".into()),+ },+ )+ .await+ .unwrap();+ journal+ .append(+ &id,+ 3,+ None,+ &JournalInput::PromptAccepted {+ task: "task_test".into(),+ turn: Some("turn_new".into()),+ },+ )+ .await+ .unwrap();+ journal+ .append(&id, 4, None, &JournalInput::Terminal("completed".into()))+ .await+ .unwrap();+ let runtime = Arc::new(Runtime {+ prs: Mutex::new(vec![]),+ reports: Mutex::new(vec![]),+ failed: AtomicBool::new(false),+ foreign: AtomicBool::new(false),+ reads: AtomicUsize::new(0),+ journal: journal.clone(),+ hold: AtomicBool::new(false),+ entered: tokio::sync::Notify::new(),+ release: tokio::sync::Notify::new(),+ });+ (id, journal, runtime)+}+#[tokio::test]+async fn delayed_pr_is_published_once_and_replayed_as_an_observed_link() {+ let (id, journal, runtime) = fixture().await;+ let service = SessionService::new(runtime.clone(), journal.clone(), None);+ let before = Sink::default();+ service.replay(&id, &before).await.unwrap();+ service.refresh_metadata().await.unwrap();+ assert!(runtime.reports.lock().unwrap().is_empty());+ assert_eq!(journal.read(&id).await.unwrap().len(), 5);+ *runtime.prs.lock().unwrap() = vec![pr("turn_new", "org/repo", 42)];+ assert_eq!(service.refresh_metadata().await.unwrap(), vec![id.clone()]);+ assert!(service.refresh_metadata().await.unwrap().is_empty());+ runtime.prs.lock().unwrap().clear();+ service.refresh_metadata().await.unwrap();+ assert_eq!(+ *runtime.reports.lock().unwrap(),+ ["https://github.com/org/repo/pull/42"]+ );+ assert_eq!(journal.read(&id).await.unwrap().len(), 6);+ *runtime.prs.lock().unwrap() = vec![pr("turn_new", "org/repo", 43)];+ service.refresh_metadata().await.unwrap();+ assert_eq!(+ runtime.reports.lock().unwrap().last().unwrap(),+ "https://github.com/org/repo/pull/43"+ );+ assert_eq!(journal.read(&id).await.unwrap().len(), 7);+ let after = Sink::default();+ service.replay(&id, &after).await.unwrap();+ let after = after.0.lock().unwrap();+ let links: Vec<_> = after+ .iter()+ .filter(|event| event.method == "adapter/pull_request")+ .collect();+ assert_eq!(links.len(), 1);+ assert_eq!(+ links[0].params["url"],+ "https://github.com/org/repo/pull/43"+ );+ assert_eq!(links[0].params["source"], "codex_cloud_metadata");+ let original: Vec<_> = after+ .iter()+ .filter(|event| event.method != "adapter/pull_request")+ .collect();+ assert_eq!(+ serde_json::to_value(&*before.0.lock().unwrap()).unwrap(),+ serde_json::to_value(original).unwrap()+ );+}+#[tokio::test]+async fn failed_publication_retries_persisted_evidence_even_after_restart_and_empty_snapshot() {+ let (id, journal, runtime) = fixture().await;+ runtime.failed.store(true, Ordering::SeqCst);+ *runtime.prs.lock().unwrap() = vec![pr("turn_new", "org/repo", 42)];+ let service = SessionService::new(runtime.clone(), journal.clone(), None);+ service.session(&id).await.unwrap();+ assert!(service.refresh_metadata().await.is_err());+ assert_eq!(runtime.reports.lock().unwrap().len(), 1);+ assert_eq!(journal.read(&id).await.unwrap().len(), 6);+ drop(service);+ runtime.prs.lock().unwrap().clear();+ runtime.failed.store(false, Ordering::SeqCst);+ let restarted = SessionService::new(runtime.clone(), journal.clone(), None);+ restarted.session(&id).await.unwrap();+ restarted.refresh_metadata().await.unwrap();+ restarted.refresh_metadata().await.unwrap();+ assert_eq!(runtime.reports.lock().unwrap().len(), 2);+ assert_eq!(journal.read(&id).await.unwrap().len(), 6);+}+#[tokio::test]+async fn only_latest_locally_accepted_turn_with_matching_repo_can_update_the_pr() {+ let (id, journal, runtime) = fixture().await;+ *runtime.prs.lock().unwrap() = vec![+ pr("foreign_turn", "org/repo", 99),+ pr("turn_new", "other/repo", 98),+ pr("turn_old", "org/repo", 1),+ ];+ let service = SessionService::new(runtime.clone(), journal, None);+ service.session(&id).await.unwrap();+ service.refresh_metadata().await.unwrap();+ assert_eq!(+ runtime.reports.lock().unwrap().last().unwrap(),+ "https://github.com/org/repo/pull/1"+ );+ runtime+ .prs+ .lock()+ .unwrap()+ .push(pr("turn_new", "org/repo", 2));+ service.refresh_metadata().await.unwrap();+ assert_eq!(+ runtime.reports.lock().unwrap().last().unwrap(),+ "https://github.com/org/repo/pull/2"+ );+ *runtime.prs.lock().unwrap() = vec![pr("turn_old", "org/repo", 3)];+ service.refresh_metadata().await.unwrap();+ assert_eq!(runtime.reports.lock().unwrap().len(), 2);+}+#[tokio::test]+async fn stale_fence_or_switched_account_stops_refresh_before_provider_reads() {+ let (id, journal, runtime) = fixture().await;+ let fenced = Arc::new(AtomicBool::new(false));+ let service = SessionService::new(+ runtime.clone(),+ FencedJournal {+ inner: journal,+ fenced: fenced.clone(),+ },+ None,+ );+ service.replay(&id, &Sink::default()).await.unwrap();+ fenced.store(true, Ordering::SeqCst);+ assert!(service.refresh_metadata().await.is_err());+ assert_eq!(runtime.reads.load(Ordering::SeqCst), 0);+ fenced.store(false, Ordering::SeqCst);+ runtime.foreign.store(true, Ordering::SeqCst);+ assert!(service.refresh_metadata().await.is_err());+ assert_eq!(runtime.reads.load(Ordering::SeqCst), 0);+ assert!(runtime.reports.lock().unwrap().is_empty());+}++#[tokio::test]+async fn slow_metadata_read_cannot_overwrite_a_newer_foreground_observation() {+ let (id, journal, runtime) = fixture().await;+ runtime.hold.store(true, Ordering::SeqCst);+ *runtime.prs.lock().unwrap() = vec![pr("turn_new", "org/repo", 1)];+ let service = Arc::new(SessionService::new(runtime.clone(), journal.clone(), None));+ let session = service.session(&id).await.unwrap();+ let refresh = {+ let service = service.clone();+ tokio::spawn(async move { service.refresh_metadata().await })+ };+ runtime.entered.notified().await;+ let mut fresh = snapshot("turn_new", "completed");+ fresh.pull_requests = vec![pr("turn_new", "org/repo", 2)];+ service+ .record(+ &id,+ &session,+ JournalInput::Poll {+ snapshot: fresh,+ native: None,+ },+ &Discard,+ )+ .await+ .unwrap();+ *runtime.prs.lock().unwrap() = vec![pr("turn_new", "org/repo", 2)];+ runtime.hold.store(false, Ordering::SeqCst);+ runtime.release.notify_one();+ refresh.await.unwrap().unwrap();+ service.refresh_metadata().await.unwrap();+ assert_eq!(+ *runtime.reports.lock().unwrap(),+ ["https://github.com/org/repo/pull/2"]+ );+ assert_eq!(journal.read(&id).await.unwrap().len(), 6);+}++#[tokio::test]+async fn pr_reload_waits_for_active_load_and_replays_the_new_link() {+ let (id, journal, runtime) = fixture().await;+ let service = Arc::new(SessionService::new(runtime.clone(), journal, None));+ let initial = Sink::default();+ let recovery = service.prepare_recovery(&id, &initial).await.unwrap();+ assert!(+ initial+ .0+ .lock()+ .unwrap()+ .iter()+ .all(|event| event.method != "adapter/pull_request")+ );++ *runtime.prs.lock().unwrap() = vec![pr("turn_new", "org/repo", 42)];+ assert_eq!(service.refresh_metadata().await.unwrap(), vec![id.clone()]);+ let reload = tokio::spawn(async move {+ let output = Sink::default();+ let recovery = service.prepare_recovery(&id, &output).await.unwrap();+ drop(recovery);+ output+ });+ tokio::task::yield_now().await;+ assert!(+ !reload.is_finished(),+ "replacement must wait for the active load"+ );+ drop(recovery);+ let output = tokio::time::timeout(std::time::Duration::from_secs(2), reload)+ .await+ .unwrap()+ .unwrap();+ let events = output.0.lock().unwrap();+ let links: Vec<_> = events+ .iter()+ .filter(|event| event.method == "adapter/pull_request")+ .collect();+ assert_eq!(links.len(), 1);+ assert_eq!(+ links[0].params["url"],+ "https://github.com/org/repo/pull/42"+ );+}diff --git a/crates/codex_cloud_agents/src/domain/cloud.rs b/crates/codex_cloud_agents/src/domain/cloud.rsnew file mode 100644index 0000000000..f498f82174--- /dev/null+++ b/crates/codex_cloud_agents/src/domain/cloud.rs@@ -0,0 +1,318 @@+//! Cloud task commands, observations, and conversation provider ports.++use super::{CredentialStore, Credentials, OAuth, Probe};+use serde::Serialize;++/// Provider identifier validated before it can become a URL segment.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(transparent)]+pub struct CloudId(String);++impl<'de> serde::Deserialize<'de> for CloudId {+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ Self::new(<String as serde::Deserialize>::deserialize(deserializer)?)+ .map_err(serde::de::Error::custom)+ }+}++impl CloudId {+ /// Accept only an opaque alphanumeric identifier with hyphens/underscores.+ pub fn new(value: String) -> Result<Self, rootcause::Report> {+ if value.is_empty()+ || value.len() > 256+ || !value+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b))+ {+ return Err(rootcause::report!("invalid cloud identifier"));+ }+ Ok(Self(value))+ }+ /// The validated provider identifier.+ pub fn as_str(&self) -> &str {+ &self.0+ }+}++/// A single explicitly requested cloud execution.+pub struct Launch {+ /// Existing cloud environment.+ pub environment: CloudId,+ /// Explicit branch; never inferred from the probe repository.+ pub branch: String,+ /// Text to send once to OpenAI.+ pub prompt: String,+}++impl Launch {+ /// Reject empty/oversized input before credential use or provider writes.+ pub fn validate(&self) -> Result<(), rootcause::Report> {+ validate_branch(&self.branch)?;+ if self.prompt.trim().is_empty() || self.prompt.len() > 64 * 1024 {+ return Err(rootcause::report!(+ "provide a branch and nonempty prompt (maximum 64 KiB)"+ ));+ }+ Ok(())+ }+}++/// Validate a branch or full Git ref before selecting a remote execution target.+pub fn validate_branch(branch: &str) -> Result<(), rootcause::Report> {+ if branch.is_empty()+ || branch.len() > 1024+ || branch.starts_with('-')+ || branch == "@"+ || branch.contains("..")+ || branch.contains("@{")+ || branch+ .chars()+ .any(|c| c.is_control() || c.is_whitespace() || "~^:?*[\\".contains(c))+ || branch.split('/').any(|part| {+ part.is_empty()+ || part.starts_with('.')+ || part.ends_with('.')+ || part.ends_with(".lock")+ })+ {+ return Err(rootcause::report!("invalid cloud Git branch"));+ }+ Ok(())+}++/// Task creation receipt; losing this response must never trigger an automatic retry.+#[derive(Debug, Clone, Serialize)]+pub struct CreatedTask {+ /// Initial assistant turn, when returned by the provider.+ pub assistant_turn_id: Option<TurnId>,+ /// Provider task identity.+ pub task_id: CloudId,+ /// Codex web task URL.+ pub url: String,+}++/// A projected task-details snapshot, not a complete conversation history.+#[derive(Debug, Clone, Serialize, serde::Deserialize)]+pub struct TaskSnapshot {+ /// Original successful provider response for native journaling; omitted from CLI output.+ #[serde(skip)]+ pub native: Option<String>,+ /// Exact requested task.+ pub task_id: CloudId,+ /// Provider title, when present.+ pub title: Option<String>,+ /// Status from the current assistant turn, unmodified; unknown values stay unknown.+ pub assistant_status: Option<String>,+ /// Selected current turns only, preserving which field each observation came from.+ pub turns: Vec<TurnSnapshot>,+ /// Verified provider PR associations, independent of proposed diffs or assistant text.+ pub pull_requests: Vec<ExternalPullRequest>,+}++/// A real GitHub pull request associated by the provider with an assistant turn.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)]+pub struct ExternalPullRequest {+ /// Provider turn association; never inferred from the current turn.+ pub assistant_turn_id: TurnId,+ /// Canonical credential-free GitHub pull request URL.+ pub url: String,+}++impl TaskSnapshot {+ /// Only explicit known assistant terminal statuses terminate observation.+ pub fn terminal(&self) -> bool {+ matches!(+ self.assistant_status.as_deref(),+ Some("completed" | "failed" | "cancelled")+ )+ }+}++/// Output available in one current turn at the time of a read.+#[derive(Debug, Clone, Serialize, serde::Deserialize)]+pub struct TurnSnapshot {+ /// Source field, such as `current_assistant_turn`.+ pub source: String,+ /// Provider turn ID, if returned.+ pub id: Option<String>,+ /// Text blocks in message output items; no invented tool/thought events.+ pub messages: Vec<String>,+ /// Output item kinds, useful for discovering provider vocabulary.+ pub output_types: Vec<String>,+ /// Whether the turn exposes a diff, without printing file contents implicitly.+ pub has_diff: bool,+}++/// Independently testable task transport, separate from OAuth.+pub trait CloudTasks: Send + Sync {+ /// Send a creation request exactly once.+ fn create(+ &self,+ auth: &Credentials,+ request: &Launch,+ ) -> impl Future<Output = Result<CreatedTask, rootcause::Report>> + Send;+ /// Fetch the current snapshot for one task.+ fn snapshot(+ &self,+ auth: &Credentials,+ task: &CloudId,+ ) -> impl Future<Output = Result<TaskSnapshot, rootcause::Report>> + Send;+}++impl<Provider: OAuth + CloudTasks, Store: CredentialStore> Probe<Provider, Store> {+ /// Launch only into an environment visible to this connection; never retry a write.+ pub async fn launch(+ &self,+ request: &Launch,+ now: u64,+ ) -> Result<CreatedTask, rootcause::Report> {+ request.validate()?;+ let auth = self.credentials(now).await?;+ let environments = self.provider.environments(&auth).await?;+ if !environments+ .iter()+ .any(|env| env.id == request.environment.as_str())+ {+ return Err(rootcause::report!(+ "environment is not visible to this connected account; no task submitted"+ ));+ }+ self.provider.create(&auth, request).await+ }++ /// Observe a task without starting, continuing or cancelling work.+ pub async fn snapshot(+ &self,+ task: &CloudId,+ now: u64,+ ) -> Result<TaskSnapshot, rootcause::Report> {+ let auth = self.credentials(now).await?;+ self.provider.snapshot(&auth, task).await+ }+}++/// Provider turn identity, including its task-qualified `~` separator.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(transparent)]+pub struct TurnId(String);++impl<'de> serde::Deserialize<'de> for TurnId {+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ Self::new(<String as serde::Deserialize>::deserialize(deserializer)?)+ .map_err(serde::de::Error::custom)+ }+}++impl TurnId {+ /// Validate an opaque turn ID before placing it in a URL.+ pub fn new(value: String) -> Result<Self, rootcause::Report> {+ if value.is_empty()+ || value.len() > 512+ || !value+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b"_-~".contains(&b))+ {+ return Err(rootcause::report!("invalid cloud turn identifier"));+ }+ Ok(Self(value))+ }+ /// Borrow the validated identity.+ pub fn as_str(&self) -> &str {+ &self.0+ }+}++/// Identified provider event; unknown methods remain available for reconciliation.+#[derive(Debug, Clone, Serialize, serde::Deserialize)]+pub struct CloudEvent {+ /// Stable outer provider event identity for replay deduplication.+ pub id: String,+ /// Provider event method, or `log` for a setup log.+ pub method: String,+ /// Structured event fields, translated by the consuming protocol adapter.+ pub params: serde_json::Value,+}++mod native;+mod snapshot;+pub use native::NativeRecord;++/// Owned event subscription; dropping it stops local observation only.+pub type CloudEventStream =+ std::pin::Pin<Box<dyn futures::Stream<Item = Result<NativeRecord, rootcause::Report>> + Send>>;++/// Continuation and observation capabilities evidenced by the official desktop client.+pub trait CloudConversation: CloudTasks {+ /// Submit one continuation, without retrying an ambiguous provider write.+ fn follow_up(+ &self,+ auth: &Credentials,+ task: &CloudId,+ turn: &TurnId,+ prompt: &str,+ ) -> impl Future<Output = Result<CreatedTask, rootcause::Report>> + Send;+ /// Request remote cancellation; callers must still verify terminal state.+ fn cancel(+ &self,+ auth: &Credentials,+ task: &CloudId,+ ) -> impl Future<Output = Result<(), rootcause::Report>> + Send;+ /// Read a particular assistant turn, independent of the task's current selection.+ fn turn(+ &self,+ auth: &Credentials,+ task: &CloudId,+ turn: &TurnId,+ ) -> impl Future<Output = Result<TaskSnapshot, rootcause::Report>> + Send;+ /// Open a replay/live event subscription with bounded parsing and no assumed cursor.+ fn stream(+ &self,+ auth: &Credentials,+ task: &CloudId,+ turn: &TurnId,+ ) -> impl Future<Output = Result<CloudEventStream, rootcause::Report>> + Send;+}++impl<Provider: OAuth + CloudConversation, Store: CredentialStore> Probe<Provider, Store> {+ /// Continue a task using saved credentials, refreshing them before submission.+ pub async fn follow_up(+ &self,+ task: &CloudId,+ turn: &TurnId,+ prompt: &str,+ now: u64,+ ) -> Result<CreatedTask, rootcause::Report> {+ if prompt.trim().is_empty() || prompt.len() > 64 * 1024 {+ return Err(rootcause::report!(+ "provide a nonempty prompt (maximum 64 KiB)"+ ));+ }+ let auth = self.credentials(now).await?;+ self.provider.follow_up(&auth, task, turn, prompt).await+ }+ /// Request remote cancellation, without claiming it is already complete.+ pub async fn cancel(&self, task: &CloudId, now: u64) -> Result<(), rootcause::Report> {+ let auth = self.credentials(now).await?;+ self.provider.cancel(&auth, task).await+ }+ /// Read the authoritative state and final output of a particular turn.+ pub async fn turn(+ &self,+ task: &CloudId,+ turn: &TurnId,+ now: u64,+ ) -> Result<TaskSnapshot, rootcause::Report> {+ let auth = self.credentials(now).await?;+ self.provider.turn(&auth, task, turn).await+ }+ /// Subscribe using current credentials; stream EOF does not imply completion.+ pub async fn stream(+ &self,+ task: &CloudId,+ turn: &TurnId,+ now: u64,+ ) -> Result<CloudEventStream, rootcause::Report> {+ let auth = self.credentials(now).await?;+ self.provider.stream(&auth, task, turn).await+ }+}diff --git a/crates/codex_cloud_agents/src/domain/cloud/native.rs b/crates/codex_cloud_agents/src/domain/cloud/native.rsnew file mode 100644index 0000000000..31756ef8ab--- /dev/null+++ b/crates/codex_cloud_agents/src/domain/cloud/native.rs@@ -0,0 +1,68 @@+//! Native SSE inputs are decoded only after the session journal accepts them.+use super::CloudEvent;+use serde::{Deserialize, Serialize};++/// Complete SSE frame, retaining its original data and optional framing fields.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct NativeRecord {+ /// SSE event name, empty when omitted.+ pub event: String,+ /// Explicit SSE id header, distinct from the WHAM JSON event identity.+ pub id: Option<String>,+ /// Original data lines joined with newlines by the SSE framer.+ pub data: String,+}+impl NativeRecord {+ /// Decode a durably captured input; unknown envelope kinds remain journaled.+ pub fn decode(&self) -> Result<Option<CloudEvent>, rootcause::Report> {+ let value: serde_json::Value = serde_json::from_str(&self.data)+ .map_err(|_| rootcause::report!("invalid cloud event JSON (body withheld)"))?;+ let kind = value.get("item_type").and_then(serde_json::Value::as_str);+ if !matches!(kind, Some("thread_event" | "log")) {+ return Ok(None);+ }+ let id = value+ .get("id")+ .and_then(serde_json::Value::as_str)+ .filter(|id| !id.is_empty() && id.len() <= 512 && !id.chars().any(char::is_control))+ .ok_or_else(|| rootcause::report!("cloud event missing valid replay identity"))?;+ if kind == Some("log") {+ return Ok(Some(CloudEvent {+ id: id.into(),+ method: "log".into(),+ params: value,+ }));+ }+ let method = value+ .pointer("/event/method")+ .and_then(serde_json::Value::as_str)+ .filter(|method| !method.is_empty() && method.len() <= 256)+ .ok_or_else(|| rootcause::report!("cloud thread event missing method"))?;+ let params = value+ .pointer("/event/params")+ .filter(|params| params.is_object())+ .ok_or_else(|| rootcause::report!("cloud thread event missing structured params"))?;+ Ok(Some(CloudEvent {+ id: id.into(),+ method: method.into(),+ params: params.clone(),+ }))+ }++ /// Construct a synthetic native envelope for a domain event in demos and fixtures.+ pub fn from_event(event: CloudEvent) -> Self {+ let data = if event.method == "log" {+ let mut value = event.params;+ value["id"] = event.id.into();+ value["item_type"] = "log".into();+ value+ } else {+ serde_json::json!({"id":event.id,"item_type":"thread_event","event":{"method":event.method,"params":event.params}})+ };+ Self {+ event: String::new(),+ id: None,+ data: data.to_string(),+ }+ }+}diff --git a/crates/codex_cloud_agents/src/domain/cloud/snapshot.rs b/crates/codex_cloud_agents/src/domain/cloud/snapshot.rsnew file mode 100644index 0000000000..a2f4e2a2fe--- /dev/null+++ b/crates/codex_cloud_agents/src/domain/cloud/snapshot.rs@@ -0,0 +1,122 @@+//! One native task/turn projection shared by transport reads and journal replay.+use super::{CloudId, ExternalPullRequest, TaskSnapshot, TurnId, TurnSnapshot};+use serde_json::Value;++impl TaskSnapshot {+ /// Interpret the original provider response while preserving it for later replay.+ pub fn from_native(task: &CloudId, data: &str) -> Result<Self, rootcause::Report> {+ let body: Value = serde_json::from_str(data)+ .map_err(|_| rootcause::report!("invalid cloud snapshot JSON (body withheld)"))?;+ let normalized = if body.get("turn").is_some() {+ serde_json::json!({"task":body.get("task"), "current_assistant_turn":body.get("turn"), "current_user_turn":body.get("user_turn")})+ } else {+ body+ };+ let mut snapshot = project(task, &normalized)?;+ snapshot.native = Some(data.to_owned());+ Ok(snapshot)+ }+}++pub(super) fn project(task: &CloudId, body: &Value) -> Result<TaskSnapshot, rootcause::Report> {+ if body.pointer("/task/id").and_then(Value::as_str) != Some(task.as_str()) {+ return Err(rootcause::report!(+ "task details identity mismatch or unexpected response shape"+ ));+ }+ let turns = [+ "current_user_turn",+ "current_assistant_turn",+ "current_diff_task_turn",+ ]+ .into_iter()+ .filter_map(|source| {+ let turn = body.get(source)?.as_object()?;+ let items = turn.get("output_items").and_then(Value::as_array);+ let messages = items+ .into_iter()+ .flatten()+ .filter(|item| item.get("type").and_then(Value::as_str) == Some("message"))+ .flat_map(|item| {+ item.get("content")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ })+ .filter(|block| block.get("content_type").and_then(Value::as_str) == Some("text"))+ .filter_map(|block| block.get("text").and_then(Value::as_str).map(str::to_owned))+ .collect();+ let output_types = items+ .into_iter()+ .flatten()+ .filter_map(|item| item.get("type").and_then(Value::as_str).map(str::to_owned))+ .collect();+ let has_diff = items+ .into_iter()+ .flatten()+ .any(|item| item.get("diff").is_some() || item.get("output_diff").is_some());+ Some(TurnSnapshot {+ source: source.to_owned(),+ id: turn.get("id").and_then(Value::as_str).map(str::to_owned),+ messages,+ output_types,+ has_diff,+ })+ })+ .collect();+ Ok(TaskSnapshot {+ native: None,+ task_id: task.clone(),+ title: body+ .pointer("/task/title")+ .and_then(Value::as_str)+ .map(str::to_owned),+ assistant_status: body+ .pointer("/current_assistant_turn/turn_status")+ .and_then(Value::as_str)+ .map(str::to_owned),+ turns,+ pull_requests: body+ .pointer("/task/external_pull_requests")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .filter_map(project_pull_request)+ .collect(),+ })+}++// Accept exactly GitHub's canonical PR URL shape. Restricting every path segment+// excludes URL userinfo, queries, fragments, encoded separators and other origins.+fn project_pull_request(value: &Value) -> Option<ExternalPullRequest> {+ let assistant_turn_id =+ TurnId::new(value.get("assistant_turn_id")?.as_str()?.to_owned()).ok()?;+ let url = value.pointer("/pull_request/url")?.as_str()?;+ let path = url.strip_prefix("https://github.com/")?;+ let parts: Vec<_> = path.split('/').collect();+ if parts.len() != 4+ || parts[2] != "pull"+ || parts[..2].iter().any(|part| {+ part.is_empty()+ || *part == "."+ || *part == ".."+ || !part+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))+ })+ || !parts[3].bytes().all(|byte| byte.is_ascii_digit())+ {+ return None;+ }+ let number = parts[3].parse::<u64>().ok()?;+ if number == 0 {+ return None;+ }+ Some(ExternalPullRequest {+ assistant_turn_id,+ url: format!("https://github.com/{}/{}/pull/{number}", parts[0], parts[1]),+ })+}++#[cfg(test)]+mod test;diff --git a/crates/codex_cloud_agents/src/domain/cloud/snapshot/test.rs b/crates/codex_cloud_agents/src/domain/cloud/snapshot/test.rsnew file mode 100644index 0000000000..5d497d66b4--- /dev/null+++ b/crates/codex_cloud_agents/src/domain/cloud/snapshot/test.rs@@ -0,0 +1,76 @@+use super::*;+use serde_json::json;++fn association(turn: &str, url: &str) -> Value {+ json!({"assistant_turn_id":turn,"pull_request":{"url":url,"state":"future_status","merged":false}})+}+fn snapshot(body: &Value) -> TaskSnapshot {+ TaskSnapshot::from_native(&CloudId::new("task-one".into()).unwrap(), &body.to_string()).unwrap()+}++#[test]+fn only_structured_external_associations_create_pr_links() {+ let body = json!({"task":{"id":"task-one"},"current_assistant_turn":{"id":"task-one~turn-1","turn_status":"completed","output_items":[+ {"type":"pr","url":"https://github.com/owner/repo/pull/9","diff":"proposal"},+ {"type":"message","content":[{"content_type":"text","text":"Created https://github.com/owner/repo/pull/9"}]}+ ]}});+ let projected = snapshot(&body);+ assert!(projected.pull_requests.is_empty());+ assert_eq!(projected.turns[0].messages.len(), 1);+ assert!(projected.turns[0].has_diff);+}++#[test]+fn task_and_turn_reads_preserve_all_turn_associations_and_raw_native_input() {+ let task = json!({"id":"task-one","external_pull_requests":[+ association("task-one~turn-1","https://github.com/owner/repo/pull/9"),+ association("task-one~turn-2","https://github.com/other/repo/pull/10")+ ]});+ for field in ["current_assistant_turn", "turn"] {+ let body =+ json!({"task":task,field:{"id":"task-one~turn-2","turn_status":"unknown_status"}});+ let projected = snapshot(&body);+ assert_eq!(projected.pull_requests.len(), 2);+ assert_eq!(+ projected.pull_requests[0].assistant_turn_id.as_str(),+ "task-one~turn-1"+ );+ assert_eq!(+ projected.pull_requests[1].url,+ "https://github.com/other/repo/pull/10"+ );+ assert_eq!(+ projected.assistant_status.as_deref(),+ Some("unknown_status")+ );+ assert!(!projected.terminal());+ assert_eq!(projected.native.as_deref(), Some(body.to_string().as_str()));+ }+}++#[test]+fn malformed_associations_do_not_break_transcript_or_invent_current_turn_binding() {+ let mut associations = vec![+ association("bad/turn", "https://github.com/owner/repo/pull/9"),+ json!({"pull_request":{"url":"https://github.com/owner/repo/pull/9"}}),+ ];+ for url in [+ "http://github.com/owner/repo/pull/9",+ "https://github.com.evil/owner/repo/pull/9",+ "https://[email protected]/owner/repo/pull/9",+ "https://github.com/owner/repo/pull/9?secret=x",+ "https://github.com/owner/repo/pull/9#x",+ "https://github.com/owner/repo/issues/9",+ "https://github.com/owner/repo/pull/0",+ "https://github.com/owner/repo/pull/-9",+ "https://github.com/owner/repo/pull/9/",+ "https://github.com/owner/%72epo/pull/9",+ ] {+ associations.push(association("turn-1", url));+ }+ let body = json!({"task":{"id":"task-one","external_pull_requests":associations},"turn":{"id":"valid-turn","turn_status":"completed"}});+ let projected = snapshot(&body);+ assert!(projected.pull_requests.is_empty());+ assert!(projected.terminal());+ assert_eq!(projected.turns[0].id.as_deref(), Some("valid-turn"));+}diff --git a/crates/codex_cloud_agents/src/domain/journal.rs b/crates/codex_cloud_agents/src/domain/journal.rsnew file mode 100644index 0000000000..d3dbc8317e--- /dev/null+++ b/crates/codex_cloud_agents/src/domain/journal.rs@@ -0,0 +1,311 @@+//! Ordered native inputs and the shared live/replay conversation reducer.+use super::cloud::{CloudEvent, NativeRecord, TaskSnapshot, TurnId};+use serde::{Deserialize, Serialize};+use std::collections::HashSet;++/// A durable input captured before decoding or projecting provider output.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub enum JournalInput {+ /// Marks a complete history beginning, including an empty new conversation.+ HistoryComplete,+ /// Original supported user text, before attempting a provider write.+ Prompt(Vec<agent_client_protocol::schema::v1::ContentBlock>),+ /// Accepted submission identity, recorded before clearing uncertain-write state.+ PromptAccepted {+ /// The remote conversation.+ task: String,+ /// The accepted assistant turn, if the provider returned it.+ turn: Option<String>,+ },+ /// Original complete SSE frame, including unknown provider payloads.+ Native(NativeRecord),+ /// Provider observation used to reconcile final output and determine status.+ Poll {+ /// Snapshot interpreted by this adapter version.+ snapshot: TaskSnapshot,+ /// Exact provider response, including unknown fields.+ native: Option<String>,+ },+ /// Changed task metadata captured without adding conversation output.+ Metadata {+ /// Provider projection, used only when native data is absent in a fixture.+ snapshot: TaskSnapshot,+ /// Exact provider response preserved before metadata publication.+ native: Option<String>,+ },+ /// Stream failure or EOF, retained without inventing a terminal outcome.+ TransportError(String),+ /// An attachment began observing an already accepted turn.+ RecoveryStarted,+ /// User requested cancellation before the provider side effect.+ CancellationRequested,+ /// Submission returned an error; its remote outcome remains uncertain.+ SubmissionError(String),+ /// Verified provider terminal state after reconciliation.+ Terminal(String),+}+/// One append-only input with a fenced sequence number.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct JournalEntry {+ /// One-based strictly increasing position within this session.+ pub sequence: i64,+ /// Provider assistant turn associated with the input, when known.+ pub turn: Option<TurnId>,+ /// Native input consumed by the reducer.+ pub input: JournalInput,+}+/// Deterministic reduction shared by live delivery and session/load replay.+#[derive(Default)]+pub struct ReplayMachine {+ sequence: i64,+ failed: bool,+ terminal: bool,+ pending_terminal: Option<String>,+ seen: HashSet<String>,+ events: Vec<CloudEvent>,+ unclaimed_fallback: String,+ poll: Option<TaskSnapshot>,+ accepted: Vec<(String, String)>,+ pull_requests: std::collections::HashMap<String, Vec<super::cloud::ExternalPullRequest>>,+}+impl ReplayMachine {+ pub(crate) fn accepted(&self, task: &str) -> Vec<String> {+ self.accepted+ .iter()+ .filter(|(id, _)| id == task)+ .map(|(_, turn)| turn.clone())+ .collect()+ }+ pub(crate) fn pull_requests(&self, task: &str) -> Vec<super::cloud::ExternalPullRequest> {+ self.pull_requests.get(task).cloned().unwrap_or_default()+ }+ fn remember_metadata(&mut self, snapshot: &TaskSnapshot) {+ let entries = self+ .pull_requests+ .entry(snapshot.task_id.as_str().into())+ .or_default();+ // Reverse each observation so a reverse search sees its first valid+ // provider entry, before any older observation of the same turn.+ entries.extend(snapshot.pull_requests.iter().rev().cloned());+ }+ /// Last successfully consumed journal sequence.+ pub fn sequence(&self) -> i64 {+ self.sequence+ }+ pub(crate) fn ensure_appendable(&self, input: &JournalInput) -> Result<(), rootcause::Report> {+ if self.failed && !matches!(input, JournalInput::CancellationRequested) {+ return Err(rootcause::report!(+ "native journal cannot be replayed; observation stopped"+ ));+ }+ Ok(())+ }+ /// Validate ordering and reduce exactly one persisted input.+ pub fn push(&mut self, entry: &JournalEntry) -> Result<Vec<CloudEvent>, rootcause::Report> {+ if self.failed+ && matches!(entry.input, JournalInput::CancellationRequested)+ && entry.sequence == self.sequence + 1+ {+ // A malformed provider record must never disable an explicit remote stop.+ self.sequence = entry.sequence;+ return Ok(Vec::new());+ }+ if self.failed {+ return Err(rootcause::report!(+ "native journal cannot be replayed; observation stopped"+ ));+ }+ let result = self.reduce(entry);+ if result.is_err() {+ self.failed = true;+ }+ result+ }+ /// Finish a replay boundary after all captured records for its last turn.+ /// Deferring lifecycle output allows late recovered records to remain in that turn.+ pub fn finish(&mut self) -> Vec<CloudEvent> {+ let Some(status) = self.pending_terminal.clone() else {+ return Vec::new();+ };+ let mut output = if status == "completed" {+ self.reconcile_final()+ } else {+ Vec::new()+ };+ if !self.terminal {+ self.terminal = true;+ output.push(CloudEvent {+ id: String::new(),+ method: "session/turn_complete".into(),+ params: serde_json::json!({"status":status}),+ });+ }+ output+ }+ fn reconcile_final(&mut self) -> Vec<CloudEvent> {+ let mut output = Vec::new();+ if let Some(snapshot) = &self.poll {+ // SSE delivery can omit earlier deltas and insert them on replay. Only+ // completed messages and final poll text are authoritative for display.+ let mut represented = String::new();+ for event in &self.events {+ if event.method == "item/completed"+ && event.params["item"]["type"].as_str() == Some("agentMessage")+ && let Some(text) = event.params["item"]["text"].as_str()+ {+ represented.push_str(text);+ }+ }+ for (index, text) in snapshot+ .turns+ .iter()+ .filter(|turn| turn.source == "current_assistant_turn")+ .flat_map(|turn| &turn.messages)+ .enumerate()+ {+ if !text.is_empty()+ && let Some(start) = represented.find(text)+ {+ // A native completed item may contain several poll message+ // fragments. Consume exact bytes so repeated messages still+ // require a separate represented occurrence.+ represented.replace_range(start..start + text.len(), "");+ continue;+ }+ output.push(CloudEvent {+ id: String::new(),+ method: "item/completed".into(),+ params: serde_json::json!({"item":{+ "id":format!("poll-message:{index}"),+ "type":"agentMessage",+ "text":text,+ }}),+ });+ }+ for event in &output {+ if let Some(text) = event.params["item"]["text"].as_str() {+ self.unclaimed_fallback.push_str(text);+ }+ }+ self.events.extend(output.iter().cloned());+ self.poll = None;+ }+ output+ }+ fn reduce(&mut self, entry: &JournalEntry) -> Result<Vec<CloudEvent>, rootcause::Report> {+ if entry.sequence != self.sequence + 1 {+ return Err(rootcause::report!("native journal sequence is incomplete"));+ }+ if self.sequence == 0 && !matches!(entry.input, JournalInput::HistoryComplete) {+ return Err(rootcause::report!(+ "native journal has no complete history boundary"+ ));+ }+ self.sequence = entry.sequence;+ let mut output = Vec::new();+ match &entry.input {+ JournalInput::PromptAccepted {+ task,+ turn: Some(turn),+ } => {+ self.accepted.push((task.clone(), turn.clone()));+ }+ JournalInput::Metadata { snapshot, native } => {+ let snapshot = match native {+ Some(native) => TaskSnapshot::from_native(&snapshot.task_id, native)?,+ None => snapshot.clone(),+ };+ self.remember_metadata(&snapshot);+ }+ JournalInput::Prompt(blocks) => {+ output.extend(self.finish());+ self.pending_terminal = None;+ let text = blocks+ .iter()+ .filter_map(|block| match block {+ agent_client_protocol::schema::v1::ContentBlock::Text(text) => {+ Some(text.text.as_str())+ }+ _ => None,+ })+ .collect::<Vec<_>>()+ .join("\n");+ self.events.clear();+ self.unclaimed_fallback.clear();+ self.terminal = false;+ self.poll = None;+ output.push(CloudEvent {+ id: String::new(),+ method: "user/message".into(),+ params: serde_json::json!({"text":text}),+ });+ }+ JournalInput::Native(record) => {+ // Keep every raw record in storage; repeated provider IDs only suppress projection.+ if let Some(event) = record.decode()? {+ let identity = if event.id.is_empty() {+ record.id.as_deref()+ } else {+ Some(event.id.as_str())+ };+ let key = identity.map(|id| {+ format!(+ "{}:{id}",+ entry.turn.as_ref().map(TurnId::as_str).unwrap_or_default()+ )+ });+ if key.is_some_and(|key| !self.seen.insert(key)) {+ return Ok(output);+ }+ if event.method == "item/agentMessage/delta" {+ // Persisted fragments remain available for diagnosis, but their+ // arrival order is not a reliable order for visible text.+ return Ok(output);+ }+ if event.method == "item/completed"+ && event.params["item"]["type"].as_str() == Some("agentMessage")+ && let Some(text) = event.params["item"]["text"].as_str()+ && !text.is_empty()+ && let Some(start) = self.unclaimed_fallback.find(text)+ {+ // Claim each fallback occurrence only once: a distinct+ // later message is allowed to repeat the same text.+ self.unclaimed_fallback+ .replace_range(start..start + text.len(), "");+ return Ok(output);+ }+ self.events.push(event.clone());+ output.push(event);+ }+ }+ JournalInput::Poll { snapshot, native } => {+ let snapshot = match native {+ Some(native) => TaskSnapshot::from_native(&snapshot.task_id, native)?,+ None => snapshot.clone(),+ };+ self.remember_metadata(&snapshot);+ // A preflight task read can discover a web-side continuation. Retain+ // that fact without attributing its output to our pinned assistant turn.+ if let Some(expected) = &entry.turn+ && let Some(actual) = snapshot+ .turns+ .iter()+ .find(|turn| turn.source == "current_assistant_turn")+ .and_then(|turn| turn.id.as_deref())+ && actual != expected.as_str()+ {+ return Ok(output);+ }+ self.poll = Some(snapshot);+ }+ _ => {}+ }+ if let JournalInput::Terminal(status) = &entry.input {+ self.pending_terminal = Some(status.clone());+ }+ Ok(output)+ }+}++#[cfg(test)]+mod test;diff --git a/crates/codex_cloud_agents/src/domain/journal/test.rs b/crates/codex_cloud_agents/src/domain/journal/test.rsnew file mode 100644index 0000000000..c8e4307d26--- /dev/null+++ b/crates/codex_cloud_agents/src/domain/journal/test.rs@@ -0,0 +1,444 @@+use super::*;+use agent_client_protocol::schema::v1::{ContentBlock, TextContent};++fn entry(sequence: i64, input: JournalInput) -> JournalEntry {+ JournalEntry {+ sequence,+ turn: Some(TurnId::new("turn~test".into()).unwrap()),+ input,+ }+}+fn native(id: &str, method: &str, params: serde_json::Value) -> JournalInput {+ JournalInput::Native(NativeRecord::from_event(CloudEvent {+ id: id.into(),+ method: method.into(),+ params,+ }))+}+fn reduce(entries: &[JournalEntry]) -> Vec<serde_json::Value> {+ let mut machine = ReplayMachine::default();+ entries+ .iter()+ .flat_map(|entry| machine.push(entry).unwrap())+ .map(|event| serde_json::to_value(event).unwrap())+ .collect()+}+#[test]+fn live_and_serialized_replay_preserve_native_unknown_records_and_suppress_duplicate_output() {+ let inputs = vec![+ JournalInput::HistoryComplete,+ JournalInput::Prompt(vec![ContentBlock::Text(TextContent::new("hello"))]),+ JournalInput::Native(NativeRecord {+ event: "future-event".into(),+ id: None,+ data: "{\"item_type\":\"unknown\",\"future\":{\"kept\":true}}".into(),+ }),+ native(+ "one",+ "item/agentMessage/delta",+ serde_json::json!({"itemId":"msg","delta":"hello"}),+ ),+ native(+ "one",+ "item/agentMessage/delta",+ serde_json::json!({"itemId":"msg","delta":"hello"}),+ ),+ native(+ "two",+ "item/completed",+ serde_json::json!({"item":{"id":"msg","type":"agentMessage","text":"hello"}}),+ ),+ JournalInput::TransportError("EOF".into()),+ JournalInput::RecoveryStarted,+ ];+ let entries: Vec<_> = inputs+ .into_iter()+ .enumerate()+ .map(|(index, input)| entry(index as i64 + 1, input))+ .collect();+ let encoded = serde_json::to_string(&entries).unwrap();+ assert!(encoded.contains("future-event"));+ let restored: Vec<JournalEntry> = serde_json::from_str(&encoded).unwrap();+ assert_eq!(reduce(&entries), reduce(&restored));+ assert_eq!(reduce(&entries).len(), 2);+}+#[test]+fn missing_history_and_sequence_gaps_fail_closed() {+ assert!(+ ReplayMachine::default()+ .push(&entry(1, JournalInput::RecoveryStarted))+ .is_err()+ );+ let mut machine = ReplayMachine::default();+ machine+ .push(&entry(1, JournalInput::HistoryComplete))+ .unwrap();+ assert!(+ machine+ .push(&entry(3, JournalInput::RecoveryStarted))+ .is_err()+ );+}+#[test]+fn completed_poll_fallback_is_emitted_once_across_repeated_recovery() {+ let snapshot = TaskSnapshot {+ pull_requests: vec![],+ native: None,+ task_id: super::super::cloud::CloudId::new("task-test".into()).unwrap(),+ title: None,+ assistant_status: Some("completed".into()),+ turns: vec![super::super::cloud::TurnSnapshot {+ source: "current_assistant_turn".into(),+ id: Some("turn~test".into()),+ messages: vec!["final output".into()],+ output_types: vec![],+ has_diff: false,+ }],+ };+ let mut machine = ReplayMachine::default();+ machine+ .push(&entry(1, JournalInput::HistoryComplete))+ .unwrap();+ machine+ .push(&entry(+ 2,+ JournalInput::Poll {+ snapshot: snapshot.clone(),+ native: None,+ },+ ))+ .unwrap();+ assert!(+ machine+ .push(&entry(3, JournalInput::Terminal("completed".into())))+ .unwrap()+ .is_empty()+ );+ assert_eq!(machine.finish().len(), 2);+ machine+ .push(&entry(4, JournalInput::RecoveryStarted))+ .unwrap();+ machine+ .push(&entry(+ 5,+ JournalInput::Poll {+ snapshot,+ native: None,+ },+ ))+ .unwrap();+ assert!(+ machine+ .push(&entry(6, JournalInput::Terminal("completed".into())))+ .unwrap()+ .is_empty()+ );+ assert!(machine.finish().is_empty());+}++#[test]+fn native_answer_recovered_after_snapshot_terminal_replaces_the_fallback() {+ let snapshot = TaskSnapshot {+ pull_requests: vec![],+ native: None,+ task_id: super::super::cloud::CloudId::new("task-test".into()).unwrap(),+ title: None,+ assistant_status: Some("completed".into()),+ turns: vec![super::super::cloud::TurnSnapshot {+ source: "current_assistant_turn".into(),+ id: Some("turn~test".into()),+ messages: vec!["answer".into()],+ output_types: vec![],+ has_diff: false,+ }],+ };+ let inputs = vec![+ JournalInput::HistoryComplete,+ JournalInput::Poll {+ snapshot,+ native: None,+ },+ JournalInput::Terminal("completed".into()),+ native(+ "late",+ "item/agentMessage/delta",+ serde_json::json!({"itemId":"msg","delta":"answer"}),+ ),+ JournalInput::Terminal("completed".into()),+ ];+ let mut machine = ReplayMachine::default();+ let mut output = Vec::new();+ for (index, input) in inputs.into_iter().enumerate() {+ output.extend(machine.push(&entry(index as i64 + 1, input)).unwrap());+ }+ output.extend(machine.finish());+ assert_eq!(+ output+ .iter()+ .filter(|event| event.method == "item/completed")+ .count(),+ 1+ );+ assert_eq!(output.last().unwrap().method, "session/turn_complete");+}++#[test]+fn missing_and_reordered_deltas_never_corrupt_completed_message_live_or_replay() {+ let inputs = vec![+ JournalInput::HistoryComplete,+ native(+ "middle",+ "item/agentMessage/delta",+ serde_json::json!({"itemId":"msg", "delta":" is"}),+ ),+ native(+ "end",+ "item/agentMessage/delta",+ serde_json::json!({"itemId":"msg", "delta":"Codex."}),+ ),+ native(+ "complete",+ "item/completed",+ serde_json::json!({"item":{"id":"msg","type":"agentMessage","text":"My name is Codex."}}),+ ),+ native(+ "start",+ "item/agentMessage/delta",+ serde_json::json!({"itemId":"msg", "delta":"My name"}),+ ),+ native(+ "middle",+ "item/agentMessage/delta",+ serde_json::json!({"itemId":"msg", "delta":" is"}),+ ),+ native(+ "complete",+ "item/completed",+ serde_json::json!({"item":{"id":"msg","type":"agentMessage","text":"My name is Codex."}}),+ ),+ ];+ let entries: Vec<_> = inputs+ .into_iter()+ .enumerate()+ .map(|(index, input)| entry(index as i64 + 1, input))+ .collect();+ let output = reduce(&entries);+ assert_eq!(output.len(), 1);+ assert_eq!(output[0]["params"]["item"]["text"], "My name is Codex.");+ let replay: Vec<JournalEntry> =+ serde_json::from_str(&serde_json::to_string(&entries).unwrap()).unwrap();+ assert_eq!(reduce(&replay), output);+}++#[test]+fn terminal_poll_preserves_multiple_equal_messages_once_across_repeated_reads() {+ let snapshot = TaskSnapshot {+ pull_requests: vec![],+ native: None,+ task_id: super::super::cloud::CloudId::new("task-test".into()).unwrap(),+ title: None,+ assistant_status: Some("completed".into()),+ turns: vec![super::super::cloud::TurnSnapshot {+ source: "current_assistant_turn".into(),+ id: Some("turn~test".into()),+ messages: vec![+ "First message".into(),+ "Same message".into(),+ "Same message".into(),+ ],+ output_types: vec![],+ has_diff: false,+ }],+ };+ let inputs = vec![+ JournalInput::HistoryComplete,+ native(+ "fragment",+ "item/agentMessage/delta",+ serde_json::json!({"itemId":"msg","delta":" message"}),+ ),+ JournalInput::Poll {+ snapshot: snapshot.clone(),+ native: None,+ },+ JournalInput::Terminal("completed".into()),+ ];+ let mut machine = ReplayMachine::default();+ for (index, input) in inputs.into_iter().enumerate() {+ assert!(+ machine+ .push(&entry(index as i64 + 1, input))+ .unwrap()+ .is_empty()+ );+ }+ let output = machine.finish();+ assert_eq!(output.len(), 4);+ assert_eq!(output[0].params["item"]["text"], "First message");+ assert_eq!(output[1].params["item"]["text"], "Same message");+ assert_eq!(output[2].params["item"]["text"], "Same message");+ assert_ne!(+ output[1].params["item"]["id"],+ output[2].params["item"]["id"]+ );+ machine+ .push(&entry(+ 5,+ JournalInput::Poll {+ snapshot,+ native: None,+ },+ ))+ .unwrap();+ assert!(machine.finish().is_empty());+}++#[test]+fn recorded_two_turn_conversation_has_identical_complete_live_and_replayed_answers() {+ let entries: Vec<JournalEntry> = serde_json::from_str(include_str!(+ "../../../tests/fixtures/missing_live_deltas.json"+ ))+ .unwrap();+ let mut live = ReplayMachine::default();+ let mut replay = ReplayMachine::default();+ let mut live_output = Vec::new();+ let mut replay_output = Vec::new();+ for entry in &entries {+ live_output.extend(live.push(entry).unwrap());+ if matches!(entry.input, JournalInput::Terminal(_)) {+ live_output.extend(live.finish());+ }+ replay_output.extend(replay.push(entry).unwrap());+ }+ replay_output.extend(replay.finish());+ let answers = |events: &[CloudEvent]| {+ events+ .iter()+ .filter(|event| {+ event.method == "item/completed" && event.params["item"]["type"] == "agentMessage"+ })+ .map(|event| event.params["item"]["text"].as_str().unwrap().to_owned())+ .collect::<Vec<_>>()+ };+ let actual = answers(&live_output);+ assert_eq!(actual, answers(&replay_output));+ assert_eq!(actual.len(), 3);+ assert_eq!(actual[0].chars().count(), 327);+ assert_eq!(actual[1].chars().count(), 688);+ assert_eq!(+ actual[2],+ "My name is **Codex**. I’m an AI coding assistant created by OpenAI."+ );+ for output in [&live_output, &replay_output] {+ assert!(+ !output+ .iter()+ .any(|event| event.method == "item/agentMessage/delta")+ );+ assert_eq!(+ output+ .iter()+ .filter(|event| event.method == "session/turn_complete")+ .count(),+ 2+ );+ }+}++#[test]+fn cancelled_and_failed_turns_do_not_publish_unverified_fragments() {+ for status in ["cancelled", "failed"] {+ let mut machine = ReplayMachine::default();+ for (index, input) in [+ JournalInput::HistoryComplete,+ native(+ "fragment",+ "item/agentMessage/delta",+ serde_json::json!({"itemId":"msg","delta":" middle of a sentence"}),+ ),+ JournalInput::Terminal(status.into()),+ ]+ .into_iter()+ .enumerate()+ {+ assert!(+ machine+ .push(&entry(index as i64 + 1, input))+ .unwrap()+ .is_empty()+ );+ }+ let output = machine.finish();+ assert_eq!(output.len(), 1);+ assert_eq!(output[0].method, "session/turn_complete");+ assert_eq!(output[0].params["status"], status);+ }+}++#[test]+fn native_completion_and_fragmented_poll_text_cover_each_other_without_duplicates() {+ let snapshot = TaskSnapshot {+ pull_requests: vec![],+ native: None,+ task_id: super::super::cloud::CloudId::new("task-test".into()).unwrap(),+ title: None,+ assistant_status: Some("completed".into()),+ turns: vec![super::super::cloud::TurnSnapshot {+ source: "current_assistant_turn".into(),+ id: Some("turn~test".into()),+ messages: vec!["Hello ".into(), "world".into()],+ output_types: vec![],+ has_diff: false,+ }],+ };+ let completion = native(+ "complete",+ "item/completed",+ serde_json::json!({+ "item":{"id":"msg","type":"agentMessage","text":"Hello world"}+ }),+ );+ for poll_first in [true, false] {+ let mut machine = ReplayMachine::default();+ machine+ .push(&entry(1, JournalInput::HistoryComplete))+ .unwrap();+ let mut sequence = 2;+ if !poll_first {+ assert_eq!(+ machine+ .push(&entry(sequence, completion.clone()))+ .unwrap()+ .len(),+ 1+ );+ sequence += 1;+ }+ machine+ .push(&entry(+ sequence,+ JournalInput::Poll {+ snapshot: snapshot.clone(),+ native: None,+ },+ ))+ .unwrap();+ machine+ .push(&entry(+ sequence + 1,+ JournalInput::Terminal("completed".into()),+ ))+ .unwrap();+ let output = machine.finish();+ assert_eq!(output.len(), if poll_first { 3 } else { 1 });+ if poll_first {+ assert!(+ machine+ .push(&entry(sequence + 2, completion.clone()))+ .unwrap()+ .is_empty()+ );+ }+ assert!(machine.finish().is_empty());+ }+}diff --git a/crates/codex_cloud_agents/src/domain/runtime.rs b/crates/codex_cloud_agents/src/domain/runtime.rsnew file mode 100644index 0000000000..061c3f4d1e--- /dev/null+++ b/crates/codex_cloud_agents/src/domain/runtime.rs@@ -0,0 +1,134 @@+//! Authenticated cloud operations used by local and hosted session services.+use super::cloud::{+ CloudConversation, CloudEventStream, CloudId, CreatedTask, Launch, TaskSnapshot, TurnId,+};+use super::{CredentialStore, OAuth, Probe, unix_now};++/// Immutable cloud destination selected before the first provider submission.+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]+pub struct CloudTarget {+ /// Existing cloud environment owned by this connection.+ pub environment: CloudId,+ /// Explicit or repository-default branch selected for this session.+ pub branch: String,+ /// Actual selected repository, when supplied by environment metadata.+ pub repository_url: Option<String>,+}+impl CloudTarget {+ /// Check the selected destination without submitting a provider request.+ pub fn validate(&self) -> Result<(), rootcause::Report> {+ Launch {+ environment: self.environment.clone(),+ branch: self.branch.clone(),+ prompt: "validate target".into(),+ }+ .validate()+ }+}+/// An account binding validated before serving a conversation.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct RuntimeIdentity {+ /// Stable connection identity; reconnecting must create a new value.+ pub connection_id: String,+ /// Provider account identity.+ pub account_id: String,+}+/// Authenticated operations. Hosted implementations resolve authorization for every call.+pub trait CloudRuntime: Send + Sync {+ /// Return the current binding or reject disconnected authorization.+ fn identity(&self) -> impl Future<Output = Result<RuntimeIdentity, rootcause::Report>> + Send;+ /// Resolve a first-prompt target, including owner configuration and any automatic choice.+ fn resolve_target(+ &self,+ prompt: &str,+ requested: Option<&CloudTarget>,+ ) -> impl Future<Output = Result<CloudTarget, rootcause::Report>> + Send;+ /// Publish verified provider PR metadata through the host's session service.+ fn report_pull_request(+ &self,+ url: &str,+ ) -> impl Future<Output = Result<(), rootcause::Report>> + Send;+ /// Submit one launch, without write retries.+ fn launch(+ &self,+ request: &Launch,+ ) -> impl Future<Output = Result<CreatedTask, rootcause::Report>> + Send;+ /// Read selected task state.+ fn snapshot(+ &self,+ task: &CloudId,+ ) -> impl Future<Output = Result<TaskSnapshot, rootcause::Report>> + Send;+ /// Submit one continuation.+ fn follow_up(+ &self,+ task: &CloudId,+ turn: &TurnId,+ prompt: &str,+ ) -> impl Future<Output = Result<CreatedTask, rootcause::Report>> + Send;+ /// Request remote cancellation.+ fn cancel(&self, task: &CloudId) -> impl Future<Output = Result<(), rootcause::Report>> + Send;+ /// Read one assistant turn.+ fn turn(+ &self,+ task: &CloudId,+ turn: &TurnId,+ ) -> impl Future<Output = Result<TaskSnapshot, rootcause::Report>> + Send;+ /// Subscribe to one turn's event history and live updates.+ fn stream(+ &self,+ task: &CloudId,+ turn: &TurnId,+ ) -> impl Future<Output = Result<CloudEventStream, rootcause::Report>> + Send;+}+impl<P: OAuth + CloudConversation, S: CredentialStore + Send + Sync> CloudRuntime for Probe<P, S> {+ async fn identity(&self) -> Result<RuntimeIdentity, rootcause::Report> {+ let auth = self+ .status()?+ .ok_or_else(|| rootcause::report!("not connected; run login first"))?;+ Ok(RuntimeIdentity {+ connection_id: auth.account_id.clone(),+ account_id: auth.account_id,+ })+ }+ async fn resolve_target(+ &self,+ _: &str,+ requested: Option<&CloudTarget>,+ ) -> Result<CloudTarget, rootcause::Report> {+ let target = requested.cloned().ok_or_else(|| {+ rootcause::report!("select an explicit environment for the standalone ACP demo")+ })?;+ target.validate()?;+ Ok(target)+ }+ async fn report_pull_request(&self, _: &str) -> Result<(), rootcause::Report> {+ Ok(())+ }+ async fn launch(&self, request: &Launch) -> Result<CreatedTask, rootcause::Report> {+ self.launch(request, unix_now()?).await+ }+ async fn snapshot(&self, task: &CloudId) -> Result<TaskSnapshot, rootcause::Report> {+ self.snapshot(task, unix_now()?).await+ }+ async fn follow_up(+ &self,+ task: &CloudId,+ turn: &TurnId,+ prompt: &str,+ ) -> Result<CreatedTask, rootcause::Report> {+ self.follow_up(task, turn, prompt, unix_now()?).await+ }+ async fn cancel(&self, task: &CloudId) -> Result<(), rootcause::Report> {+ self.cancel(task, unix_now()?).await+ }+ async fn turn(&self, task: &CloudId, turn: &TurnId) -> Result<TaskSnapshot, rootcause::Report> {+ self.turn(task, turn, unix_now()?).await+ }+ async fn stream(+ &self,+ task: &CloudId,+ turn: &TurnId,+ ) -> Result<CloudEventStream, rootcause::Report> {+ self.stream(task, turn, unix_now()?).await+ }+}diff --git a/crates/codex_cloud_agents/src/domain/test.rs b/crates/codex_cloud_agents/src/domain/test.rsnew file mode 100644index 0000000000..fd40b70f3c--- /dev/null+++ b/crates/codex_cloud_agents/src/domain/test.rs@@ -0,0 +1,287 @@+use super::*;+use std::collections::VecDeque;+use std::sync::{+ Mutex,+ atomic::{AtomicUsize, Ordering},+};++fn credentials(account: &str, expiry: u64) -> Credentials {+ Credentials {+ version: 1,+ access_token: Secret::new("test-access".to_owned()).unwrap(),+ refresh_token: Secret::new("test-refresh".to_owned()).unwrap(),+ expires_at: expiry,+ account_id: account.to_owned(),+ }+}++#[derive(Default)]+struct Store {+ value: Mutex<Option<Credentials>>,+ saves: AtomicUsize,+}+impl CredentialStore for Store {+ fn load(&self) -> Result<Option<Credentials>, rootcause::Report> {+ Ok(self+ .value+ .lock()+ .unwrap()+ .as_ref()+ .map(|value| serde_json::from_value(serde_json::to_value(value).unwrap()).unwrap()))+ }+ fn save(&self, value: &Credentials) -> Result<(), rootcause::Report> {+ *self.value.lock().unwrap() =+ Some(serde_json::from_value(serde_json::to_value(value).unwrap()).unwrap());+ self.saves.fetch_add(1, Ordering::SeqCst);+ Ok(())+ }+ fn clear(&self) -> Result<(), rootcause::Report> {+ *self.value.lock().unwrap() = None;+ Ok(())+ }+}++struct Provider {+ polls: Mutex<VecDeque<LoginPoll>>,+ poll_count: AtomicUsize,+ refresh_account: &'static str,+ refresh_count: AtomicUsize,+ reads: AtomicUsize,+ creates: AtomicUsize,+ environment_visible: bool,+}+impl Provider {+ fn new(polls: Vec<LoginPoll>) -> Self {+ Self {+ polls: Mutex::new(polls.into()),+ poll_count: AtomicUsize::new(0),+ refresh_account: "account-a",+ refresh_count: AtomicUsize::new(0),+ reads: AtomicUsize::new(0),+ creates: AtomicUsize::new(0),+ environment_visible: false,+ }+ }+}+fn login() -> DeviceLogin {+ DeviceLogin {+ verification_url: "https://example.test/device".to_owned(),+ user_code: "ABCD".to_owned(),+ device_auth_id: Secret::new("device".to_owned()).unwrap(),+ interval: Duration::from_secs(5),+ timeout: Duration::from_secs(11),+ }+}+impl OAuth for Provider {+ async fn begin(&self) -> Result<DeviceLogin, rootcause::Report> {+ Ok(login())+ }+ async fn poll(&self, _: &DeviceLogin) -> Result<LoginPoll, rootcause::Report> {+ self.poll_count.fetch_add(1, Ordering::SeqCst);+ Ok(self+ .polls+ .lock()+ .unwrap()+ .pop_front()+ .unwrap_or(LoginPoll::Pending))+ }+ async fn refresh(&self, _: &Credentials) -> Result<Credentials, rootcause::Report> {+ self.refresh_count.fetch_add(1, Ordering::SeqCst);+ tokio::task::yield_now().await;+ Ok(credentials(self.refresh_account, 1000))+ }+ async fn environments(&self, _: &Credentials) -> Result<Vec<Environment>, rootcause::Report> {+ self.reads.fetch_add(1, Ordering::SeqCst);+ Ok(if self.environment_visible {+ vec![Environment {+ repositories: vec![],+ id: "env-test".to_owned(),+ label: None,+ }]+ } else {+ vec![]+ })+ }+}++impl cloud::CloudTasks for Provider {+ async fn create(+ &self,+ _: &Credentials,+ _: &cloud::Launch,+ ) -> Result<cloud::CreatedTask, rootcause::Report> {+ self.creates.fetch_add(1, Ordering::SeqCst);+ Err(rootcause::report!("submission outcome unknown"))+ }+ async fn snapshot(+ &self,+ _: &Credentials,+ _: &cloud::CloudId,+ ) -> Result<cloud::TaskSnapshot, rootcause::Report> {+ Err(rootcause::report!("no fixture"))+ }+}++#[tokio::test]+async fn invisible_environment_blocks_launch_and_ambiguous_submission_is_not_retried() {+ let request = cloud::Launch {+ environment: cloud::CloudId::new("env-test".to_owned()).unwrap(),+ branch: "main".to_owned(),+ prompt: "Say hello".to_owned(),+ };+ for visible in [false, true] {+ let store = Store::default();+ store.save(&credentials("account-a", 1000)).unwrap();+ let mut provider = Provider::new(vec![]);+ provider.environment_visible = visible;+ let probe = Probe::new(provider, store);+ assert!(probe.launch(&request, 1).await.is_err());+ assert_eq!(+ probe.provider.creates.load(Ordering::SeqCst),+ usize::from(visible)+ );+ }+}++#[test]+fn task_paths_and_launch_inputs_are_validated() {+ for id in [+ "",+ "../task",+ "task?x=1",+ "task/other",+ "task%2fother",+ "task\n",+ ] {+ assert!(cloud::CloudId::new(id.to_owned()).is_err());+ }+ let mut request = cloud::Launch {+ environment: cloud::CloudId::new("env-test".to_owned()).unwrap(),+ branch: "main".to_owned(),+ prompt: " ".to_owned(),+ };+ assert!(request.validate().is_err());+ request.prompt = "x".repeat(64 * 1024 + 1);+ assert!(request.validate().is_err());+}++#[tokio::test(start_paused = true)]+async fn polls_at_interval_and_saves_only_after_completion() {+ let probe = Probe::new(+ Provider::new(vec![+ LoginPoll::Pending,+ LoginPoll::Complete(credentials("account-a", 1000)),+ ]),+ Store::default(),+ );+ let start = tokio::time::Instant::now();+ probe.finish_login(&login()).await.unwrap();+ assert_eq!(start.elapsed(), Duration::from_secs(5));+ assert_eq!(probe.store.saves.load(Ordering::SeqCst), 1);+ assert_eq!(probe.status().unwrap().unwrap().account_id, "account-a");+}++#[tokio::test(start_paused = true)]+async fn expired_login_stops_polling_without_saving() {+ let probe = Probe::new(Provider::new(vec![]), Store::default());+ assert!(probe.finish_login(&login()).await.is_err());+ assert_eq!(probe.provider.poll_count.load(Ordering::SeqCst), 3);+ assert_eq!(probe.store.saves.load(Ordering::SeqCst), 0);+}++#[tokio::test(start_paused = true)]+async fn dropped_login_cannot_save_late_credentials() {+ let probe = Probe::new(+ Provider::new(vec![+ LoginPoll::Pending,+ LoginPoll::Complete(credentials("account-a", 1000)),+ ]),+ Store::default(),+ );+ assert!(+ tokio::time::timeout(Duration::from_secs(1), probe.finish_login(&login()))+ .await+ .is_err()+ );+ tokio::time::advance(Duration::from_secs(20)).await;+ assert_eq!(probe.store.saves.load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn refresh_is_saved_before_cloud_read() {+ let store = Store::default();+ store.save(&credentials("account-a", 100)).unwrap();+ let probe = Probe::new(Provider::new(vec![]), store);+ probe.environments(100).await.unwrap();+ assert_eq!(probe.provider.refresh_count.load(Ordering::SeqCst), 1);+ assert_eq!(probe.status().unwrap().unwrap().expires_at, 1000);+ probe.environments(100).await.unwrap();+ assert_eq!(probe.provider.refresh_count.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn refresh_cannot_switch_account_or_use_it_for_a_read() {+ let store = Store::default();+ store.save(&credentials("account-a", 100)).unwrap();+ let mut provider = Provider::new(vec![]);+ provider.refresh_account = "account-b";+ let probe = Probe::new(provider, store);+ assert!(probe.environments(100).await.is_err());+ assert_eq!(probe.status().unwrap().unwrap().account_id, "account-a");+ assert_eq!(probe.provider.reads.load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn connection_requires_explicit_logout_before_replacement() {+ let store = Store::default();+ store.save(&credentials("account-a", 1000)).unwrap();+ let probe = Probe::new(Provider::new(vec![]), store);+ assert!(probe.begin_login().await.is_err());+ probe.logout().unwrap();+ assert!(probe.begin_login().await.is_ok());+ assert!(probe.environments(1).await.is_err());+}++#[test]+fn rejects_header_injection_and_invalid_state_without_echoing_secrets() {+ let mut value = credentials("account-a", 1);+ value.account_id = "account\r\nInjected: secret-marker".to_owned();+ let error = value.validate().unwrap_err().to_string();+ assert!(!error.contains("secret-marker"));+ value.account_id = "account-a".to_owned();+ value.version = 2;+ assert!(value.validate().is_err());+}++#[tokio::test]+async fn concurrent_credential_reads_rotate_refresh_token_once() {+ let store = Store::default();+ store.save(&credentials("account-a", 100)).unwrap();+ let probe = Probe::new(Provider::new(vec![]), store);+ let (first, second) = tokio::join!(probe.environments(100), probe.environments(100));+ first.unwrap();+ second.unwrap();+ assert_eq!(probe.provider.refresh_count.load(Ordering::SeqCst), 1);+ assert_eq!(probe.provider.reads.load(Ordering::SeqCst), 2);+}++#[test]+fn validates_remote_branch_before_launch() {+ for branch in [+ "",+ "bad ref",+ "main..other",+ "main@{1}",+ "-main",+ "a.lock",+ "a/.hidden",+ "a/",+ "a\\b",+ "a?b",+ ] {+ assert!(cloud::validate_branch(branch).is_err(), "{branch}");+ }+ for branch in ["main", "feature/work", "refs/heads/main", "release-1.2"] {+ assert!(cloud::validate_branch(branch).is_ok(), "{branch}");+ }+}diff --git a/crates/codex_cloud_agents/src/inbound/acp.rs b/crates/codex_cloud_agents/src/inbound/acp.rsnew file mode 100644index 0000000000..efdc1cea73--- /dev/null+++ b/crates/codex_cloud_agents/src/inbound/acp.rs@@ -0,0 +1,411 @@+//! ACP v1 transport and cloud event projection.+use crate::domain::acp_session::{Outcome, SessionService, SessionSink, SessionStore};+use crate::domain::cloud::CloudEvent;+use crate::domain::runtime::CloudRuntime;+use agent_client_protocol::schema::{ProtocolVersion, v1::*};+use agent_client_protocol::{+ Agent, ByteStreams, Client, ConnectionTo, on_receive_notification, on_receive_request,+};+use std::collections::HashMap;+use std::sync::{Arc, Mutex};+use tokio_util::compat::{TokioAsyncReadCompatExt as _, TokioAsyncWriteCompatExt as _};++mod citations;++struct Sink {+ connection: ConnectionTo<Client>,+ session: SessionId,+ replay: bool,+ text: Mutex<HashMap<String, String>>,+}+impl SessionSink for Sink {+ fn emit(&self, event: &CloudEvent) -> Result<(), rootcause::Report> {+ if event.method == "session/turn_complete" {+ if self.replay {+ use agent_runtime_protocol::domain::turn::{TurnCompleteNotification, TurnOutcome};+ let outcome = match event.params["status"].as_str() {+ Some("completed") => TurnOutcome::Finished,+ Some("cancelled") => TurnOutcome::Cancelled,+ Some("failed") => TurnOutcome::Failed {+ message: "cloud assistant turn failed".into(),+ },+ _ => return Err(rootcause::report!("unknown terminal journal outcome")),+ };+ self.connection+ .send_notification(TurnCompleteNotification {+ session_id: self.session.clone(),+ outcome,+ })+ .map_err(|_| rootcause::report!("ACP client disconnected"))?;+ }+ return Ok(());+ }+ if event.method == "user/message" && !self.replay {+ return Ok(());+ }+ for update in project(+ event,+ &mut self.text.lock().expect("text projection poisoned"),+ ) {+ self.connection+ .send_notification(SessionNotification::new(self.session.clone(), update))+ .map_err(|_| rootcause::report!("ACP client disconnected"))?;+ }+ Ok(())+ }+}+struct RecoverySink {+ session: SessionId,+ reload: Option<tokio::sync::mpsc::UnboundedSender<SessionId>>,+ changed: std::sync::atomic::AtomicBool,+}+impl SessionSink for RecoverySink {+ fn emit(&self, _: &CloudEvent) -> Result<(), rootcause::Report> {+ self.changed+ .store(true, std::sync::atomic::Ordering::SeqCst);+ Ok(())+ }+ fn recovered(&self) -> Result<bool, rootcause::Report> {+ if !self.changed.load(std::sync::atomic::Ordering::SeqCst) {+ return Ok(false);+ }+ if let Some(reload) = &self.reload {+ reload+ .send(self.session.clone())+ .map_err(|_| rootcause::report!("ACP host disconnected during recovery"))?;+ Ok(true)+ } else {+ eprintln!("Recovered Codex history is available through session/load");+ Ok(false)+ }+ }+}+fn chunk(text: &str) -> ContentChunk {+ ContentChunk::new(ContentBlock::Text(TextContent::new(text)))+}+fn project(event: &CloudEvent, text: &mut HashMap<String, String>) -> Vec<SessionUpdate> {+ let p = &event.params;+ let item_id = p+ .get("itemId")+ .and_then(serde_json::Value::as_str)+ .unwrap_or("")+ .to_owned();+ match event.method.as_str() {+ "adapter/pull_request" => {+ if text+ .insert(format!("tool:{}", event.id), String::new())+ .is_some()+ {+ return Vec::new();+ }+ let Some(url) = p["url"].as_str() else {+ return Vec::new();+ };+ vec")),+ ))]),+ )]+ }+ "user/message" => {+ text.clear();+ vec![SessionUpdate::UserMessageChunk(chunk(+ p["text"].as_str().unwrap_or(""),+ ))]+ }+ "item/reasoning/summaryTextDelta" | "item/reasoning/textDelta" => {+ vec![SessionUpdate::AgentThoughtChunk(chunk(+ p["delta"].as_str().unwrap_or(""),+ ))]+ }+ "item/completed" if p["item"]["type"].as_str() == Some("agentMessage") => {+ let item = &p["item"];+ let id = item["id"].as_str().unwrap_or("");+ let final_text = item["text"].as_str().unwrap_or("");+ if final_text.is_empty() || text.insert(format!("done:{id}"), String::new()).is_some() {+ return Vec::new();+ }+ let separator = if text+ .insert("message-separator".into(), String::new())+ .is_some()+ {+ "\n\n"+ } else {+ ""+ };+ vec![SessionUpdate::AgentMessageChunk(chunk(&format!(+ "{separator}{}",+ citations::markdown(final_text)+ )))]+ }+ "item/commandExecution/outputDelta" => {+ let output = text.entry(format!("output:{item_id}")).or_default();+ output.push_str(p["delta"].as_str().unwrap_or(""));+ vec![SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(+ item_id,+ ToolCallUpdateFields::new().content(vec![ToolCallContent::from(+ ContentBlock::Text(TextContent::new(output.as_str())),+ )]),+ ))]+ }+ "item/started" | "item/completed"+ if matches!(+ p["item"]["type"].as_str(),+ Some("commandExecution" | "fileChange" | "mcpToolCall" | "webSearch")+ ) =>+ {+ let item = &p["item"];+ let id = item["id"].as_str().unwrap_or("");+ if id.is_empty() {+ return Vec::new();+ }+ let kind = match item["type"].as_str() {+ Some("commandExecution") => ToolKind::Execute,+ Some("fileChange") => ToolKind::Edit,+ Some("webSearch") => ToolKind::Search,+ _ => ToolKind::Other,+ };+ let title = item["command"]+ .as_str()+ .or_else(|| item["tool"].as_str())+ .unwrap_or_else(|| item["type"].as_str().unwrap_or("Cloud tool"));+ let status = if event.method == "item/started" {+ ToolCallStatus::InProgress+ } else if item["status"].as_str() == Some("failed")+ || item["exitCode"].as_i64().is_some_and(|code| code != 0)+ {+ ToolCallStatus::Failed+ } else {+ ToolCallStatus::Completed+ };+ let content: Vec<ToolCallContent> = item["aggregatedOutput"]+ .as_str()+ .filter(|output| !output.is_empty())+ .map(|output| ToolCallContent::from(ContentBlock::Text(TextContent::new(output))))+ .into_iter()+ .collect();+ let key = format!("tool:{id}");+ if text.insert(key, String::new()).is_none() {+ vec![SessionUpdate::ToolCall(+ ToolCall::new(id.to_owned(), title)+ .kind(kind)+ .status(status)+ .raw_input(item.clone())+ .content(content),+ )]+ } else {+ vec![SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(+ id.to_owned(),+ ToolCallUpdateFields::new()+ .kind(kind)+ .status(status)+ .raw_output(item.clone())+ .content(content),+ ))]+ }+ }+ _ => Vec::new(),+ }+}+fn sink(connection: ConnectionTo<Client>, session: SessionId, replay: bool) -> Sink {+ Sink {+ connection,+ session,+ replay,+ text: Mutex::new(HashMap::new()),+ }+}+fn error(error: rootcause::Report) -> Error {+ Error::new(-32603, error.format_current_context().to_string())+}+fn prompt_text(blocks: Vec<ContentBlock>) -> Result<String, Error> {+ let mut texts = Vec::new();+ for block in blocks {+ match block {+ ContentBlock::Text(text) => texts.push(text.text),+ _ => return Err(Error::new(-32602, "Only text prompts are supported")),+ }+ }+ let text = texts.join("\n");+ if text.trim().is_empty() || text.len() > 64 * 1024 {+ return Err(Error::new(+ -32602,+ "Provide a nonempty text prompt (maximum 64 KiB)",+ ));+ }+ Ok(text)+}+/// Serve ACP on tokio byte streams; all writes belong to the SDK's ordered queue.+///+/// Long prompts and cancellation run independently of request dispatch. MCP,+/// terminal, filesystem, model selection and interactive approvals are unsupported.+/// # Errors+/// Returns SDK transport errors; individual operation errors are ACP responses.+pub async fn serve<Runtime, J, R, W>(+ service: Arc<SessionService<Runtime, J>>,+ reader: R,+ writer: W,+ reload: Option<tokio::sync::mpsc::UnboundedSender<SessionId>>,+) -> Result<(), Error>+where+ Runtime: CloudRuntime + 'static,+ J: SessionStore + 'static,+ R: tokio::io::AsyncRead + Send + 'static,+ W: tokio::io::AsyncWrite + Send + 'static,+{+ let metadata_service = service.clone();+ let metadata_reload = reload.clone();+ let connection = Agent+ .builder()+ .name("codex-cloud-acp")+ .on_receive_request(+ async move |request: InitializeRequest, responder, _connection| {+ responder.respond(+ InitializeResponse::new(request.protocol_version.min(ProtocolVersion::V1))+ .agent_info(Implementation::new("codex_acp", env!("CARGO_PKG_VERSION")))+ .agent_capabilities(AgentCapabilities::default().load_session(true)),+ )+ },+ on_receive_request!(),+ )+ .on_receive_request(+ {+ let service = service.clone();+ async move |request: NewSessionRequest, responder, _connection| {+ if !request.mcp_servers.is_empty() {+ return responder.respond_with_error(Error::new(+ -32602,+ "MCP servers are not supported by this cloud adapter",+ ));+ }+ match service.new_session().await {+ Ok(id) => responder.respond(NewSessionResponse::new(SessionId::new(id))),+ Err(e) => responder.respond_with_error(error(e)),+ }+ }+ },+ on_receive_request!(),+ )+ .on_receive_request(+ {+ let service = service.clone();+ async move |request: LoadSessionRequest, responder, connection| {+ let reload = reload.clone();+ if !request.mcp_servers.is_empty() {+ return responder.respond_with_error(Error::new(+ -32602,+ "MCP servers are not supported by this cloud adapter",+ ));+ }+ let notifier = sink(connection.clone(), request.session_id.clone(), true);+ let service = service.clone();+ connection.spawn(async move {+ let recovery = match service+ .prepare_recovery(&request.session_id.to_string(), ¬ifier)+ .await+ {+ Ok(recovery) => recovery,+ Err(e) => return responder.respond_with_error(error(e)),+ };+ responder.respond(LoadSessionResponse::new())?;+ let capture = RecoverySink {+ session: request.session_id.clone(),+ reload,+ changed: std::sync::atomic::AtomicBool::new(false),+ };+ service+ .finish_recovery(&request.session_id.to_string(), recovery, &capture)+ .await+ .map(|_| ())+ .map_err(error)+ })+ }+ },+ on_receive_request!(),+ )+ .on_receive_request(+ {+ let service = service.clone();+ async move |request: PromptRequest, responder, connection| {+ let _text = match prompt_text(request.prompt.clone()) {+ Ok(text) => text,+ Err(e) => return responder.respond_with_error(e),+ };+ let service = service.clone();+ let notifier = sink(connection.clone(), request.session_id.clone(), false);+ connection.spawn(async move {+ match service+ .prompt(&request.session_id.to_string(), request.prompt, ¬ifier)+ .await+ {+ Ok(outcome) => {+ let stop = match outcome {+ Outcome::Completed => StopReason::EndTurn,+ Outcome::Cancelled => StopReason::Cancelled,+ };+ let _ = responder.respond(PromptResponse::new(stop));+ }+ Err(e) => {+ let _ = responder.respond_with_error(error(e));+ }+ }+ Ok(())+ })+ }+ },+ on_receive_request!(),+ )+ .on_receive_notification(+ {+ let service = service.clone();+ async move |request: CancelNotification, connection| {+ let service = service.clone();+ connection.spawn(async move {+ if let Err(e) = service.cancel(&request.session_id.to_string()).await {+ eprintln!("codex_acp: cancellation failed: {e}");+ }+ Ok(())+ })+ }+ },+ on_receive_notification!(),+ )+ .connect_to(ByteStreams::new(writer.compat_write(), reader.compat()));+ let refresh = async move {+ let base = std::time::Duration::from_secs(20);+ let mut delay = base;+ loop {+ tokio::select! {+ _=tokio::time::sleep(delay)=>{},+ _=metadata_service.metadata_changed()=>{delay=base;}+ }+ match metadata_service.refresh_metadata().await {+ Ok(changed) => {+ delay = base;+ if let Some(reload) = &metadata_reload {+ for id in changed {+ if reload.send(SessionId::new(id)).is_err() {+ return;+ }+ }+ }+ }+ Err(error) => {+ eprintln!("codex_acp: metadata refresh unavailable: {error}");+ delay = delay+ .saturating_mul(2)+ .min(std::time::Duration::from_secs(300));+ }+ }+ }+ };+ tokio::pin!(connection);+ tokio::select! {result=&mut connection=>result, _=refresh=>connection.await}+}+#[cfg(test)]+mod test;diff --git a/crates/codex_cloud_agents/src/inbound/acp/citations.rs b/crates/codex_cloud_agents/src/inbound/acp/citations.rsnew file mode 100644index 0000000000..20bdf993f8--- /dev/null+++ b/crates/codex_cloud_agents/src/inbound/acp/citations.rs@@ -0,0 +1,35 @@+//! Present cloud file citations without inventing a URL for the remote checkout.++use lazy_regex::{Captures, regex, regex_captures};++pub(super) fn markdown(text: &str) -> String {+ regex!(r"【F:([^】]*)】")+ .replace_all(text, |captures: &Captures<'_>| {+ let Some(label) = label(&captures[1]) else {+ return captures[0].to_owned();+ };+ // A longer delimiter also handles filenames containing backticks.+ let delimiter =+ "`".repeat(label.split(|c| c != '`').map(str::len).max().unwrap_or(0) + 1);+ let padding = if delimiter.len() > 1 { " " } else { "" };+ format!("{delimiter}{padding}{label}{padding}{delimiter}")+ })+ .into_owned()+}++fn label(citation: &str) -> Option<String> {+ let (_, path, start, end) =+ regex_captures!(r"\A([^†【】\p{Cc}]+)†L([0-9]+)(?:-L([0-9]+))?\z", citation)?;+ if path.trim().is_empty() {+ return None;+ }+ let start = start.parse::<u32>().ok().filter(|n| *n > 0)?;+ if end.is_empty() {+ return Some(format!("{path}:{start}"));+ }+ let end = end.parse::<u32>().ok()?;+ (end >= start).then(|| format!("{path}:{start}-{end}"))+}++#[cfg(test)]+mod test;diff --git a/crates/codex_cloud_agents/src/inbound/acp/citations/test.rs b/crates/codex_cloud_agents/src/inbound/acp/citations/test.rsnew file mode 100644index 0000000000..99e18003a4--- /dev/null+++ b/crates/codex_cloud_agents/src/inbound/acp/citations/test.rs@@ -0,0 +1,55 @@+use super::markdown;++#[test]+fn converts_reported_gitkeep_and_line_ranges_without_changing_markdown() {+ assert_eq!(+ markdown(+ "- The only tracked file is an empty `.gitkeep`. 【F:.gitkeep†L1】\n\nSee 【F:src/main.rs†L2-L12】."+ ),+ "- The only tracked file is an empty `.gitkeep`. `.gitkeep:1`\n\nSee `src/main.rs:2-12`."+ );+}++#[test]+fn filenames_cannot_escape_the_markdown_code_span() {+ assert_eq!(+ markdown("【F:a`[b](https://example.com).rs†L2】 【F:目录/a file.rs†L1】"),+ "`` a`[b](https://example.com).rs:2 `` `目录/a file.rs:1`"+ );+}++#[test]+fn preserves_unknown_or_malformed_citations() {+ for text in [+ "【F:.gitkeep†L1",+ "【F:file】",+ "【F:†L1】",+ "【F:file†L0】",+ "【F:file†L3-L1】",+ "【F:file†L1-L2-L3】",+ "【F:file†Lx】",+ "【F:file†L1-L0】",+ "【F:file†L+1】",+ "【F:file†L١】",+ "【F: †L1】",+ "【F:file†L1†L2】",+ "【F:file\u{85}name†L1】",+ "【F:outer 【F:inner†L1】",+ "【F:file†L1\n】",+ "【F:file†L9999999999999999999999】",+ "【F:file\nname†L1】",+ "【other†L1】",+ "**Normal Markdown** with `code` and 💙.",+ ] {+ assert_eq!(markdown(text), text);+ }+}++#[test]+fn preserves_malformed_boundaries_and_normalizes_valid_line_numbers() {+ assert_eq!(+ markdown("【F:outer 【F:inner†L1】 【F:file†L0002-L0003】 【F:last†L4"),+ "【F:outer 【F:inner†L1】 `file:2-3` 【F:last†L4"+ );+ assert_eq!(markdown("【F:a```b.rs†L1】"), "```` a```b.rs:1 ````");+}diff --git a/crates/codex_cloud_agents/src/inbound/acp/snapshots/codex_cloud_agents__inbound__acp__test__completed_messages_ignore_unordered_deltas_and_repeated_completions.snap b/crates/codex_cloud_agents/src/inbound/acp/snapshots/codex_cloud_agents__inbound__acp__test__completed_messages_ignore_unordered_deltas_and_repeated_completions.snapnew file mode 100644index 0000000000..982c18dcbf--- /dev/null+++ b/crates/codex_cloud_agents/src/inbound/acp/snapshots/codex_cloud_agents__inbound__acp__test__completed_messages_ignore_unordered_deltas_and_repeated_completions.snap@@ -0,0 +1,20 @@+---+source: crates/codex_cloud_agents/src/inbound/acp/test.rs+expression: updates+---+[+ {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "hello world"+ }+ },+ {+ "sessionUpdate": "agent_thought_chunk",+ "content": {+ "type": "text",+ "text": "thinking"+ }+ }+]diff --git a/crates/codex_cloud_agents/src/inbound/acp/snapshots/codex_cloud_agents__inbound__acp__test__distinct_complete_messages_have_markdown_boundaries_and_reset_on_new_turn.snap b/crates/codex_cloud_agents/src/inbound/acp/snapshots/codex_cloud_agents__inbound__acp__test__distinct_complete_messages_have_markdown_boundaries_and_reset_on_new_turn.snapnew file mode 100644index 0000000000..f40f8ab0e8--- /dev/null+++ b/crates/codex_cloud_agents/src/inbound/acp/snapshots/codex_cloud_agents__inbound__acp__test__distinct_complete_messages_have_markdown_boundaries_and_reset_on_new_turn.snap@@ -0,0 +1,34 @@+---+source: crates/codex_cloud_agents/src/inbound/acp/test.rs+expression: updates+---+[+ {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "## Hello"+ }+ },+ {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "\n\n- A list"+ }+ },+ {+ "sessionUpdate": "user_message_chunk",+ "content": {+ "type": "text",+ "text": "Next question"+ }+ },+ {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "New answer"+ }+ }+]diff --git a/crates/codex_cloud_agents/src/inbound/acp/snapshots/codex_cloud_agents__inbound__acp__test__reported_gitkeep_citation.snap b/crates/codex_cloud_agents/src/inbound/acp/snapshots/codex_cloud_agents__inbound__acp__test__reported_gitkeep_citation.snapnew file mode 100644index 0000000000..c398b5281f--- /dev/null+++ b/crates/codex_cloud_agents/src/inbound/acp/snapshots/codex_cloud_agents__inbound__acp__test__reported_gitkeep_citation.snap@@ -0,0 +1,13 @@+---+source: crates/codex_cloud_agents/src/inbound/acp/test.rs+expression: updates+---+[+ {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "## Status\n\nIt’s going well! I inspected the repository, and it is currently an **empty placeholder/test repository** rather than an implemented project.\n\n### What’s in the repository?\n\n- The current branch is `work`.\n- The Git history contains one commit: **“Initialize repository.”**\n- The only tracked file is an empty `.gitkeep`, which is commonly used to retain an otherwise empty directory in Git. `.gitkeep:1`\n- There is no README, source code, dependency manifest, tests, or configured Git remote, so the repository does not yet have a defined application purpose.\n"+ }+ }+]diff --git a/crates/codex_cloud_agents/src/inbound/acp/test.rs b/crates/codex_cloud_agents/src/inbound/acp/test.rsnew file mode 100644index 0000000000..6a36a80c81--- /dev/null+++ b/crates/codex_cloud_agents/src/inbound/acp/test.rs@@ -0,0 +1,95 @@+use super::*;+use serde_json::json;++#[test]+fn reported_gitkeep_citation_is_markdown_in_native_and_poll_messages() {+ // Text transcribed from the user's rendered reply, not a provider recording.+ let body = include_str!("../../../tests/fixtures/reported_gitkeep_message.md");+ for id in ["native-message", "poll-message:0"] {+ let event = CloudEvent {+ id: "citation-example".into(),+ method: "item/completed".into(),+ params: json!({"item":{"id":id,"type":"agentMessage","text":body}}),+ };+ let mut state = HashMap::new();+ let updates = project(&event, &mut state);+ insta::assert_json_snapshot!("reported_gitkeep_citation", updates);+ assert!(project(&event, &mut state).is_empty());+ assert_eq!(event.params["item"]["text"], body, "raw text stays intact");+ }+}+#[test]+fn completed_messages_ignore_unordered_deltas_and_repeated_completions() {+ let mut state = HashMap::new();+ let mut updates = Vec::new();+ for (method, params) in [+ (+ "item/agentMessage/delta",+ json!({"itemId":"m","delta":" world"}),+ ),+ (+ "item/completed",+ json!({"item":{"id":"m","type":"agentMessage","text":"hello world"}}),+ ),+ (+ "item/completed",+ json!({"item":{"id":"m","type":"agentMessage","text":"hello world"}}),+ ),+ (+ "item/agentMessage/delta",+ json!({"itemId":"m","delta":"hello"}),+ ),+ (+ "item/reasoning/summaryTextDelta",+ json!({"delta":"thinking"}),+ ),+ ] {+ updates.extend(project(+ &CloudEvent {+ id: String::new(),+ method: method.into(),+ params,+ },+ &mut state,+ ));+ }+ insta::assert_json_snapshot!(updates);+}++#[test]+fn distinct_complete_messages_have_markdown_boundaries_and_reset_on_new_turn() {+ let mut state = HashMap::new();+ let mut updates = Vec::new();+ for (method, params) in [+ (+ "item/completed",+ json!({"item":{"id":"m1","type":"agentMessage","text":"## Hello"}}),+ ),+ (+ "item/completed",+ json!({"item":{"id":"m2","type":"agentMessage","text":"- A list"}}),+ ),+ ("user/message", json!({"text":"Next question"})),+ (+ "item/completed",+ json!({"item":{"id":"m3","type":"agentMessage","text":"New answer"}}),+ ),+ ] {+ updates.extend(project(+ &CloudEvent {+ id: String::new(),+ method: method.into(),+ params,+ },+ &mut state,+ ));+ }+ insta::assert_json_snapshot!(updates);+}+#[test]+fn unsupported_prompt_content_is_rejected() {+ let blocks =+ serde_json::from_value(json!([{"type":"image","data":"AA==","mimeType":"image/png"}]))+ .unwrap();+ assert!(prompt_text(blocks).is_err());+}diff --git a/crates/codex_cloud_agents/src/inbound/mod.rs b/crates/codex_cloud_agents/src/inbound/mod.rsnew file mode 100644index 0000000000..6653b40f63--- /dev/null+++ b/crates/codex_cloud_agents/src/inbound/mod.rs@@ -0,0 +1,3 @@+//! Client-facing protocol adapters.+/// Stdio and in-memory Agent Client Protocol server.+pub mod acp;diff --git a/crates/codex_cloud_agents/src/lib.rs b/crates/codex_cloud_agents/src/lib.rsnew file mode 100644index 0000000000..d457483242--- /dev/null+++ b/crates/codex_cloud_agents/src/lib.rs@@ -0,0 +1,9 @@+#![deny(missing_docs)]+//! Codex cloud transport and ACP conversations for standalone and hosted runtimes.++/// OAuth orchestration and credential contracts.+pub mod domain;+/// ACP protocol adapters.+pub mod inbound;+/// OpenAI HTTP and optional PostgreSQL storage adapters.+pub mod outbound;diff --git a/crates/codex_cloud_agents/src/main.rs b/crates/codex_cloud_agents/src/main.rsnew file mode 100644index 0000000000..6f9d54ac28--- /dev/null+++ b/crates/codex_cloud_agents/src/main.rs@@ -0,0 +1,263 @@+//! Composition root and CLI for our own direct-OAuth feasibility binary.++use clap::{Parser, Subcommand};+use codex_cloud_agents::domain::cloud::{CloudId, Launch};+use codex_cloud_agents::domain::{Probe, unix_now};+use codex_cloud_agents::outbound::openai::OpenAi;+use credentials::JsonStore;+#[path = "credentials.rs"]+mod credentials;+use std::io::Write as _;+use std::path::PathBuf;+use std::process::ExitCode;++#[cfg(test)]+#[path = "main/test.rs"]+mod test;++#[derive(Parser)]+#[command(+ version,+ about = "Direct ChatGPT OAuth and cloud-task probe. Only launch starts cloud work."+)]+struct Args {+ /// Private directory for credentials.json (separate from ~/.codex).+ #[arg(long)]+ state_dir: PathBuf,+ #[command(subcommand)]+ command: Command,+}++#[derive(Subcommand)]+enum Command {+ /// Start our device-code OAuth flow; open the printed link and enter its code.+ Login,+ /// Print safe local connection metadata. Does not validate with OpenAI.+ Status,+ /// Read cloud environment IDs/labels, refreshing credentials if needed.+ Environments,+ /// Submit one cloud task. This executes work using the connected account.+ Launch {+ #[arg(long)]+ environment: String,+ #[arg(long)]+ branch: String,+ /// UTF-8 text file; avoids putting the prompt in shell history/arguments.+ #[arg(long)]+ prompt_file: PathBuf,+ /// Follow changed snapshots as NDJSON after creation (polling, not token streaming).+ #[arg(long)]+ stream: bool,+ },+ /// Resume changed-snapshot output for an existing task without launching work.+ Stream { task: String },+ /// Print one projected snapshot (current turns, not full history).+ Inspect { task: String },+ /// Print timestamped JSON snapshots. Ctrl-C stops watching, not remote work.+ Watch {+ task: String,+ #[arg(long, default_value_t = 120, value_parser = clap::value_parser!(u32).range(1..=720))]+ samples: u32,+ #[arg(long, default_value_t = 5, value_parser = clap::value_parser!(u32).range(1..=3600))]+ interval_seconds: u32,+ },+ /// Delete this probe's credentials. Does not revoke OpenAI access or stop tasks.+ Logout,+}++#[tokio::main]+async fn main() -> ExitCode {+ match run(Args::parse()).await {+ Ok(()) => ExitCode::SUCCESS,+ Err(error) => {+ eprintln!("codex-cloud-probe: {error}");+ ExitCode::FAILURE+ }+ }+}++async fn run(args: Args) -> Result<(), rootcause::Report> {+ let store = JsonStore::open(&args.state_dir)?;+ let probe = Probe::new(OpenAi::new()?, store);+ match args.command {+ Command::Login => {+ let login = probe.begin_login().await?;+ println!(+ "Open {}\nEnter code: {}",+ login.verification_url, login.user_code+ );+ println!(+ "Waiting for OpenAI verification (up to {} seconds). Ctrl-C cancels local login.",+ login.timeout.as_secs()+ );+ tokio::select! {+ result = probe.finish_login(&login) => result?,+ signal = tokio::signal::ctrl_c() => {+ signal?;+ return Err(rootcause::report!("login cancelled; no credentials saved"));+ }+ }+ println!(+ "Connected. Credentials saved in {}",+ args.state_dir.join("credentials.json").display()+ );+ println!("No cloud task was launched. Run status or environments next.");+ }+ Command::Status => {+ let output = match probe.status()? {+ None => serde_json::json!({"connected": false}),+ Some(credentials) => serde_json::json!({+ "connected": true,+ "account_id": credentials.account_id,+ "expires_at": credentials.expires_at,+ "access_token_expired": credentials.expires_at <= unix_now()?,+ "verification": "local metadata only; use environments for an authenticated cloud read",+ }),+ };+ println!("{}", serde_json::to_string_pretty(&output)?);+ }+ Command::Environments => {+ let environments = probe.environments(unix_now()?).await?;+ println!("{}", serde_json::to_string_pretty(&environments)?);+ }+ Command::Launch {+ environment,+ branch,+ prompt_file,+ stream,+ } => {+ use std::io::Read as _;+ let mut prompt = String::new();+ std::fs::File::open(prompt_file)?+ .take(64 * 1024 + 1)+ .read_to_string(&mut prompt)?;+ let request = Launch {+ environment: CloudId::new(environment)?,+ branch,+ prompt,+ };+ let created = probe.launch(&request, unix_now()?).await?;+ if stream {+ // Flush the receipt before the first read so observation errors cannot hide it.+ println!("{}", serde_json::json!({"event":"created", "task":created}));+ std::io::stdout().flush()?;+ stream_task(&probe, &created.task_id).await?;+ } else {+ println!("{}", serde_json::to_string_pretty(&created)?);+ }+ }+ Command::Stream { task } => {+ stream_task(&probe, &CloudId::new(task)?).await?;+ }+ Command::Inspect { task } => {+ let task = CloudId::new(task)?;+ println!(+ "{}",+ serde_json::to_string_pretty(&probe.snapshot(&task, unix_now()?).await?)?+ );+ }+ Command::Watch {+ task,+ samples,+ interval_seconds,+ } => {+ let task = CloudId::new(task)?;+ let watch = async {+ for index in 0..samples {+ let snapshot = probe.snapshot(&task, unix_now()?).await?;+ println!(+ "{}",+ serde_json::to_string(+ &serde_json::json!({"observed_at": unix_now()?, "snapshot": snapshot})+ )?+ );+ if snapshot.terminal() {+ return Ok::<(), rootcause::Report>(());+ }+ if index + 1 < samples {+ tokio::time::sleep(std::time::Duration::from_secs(u64::from(+ interval_seconds,+ )))+ .await;+ }+ }+ eprintln!("Sample limit reached. Remote work may still be running.");+ Ok(())+ };+ tokio::select! {+ result = watch => result?,+ signal = tokio::signal::ctrl_c() => {+ signal?;+ eprintln!("Stopped watching. Remote work was not cancelled.");+ }+ }+ }+ Command::Logout => {+ probe.logout()?;+ println!(+ "Local credentials removed. OpenAI access was not revoked; remote tasks were not stopped."+ );+ }+ }+ Ok(())+}++/// Remember only the last observation, including text replacements and status-only changes.+#[derive(Default)]+struct Changes {+ previous: Option<serde_json::Value>,+}++impl Changes {+ fn observe(&mut self, snapshot: serde_json::Value) -> Option<serde_json::Value> {+ if self.previous.as_ref() == Some(&snapshot) {+ return None;+ }+ self.previous = Some(snapshot.clone());+ Some(snapshot)+ }+}++async fn stream_task(+ probe: &Probe<OpenAi, JsonStore>,+ task: &CloudId,+) -> Result<(), rootcause::Report> {+ eprintln!(+ "Polling every 1 second. Text appears when exposed by the cloud API. Ctrl-C stops observation only."+ );+ let follow = async {+ let mut changes = Changes::default();+ loop {+ let snapshot = probe.snapshot(task, unix_now()?).await?;+ let terminal = snapshot.terminal();+ let failed = matches!(+ snapshot.assistant_status.as_deref(),+ Some("failed" | "cancelled")+ );+ if let Some(snapshot) = changes.observe(serde_json::to_value(&snapshot)?) {+ println!(+ "{}",+ serde_json::json!({"event":"snapshot", "observed_at":unix_now()?, "snapshot":snapshot})+ );+ std::io::stdout().flush()?;+ }+ if terminal {+ if failed {+ return Err(rootcause::report!(+ "cloud task failed or was cancelled; see the last snapshot and Codex web"+ ));+ }+ return Ok::<(), rootcause::Report>(());+ }+ tokio::time::sleep(std::time::Duration::from_secs(5)).await;+ }+ };+ tokio::select! {+ result = follow => result,+ signal = tokio::signal::ctrl_c() => {+ signal?;+ eprintln!("Stopped streaming. Remote work was not cancelled. Resume with: stream {}", task.as_str());+ Ok(())+ }+ }+}diff --git a/crates/codex_cloud_agents/src/main/test.rs b/crates/codex_cloud_agents/src/main/test.rsnew file mode 100644index 0000000000..1fb5590f74--- /dev/null+++ b/crates/codex_cloud_agents/src/main/test.rs@@ -0,0 +1,79 @@+use super::*;+use clap::CommandFactory as _;++#[test]+fn cli_definition_and_documented_login_invocation_are_valid() {+ Args::command().debug_assert();+ let args = Args::try_parse_from([+ "codex-cloud-probe",+ "--state-dir",+ "/tmp/private-probe",+ "login",+ ])+ .unwrap();+ assert_eq!(args.state_dir, PathBuf::from("/tmp/private-probe"));+ assert!(matches!(args.command, Command::Login));+ assert!(Args::try_parse_from(["codex-cloud-probe", "login"]).is_err());+}++#[tokio::test]+async fn status_and_logout_do_not_require_network_or_existing_credentials() {+ let root = tempfile::tempdir().unwrap();+ let state_dir = root.path().join("private-probe");+ run(Args {+ state_dir: state_dir.clone(),+ command: Command::Status,+ })+ .await+ .unwrap();+ assert!(!state_dir.join("credentials.json").exists());+ run(Args {+ state_dir,+ command: Command::Logout,+ })+ .await+ .unwrap();+}++#[test]+fn launch_stream_and_resume_parse_without_starting_work() {+ let args = Args::try_parse_from([+ "codex-cloud-probe",+ "--state-dir",+ "/tmp/probe",+ "launch",+ "--environment",+ "env-test",+ "--branch",+ "main",+ "--prompt-file",+ "/tmp/prompt.txt",+ "--stream",+ ])+ .unwrap();+ assert!(matches!(args.command, Command::Launch { stream: true, .. }));+ let args = Args::try_parse_from([+ "codex-cloud-probe",+ "--state-dir",+ "/tmp/probe",+ "stream",+ "task-test",+ ])+ .unwrap();+ assert!(matches!(args.command, Command::Stream { .. }));+}++#[test]+fn observation_changes_preserve_revisions_and_terminal_empty_output() {+ let mut changes = Changes::default();+ let running = serde_json::json!({"status":"in_progress", "messages":[]});+ assert_eq!(changes.observe(running.clone()), Some(running.clone()));+ assert!(changes.observe(running).is_none());+ for text in ["hello", "hello world", "corrected", ""] {+ let update = serde_json::json!({"status":"in_progress", "messages":[text]});+ assert_eq!(changes.observe(update.clone()), Some(update.clone()));+ assert!(changes.observe(update).is_none());+ }+ let complete = serde_json::json!({"status":"completed", "messages":[]});+ assert_eq!(changes.observe(complete.clone()), Some(complete));+}diff --git a/crates/codex_cloud_agents/src/outbound/mod.rs b/crates/codex_cloud_agents/src/outbound/mod.rsnew file mode 100644index 0000000000..3b4128b5b6--- /dev/null+++ b/crates/codex_cloud_agents/src/outbound/mod.rs@@ -0,0 +1,5 @@+//! Cloud transport and persistence adapters.++pub mod openai;+#[cfg(feature = "postgres")]+pub mod postgres_journal;diff --git a/crates/codex_cloud_agents/src/outbound/openai.rs b/crates/codex_cloud_agents/src/outbound/openai.rsnew file mode 100644index 0000000000..dbdbe316c1--- /dev/null+++ b/crates/codex_cloud_agents/src/outbound/openai.rs@@ -0,0 +1,296 @@+//! Direct HTTP implementation of the device flow observed in Codex and OpenCode.++use crate::domain::{+ Credentials, DeviceLogin, Environment, EnvironmentRepository, LoginPoll, OAuth, Secret,+ unix_now,+};+use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};+use reqwest::{Client, Response, StatusCode};+use serde::{Deserialize, de::DeserializeOwned};+use std::time::Duration;++#[cfg(test)]+mod test;++mod environments;+mod tasks;++const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";+const ISSUER: &str = "https://auth.openai.com";+const CLOUD: &str = "https://chatgpt.com/backend-api";+const MAX_BODY: usize = 1024 * 1024;++/// Fixed production origins; endpoint overrides are only available inside tests.+pub struct OpenAi {+ client: Client,+ issuer: String,+ cloud: String,+}++impl OpenAi {+ /// Build a client with bounded requests and redirects disabled.+ pub fn new() -> Result<Self, rootcause::Report> {+ Ok(Self {+ client: Client::builder()+ .user_agent(concat!("macro-codex-probe/", env!("CARGO_PKG_VERSION")))+ .redirect(reqwest::redirect::Policy::none())+ .connect_timeout(Duration::from_secs(10))+ .timeout(Duration::from_secs(30))+ .build()?,+ issuer: ISSUER.to_owned(),+ cloud: CLOUD.to_owned(),+ })+ }++ async fn tokens(&self, form: &[(&str, &str)]) -> Result<Tokens, rootcause::Report> {+ let response = self+ .client+ .post(format!("{}/oauth/token", self.issuer))+ .form(form)+ .send()+ .await+ .map_err(|_| rootcause::report!("token request failed (network/timeout)"))?;+ decode(response, "token exchange/refresh").await+ }+}++impl OAuth for OpenAi {+ async fn begin(&self) -> Result<DeviceLogin, rootcause::Report> {+ let response = self+ .client+ .post(format!("{}/api/accounts/deviceauth/usercode", self.issuer))+ .json(&serde_json::json!({"client_id": CLIENT_ID}))+ .send()+ .await+ .map_err(|_| rootcause::report!("device login request failed (network/timeout)"))?;+ let device: DeviceResponse = decode(+ response,+ "start device login (enable device login in ChatGPT settings if unavailable)",+ )+ .await?;+ let interval = match device.interval {+ Some(Interval::Text(value)) => value+ .trim()+ .parse::<u64>()+ .map_err(|_| rootcause::report!("invalid device polling interval"))?,+ Some(Interval::Number(value)) => value,+ None => 5,+ };+ // Never poll faster than the server requested. The login itself is bounded.+ let interval = interval+ .max(1)+ .checked_add(3)+ .ok_or_else(|| rootcause::report!("invalid device polling interval"))?;+ if device.user_code.is_empty()+ || device.user_code.len() > 128+ || device.user_code.chars().any(char::is_control)+ {+ return Err(rootcause::report!("invalid device user code"));+ }+ Ok(DeviceLogin {+ verification_url: format!("{}/codex/device", self.issuer),+ user_code: device.user_code,+ device_auth_id: Secret::new(device.device_auth_id)?,+ interval: Duration::from_secs(interval),+ timeout: Duration::from_secs(device.expires_in.unwrap_or(900).min(900)),+ })+ }++ async fn poll(&self, login: &DeviceLogin) -> Result<LoginPoll, rootcause::Report> {+ let response = self.client.post(format!("{}/api/accounts/deviceauth/token", self.issuer))+ .json(&serde_json::json!({"device_auth_id": login.device_auth_id.expose(), "user_code": login.user_code}))+ .send().await.map_err(|_| rootcause::report!("device poll failed (network/timeout)"))?;+ // These two pending statuses match both supplied implementations.+ if matches!(+ response.status(),+ StatusCode::FORBIDDEN | StatusCode::NOT_FOUND+ ) {+ return Ok(LoginPoll::Pending);+ }+ let code: CodeResponse = decode(response, "device verification").await?;+ let redirect = format!("{}/deviceauth/callback", self.issuer);+ let tokens = self+ .tokens(&[+ ("grant_type", "authorization_code"),+ ("client_id", CLIENT_ID),+ ("code", code.authorization_code.expose()),+ ("code_verifier", code.code_verifier.expose()),+ ("redirect_uri", &redirect),+ ])+ .await?;+ Ok(LoginPoll::Complete(tokens.credentials(None, unix_now()?)?))+ }++ async fn refresh(&self, current: &Credentials) -> Result<Credentials, rootcause::Report> {+ self.tokens(&[+ ("grant_type", "refresh_token"),+ ("client_id", CLIENT_ID),+ ("refresh_token", current.refresh_token.expose()),+ ])+ .await?+ .credentials(Some(current), unix_now()?)+ }++ async fn environments(+ &self,+ credentials: &Credentials,+ ) -> Result<Vec<Environment>, rootcause::Report> {+ let response = self+ .client+ .get(format!("{}/wham/environments", self.cloud))+ .bearer_auth(credentials.access_token.expose())+ .header("ChatGPT-Account-Id", &credentials.account_id)+ .header("originator", "macro-codex-probe")+ .send()+ .await+ .map_err(|_| rootcause::report!("environment request failed (network/timeout)"))?;+ let environments: Vec<environments::ProviderEnvironment> =+ decode(response, "list cloud environments").await?;+ environments+ .into_iter()+ .map(environments::ProviderEnvironment::project)+ .collect()+ }+}++async fn response_body(+ mut response: Response,+ operation: &str,+) -> Result<zeroize::Zeroizing<Vec<u8>>, rootcause::Report> {+ let status = response.status();+ if !status.is_success() {+ // Never include provider bodies: error payloads can echo credentials.+ return Err(rootcause::report!(+ "{operation}: HTTP {status}; no automatic retry. For 401/invalid grant, log in again"+ ));+ }+ let mut bytes = zeroize::Zeroizing::new(Vec::new());+ while let Some(chunk) = response+ .chunk()+ .await+ .map_err(|_| rootcause::report!("provider response interrupted"))?+ {+ if bytes.len().saturating_add(chunk.len()) > MAX_BODY {+ return Err(rootcause::report!("provider response exceeds 1 MiB limit"));+ }+ bytes.extend_from_slice(&chunk);+ }+ Ok(bytes)+}++async fn decode<T: DeserializeOwned>(+ response: Response,+ operation: &str,+) -> Result<T, rootcause::Report> {+ let bytes = response_body(response, operation).await?;+ serde_json::from_slice(&bytes)+ .map_err(|_| rootcause::report!("{operation}: unexpected response shape (body withheld)"))+}++async fn native_body(response: Response, operation: &str) -> Result<String, rootcause::Report> {+ let bytes = response_body(response, operation).await?;+ String::from_utf8(bytes.to_vec())+ .map_err(|_| rootcause::report!("{operation}: response was not UTF-8 (body withheld)"))+}++#[derive(Deserialize)]+#[serde(untagged)]+enum Interval {+ Text(String),+ Number(u64),+}++#[derive(Deserialize)]+struct DeviceResponse {+ device_auth_id: String,+ #[serde(alias = "usercode")]+ user_code: String,+ interval: Option<Interval>,+ expires_in: Option<u64>,+}++#[derive(Deserialize)]+struct CodeResponse {+ authorization_code: Secret,+ code_verifier: Secret,+}++#[derive(Deserialize)]+struct Tokens {+ access_token: Secret,+ refresh_token: Option<Secret>,+ id_token: Option<Secret>,+ expires_in: Option<u64>,+}++#[derive(Deserialize, Default)]+struct Claims {+ exp: Option<u64>,+ chatgpt_account_id: Option<String>,+ #[serde(rename = "https://api.openai.com/auth")]+ auth: Option<AccountClaims>,+}+#[derive(Deserialize)]+struct AccountClaims {+ chatgpt_account_id: Option<String>,+}++impl Claims {+ fn read(token: &Secret) -> Self {+ token+ .expose()+ .split('.')+ .nth(1)+ .and_then(|part| URL_SAFE_NO_PAD.decode(part).ok())+ .and_then(|bytes| serde_json::from_slice(&bytes).ok())+ .unwrap_or_default()+ }+ fn account(self) -> Option<String> {+ self.chatgpt_account_id+ .or_else(|| self.auth.and_then(|auth| auth.chatgpt_account_id))+ }+}++impl Tokens {+ fn credentials(+ self,+ previous: Option<&Credentials>,+ now: u64,+ ) -> Result<Credentials, rootcause::Report> {+ let access_claims = Claims::read(&self.access_token);+ let expires_at = self+ .expires_in+ .and_then(|seconds| now.checked_add(seconds))+ .or(access_claims.exp)+ .filter(|expiry| *expiry > now)+ .ok_or_else(|| rootcause::report!("token response has no usable expiry"))?;+ let account_id = access_claims+ .account()+ .or_else(|| {+ self.id_token+ .as_ref()+ .and_then(|token| Claims::read(token).account())+ })+ .or_else(|| previous.map(|old| old.account_id.clone()))+ .ok_or_else(|| rootcause::report!("token response has no ChatGPT account ID"))?;+ let refresh_token = match self.refresh_token {+ Some(token) => token,+ None => Secret::new(+ previous+ .ok_or_else(|| rootcause::report!("login response has no refresh token"))?+ .refresh_token+ .expose()+ .to_owned(),+ )?,+ };+ let credentials = Credentials {+ version: 1,+ access_token: self.access_token,+ refresh_token,+ expires_at,+ account_id,+ };+ credentials.validate()?;+ Ok(credentials)+ }+}diff --git a/crates/codex_cloud_agents/src/outbound/openai/environments.rs b/crates/codex_cloud_agents/src/outbound/openai/environments.rsnew file mode 100644index 0000000000..b2302a8fc1--- /dev/null+++ b/crates/codex_cloud_agents/src/outbound/openai/environments.rs@@ -0,0 +1,88 @@+//! Project repository identity without retaining provider setup or secret fields.++use super::{Environment, EnvironmentRepository};+use crate::domain::cloud::CloudId;+use serde::Deserialize;+use std::collections::HashMap;++#[derive(Deserialize)]+pub(super) struct ProviderEnvironment {+ id: String,+ label: Option<String>,+ #[serde(default)]+ repos: Vec<String>,+ #[serde(default)]+ repo_map: HashMap<String, ProviderRepository>,+}++#[derive(Deserialize)]+struct ProviderRepository {+ repository_full_name: Option<String>,+ clone_url: Option<String>,+ default_branch: Option<String>,+}++impl ProviderEnvironment {+ pub(super) fn project(self) -> Result<Environment, rootcause::Report> {+ CloudId::new(self.id.clone())?;+ // Missing or invalid primary metadata must not promote a secondary repo.+ // Keep the environment available for explicit selection, without auto candidates.+ let repositories = self+ .repos+ .iter()+ .map(|id| self.repo_map.get(id)?.project())+ .collect::<Option<Vec<_>>>()+ .unwrap_or_default();+ Ok(Environment {+ id: self.id,+ label: self.label,+ repositories,+ })+ }+}++impl ProviderRepository {+ fn project(&self) -> Option<EnvironmentRepository> {+ let full_name = self.repository_full_name.as_deref()?;+ let parts: Vec<_> = full_name.split('/').collect();+ if parts.len() != 2+ || parts.iter().any(|part| {+ part.is_empty()+ || *part == "."+ || *part == ".."+ || !part+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))+ })+ {+ return None;+ }+ let clone_url = self.clone_url.as_deref()?;+ let url = reqwest::Url::parse(clone_url).ok()?;+ if url.scheme() != "https"+ || url.host_str().is_none()+ || !url.username().is_empty()+ || url.password().is_some()+ || url.query().is_some()+ || url.fragment().is_some()+ || url+ .path()+ .trim_start_matches('/')+ .strip_suffix(".git")+ .unwrap_or(url.path().trim_start_matches('/'))+ != full_name+ {+ return None;+ }+ let default_branch = self.default_branch.as_deref()?;+ crate::domain::cloud::validate_branch(default_branch).ok()?;+ Some(EnvironmentRepository {+ full_name: full_name.into(),+ clone_url: url.to_string(),+ default_branch: default_branch.into(),+ })+ }+}++#[cfg(test)]+mod test;diff --git a/crates/codex_cloud_agents/src/outbound/openai/environments/test.rs b/crates/codex_cloud_agents/src/outbound/openai/environments/test.rsnew file mode 100644index 0000000000..f62943a7e7--- /dev/null+++ b/crates/codex_cloud_agents/src/outbound/openai/environments/test.rs@@ -0,0 +1,62 @@+use super::*;+use serde_json::json;++fn repository(name: &str) -> serde_json::Value {+ json!({"repository_full_name":name,"clone_url":format!("https://github.com/{name}.git"),"default_branch":"trunk", "secret":"private-marker"})+}++#[test]+fn projects_ordered_repositories_and_omits_private_configuration() {+ let raw = json!({"id":"env-1","label":"Misleading label","repos":["two","one"],+ "repo_map":{"one":repository("owner/one"),"two":repository("owner/two")},+ "env_vars":{"KEY":"private-marker"},"setup":"private-marker","secrets":{"key":"private-marker"}});+ let environment = serde_json::from_value::<ProviderEnvironment>(raw)+ .unwrap()+ .project()+ .unwrap();+ assert_eq!(+ environment+ .repositories+ .iter()+ .map(|repo| repo.full_name.as_str())+ .collect::<Vec<_>>(),+ vec!["owner/two", "owner/one"]+ );+ assert_eq!(environment.repositories[0].default_branch, "trunk");+ let output = serde_json::to_string(&environment).unwrap();+ assert!(!output.contains("private-marker"));+ assert!(!output.contains("repo_map"));+}++#[test]+fn invalid_primary_never_promotes_secondary_and_url_identity_is_verified() {+ for url in [+ "https://[email protected]/owner/one.git",+ "https://github.com/owner/one.git?token=secret",+ "https://github.com/owner/one.git#secret",+ "https://github.com/other/one.git",+ "http://github.com/owner/one.git",+ ] {+ let mut first = repository("owner/one");+ first["clone_url"] = url.into();+ let raw = json!({"id":"env-1","label":"owner/two","repos":["one","two"],"repo_map":{"one":first,"two":repository("owner/two")}});+ assert!(+ serde_json::from_value::<ProviderEnvironment>(raw)+ .unwrap()+ .project()+ .unwrap()+ .repositories+ .is_empty()+ );+ }+ let raw =+ json!({"id":"env-1","repos":["missing","two"],"repo_map":{"two":repository("owner/two")}});+ assert!(+ serde_json::from_value::<ProviderEnvironment>(raw)+ .unwrap()+ .project()+ .unwrap()+ .repositories+ .is_empty()+ );+}diff --git a/crates/codex_cloud_agents/src/outbound/openai/tasks.rs b/crates/codex_cloud_agents/src/outbound/openai/tasks.rsnew file mode 100644index 0000000000..441617cb2a--- /dev/null+++ b/crates/codex_cloud_agents/src/outbound/openai/tasks.rs@@ -0,0 +1,99 @@+//! Source-derived task HTTP endpoints, isolated from the OAuth lifecycle.++use super::{OpenAi, decode};+use crate::domain::Credentials;+use crate::domain::cloud::{CloudId, CloudTasks, CreatedTask, Launch, TaskSnapshot, TurnId};+use serde::Deserialize;++mod conversation;+mod stream;++#[cfg(test)]+mod test;+#[cfg(test)]+use serde_json::Value;++impl CloudTasks for OpenAi {+ async fn create(+ &self,+ auth: &Credentials,+ request: &Launch,+ ) -> Result<CreatedTask, rootcause::Report> {+ let response = self.client.post(format!("{}/wham/tasks", self.cloud))+ .bearer_auth(auth.access_token.expose())+ .header("ChatGPT-Account-Id", &auth.account_id)+ .header("originator", "macro-codex-probe")+ .json(&serde_json::json!({+ "new_task": {"environment_id": request.environment.as_str(), "branch": request.branch, "run_environment_in_qa_mode": false},+ "input_items": [{"type":"message", "role":"user", "content":[{"content_type":"text", "text":request.prompt}]}],+ })).send().await+ .map_err(|_| rootcause::report!("task submission outcome unknown (network/timeout); inspect Codex web before retrying"))?;+ let body: CreateResponse = decode(+ response,+ "create task; acceptance may be unknown, inspect Codex web before retrying",+ )+ .await?;+ receipt(body)+ }++ async fn snapshot(+ &self,+ auth: &Credentials,+ task: &CloudId,+ ) -> Result<TaskSnapshot, rootcause::Report> {+ let response = self+ .client+ .get(format!("{}/wham/tasks/{}", self.cloud, task.as_str()))+ .bearer_auth(auth.access_token.expose())+ .header("ChatGPT-Account-Id", &auth.account_id)+ .header("originator", "macro-codex-probe")+ .send()+ .await+ .map_err(|_| {+ rootcause::report!(+ "task observation failed (network/timeout); remote work may still be running"+ )+ })?;+ let body = super::native_body(response, "read task details").await?;+ TaskSnapshot::from_native(task, &body)+ }+}++#[derive(Deserialize)]+struct TaskIdentity {+ id: String,+}+#[derive(Deserialize)]+struct CreateResponse {+ task: Option<TaskIdentity>,+ id: Option<String>,+ assistant_turn: Option<TaskIdentity>,+ turn: Option<TaskIdentity>,+ assistant_turn_id: Option<String>,+}++#[cfg(test)]+fn project(task: &CloudId, body: &Value) -> Result<TaskSnapshot, rootcause::Report> {+ TaskSnapshot::from_native(task, &body.to_string())+}++fn receipt(body: CreateResponse) -> Result<CreatedTask, rootcause::Report> {+ let id = body.task.map(|task| task.id).or(body.id).ok_or_else(|| {+ rootcause::report!(+ "creation returned no task ID; acceptance unknown, inspect Codex web before retrying"+ )+ })?;+ let task_id = CloudId::new(id)?;+ let assistant_turn_id = body+ .turn+ .or(body.assistant_turn)+ .map(|turn| turn.id)+ .or(body.assistant_turn_id)+ .map(TurnId::new)+ .transpose()?;+ Ok(CreatedTask {+ url: format!("https://chatgpt.com/codex/tasks/{}", task_id.as_str()),+ task_id,+ assistant_turn_id,+ })+}diff --git a/crates/codex_cloud_agents/src/outbound/openai/tasks/conversation.rs b/crates/codex_cloud_agents/src/outbound/openai/tasks/conversation.rsnew file mode 100644index 0000000000..eab7ce4380--- /dev/null+++ b/crates/codex_cloud_agents/src/outbound/openai/tasks/conversation.rs@@ -0,0 +1,141 @@+//! Desktop 26.908.70816 WHAM continuation, cancellation and turn subscription.++use super::{CreateResponse, receipt, stream};+use crate::domain::Credentials;+use crate::domain::cloud::{+ CloudConversation, CloudEventStream, CloudId, CreatedTask, TaskSnapshot, TurnId,+};+use crate::outbound::openai::{OpenAi, decode};+use serde_json::Value;+use std::time::Duration;++impl CloudConversation for OpenAi {+ async fn follow_up(+ &self,+ auth: &Credentials,+ task: &CloudId,+ turn: &TurnId,+ prompt: &str,+ ) -> Result<CreatedTask, rootcause::Report> {+ let response = self.client.post(format!("{}/wham/tasks", self.cloud))+ .bearer_auth(auth.access_token.expose())+ .header("ChatGPT-Account-Id", &auth.account_id)+ .header("originator", "macro-codex-probe")+ .json(&serde_json::json!({+ "follow_up": {"task_id":task.as_str(), "turn_id":turn.as_str(), "environment_mode":"code"},+ "input_items":[{"type":"message","role":"user","content":[{"content_type":"text","text":prompt}]}]+ })).send().await.map_err(|_| rootcause::report!("follow-up acceptance unknown (network/timeout); inspect Codex web before retrying"))?;+ let body: CreateResponse = decode(+ response,+ "follow-up; acceptance may be unknown, inspect Codex web before retrying",+ )+ .await?;+ let created = receipt(body)?;+ if created.task_id != *task {+ return Err(rootcause::report!(+ "follow-up task identity mismatch; acceptance unknown, inspect Codex web"+ ));+ }+ Ok(created)+ }++ async fn cancel(&self, auth: &Credentials, task: &CloudId) -> Result<(), rootcause::Report> {+ let response = self+ .client+ .post(format!(+ "{}/wham/tasks/{}/cancel",+ self.cloud,+ task.as_str()+ ))+ .bearer_auth(auth.access_token.expose())+ .header("ChatGPT-Account-Id", &auth.account_id)+ .header("originator", "macro-codex-probe")+ .send()+ .await+ .map_err(|_| {+ rootcause::report!("remote cancellation outcome unknown (network/timeout)")+ })?;+ let body: Value = decode(response, "cancel task").await?;+ if body.get("success").and_then(Value::as_bool) != Some(true) {+ return Err(rootcause::report!(+ "provider did not confirm cancellation request; inspect remote task state"+ ));+ }+ Ok(())+ }++ async fn turn(+ &self,+ auth: &Credentials,+ task: &CloudId,+ turn: &TurnId,+ ) -> Result<TaskSnapshot, rootcause::Report> {+ let response = self+ .client+ .get(format!(+ "{}/wham/tasks/{}/turns/{}",+ self.cloud,+ task.as_str(),+ turn.as_str()+ ))+ .bearer_auth(auth.access_token.expose())+ .header("ChatGPT-Account-Id", &auth.account_id)+ .header("originator", "macro-codex-probe")+ .send()+ .await+ .map_err(|_| rootcause::report!("turn observation failed (network/timeout)"))?;+ let body = crate::outbound::openai::native_body(response, "read turn").await?;+ let snapshot = TaskSnapshot::from_native(task, &body)?;+ if !snapshot.turns.iter().any(|item| {+ item.source == "current_assistant_turn" && item.id.as_deref() == Some(turn.as_str())+ }) {+ return Err(rootcause::report!(+ "turn identity mismatch or unexpected response shape"+ ));+ }+ Ok(snapshot)+ }++ async fn stream(+ &self,+ auth: &Credentials,+ task: &CloudId,+ turn: &TurnId,+ ) -> Result<CloudEventStream, rootcause::Report> {+ let response = self+ .client+ .get(format!(+ "{}/wham/tasks/{}/turns/{}/stream?item_type=thread_event&item_type=log",+ self.cloud,+ task.as_str(),+ turn.as_str()+ ))+ .bearer_auth(auth.access_token.expose())+ .header("ChatGPT-Account-Id", &auth.account_id)+ .header("originator", "macro-codex-probe")+ .header("Accept", "text/event-stream")+ .timeout(Duration::from_secs(30 * 60))+ .send()+ .await+ .map_err(|_| rootcause::report!("event subscription failed (network/timeout)"))?;+ if !response.status().is_success() {+ let status = response.status();+ return Err(rootcause::report!(+ "event subscription HTTP {status}; remote work may still be running"+ ));+ }+ if response+ .headers()+ .get("content-type")+ .and_then(|value| value.to_str().ok())+ .and_then(|value| value.split(';').next())+ .map(str::trim)+ != Some("text/event-stream")+ {+ return Err(rootcause::report!(+ "event subscription returned an unexpected content type"+ ));+ }+ Ok(stream::subscribe(response))+ }+}diff --git a/crates/codex_cloud_agents/src/outbound/openai/tasks/stream.rs b/crates/codex_cloud_agents/src/outbound/openai/tasks/stream.rsnew file mode 100644index 0000000000..2befb01b8c--- /dev/null+++ b/crates/codex_cloud_agents/src/outbound/openai/tasks/stream.rs@@ -0,0 +1,140 @@+//! Incremental SSE framing. Interpretation belongs after durable journal append.++use crate::domain::cloud::{CloudEventStream, NativeRecord};+use std::collections::VecDeque;+use std::time::Duration;++const MAX_EVENT_BYTES: usize = 1024 * 1024;+const MAX_EVENTS: usize = 100_000;++#[cfg(test)]+mod test;++#[derive(Default)]+struct Parser {+ line: Vec<u8>,+ data: Vec<u8>,+ event: String,+ id: Option<String>,+ count: usize,+ ready: VecDeque<NativeRecord>,+ previous_cr: bool,+}+impl Parser {+ fn push(&mut self, bytes: &[u8]) -> Result<(), rootcause::Report> {+ for &byte in bytes {+ if byte == b'\n' && self.previous_cr {+ self.previous_cr = false;+ continue;+ }+ self.previous_cr = byte == b'\r';+ if byte == b'\n' || byte == b'\r' {+ self.end_line()?;+ } else {+ if self.line.len()+ + self.data.len()+ + self.event.len()+ + self.id.as_ref().map_or(0, String::len)+ >= MAX_EVENT_BYTES+ {+ return Err(rootcause::report!("cloud event exceeds 1 MiB limit"));+ }+ self.line.push(byte);+ }+ }+ Ok(())+ }+ fn end_line(&mut self) -> Result<(), rootcause::Report> {+ let line = std::mem::take(&mut self.line);+ if line.is_empty() {+ if !self.data.is_empty() {+ if self.count >= MAX_EVENTS {+ return Err(rootcause::report!(+ "cloud stream exceeds 100000 record limit"+ ));+ }+ self.count += 1;+ let mut data = std::mem::take(&mut self.data);+ data.pop(); // SSE joins data lines without a final newline.+ self.ready.push_back(NativeRecord {+ event: std::mem::take(&mut self.event),+ id: self.id.take(),+ data: String::from_utf8(data)+ .map_err(|_| rootcause::report!("cloud SSE data was not UTF-8"))?,+ });+ }+ self.event.clear();+ self.id = None;+ return Ok(());+ }+ if line.starts_with(b":") {+ return Ok(());+ }+ let split = line+ .iter()+ .position(|byte| *byte == b':')+ .unwrap_or(line.len());+ let field = &line[..split];+ let mut value = line.get(split + 1..).unwrap_or_default();+ if value.first() == Some(&b' ') {+ value = &value[1..];+ }+ match field {+ b"data" => {+ self.data.extend_from_slice(value);+ self.data.push(b'\n');+ }+ b"event" => {+ self.event = String::from_utf8(value.to_vec())+ .map_err(|_| rootcause::report!("cloud SSE event was not UTF-8"))?+ }+ b"id" if !value.contains(&0) => {+ self.id = Some(+ String::from_utf8(value.to_vec())+ .map_err(|_| rootcause::report!("cloud SSE id was not UTF-8"))?,+ )+ }+ _ => {}+ }+ Ok(())+ }+}++pub(super) fn subscribe(response: reqwest::Response) -> CloudEventStream {+ let state = Some((response, Parser::default()));+ Box::pin(futures::stream::unfold(state, |state| async move {+ let (mut response, mut parser) = state?;+ loop {+ if let Some(event) = parser.ready.pop_front() {+ return Some((Ok(event), Some((response, parser))));+ }+ let chunk = tokio::time::timeout(Duration::from_secs(90), response.chunk()).await;+ match chunk {+ Ok(Ok(Some(bytes))) => {+ if let Err(error) = parser.push(&bytes) {+ return Some((Err(error), None));+ }+ }+ Ok(Ok(None)) => {+ if !parser.line.is_empty() || !parser.data.is_empty() {+ return Some((+ Err(rootcause::report!(+ "cloud event stream ended mid-record; reconcile remote turn"+ )),+ None,+ ));+ }+ return None;+ }+ _ => {+ return Some((+ Err(rootcause::report!(+ "cloud event stream interrupted or idle; reconcile remote turn"+ )),+ None,+ ));+ }+ }+ }+ }))+}diff --git a/crates/codex_cloud_agents/src/outbound/openai/tasks/stream/test.rs b/crates/codex_cloud_agents/src/outbound/openai/tasks/stream/test.rsnew file mode 100644index 0000000000..5d5bedd4fb--- /dev/null+++ b/crates/codex_cloud_agents/src/outbound/openai/tasks/stream/test.rs@@ -0,0 +1,82 @@+use super::*;++const DELTA: &str = "data: {\"id\":\"event-1\",\"item_type\":\"thread_event\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"🐺\"}}}\r\n\r\n";++#[test]+fn byte_fragmentation_preserves_unicode_crlf_and_replay_identity() {+ let mut parser = Parser::default();+ for byte in DELTA.bytes().chain(DELTA.bytes()) {+ parser.push(&[byte]).unwrap();+ }+ assert_eq!(+ parser.ready.len(),+ 2,+ "deduplication happens after raw capture"+ );+ let event = parser.ready.pop_front().unwrap().decode().unwrap().unwrap();+ assert_eq!(event.id, "event-1");+ assert_eq!(event.params["delta"], "🐺");+ assert!(parser.line.is_empty());+ assert!(parser.data.is_empty());+}++#[test]+fn comments_multiline_data_and_unknown_methods_are_preserved() {+ let mut parser = Parser::default();+ parser+ .push(+ b": heartbeat\n\ndata: {\"id\":\"2\",\"item_type\":\"thread_event\",\n\+data: \"event\":{\"method\":\"future/event\",\"params\":{}}}\n\n",+ )+ .unwrap();+ assert_eq!(+ parser+ .ready+ .pop_front()+ .unwrap()+ .decode()+ .unwrap()+ .unwrap()+ .method,+ "future/event"+ );+}++#[test]+fn captures_malformed_payloads_before_decode_and_rejects_oversized_framing() {+ for data in [+ b"data: broken\n\n".as_slice(),+ b"data: {\"item_type\":\"thread_event\"}\n\n",+ ] {+ let mut parser = Parser::default();+ parser.push(data).unwrap();+ assert!(parser.ready.pop_front().unwrap().decode().is_err());+ }+ assert!(+ Parser::default()+ .push(&vec![b'x'; MAX_EVENT_BYTES + 1])+ .is_err()+ );+}++#[test]+fn log_envelopes_keep_their_identity() {+ let mut parser = Parser::default();+ parser+ .push(b"data: {\"id\":\"log-1\",\"item_type\":\"log\",\"line\":\"setup\"}\r\r")+ .unwrap();+ let event = parser.ready.pop_front().unwrap().decode().unwrap().unwrap();+ assert_eq!(event.method, "log");+ assert_eq!(event.params["line"], "setup");+}++#[test]+fn unknown_envelopes_and_sse_headers_survive_native_capture() {+ let mut parser = Parser::default();+ parser.push(b"event: future\nid: wire-1\ndata: {\"item_type\":\"new_kind\",\"unknown\": [1, 2]}\n\n").unwrap();+ let record = parser.ready.pop_front().unwrap();+ assert_eq!(record.event, "future");+ assert_eq!(record.id.as_deref(), Some("wire-1"));+ assert_eq!(record.data, r#"{"item_type":"new_kind","unknown": [1, 2]}"#);+ assert!(record.decode().unwrap().is_none());+}diff --git a/crates/codex_cloud_agents/src/outbound/openai/tasks/test.rs b/crates/codex_cloud_agents/src/outbound/openai/tasks/test.rsnew file mode 100644index 0000000000..1650d8f75e--- /dev/null+++ b/crates/codex_cloud_agents/src/outbound/openai/tasks/test.rs@@ -0,0 +1,101 @@+use super::*;++#[test]+fn creation_receipt_preserves_task_qualified_turn_identity() {+ let body =+ serde_json::json!({"task":{"id":"task_e_123"},"turn":{"id":"task_e_123~assttrn_e_456"}});+ let created = receipt(serde_json::from_value(body).unwrap()).unwrap();+ assert_eq!(created.task_id.as_str(), "task_e_123");+ assert_eq!(+ created.assistant_turn_id.unwrap().as_str(),+ "task_e_123~assttrn_e_456"+ );+ assert!(TurnId::new("../other".to_owned()).is_err());+ assert!(CloudId::new("task/other".to_owned()).is_err());+}++#[test]+fn task_projection_checks_identity_and_unknown_status_is_not_terminal() {+ let task = CloudId::new("task_e_123".to_owned()).unwrap();+ let body = serde_json::json!({"task":{"id":"task_e_123"},"current_assistant_turn":{"id":"task_e_123~assttrn_e_456", "turn_status":"future_status", "output_items":[{"type":"message","content":[{"content_type":"text","text":"done"}]}]}});+ let snapshot = project(&task, &body).unwrap();+ assert!(!snapshot.terminal());+ assert_eq!(snapshot.turns[0].messages, ["done"]);+ assert!(project(&CloudId::new("different".to_owned()).unwrap(), &body).is_err());+}++#[tokio::test]+async fn conversation_routes_payloads_and_replay_match_desktop_contract() {+ use crate::domain::Secret;+ use crate::domain::cloud::CloudConversation;+ use axum::{+ Router,+ body::{Body, to_bytes},+ extract::Request,+ response::Response,+ routing::any,+ };+ use futures::StreamExt;+ let app = Router::new().fallback(any(async |request: Request| {+ let (parts, body) = request.into_parts();+ assert_eq!(parts.headers["chatgpt-account-id"], "test-account");+ assert_eq!(parts.headers["authorization"], "Bearer test-access");+ let path = parts.uri.path();+ let (content_type, reply) = if path.ends_with("/stream") {+ assert_eq!(parts.uri.query(), Some("item_type=thread_event&item_type=log"));+ ("text/event-stream", "data: {\"id\":\"event1\",\"item_type\":\"thread_event\",\"event\":{\"method\":\"turn/completed\",\"params\":{}}}\n\n")+ } else if path.ends_with("/cancel") {+ assert_eq!(parts.method, "POST");+ assert!(to_bytes(body, 1024).await.unwrap().is_empty());+ ("application/json", r#"{"success":true}"#)+ } else if path == "/wham/tasks" {+ assert_eq!(parts.method, "POST");+ let body: Value = serde_json::from_slice(&to_bytes(body, 4096).await.unwrap()).unwrap();+ assert_eq!(body["follow_up"], serde_json::json!({"task_id":"task_test", "turn_id":"task_test~turn_old", "environment_mode":"code"}));+ assert_eq!(body["input_items"][0]["content"][0]["text"], "next prompt");+ ("application/json", r#"{"task":{"id":"task_test"},"turn":{"id":"task_test~turn_new"}}"#)+ } else {+ assert_eq!(path, "/wham/tasks/task_test/turns/task_test~turn_new");+ ("application/json", r#"{"task":{"id":"task_test"},"turn":{"id":"task_test~turn_new","turn_status":"cancelled","output_items":[]}}"#)+ };+ Response::builder().header("content-type", content_type).body(Body::from(reply)).unwrap()+ }));+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let origin = format!("http://{}", listener.local_addr().unwrap());+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let mut provider = OpenAi::new().unwrap();+ provider.cloud = origin;+ let auth = Credentials {+ version: 1,+ access_token: Secret::new("test-access".to_owned()).unwrap(),+ refresh_token: Secret::new("test-refresh".to_owned()).unwrap(),+ expires_at: 1000,+ account_id: "test-account".to_owned(),+ };+ let task = CloudId::new("task_test".to_owned()).unwrap();+ let turn = TurnId::new("task_test~turn_old".to_owned()).unwrap();+ let created = provider+ .follow_up(&auth, &task, &turn, "next prompt")+ .await+ .unwrap();+ let turn = created.assistant_turn_id.unwrap();+ let mut stream = provider.stream(&auth, &task, &turn).await.unwrap();+ assert_eq!(+ stream+ .next()+ .await+ .unwrap()+ .unwrap()+ .decode()+ .unwrap()+ .unwrap()+ .method,+ "turn/completed"+ );+ assert!(stream.next().await.is_none());+ provider.cancel(&auth, &task).await.unwrap();+ let snapshot = provider.turn(&auth, &task, &turn).await.unwrap();+ assert!(snapshot.terminal());+ assert_eq!(snapshot.assistant_status.as_deref(), Some("cancelled"));+ server.abort();+}diff --git a/crates/codex_cloud_agents/src/outbound/openai/test.rs b/crates/codex_cloud_agents/src/outbound/openai/test.rsnew file mode 100644index 0000000000..327c7fe160--- /dev/null+++ b/crates/codex_cloud_agents/src/outbound/openai/test.rs@@ -0,0 +1,336 @@+use super::*;+use crate::domain::cloud::{CloudId, CloudTasks, Launch};+use axum::{+ Router,+ body::{Body, to_bytes},+ extract::{Request, State},+ response::Response as AxumResponse,+ routing::any,+};+use std::collections::VecDeque;+use std::sync::{Arc, Mutex};++type Recorded = (String, reqwest::header::HeaderMap, String);+struct Mock {+ replies: Mutex<VecDeque<(u16, String)>>,+ requests: Mutex<Vec<Recorded>>,+}+struct Server {+ task: tokio::task::JoinHandle<()>,+ mock: Arc<Mock>,+ provider: OpenAi,+}+impl Drop for Server {+ fn drop(&mut self) {+ self.task.abort();+ }+}+async fn server(replies: Vec<(u16, String)>) -> Server {+ let mock = Arc::new(Mock {+ replies: Mutex::new(replies.into()),+ requests: Mutex::new(vec![]),+ });+ let app = Router::new()+ .fallback(any(+ async |State(mock): State<Arc<Mock>>, request: Request| {+ let (parts, body) = request.into_parts();+ let text =+ String::from_utf8(to_bytes(body, MAX_BODY).await.unwrap().to_vec()).unwrap();+ mock.requests.lock().unwrap().push((+ format!("{} {}", parts.method, parts.uri.path()),+ parts.headers,+ text,+ ));+ let (status, body) = mock+ .replies+ .lock()+ .unwrap()+ .pop_front()+ .expect("unexpected HTTP request");+ AxumResponse::builder()+ .status(status)+ .header("content-type", "application/json")+ .body(Body::from(body))+ .unwrap()+ },+ ))+ .with_state(mock.clone());+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let origin = format!("http://{}", listener.local_addr().unwrap());+ let task = tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });+ let mut provider = OpenAi::new().unwrap();+ provider.issuer = origin.clone();+ provider.cloud = origin;+ Server {+ task,+ mock,+ provider,+ }+}+fn jwt(account: &str) -> String {+ format!("header.{}.signature", URL_SAFE_NO_PAD.encode(serde_json::json!({"https://api.openai.com/auth": {"chatgpt_account_id": account}, "exp": 4102444800_u64}).to_string()))+}+fn token_body(refresh: bool) -> String {+ let mut body = serde_json::json!({"access_token": jwt("account-a"), "expires_in": 3600});+ if refresh {+ body["refresh_token"] = "test-refresh".into();+ }+ body.to_string()+}+fn device_body(interval: serde_json::Value) -> String {+ serde_json::json!({"device_auth_id": "private-device", "user_code": "ABCD-1234", "interval": interval}).to_string()+}++#[tokio::test]+async fn direct_device_flow_sends_codex_client_and_pkce_exchange() {+ let server = server(vec![+ (200, device_body("5".into())),+ (403, "pending".to_owned()),+ (404, "pending".to_owned()),+ (+ 200,+ serde_json::json!({"authorization_code":"code", "code_verifier":"verifier"})+ .to_string(),+ ),+ (200, token_body(true)),+ ])+ .await;+ let login = server.provider.begin().await.unwrap();+ assert_eq!(login.interval, Duration::from_secs(8));+ assert_eq!(login.user_code, "ABCD-1234");+ assert!(matches!(+ server.provider.poll(&login).await.unwrap(),+ LoginPoll::Pending+ ));+ assert!(matches!(+ server.provider.poll(&login).await.unwrap(),+ LoginPoll::Pending+ ));+ let LoginPoll::Complete(tokens) = server.provider.poll(&login).await.unwrap() else {+ panic!("expected completion")+ };+ assert_eq!(tokens.account_id, "account-a");+ let requests = server.mock.requests.lock().unwrap();+ assert_eq!(requests[0].0, "POST /api/accounts/deviceauth/usercode");+ assert_eq!(+ serde_json::from_str::<serde_json::Value>(&requests[0].2).unwrap()["client_id"],+ CLIENT_ID+ );+ assert_eq!(requests[4].0, "POST /oauth/token");+ let form: std::collections::HashMap<_, _> =+ reqwest::Url::parse(&format!("http://localhost/?{}", requests[4].2))+ .unwrap()+ .query_pairs()+ .into_owned()+ .collect();+ assert_eq!(form["grant_type"], "authorization_code");+ assert_eq!(form["code_verifier"], "verifier");+ assert_eq!(form["client_id"], CLIENT_ID);+ assert_eq!(+ form["redirect_uri"],+ format!("{}/deviceauth/callback", server.provider.issuer)+ );+}++#[tokio::test]+async fn numeric_interval_and_safe_environment_projection() {+ let server = server(vec![+ (200, device_body(7.into())),+ (+ 200,+ r#"[{"id":"env-1","label":"Test","setup_script":"secret-marker"}]"#.to_owned(),+ ),+ ])+ .await;+ assert_eq!(+ server.provider.begin().await.unwrap().interval,+ Duration::from_secs(10)+ );+ let tokens: Tokens = serde_json::from_str(&token_body(true)).unwrap();+ let credentials = tokens.credentials(None, 1).unwrap();+ let environments = server.provider.environments(&credentials).await.unwrap();+ assert_eq!(+ environments,+ vec![Environment {+ repositories: vec![],+ id: "env-1".to_owned(),+ label: Some("Test".to_owned())+ }]+ );+ let requests = server.mock.requests.lock().unwrap();+ assert_eq!(requests[1].0, "GET /wham/environments");+ assert_eq!(requests[1].1["chatgpt-account-id"], "account-a");+ assert_eq!(+ requests[1].1["authorization"],+ format!("Bearer {}", credentials.access_token.expose())+ );+ assert!(+ !serde_json::to_string(&environments)+ .unwrap()+ .contains("secret-marker")+ );+}++#[tokio::test]+async fn refresh_keeps_old_refresh_token_if_provider_omits_rotation() {+ let server = server(vec![(200, token_body(false))]).await;+ let credentials = serde_json::from_str::<Tokens>(&token_body(true))+ .unwrap()+ .credentials(None, 1)+ .unwrap();+ let next = server.provider.refresh(&credentials).await.unwrap();+ assert_eq!(next.refresh_token.expose(), "test-refresh");+ assert_eq!(next.account_id, credentials.account_id);+ assert!(+ server.mock.requests.lock().unwrap()[0]+ .2+ .contains("grant_type=refresh_token")+ );+}++#[tokio::test]+async fn provider_errors_and_invalid_json_never_echo_bodies_or_retry() {+ for (status, body) in [+ (400, "secret-marker"),+ (429, "secret-marker"),+ (500, "secret-marker"),+ (302, "secret-marker"),+ (200, "secret-marker"),+ ] {+ let server = server(vec![(status, body.to_owned())]).await;+ let error = server.provider.begin().await.err().unwrap().to_string();+ assert!(!error.contains("secret-marker"));+ assert_eq!(server.mock.requests.lock().unwrap().len(), 1);+ }+}++#[tokio::test]+async fn rejects_oversized_response() {+ let server = server(vec![(200, " ".repeat(MAX_BODY + 1))]).await;+ assert!(+ server+ .provider+ .begin()+ .await+ .err()+ .unwrap()+ .to_string()+ .contains("1 MiB")+ );+}++#[test]+fn token_metadata_is_required_and_secrets_are_not_in_errors() {+ let tokens: Tokens = serde_json::from_value(serde_json::json!({"access_token":"secret-marker", "refresh_token":"refresh", "expires_in":3600})).unwrap();+ let error = tokens.credentials(None, 1).err().unwrap().to_string();+ assert!(!error.contains("secret-marker"));+ assert!(error.contains("account ID"));+ let tokens: Tokens = serde_json::from_str(&token_body(false)).unwrap();+ assert!(tokens.credentials(None, 1).is_err());+}++#[tokio::test]+async fn task_creation_uses_observed_payload_and_account_headers_once() {+ for body in [r#"{"task":{"id":"task_test"}}"#, r#"{"id":"task_test"}"#] {+ let server = server(vec![(200, body.to_owned())]).await;+ let credentials = serde_json::from_str::<Tokens>(&token_body(true))+ .unwrap()+ .credentials(None, 1)+ .unwrap();+ let prompt = "Quote 'hello'; $(this is data)\nNext line";+ let request = Launch {+ environment: CloudId::new("env-test".to_owned()).unwrap(),+ branch: "feature/test".to_owned(),+ prompt: prompt.to_owned(),+ };+ let created = server+ .provider+ .create(&credentials, &request)+ .await+ .unwrap();+ assert_eq!(created.url, "https://chatgpt.com/codex/tasks/task_test");+ let requests = server.mock.requests.lock().unwrap();+ assert_eq!(requests.len(), 1);+ assert_eq!(requests[0].0, "POST /wham/tasks");+ assert_eq!(requests[0].1["chatgpt-account-id"], "account-a");+ let body: serde_json::Value = serde_json::from_str(&requests[0].2).unwrap();+ assert_eq!(+ body,+ serde_json::json!({+ "new_task":{"environment_id":"env-test", "branch":"feature/test", "run_environment_in_qa_mode":false},+ "input_items":[{"type":"message","role":"user","content":[{"content_type":"text","text":prompt}]}],+ })+ );+ }+}++#[tokio::test]+async fn unknown_creation_response_never_retries_or_exposes_body() {+ let server = server(vec![(200, r#"{"unexpected":"secret-marker"}"#.to_owned())]).await;+ let credentials = serde_json::from_str::<Tokens>(&token_body(true))+ .unwrap()+ .credentials(None, 1)+ .unwrap();+ let request = Launch {+ environment: CloudId::new("env-test".to_owned()).unwrap(),+ branch: "main".to_owned(),+ prompt: "test".to_owned(),+ };+ let error = server+ .provider+ .create(&credentials, &request)+ .await+ .unwrap_err()+ .to_string();+ assert!(error.contains("acceptance unknown"));+ assert!(!error.contains("secret-marker"));+ assert_eq!(server.mock.requests.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn snapshots_preserve_partial_text_unknown_kinds_and_status_without_fake_completion() {+ let bodies = ["in_progress", "new_provider_status", "completed"].map(|status| serde_json::json!({+ "task":{"id":"task_test","title":"Test","summary":{"files_changed":2}},+ "current_assistant_turn": {"id":"turn-1", "turn_status":status, "output_items":[+ {"type":"message","content":[{"content_type":"text","text":"Partial 🐺"}]},+ {"type":"new_tool","secret":"not included"}+ ]},+ "current_diff_task_turn":{"id":"turn-2","output_items":[{"type":"output_diff","diff":"private file contents"}]}+ }).to_string());+ let server = server(bodies.into_iter().map(|body| (200, body)).collect()).await;+ let credentials = serde_json::from_str::<Tokens>(&token_body(true))+ .unwrap()+ .credentials(None, 1)+ .unwrap();+ let task = CloudId::new("task_test".to_owned()).unwrap();+ for terminal in [false, false, true] {+ let snapshot = server.provider.snapshot(&credentials, &task).await.unwrap();+ assert_eq!(snapshot.terminal(), terminal);+ assert_eq!(snapshot.turns[0].messages, ["Partial 🐺"]);+ assert_eq!(snapshot.turns[0].output_types, ["message", "new_tool"]);+ assert!(snapshot.turns[1].has_diff);+ let json = serde_json::to_string(&snapshot).unwrap();+ assert!(!json.contains("private file contents"));+ assert!(!json.contains("files_changed"));+ assert!(!json.contains("not included"));+ }+}++#[tokio::test]+async fn wrong_task_id_and_non_task_response_are_rejected() {+ let server = server(vec![+ (200, r#"{"task":{"id":"another-task"}}"#.to_owned()),+ (200, "{}".to_owned()),+ ])+ .await;+ let credentials = serde_json::from_str::<Tokens>(&token_body(true))+ .unwrap()+ .credentials(None, 1)+ .unwrap();+ let task = CloudId::new("task_test".to_owned()).unwrap();+ for _ in 0..2 {+ assert!(server.provider.snapshot(&credentials, &task).await.is_err());+ }+}diff --git a/crates/codex_cloud_agents/src/outbound/postgres_journal.rs b/crates/codex_cloud_agents/src/outbound/postgres_journal.rsnew file mode 100644index 0000000000..8baafce01d--- /dev/null+++ b/crates/codex_cloud_agents/src/outbound/postgres_journal.rs@@ -0,0 +1,187 @@+//! Durable cloud conversations bound to the host session's management claim.++use crate::domain::acp_session::{SessionStore, StoredSession};+use crate::domain::cloud::TurnId;+use crate::domain::journal::{JournalEntry, JournalInput};+use agent_session::domain::model::{AgentSessionId, ManagerFence, ReplicaId};+use sqlx::PgPool;+use std::sync::{Arc, OnceLock};++/// Journal for one Macro session and one activated runtime attachment.+pub struct PgCodexJournal {+ pool: PgPool,+ session: AgentSessionId,+ replica: ReplicaId,+ fence: OnceLock<ManagerFence>,+}++impl PgCodexJournal {+ /// Create an inactive journal; activate it only after acquiring management.+ pub fn new(pool: PgPool, session: AgentSessionId, replica: ReplicaId) -> Self {+ Self {+ pool,+ session,+ replica,+ fence: OnceLock::new(),+ }+ }++ /// Bind this attachment permanently to its acquired management generation.+ pub fn activate(+ &self,+ session: AgentSessionId,+ replica: ReplicaId,+ fence: ManagerFence,+ ) -> Result<(), rootcause::Report> {+ if session != self.session || replica != self.replica {+ return Err(rootcause::report!(+ "Codex journal attachment identity mismatch"+ ));+ }+ if self.fence.set(fence).is_err() && self.fence.get() != Some(&fence) {+ return Err(rootcause::report!(+ "Codex journal attachment cannot be rebound"+ ));+ }+ Ok(())+ }++ fn check_id(&self, id: &str) -> Result<(), rootcause::Report> {+ if id != self.session.to_string() {+ return Err(rootcause::report!(+ "Codex journal session identity mismatch"+ ));+ }+ Ok(())+ }++ async fn lock_owner(+ &self,+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,+ ) -> Result<(), rootcause::Report> {+ let expected = self+ .fence+ .get()+ .ok_or_else(|| rootcause::report!("Codex journal attachment is not activated"))?;+ // Hold the same row used for takeover until this checkpoint commits.+ // Ordinary log writers also lock it, so contention is not lost ownership.+ let current = sqlx::query_scalar!("SELECT manager_fence FROM agent_session WHERE id = $1 AND manager_replica_id = $2 FOR UPDATE", self.session.as_uuid(), self.replica.as_uuid())+ .fetch_optional(&mut **tx).await.map_err(|e| rootcause::report!(e))?+ .ok_or_else(|| rootcause::report!("Codex journal writer fenced out"))?;+ if ManagerFence(current) != *expected {+ return Err(rootcause::report!("Codex journal writer fenced out"));+ }+ Ok(())+ }+}++impl SessionStore for Arc<PgCodexJournal> {+ async fn load(&self, id: &str) -> Result<Option<StoredSession>, rootcause::Report> {+ self.check_id(id)?;+ let mut tx = self.pool.begin().await.map_err(|e| rootcause::report!(e))?;+ self.lock_owner(&mut tx).await?;+ let state = sqlx::query_scalar!("SELECT state FROM codex_cloud_sessions WHERE agent_session_id = $1 AND acp_session_id = $2", self.session.as_uuid(), id)+ .fetch_optional(&mut *tx).await.map_err(|e| rootcause::report!(e))?;+ tx.commit().await.map_err(|e| rootcause::report!(e))?;+ state+ .map(|value| {+ serde_json::from_value(value)+ .map_err(|_| rootcause::report!("Invalid Codex session journal"))+ })+ .transpose()+ }++ async fn save(&self, id: &str, state: &StoredSession) -> Result<(), rootcause::Report> {+ self.check_id(id)?;+ let payload = serde_json::to_value(state)+ .map_err(|_| rootcause::report!("Could not encode Codex session journal"))?;+ let mut tx = self.pool.begin().await.map_err(|e| rootcause::report!(e))?;+ self.lock_owner(&mut tx).await?;+ sqlx::query!("INSERT INTO codex_cloud_sessions (agent_session_id, acp_session_id, state) VALUES ($1, $2, $3) ON CONFLICT (agent_session_id) DO UPDATE SET state = EXCLUDED.state", self.session.as_uuid(), id, payload)+ .execute(&mut *tx).await.map_err(|e| rootcause::report!(e))?;+ tx.commit().await.map_err(|e| rootcause::report!(e))?;+ Ok(())+ }++ async fn read(&self, id: &str) -> Result<Vec<JournalEntry>, rootcause::Report> {+ self.check_id(id)?;+ let mut tx = self.pool.begin().await.map_err(|e| rootcause::report!(e))?;+ self.lock_owner(&mut tx).await?;+ let rows = sqlx::query!(+ "SELECT sequence, turn_id, input FROM codex_journal_input WHERE agent_session_id = $1 ORDER BY sequence",+ self.session.as_uuid()+ ).fetch_all(&mut *tx).await.map_err(|e| rootcause::report!(e))?;+ tx.commit().await.map_err(|e| rootcause::report!(e))?;+ let mut entries = Vec::with_capacity(rows.len());+ for (index, row) in rows.into_iter().enumerate() {+ if row.sequence+ != i64::try_from(index)+ .ok()+ .and_then(|index| index.checked_add(1))+ .ok_or_else(|| rootcause::report!("Codex journal sequence overflow"))?+ {+ return Err(rootcause::report!(+ "Codex journal history has a sequence gap; complete replay unavailable"+ ));+ }+ entries.push(JournalEntry {+ sequence: row.sequence,+ turn: row.turn_id.map(TurnId::new).transpose()?,+ input: serde_json::from_value(row.input).map_err(|_| {+ rootcause::report!(+ "Invalid Codex native journal input; complete replay unavailable"+ )+ })?,+ });+ }+ Ok(entries)+ }++ async fn append(+ &self,+ id: &str,+ expected: i64,+ turn: Option<&TurnId>,+ input: &JournalInput,+ ) -> Result<JournalEntry, rootcause::Report> {+ self.check_id(id)?;+ let sequence = expected+ .checked_add(1)+ .filter(|sequence| *sequence > 0)+ .ok_or_else(|| rootcause::report!("invalid Codex journal expected sequence"))?;+ let payload = serde_json::to_value(input)+ .map_err(|_| rootcause::report!("Could not encode Codex native journal input"))?;+ let mut tx = self.pool.begin().await.map_err(|e| rootcause::report!(e))?;+ self.lock_owner(&mut tx).await?;+ let high = sqlx::query_scalar!(+ "SELECT COALESCE(MAX(sequence), 0) AS \"high!\" FROM codex_journal_input WHERE agent_session_id = $1",+ self.session.as_uuid()+ ).fetch_one(&mut *tx).await.map_err(|e| rootcause::report!(e))?;+ if high != expected {+ return Err(rootcause::report!(+ "Codex journal sequence changed; reload required"+ ));+ }+ let turn_id = turn.map(TurnId::as_str);+ sqlx::query!(+ "INSERT INTO codex_journal_input (agent_session_id, sequence, turn_id, input) VALUES ($1, $2, $3, $4)",+ self.session.as_uuid(), sequence, turn_id, payload+ ).execute(&mut *tx).await.map_err(|e| rootcause::report!(e))?;+ tx.commit().await.map_err(|e| rootcause::report!(e))?;+ Ok(JournalEntry {+ sequence,+ turn: turn.cloned(),+ input: input.clone(),+ })+ }++ async fn validate(&self) -> Result<(), rootcause::Report> {+ let mut tx = self.pool.begin().await.map_err(|e| rootcause::report!(e))?;+ self.lock_owner(&mut tx).await?;+ tx.commit().await.map_err(|e| rootcause::report!(e))?;+ Ok(())+ }+}++#[cfg(test)]+mod test;diff --git a/crates/codex_cloud_agents/src/outbound/postgres_journal/test.rs b/crates/codex_cloud_agents/src/outbound/postgres_journal/test.rsnew file mode 100644index 0000000000..f21891c7ec--- /dev/null+++ b/crates/codex_cloud_agents/src/outbound/postgres_journal/test.rs@@ -0,0 +1,237 @@+use super::*;+use uuid::Uuid;++#[sqlx::test(migrations = false)]+async fn journal_survives_takeover_and_rejects_stale_or_foreign_attachments(pool: PgPool) {+ tables(&pool).await;+ let session = AgentSessionId::new_from_uuid(Uuid::from_u128(1));+ let replica = ReplicaId::from_uuid(Uuid::from_u128(2));+ let other = ReplicaId::from_uuid(Uuid::from_u128(3));+ let id = session.to_string();+ sqlx::query!(+ "INSERT INTO agent_session (id, manager_replica_id, manager_fence) VALUES ($1, $2, 1)",+ session.as_uuid(),+ replica.as_uuid()+ )+ .execute(&pool)+ .await+ .unwrap();+ let journal = Arc::new(PgCodexJournal::new(pool.clone(), session, replica));+ assert!(journal.validate().await.is_err());+ assert!(journal.load(&id).await.is_err());+ assert!(journal.activate(session, other, ManagerFence(1)).is_err());+ journal.activate(session, replica, ManagerFence(1)).unwrap();+ assert!(journal.load(&id).await.unwrap().is_none());+ let state = StoredSession {+ task: Some("task-before-restart".into()),+ uncertain_write: true,+ ..StoredSession::default()+ };+ journal.save(&id, &state).await.unwrap();+ journal+ .append(&id, 0, None, &JournalInput::HistoryComplete)+ .await+ .unwrap();+ let turn = TurnId::new("task-before-restart~turn-1".into()).unwrap();+ journal+ .append(&id, 1, Some(&turn), &prompt("original prompt 🐺"))+ .await+ .unwrap();+ assert!(journal.read("another-session").await.is_err());+ assert!(+ journal+ .append("another-session", 2, None, &JournalInput::HistoryComplete)+ .await+ .is_err()+ );+ assert!(journal.load("another-session").await.is_err());+ assert!(journal.save("another-session", &state).await.is_err());+ let wrong_replica = Arc::new(PgCodexJournal::new(pool.clone(), session, other));+ wrong_replica+ .activate(session, other, ManagerFence(1))+ .unwrap();+ assert!(wrong_replica.validate().await.is_err());+ sqlx::query!(+ "UPDATE agent_session SET manager_fence = 2 WHERE id = $1",+ session.as_uuid()+ )+ .execute(&pool)+ .await+ .unwrap();+ assert!(journal.validate().await.is_err());+ assert!(journal.load(&id).await.is_err());+ assert!(journal.read(&id).await.is_err());+ assert!(+ journal+ .append(&id, 2, None, &JournalInput::HistoryComplete)+ .await+ .is_err()+ );+ assert!(journal.save(&id, &StoredSession::default()).await.is_err());+ assert!(journal.activate(session, replica, ManagerFence(2)).is_err());+ let successor = Arc::new(PgCodexJournal::new(pool.clone(), session, replica));+ successor+ .activate(session, replica, ManagerFence(2))+ .unwrap();+ let inputs = successor.read(&id).await.unwrap();+ assert_eq!(inputs.len(), 2);+ assert_eq!(inputs[1].turn.as_ref().unwrap().as_str(), turn.as_str());+ assert_eq!(+ serde_json::to_value(&inputs[1].input).unwrap(),+ serde_json::to_value(prompt("original prompt 🐺")).unwrap()+ );+ let restored = successor.load(&id).await.unwrap().unwrap();+ assert_eq!(restored.task.as_deref(), Some("task-before-restart"));+ assert!(+ restored.uncertain_write,+ "restart must preserve the no-retry guard"+ );+ successor+ .save(&id, &StoredSession::default())+ .await+ .unwrap();+ assert!(successor.load(&id).await.unwrap().unwrap().task.is_none());+ assert_eq!(+ successor.read(&id).await.unwrap().len(),+ 2,+ "metadata checkpoints cannot rewrite native history"+ );+ sqlx::query!("DELETE FROM agent_session WHERE id = $1", session.as_uuid())+ .execute(&pool)+ .await+ .unwrap();+ let count = sqlx::query_scalar!("SELECT count(*) AS \"count!\" FROM codex_cloud_sessions")+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(count, 0);+ let native_count =+ sqlx::query_scalar!("SELECT count(*) AS \"count!\" FROM codex_journal_input")+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(native_count, 0);+}++async fn tables(pool: &PgPool) {+ sqlx::raw_sql("CREATE TABLE agent_session(id uuid PRIMARY KEY, manager_replica_id uuid, manager_fence bigint NOT NULL)")+ .execute(pool).await.unwrap();+ sqlx::raw_sql(include_str!(+ "../../../../macro_db_client/migrations/20260915231629_codex_cloud_session_journal.sql"+ ))+ .execute(pool)+ .await+ .unwrap();+ sqlx::raw_sql(include_str!(+ "../../../../macro_db_client/migrations/20260915231630_codex_cloud_native_inputs.sql"+ ))+ .execute(pool)+ .await+ .unwrap();+}++async fn active(pool: &PgPool) -> (Arc<PgCodexJournal>, String) {+ tables(pool).await;+ let session = AgentSessionId::new_from_uuid(Uuid::now_v7());+ let replica = ReplicaId::from_uuid(Uuid::now_v7());+ sqlx::query!(+ "INSERT INTO agent_session (id, manager_replica_id, manager_fence) VALUES ($1, $2, 1)",+ session.as_uuid(),+ replica.as_uuid()+ )+ .execute(pool)+ .await+ .unwrap();+ let journal = Arc::new(PgCodexJournal::new(pool.clone(), session, replica));+ journal.activate(session, replica, ManagerFence(1)).unwrap();+ let id = session.to_string();+ journal.save(&id, &StoredSession::default()).await.unwrap();+ (journal, id)+}++#[sqlx::test(migrations = false)]+async fn append_compares_sequence_under_the_same_owner_lock(pool: PgPool) {+ let (journal, id) = active(&pool).await;+ let input = JournalInput::HistoryComplete;+ let (first, second) = tokio::join!(+ journal.append(&id, 0, None, &input),+ journal.append(&id, 0, None, &input)+ );+ assert_ne!(first.is_ok(), second.is_ok());+ let entries = journal.read(&id).await.unwrap();+ assert_eq!(entries.len(), 1);+ assert_eq!(entries[0].sequence, 1);+ assert!(journal.append(&id, -1, None, &input).await.is_err());+ assert!(journal.append(&id, i64::MAX, None, &input).await.is_err());+ assert_eq!(journal.read(&id).await.unwrap().len(), 1);+}++#[sqlx::test(migrations = false)]+async fn native_read_rejects_gaps_instead_of_replaying_partial_history(pool: PgPool) {+ let (journal, id) = active(&pool).await;+ journal+ .append(&id, 0, None, &JournalInput::HistoryComplete)+ .await+ .unwrap();+ journal+ .append(&id, 1, None, &prompt("second"))+ .await+ .unwrap();+ sqlx::query!(+ "DELETE FROM codex_journal_input WHERE agent_session_id = $1 AND sequence = 1",+ journal.session.as_uuid()+ )+ .execute(&pool)+ .await+ .unwrap();+ let error = journal.read(&id).await.err().unwrap().to_string();+ assert!(error.contains("sequence gap"));+}++#[sqlx::test(migrations = false)]+async fn unknown_native_payloads_roundtrip_verbatim_without_translation(pool: PgPool) {+ use crate::domain::cloud::NativeRecord;+ let (journal, id) = active(&pool).await;+ journal+ .append(&id, 0, None, &JournalInput::HistoryComplete)+ .await+ .unwrap();+ let raw = " {\"unknown_future_field\": [1, 2], \"text\":\"🐺\\nsecond line\"}\n";+ let input = JournalInput::Native(NativeRecord {+ event: "future-event".into(),+ id: Some("provider-id".into()),+ data: raw.into(),+ });+ let turn = TurnId::new("task-a~turn-a".into()).unwrap();+ journal.append(&id, 1, Some(&turn), &input).await.unwrap();+ let rows = journal.read(&id).await.unwrap();+ let JournalInput::Native(record) = &rows[1].input else {+ panic!("expected native input")+ };+ assert_eq!(record.data, raw);+ assert_eq!(record.event, "future-event");+ assert_eq!(record.id.as_deref(), Some("provider-id"));+ assert_eq!(rows[1].turn.as_ref().unwrap().as_str(), turn.as_str());+ let malformed = JournalInput::Native(NativeRecord {+ event: String::new(),+ id: None,+ data: "not-json provider bytes 🐺".into(),+ });+ journal+ .append(&id, 2, Some(&turn), &malformed)+ .await+ .unwrap();+ let rows = journal.read(&id).await.unwrap();+ let JournalInput::Native(record) = &rows[2].input else {+ panic!("expected native input")+ };+ assert_eq!(+ record.data, "not-json provider bytes 🐺",+ "capture must precede provider JSON decoding"+ );+}++fn prompt(text: &str) -> JournalInput {+ use agent_client_protocol::schema::v1::{ContentBlock, TextContent};+ JournalInput::Prompt(vec![ContentBlock::Text(TextContent::new(text))])+}diff --git a/crates/codex_cloud_agents/tests/fixtures/live_text_replacement.jsonl b/crates/codex_cloud_agents/tests/fixtures/live_text_replacement.jsonlnew file mode 100644index 0000000000..eab9b7ac79--- /dev/null+++ b/crates/codex_cloud_agents/tests/fixtures/live_text_replacement.jsonl@@ -0,0 +1,238 @@+{"direction":"to_runtime","frame":{"jsonrpc":"2.0","id":1,"method":"session/prompt","params":{"sessionId":"session-recorded","prompt":[{"type":"text","text":"This is a read-only prose streaming smoke test. Do not use any tools, read or modify any files, run commands, make commits, or create a pull request. Answer directly with approximately 200 words explaining how to make a cup of tea. Include two Markdown headings, one numbered list, and one tea emoji. Do not mention the repository or this test."}]}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"##"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\n"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug,"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water,"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle,"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-le"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an inf"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk,"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon,"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white,"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.**"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or inf"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately "},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 mill"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 millilit"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters,"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup,"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Ste"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.**"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes,"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes,"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.**"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or inf"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag,"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-t"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.**"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir in"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir in milk"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir in milk lemon"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir in milk lemon honey"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir in milk lemon honey,"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir in milk lemon honey, sugar"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir in milk lemon honey, sugar,"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir in milk lemon honey, sugar, it"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir in milk lemon honey, sugar, it to"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir in milk lemon honey, sugar, it to cool"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir in milk lemon honey, sugar, it to cool a"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir in milk lemon honey, sugar, it to cool a drinking"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir in milk lemon honey, sugar, it to cool a drinking."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir in milk lemon honey, sugar, it to cool a drinking. it"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir in milk lemon honey, sugar, it to cool a drinking. it pleasantly"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey or sugar if you additions.ly drawn water generally cleaner flavor water that has been boiled. ☕\n\n Brewing Tea1.Heat the water Bring fresh to a for black or herbal For green or white, water excessive taste the. water inside discard This it3 **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding Stir in milk lemon honey, sugar, it to cool a drinking. it pleasantly warm"},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-recorded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## What You’ll Need\n\nGather a mug, fresh water, a kettle, and your preferred tea. You can use a tea bag or about one teaspoon of loose-leaf tea in an infuser. Keep milk, lemon, honey, or sugar nearby if you enjoy additions. Freshly drawn water generally produces a brighter, cleaner flavor than water that has been boiled repeatedly. ☕\n\n## Brewing the Tea\n\n1. **Heat the water.** Bring fresh water to a boil for black or herbal tea. For green or white tea, let the boiled water cool briefly so that excessive heat does not make the leaves taste bitter.\n2. **Warm the mug.** Swirl a little hot water inside the mug, then discard it. This optional step helps the tea remain warm while it brews.\n3. **Add the tea.** Place the tea bag or infuser in the mug. Pour approximately 250 milliliters, or one cup, of hot water over it.\n4. **Steep carefully.** Brew green tea for about two to three minutes, black tea for three to five minutes, and herbal tea for five to seven minutes. Follow the package directions when available.\n5. **Remove the leaves.** Lift out the tea bag or infuser. Avoid squeezing the bag, since that can release bitter-tasting compounds.\n6. **Finish and serve.** Taste the tea before adding anything. Stir in milk, lemon, honey, or sugar if desired, then allow it to cool to a comfortable drinking temperature. Enjoy it while pleasantly warm."},"_meta":{"macro.textReplace":{"id":"message-recorded"}}}}}}+{"direction":"to_server","frame":{"jsonrpc":"2.0","id":1,"result":{"stopReason":"end_turn"}}}diff --git a/crates/codex_cloud_agents/tests/fixtures/missing_live_deltas.json b/crates/codex_cloud_agents/tests/fixtures/missing_live_deltas.jsonnew file mode 100644index 0000000000..85926100d7--- /dev/null+++ b/crates/codex_cloud_agents/tests/fixtures/missing_live_deltas.json@@ -0,0 +1,2339 @@+[+ {+ "sequence": 1,+ "turn": null,+ "input": "HistoryComplete"+ },+ {+ "sequence": 2,+ "turn": null,+ "input": {+ "Prompt": [+ {+ "type": "text",+ "text": "wh atis this repo how is ti going man"+ }+ ]+ }+ },+ {+ "sequence": 3,+ "turn": "record_1",+ "input": {+ "PromptAccepted": {+ "task": "record_2",+ "turn": "record_1"+ }+ }+ },+ {+ "sequence": 4,+ "turn": "record_1",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_3",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_1",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "in_progress"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 5,+ "turn": "record_1",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_3",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_1",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "in_progress"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 6,+ "turn": "record_1",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_3",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_1",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "in_progress"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 7,+ "turn": "record_1",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_3",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_1",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "in_progress"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 8,+ "turn": "record_1",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_3",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_1",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "in_progress"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 9,+ "turn": "record_1",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_3",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_1",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "in_progress"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 10,+ "turn": "record_1",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_3",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_1",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "in_progress"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 11,+ "turn": "record_1",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_3",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_1",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "in_progress"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 12,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_4\",\"event\":{\"method\":\"item/reasoning/summaryPartAdded\",\"params\":{\"itemId\":\"record_5\",\"summaryIndex\":0,\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 13,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_8\",\"event\":{\"method\":\"item/reasoning/summaryTextDelta\",\"params\":{\"delta\":\"**Inspecting AGENTS and files**\",\"itemId\":\"record_5\",\"summaryIndex\":0,\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 14,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_9\",\"event\":{\"method\":\"item/completed\",\"params\":{\"item\":{\"content\":[],\"id\":\"record_5\",\"summary\":[\"**Inspecting AGENTS and files**\"],\"type\":\"reasoning\"},\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 15,+ "turn": "record_1",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_3",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_1",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "in_progress"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 16,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_10\",\"event\":{\"method\":\"item/reasoning/summaryPartAdded\",\"params\":{\"itemId\":\"record_11\",\"summaryIndex\":0,\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 17,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_12\",\"event\":{\"method\":\"item/reasoning/summaryTextDelta\",\"params\":{\"delta\":\"**Inspecting hidden files and git history**\",\"itemId\":\"record_11\",\"summaryIndex\":0,\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 18,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_13\",\"event\":{\"method\":\"item/completed\",\"params\":{\"item\":{\"content\":[],\"id\":\"record_11\",\"summary\":[\"**Inspecting hidden files and git history**\"],\"type\":\"reasoning\"},\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 19,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_14\",\"event\":{\"method\":\"item/completed\",\"params\":{\"item\":{\"aggregatedOutput\":\"--- directory ---\\nd ./.git\\nd ./.git/branches\\nd ./.git/hooks\\nd ./.git/info\\nd ./.git/logs\\nd ./.git/objects\\nd ./.git/refs\\nf ./.git/FETCH_HEAD\\nf ./.git/HEAD\\nf ./.git/config\\nf ./.git/description\\nf ./.git/index\\nf ./.git/packed-refs\\nf ./.gitkeep\\n--- recent commits ---\\ndb7978a (HEAD -> work) Initialize repository\\n--- HEAD tree ---\\n.gitkeep\\n--- remotes ---\\n\",\"command\":\"/bin/bash -lc \\\"printf '%s\\\\\\\\n' '--- directory ---' && find . -maxdepth 2 -mindepth 1 -printf '%y %p\\\\\\\\n' | sort | sed -n '1,160p' && printf '%s\\\\\\\\n' '--- recent commits ---' && git log --oneline --decorate --all -10 && printf '%s\\\\\\\\n' '--- HEAD tree ---' && git ls-tree -r --name-only HEAD 2>&1 || true && printf '%s\\\\\\\\n' '--- remotes ---' && git remote -v\\\"\",\"commandActions\":[{\"command\":\"printf '%s\\\\n' '--- directory ---' && find . -maxdepth 2 -mindepth 1 -printf '%y %p\\\\n' | sort | sed -n '1,160p' && printf '%s\\\\n' '--- recent commits ---' && git log --oneline --decorate --all -10 && printf '%s\\\\n' '--- HEAD tree ---' && git ls-tree -r --name-only HEAD 2>&1 || true && printf '%s\\\\n' '--- remotes ---' && git remote -v\",\"type\":\"unknown\"}],\"cwd\":\"/workspace/temp-test-repo\",\"durationMs\":0,\"exitCode\":0,\"id\":\"record_15\",\"processId\":\"38458\",\"source\":\"unifiedExecStartup\",\"status\":\"completed\",\"type\":\"commandExecution\"},\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 20,+ "turn": "record_1",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_3",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_1",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "in_progress"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 21,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_16\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"!\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 22,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_18\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"\\n\\n\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 23,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_19\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"’m\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 24,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_20\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"—\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 25,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_21\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"##\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 26,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_22\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" this\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 27,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_23\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"?\\n\\n\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 28,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_24\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"empty\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 29,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_25\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\":\\n\\n\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 30,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_26\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" It\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 31,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_27\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" contains\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 32,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_28\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" no\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 33,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_29\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" application\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 34,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_30\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" dependencies\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 35,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_31\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\",\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 36,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_32\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" tracked\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 37,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_33\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" `.\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 38,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_34\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" to\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 39,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_35\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" keep\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 40,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_36\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" otherwise\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 41,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_37\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" directory\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 42,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_38\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"L\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 43,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_39\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"-\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 44,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_40\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" named\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 45,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_41\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" **\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 46,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_42\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" repository\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 47,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_43\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" the\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 48,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_44\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"`\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 49,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_45\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\".\\n\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 50,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_46\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"-\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 51,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_47\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" so\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 52,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_48\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" it\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 53,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_49\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" currently\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 54,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_50\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" a\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 55,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_51\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" or\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 56,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_52\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" other\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 57,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_53\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" remote\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 58,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_54\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" **\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 59,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_55\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" just\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 60,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_56\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" blank\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 61,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_57\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" used\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 62,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_58\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" to\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 63,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_59\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" or\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 64,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_60\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" a\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 65,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_61\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" project\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 66,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_62\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"##\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 67,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_63\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" performed\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 68,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_64\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"pwd\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 69,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_65\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"-\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 70,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_66\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" ✅\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 71,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_67\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" `\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 72,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_68\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"find\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 73,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_69\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" ..\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 74,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_70\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\".md\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 75,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_71\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" -\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 76,+ "turn": "record_1",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_3",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_1",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "in_progress"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 77,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_72\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"print\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 78,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_73\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"`\\n\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 79,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_74\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"-\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 80,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_75\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" ✅\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 81,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_76\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" `\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 82,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_77\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"rg\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 83,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_78\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" '!\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 84,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_79\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"node\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 85,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_80\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"git\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 86,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_81\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"short\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 87,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_82\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" ✅\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 88,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_83\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"2\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 89,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_84\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"mind\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 90,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_85\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" '%\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 91,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_86\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"git\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 92,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_87\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" --\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 93,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_88\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" -\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 94,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_89\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" ✅\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 95,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_90\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" `\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 96,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_91\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"git\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 97,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_92\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" -\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 98,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_93\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"-only\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 99,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_94\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"-\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 100,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_95\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" `\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 101,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_96\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"git\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 102,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_97\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" remote\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 103,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_98\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" -\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 104,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_99\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"`\\n\\n\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 105,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_100\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" modify\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 106,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_101\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" anything\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 107,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_102\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" so\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 108,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_103\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" commit\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 109,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_104\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" open\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 110,+ "turn": "record_1",+ "input": {+ "TransportError": "EOF"+ }+ },+ {+ "sequence": 111,+ "turn": "record_1",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_3",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_1",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [+ "## Hey! 👋\n\nI’m doing well, man—thanks for asking.\n\n## What is this repository?\n\nThis is currently an **empty temporary test repository**:\n\n- It contains no application source code, documentation, dependencies, or tests.\n- Its only tracked file is `.gitkeep`, which is commonly used to keep an otherwise empty directory in Git. ",+ "\n- The repository has a single commit named **“Initialize repository.”**\n- You’re on the `work` branch.\n- No Git remote is configured, so it is not currently connected to a GitHub or other remote repository.\n\nIn short: **it’s just a blank sandbox that can be used to test changes or start a new project.**\n\n## Checks performed\n\n- ✅ `pwd`\n- ✅ `find .. -name AGENTS.md -print`\n- ✅ `rg --files -g '!node_modules'`\n- ✅ `git status --short --branch`\n- ✅ `find . -maxdepth 2 -mindepth 1 -printf '%y %p\\n'`\n- ✅ `git log --oneline --decorate --all -10`\n- ✅ `git ls-tree -r --name-only HEAD`\n- ✅ `git remote -v`\n\nI didn’t modify anything, so there was nothing to commit or open a pull request for."+ ],+ "output_types": [+ "message",+ "partial_repo_snapshot"+ ]+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "completed"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 112,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_4\",\"event\":{\"method\":\"item/reasoning/summaryPartAdded\",\"params\":{\"itemId\":\"record_5\",\"summaryIndex\":0,\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 113,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_8\",\"event\":{\"method\":\"item/reasoning/summaryTextDelta\",\"params\":{\"delta\":\"**Inspecting AGENTS and files**\",\"itemId\":\"record_5\",\"summaryIndex\":0,\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 114,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_9\",\"event\":{\"method\":\"item/completed\",\"params\":{\"item\":{\"content\":[],\"id\":\"record_5\",\"summary\":[\"**Inspecting AGENTS and files**\"],\"type\":\"reasoning\"},\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 115,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_105\",\"event\":{\"method\":\"item/completed\",\"params\":{\"item\":{\"aggregatedOutput\":\"/workspace/temp-test-repo\\n--- AGENTS files ---\\n--- top-level files ---\\n--- git status ---\\n## work\\n\",\"command\":\"/bin/bash -lc \\\"pwd && printf '%s\\\\\\\\n' '--- AGENTS files ---' && find .. -name AGENTS.md -print && printf '%s\\\\\\\\n' '--- top-level files ---' && rg --files -g '\\\"'!node_modules'\\\"' | sed -n '1,120p' && printf '%s\\\\\\\\n' '--- git status ---' && git status --short --branch\\\"\",\"commandActions\":[{\"command\":\"pwd && printf '%s\\\\n' '--- AGENTS files ---' && find .. -name AGENTS.md -print && printf '%s\\\\n' '--- top-level files ---' && rg --files -g '!node_modules' | sed -n '1,120p' && printf '%s\\\\n' '--- git status ---' && git status --short --branch\",\"type\":\"unknown\"}],\"cwd\":\"/workspace/temp-test-repo\",\"durationMs\":0,\"exitCode\":0,\"id\":\"record_106\",\"processId\":\"3929\",\"source\":\"unifiedExecStartup\",\"status\":\"completed\",\"type\":\"commandExecution\"},\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 116,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_10\",\"event\":{\"method\":\"item/reasoning/summaryPartAdded\",\"params\":{\"itemId\":\"record_11\",\"summaryIndex\":0,\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 117,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_12\",\"event\":{\"method\":\"item/reasoning/summaryTextDelta\",\"params\":{\"delta\":\"**Inspecting hidden files and git history**\",\"itemId\":\"record_11\",\"summaryIndex\":0,\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 118,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_13\",\"event\":{\"method\":\"item/completed\",\"params\":{\"item\":{\"content\":[],\"id\":\"record_11\",\"summary\":[\"**Inspecting hidden files and git history**\"],\"type\":\"reasoning\"},\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 119,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_14\",\"event\":{\"method\":\"item/completed\",\"params\":{\"item\":{\"aggregatedOutput\":\"--- directory ---\\nd ./.git\\nd ./.git/branches\\nd ./.git/hooks\\nd ./.git/info\\nd ./.git/logs\\nd ./.git/objects\\nd ./.git/refs\\nf ./.git/FETCH_HEAD\\nf ./.git/HEAD\\nf ./.git/config\\nf ./.git/description\\nf ./.git/index\\nf ./.git/packed-refs\\nf ./.gitkeep\\n--- recent commits ---\\ndb7978a (HEAD -> work) Initialize repository\\n--- HEAD tree ---\\n.gitkeep\\n--- remotes ---\\n\",\"command\":\"/bin/bash -lc \\\"printf '%s\\\\\\\\n' '--- directory ---' && find . -maxdepth 2 -mindepth 1 -printf '%y %p\\\\\\\\n' | sort | sed -n '1,160p' && printf '%s\\\\\\\\n' '--- recent commits ---' && git log --oneline --decorate --all -10 && printf '%s\\\\\\\\n' '--- HEAD tree ---' && git ls-tree -r --name-only HEAD 2>&1 || true && printf '%s\\\\\\\\n' '--- remotes ---' && git remote -v\\\"\",\"commandActions\":[{\"command\":\"printf '%s\\\\n' '--- directory ---' && find . -maxdepth 2 -mindepth 1 -printf '%y %p\\\\n' | sort | sed -n '1,160p' && printf '%s\\\\n' '--- recent commits ---' && git log --oneline --decorate --all -10 && printf '%s\\\\n' '--- HEAD tree ---' && git ls-tree -r --name-only HEAD 2>&1 || true && printf '%s\\\\n' '--- remotes ---' && git remote -v\",\"type\":\"unknown\"}],\"cwd\":\"/workspace/temp-test-repo\",\"durationMs\":0,\"exitCode\":0,\"id\":\"record_15\",\"processId\":\"38458\",\"source\":\"unifiedExecStartup\",\"status\":\"completed\",\"type\":\"commandExecution\"},\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 120,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_107\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"##\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 121,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_108\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" Hey\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 122,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_16\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"!\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 123,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_109\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" 👋\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 124,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_18\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"\\n\\n\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 125,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_110\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"I\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 126,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_19\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"’m\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 127,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_111\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" doing\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 128,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_112\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" well\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 129,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_113\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\",\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 130,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_114\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" man\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 131,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_20\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"—\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 132,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_115\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"thanks\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 133,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_116\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" for\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 134,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_117\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" asking\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 135,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_118\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\".\\n\\n\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 136,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_21\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"##\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 137,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_119\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" What\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 138,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_120\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" is\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 139,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_22\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" this\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 140,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_121\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" repository\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 141,+ "turn": "record_1",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_23\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"?\\n\\n\",\"itemId\":\"record_17\",\"threadId\":\"record_6\",\"turnId\":\"record_7\"}}}"+ }+ }+ },+ {+ "sequence": 142,+ "turn": "record_1",+ "input": {+ "Terminal": "completed"+ }+ },+ {+ "sequence": 143,+ "turn": "record_1",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_3",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_1",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [+ "## Hey! 👋\n\nI’m doing well, man—thanks for asking.\n\n## What is this repository?\n\nThis is currently an **empty temporary test repository**:\n\n- It contains no application source code, documentation, dependencies, or tests.\n- Its only tracked file is `.gitkeep`, which is commonly used to keep an otherwise empty directory in Git. ",+ "\n- The repository has a single commit named **“Initialize repository.”**\n- You’re on the `work` branch.\n- No Git remote is configured, so it is not currently connected to a GitHub or other remote repository.\n\nIn short: **it’s just a blank sandbox that can be used to test changes or start a new project.**\n\n## Checks performed\n\n- ✅ `pwd`\n- ✅ `find .. -name AGENTS.md -print`\n- ✅ `rg --files -g '!node_modules'`\n- ✅ `git status --short --branch`\n- ✅ `find . -maxdepth 2 -mindepth 1 -printf '%y %p\\n'`\n- ✅ `git log --oneline --decorate --all -10`\n- ✅ `git ls-tree -r --name-only HEAD`\n- ✅ `git remote -v`\n\nI didn’t modify anything, so there was nothing to commit or open a pull request for."+ ],+ "output_types": [+ "message",+ "partial_repo_snapshot"+ ]+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "completed"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 144,+ "turn": "record_1",+ "input": {+ "Prompt": [+ {+ "type": "text",+ "text": "what is your name"+ }+ ]+ }+ },+ {+ "sequence": 145,+ "turn": "record_122",+ "input": {+ "PromptAccepted": {+ "task": "record_2",+ "turn": "record_122"+ }+ }+ },+ {+ "sequence": 146,+ "turn": "record_122",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_123",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_122",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "in_progress"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 147,+ "turn": "record_122",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_123",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_122",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "in_progress"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 148,+ "turn": "record_122",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_123",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_122",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "in_progress"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 149,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_124\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" is\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 150,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_127\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"**\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 151,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_128\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"’m\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 152,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_129\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" an\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 153,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_130\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" AI\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 154,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_131\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" coding\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 155,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_132\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" assistant\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 156,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_133\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" by\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 157,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_134\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"AI\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 158,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_135\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\".\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 159,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_136\",\"event\":{\"method\":\"item/completed\",\"params\":{\"item\":{\"id\":\"record_125\",\"phase\":\"final_answer\",\"text\":\"My name is **Codex**. I’m an AI coding assistant created by OpenAI.\",\"type\":\"agentMessage\"},\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 160,+ "turn": "record_122",+ "input": {+ "TransportError": "EOF"+ }+ },+ {+ "sequence": 161,+ "turn": "record_122",+ "input": {+ "Poll": {+ "snapshot": {+ "title": null,+ "turns": [+ {+ "id": "record_123",+ "source": "current_user_turn",+ "has_diff": false,+ "messages": [],+ "output_types": []+ },+ {+ "id": "record_122",+ "source": "current_assistant_turn",+ "has_diff": false,+ "messages": [+ "My name is **Codex**. I’m an AI coding assistant created by OpenAI."+ ],+ "output_types": [+ "message",+ "partial_repo_snapshot"+ ]+ }+ ],+ "task_id": "record_2",+ "pull_requests": [],+ "assistant_status": "completed"+ },+ "native": null+ }+ }+ },+ {+ "sequence": 162,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_137\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"My\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 163,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_138\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" name\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 164,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_124\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" is\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 165,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_139\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" **\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 166,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_140\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"Cod\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 167,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_141\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"ex\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 168,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_127\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"**\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 169,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_142\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\".\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 170,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_143\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" I\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 171,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_128\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"’m\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 172,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_129\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" an\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 173,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_130\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" AI\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 174,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_131\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" coding\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 175,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_132\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" assistant\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 176,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_144\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" created\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 177,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_133\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" by\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 178,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_145\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\" Open\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 179,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_134\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\"AI\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 180,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_135\",\"event\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"delta\":\".\",\"itemId\":\"record_125\",\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 181,+ "turn": "record_122",+ "input": {+ "Native": {+ "event": "",+ "id": null,+ "data": "{\"item_type\":\"thread_event\",\"id\":\"record_136\",\"event\":{\"method\":\"item/completed\",\"params\":{\"item\":{\"id\":\"record_125\",\"phase\":\"final_answer\",\"text\":\"My name is **Codex**. I’m an AI coding assistant created by OpenAI.\",\"type\":\"agentMessage\"},\"threadId\":\"record_6\",\"turnId\":\"record_126\"}}}"+ }+ }+ },+ {+ "sequence": 182,+ "turn": "record_122",+ "input": {+ "Terminal": "completed"+ }+ }+]diff --git a/crates/codex_cloud_agents/tests/fixtures/recorded_cloud_turn.json b/crates/codex_cloud_agents/tests/fixtures/recorded_cloud_turn.jsonnew file mode 100644index 0000000000..4fc9c33ab3--- /dev/null+++ b/crates/codex_cloud_agents/tests/fixtures/recorded_cloud_turn.json@@ -0,0 +1,207 @@+[+ {+ "id": "recorded-id-1",+ "method": "turn/started",+ "params": {+ "threadId": "recorded-id-2",+ "turn": {+ "error": null,+ "id": "recorded-id-3",+ "items": [],+ "itemsView": "notLoaded",+ "startedAt": 1000,+ "status": "inProgress"+ }+ }+ },+ {+ "id": "recorded-id-4",+ "method": "item/completed",+ "params": {+ "completedAtMs": 1000,+ "item": {+ "clientId": null,+ "content": [+ {+ "text": "Please inspect the example repository read-only.",+ "text_elements": [],+ "type": "text"+ }+ ],+ "id": "recorded-id-5",+ "type": "userMessage"+ },+ "threadId": "recorded-id-2",+ "turnId": "recorded-id-3"+ }+ },+ {+ "id": "recorded-id-6",+ "method": "item/completed",+ "params": {+ "completedAtMs": 1000,+ "item": {+ "aggregatedOutput": "safe-output\n",+ "command": "printf \"safe-output\\n\"",+ "commandActions": [+ {+ "command": "printf \"safe-output\\n\"",+ "type": "unknown"+ }+ ],+ "cwd": "/workspace/example",+ "durationMs": 1000,+ "exitCode": 0,+ "id": "recorded-id-7",+ "processId": "recorded-id-8",+ "source": "unifiedExecStartup",+ "status": "completed",+ "type": "commandExecution"+ },+ "threadId": "recorded-id-2",+ "turnId": "recorded-id-3"+ }+ },+ {+ "id": "recorded-id-9",+ "method": "item/agentMessage/delta",+ "params": {+ "delta": "Safe text. ",+ "itemId": "recorded-id-10",+ "threadId": "recorded-id-2",+ "turnId": "recorded-id-3"+ }+ },+ {+ "id": "recorded-id-11",+ "method": "item/agentMessage/delta",+ "params": {+ "delta": "Safe text. ",+ "itemId": "recorded-id-10",+ "threadId": "recorded-id-2",+ "turnId": "recorded-id-3"+ }+ },+ {+ "id": "recorded-id-12",+ "method": "item/agentMessage/delta",+ "params": {+ "delta": "Safe text. ",+ "itemId": "recorded-id-10",+ "threadId": "recorded-id-2",+ "turnId": "recorded-id-3"+ }+ },+ {+ "id": "recorded-id-13",+ "method": "item/agentMessage/delta",+ "params": {+ "delta": "Safe text. ",+ "itemId": "recorded-id-10",+ "threadId": "recorded-id-2",+ "turnId": "recorded-id-3"+ }+ },+ {+ "id": "recorded-id-14",+ "method": "item/agentMessage/delta",+ "params": {+ "delta": "Safe text. ",+ "itemId": "recorded-id-10",+ "threadId": "recorded-id-2",+ "turnId": "recorded-id-3"+ }+ },+ {+ "id": "recorded-id-15",+ "method": "item/agentMessage/delta",+ "params": {+ "delta": "Safe text. ",+ "itemId": "recorded-id-10",+ "threadId": "recorded-id-2",+ "turnId": "recorded-id-3"+ }+ },+ {+ "id": "recorded-id-16",+ "method": "item/agentMessage/delta",+ "params": {+ "delta": "Safe text. ",+ "itemId": "recorded-id-10",+ "threadId": "recorded-id-2",+ "turnId": "recorded-id-3"+ }+ },+ {+ "id": "recorded-id-17",+ "method": "item/agentMessage/delta",+ "params": {+ "delta": "Safe text. ",+ "itemId": "recorded-id-10",+ "threadId": "recorded-id-2",+ "turnId": "recorded-id-3"+ }+ },+ {+ "id": "recorded-id-18",+ "method": "item/agentMessage/delta",+ "params": {+ "delta": "Safe text. ",+ "itemId": "recorded-id-10",+ "threadId": "recorded-id-2",+ "turnId": "recorded-id-3"+ }+ },+ {+ "id": "recorded-id-19",+ "method": "item/agentMessage/delta",+ "params": {+ "delta": "Safe text. ",+ "itemId": "recorded-id-10",+ "threadId": "recorded-id-2",+ "turnId": "recorded-id-3"+ }+ },+ {+ "id": "recorded-id-20",+ "method": "item/agentMessage/delta",+ "params": {+ "delta": "Safe text. ",+ "itemId": "recorded-id-10",+ "threadId": "recorded-id-2",+ "turnId": "recorded-id-3"+ }+ },+ {+ "id": "recorded-id-21",+ "method": "item/completed",+ "params": {+ "completedAtMs": 1000,+ "item": {+ "id": "recorded-id-10",+ "phase": "final_answer",+ "text": "Safe text. Safe text. Safe text. Safe text. Safe text. Safe text. Safe text. Safe text. Safe text. Safe text. Safe text. ",+ "type": "agentMessage"+ },+ "threadId": "recorded-id-2",+ "turnId": "recorded-id-3"+ }+ },+ {+ "id": "recorded-id-22",+ "method": "turn/completed",+ "params": {+ "threadId": "recorded-id-2",+ "turn": {+ "completedAt": 1000,+ "durationMs": 1000,+ "error": null,+ "id": "recorded-id-3",+ "items": [],+ "itemsView": "notLoaded",+ "startedAt": 1000,+ "status": "completed"+ }+ }+ }+]diff --git a/crates/codex_cloud_agents/tests/fixtures/reported_gitkeep_message.md b/crates/codex_cloud_agents/tests/fixtures/reported_gitkeep_message.mdnew file mode 100644index 0000000000..a8698ebd25--- /dev/null+++ b/crates/codex_cloud_agents/tests/fixtures/reported_gitkeep_message.md@@ -0,0 +1,10 @@+## Status++It’s going well! I inspected the repository, and it is currently an **empty placeholder/test repository** rather than an implemented project.++### What’s in the repository?++- The current branch is `work`.+- The Git history contains one commit: **“Initialize repository.”**+- The only tracked file is an empty `.gitkeep`, which is commonly used to retain an otherwise empty directory in Git. 【F:.gitkeep†L1】+- There is no README, source code, dependency manifest, tests, or configured Git remote, so the repository does not yet have a defined application purpose.diff --git a/crates/codex_cloud_agents/tests/fold.rs b/crates/codex_cloud_agents/tests/fold.rsnew file mode 100644index 0000000000..5003ea5289--- /dev/null+++ b/crates/codex_cloud_agents/tests/fold.rs@@ -0,0 +1,906 @@+//! Served Codex byte streams folded by the same replacement machine as the app.+use agent_client_protocol::RawJsonRpcMessage;+use agent_fold::domain::{+ fold::{FoldMachineImpl, fold},+ log::{AgentSessionId, AgentSessionLog, Message},+ model::{FoldEvent, FoldedMessage, StopReason},+ ports::FoldMachine as _,+};+use agent_runtime_protocol::domain::schema::v0::{AcpMessage, ToRuntimeMessage, ToServerMessage};+use codex_cloud_agents::{+ domain::{+ acp_session::{SessionService, SessionStore, StoredSession},+ cloud::{+ CloudEvent, CloudEventStream, CloudId, CreatedTask, ExternalPullRequest, Launch,+ NativeRecord, TaskSnapshot, TurnId, TurnSnapshot,+ },+ journal::{JournalEntry, JournalInput},+ runtime::{CloudRuntime, RuntimeIdentity},+ },+ inbound::acp::serve,+};+use serde_json::{Value, json};+use std::{+ collections::HashMap,+ sync::{+ Arc, Mutex,+ atomic::{AtomicBool, Ordering},+ },+ time::Duration,+};+use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader, DuplexStream};++type Result<T> = std::result::Result<T, rootcause::Report>;++#[derive(Clone, Default)]+struct Journal {+ sessions: Arc<Mutex<HashMap<String, StoredSession>>>,+ fail_load: Arc<AtomicBool>,+ entries: Arc<Mutex<HashMap<String, Vec<JournalEntry>>>>,+}+impl SessionStore for Journal {+ async fn load(&self, id: &str) -> Result<Option<StoredSession>> {+ if self.fail_load.load(Ordering::SeqCst) {+ return Err(rootcause::report!("history unavailable"));+ }+ Ok(self.sessions.lock().unwrap().get(id).cloned())+ }+ async fn save(&self, id: &str, state: &StoredSession) -> Result<()> {+ self.sessions+ .lock()+ .unwrap()+ .insert(id.to_owned(), state.clone());+ Ok(())+ }+ async fn validate(&self) -> Result<()> {+ Ok(())+ }+ async fn read(&self, id: &str) -> Result<Vec<JournalEntry>> {+ Ok(self+ .entries+ .lock()+ .unwrap()+ .get(id)+ .cloned()+ .unwrap_or_default())+ }+ async fn append(+ &self,+ id: &str,+ expected: i64,+ turn: Option<&TurnId>,+ input: &JournalInput,+ ) -> Result<JournalEntry> {+ let mut entries = self.entries.lock().unwrap();+ let rows = entries.entry(id.into()).or_default();+ if rows.len() as i64 != expected {+ return Err(rootcause::report!("journal sequence conflict"));+ }+ let entry = JournalEntry {+ sequence: expected + 1,+ turn: turn.cloned(),+ input: input.clone(),+ };+ rows.push(entry.clone());+ Ok(entry)+ }+}+#[derive(Default)]+struct Calls {+ prs: Vec<ExternalPullRequest>,+ launches: usize,+ followups: Vec<(String, String, String)>,+ turn: usize,+ holding: bool,+ cancelled: bool,+ final_only: bool,+ late_record: bool,+}+#[derive(Clone, Default)]+struct Runtime(Arc<Mutex<Calls>>);+impl Runtime {+ fn receipt(&self) -> Result<CreatedTask> {+ let mut calls = self.0.lock().unwrap();+ calls.turn += 1;+ calls.cancelled = false;+ Ok(CreatedTask {+ task_id: CloudId::new("task-fold".into())?,+ assistant_turn_id: Some(TurnId::new(format!("turn-{}", calls.turn))?),+ url: "https://chatgpt.com/codex/tasks/task-fold".into(),+ })+ }+ fn state(&self) -> Result<TaskSnapshot> {+ let pull_requests = self.0.lock().unwrap().prs.clone();+ Ok(TaskSnapshot {+ pull_requests,+ task_id: CloudId::new("task-fold".into())?,+ title: None,+ native: None,+ assistant_status: Some({+ let calls = self.0.lock().unwrap();+ if calls.cancelled {+ "cancelled"+ } else if calls.holding {+ "in_progress"+ } else {+ "completed"+ }+ .into()+ }),+ turns: vec![TurnSnapshot {+ source: "current_assistant_turn".into(),+ id: Some(format!("turn-{}", self.0.lock().unwrap().turn)),+ messages: if self.0.lock().unwrap().final_only {+ vec!["Snapshot answer".into()]+ } else {+ vec![]+ },+ output_types: vec![],+ has_diff: false,+ }],+ })+ }+}+impl CloudRuntime for Runtime {+ async fn report_pull_request(&self, _: &str) -> Result<()> {+ Ok(())+ }+ async fn identity(&self) -> Result<RuntimeIdentity> {+ Ok(RuntimeIdentity {+ connection_id: "connection-fold".into(),+ account_id: "account-fold".into(),+ })+ }+ async fn resolve_target(+ &self,+ _: &str,+ requested: Option<&codex_cloud_agents::domain::runtime::CloudTarget>,+ ) -> Result<codex_cloud_agents::domain::runtime::CloudTarget> {+ Ok(requested.unwrap().clone())+ }+ async fn launch(&self, request: &Launch) -> Result<CreatedTask> {+ {+ let mut calls = self.0.lock().unwrap();+ calls.launches += 1;+ calls.holding = request.prompt == "hold";+ }+ self.receipt()+ }+ async fn snapshot(&self, _: &CloudId) -> Result<TaskSnapshot> {+ self.state()+ }+ async fn follow_up(&self, task: &CloudId, turn: &TurnId, prompt: &str) -> Result<CreatedTask> {+ self.0.lock().unwrap().holding = prompt == "hold";+ self.0.lock().unwrap().followups.push((+ task.as_str().into(),+ turn.as_str().into(),+ prompt.into(),+ ));+ self.receipt()+ }+ async fn cancel(&self, _: &CloudId) -> Result<()> {+ self.0.lock().unwrap().cancelled = true;+ Ok(())+ }+ async fn turn(&self, _: &CloudId, _: &TurnId) -> Result<TaskSnapshot> {+ self.state()+ }+ async fn stream(&self, _: &CloudId, turn: &TurnId) -> Result<CloudEventStream> {+ if self.0.lock().unwrap().final_only {+ return Ok(Box::pin(futures::stream::empty()));+ }+ let turn = turn.as_str();+ let message = format!("{turn}-message");+ let text = format!("Answer for {turn}");+ let event = CloudEvent {+ id: format!("{turn}-delta"),+ method: "item/agentMessage/delta".into(),+ params: json!({"threadId":"thread-fold","turnId":turn,"itemId":message,"delta":text}),+ };+ if self.0.lock().unwrap().holding {+ use futures::StreamExt as _;+ let event = CloudEvent {+ id: format!("{turn}-thought"),+ method: "item/reasoning/summaryTextDelta".into(),+ params: json!({"delta":"Working"}),+ };+ return Ok(Box::pin(+ futures::stream::iter(vec![+ Ok(NativeRecord::from_event(CloudEvent {+ id: format!("{turn}-partial"),+ method: "item/agentMessage/delta".into(),+ params: json!({"itemId":message,"delta":"Incomplete answer"}),+ })),+ Ok(NativeRecord::from_event(event)),+ ])+ .chain(futures::stream::pending()),+ ));+ }+ let mut records = vec![+ Ok(NativeRecord::from_event(event.clone())),+ Ok(NativeRecord::from_event(event)), // Real reconnect overlap must not duplicate a delta.+ Ok(NativeRecord::from_event(CloudEvent {+ id: format!("{turn}-message-completed"),+ method: "item/completed".into(),+ params: json!({"threadId":"thread-fold","turnId":turn,"item":{"id":message,"type":"agentMessage","text":text}}),+ })),+ Ok(NativeRecord::from_event(CloudEvent {+ id: format!("{turn}-completed"),+ method: "turn/completed".into(),+ params: json!({"threadId":"thread-fold","turn":{"id":turn,"status":"completed"}}),+ })),+ ];+ if self.0.lock().unwrap().late_record {+ records.insert(2, Ok(NativeRecord::from_event(CloudEvent {+ id: format!("{turn}-late"),+ method: "item/completed".into(),+ params: json!({"threadId":"thread-fold","turnId":turn,"item":{"id":format!("{turn}-late-message"),"type":"agentMessage","text":"Late historical answer"}}),+ })));+ }+ Ok(Box::pin(futures::stream::iter(records)))+ }+}++struct Client {+ read: BufReader<tokio::io::ReadHalf<DuplexStream>>,+ write: tokio::io::WriteHalf<DuplexStream>,+ server: tokio::task::JoinHandle<()>,+}+impl Client {+ fn new(runtime: Runtime, journal: Journal) -> Self {+ Self::with_reload(runtime, journal, None)+ }+ fn with_reload(+ runtime: Runtime,+ journal: Journal,+ reload: Option<+ tokio::sync::mpsc::UnboundedSender<agent_client_protocol::schema::v1::SessionId>,+ >,+ ) -> Self {+ let service = Arc::new(SessionService::new(+ Arc::new(runtime),+ journal,+ Some(codex_cloud_agents::domain::runtime::CloudTarget {+ environment: CloudId::new("environment-fold".into()).unwrap(),+ branch: "main".into(),+ repository_url: Some("https://github.com/org/repo".into()),+ }),+ ));+ let (client, agent) = tokio::io::duplex(128 * 1024);+ let (read, write) = tokio::io::split(client);+ let (input, output) = tokio::io::split(agent);+ let server = tokio::spawn(async move {+ let _ = serve(service, input, output, reload).await;+ });+ Self {+ read: BufReader::new(read),+ write,+ server,+ }+ }+ async fn call(+ &mut self,+ log: &mut Vec<AgentSessionLog>,+ id: u64,+ method: &str,+ params: Value,+ ) -> Vec<Value> {+ let request = json!({"jsonrpc":"2.0","id":id,"method":method,"params":params});+ self.send(log, request).await;+ self.collect(log, id).await+ }+ async fn send(&mut self, log: &mut Vec<AgentSessionLog>, request: Value) {+ log.push(entry(true, request.clone()));+ self.write+ .write_all(format!("{request}\n").as_bytes())+ .await+ .unwrap();+ self.write.flush().await.unwrap();+ }+ async fn collect(&mut self, log: &mut Vec<AgentSessionLog>, id: u64) -> Vec<Value> {+ let mut frames = Vec::new();+ loop {+ let mut line = String::new();+ let count =+ tokio::time::timeout(Duration::from_secs(10), self.read.read_line(&mut line))+ .await+ .expect("ACP timed out")+ .unwrap();+ assert_ne!(count, 0, "ACP closed before response");+ let frame: Value = serde_json::from_str(&line).expect("clean JSON stdout");+ log.push(entry(false, frame.clone()));+ let done = frame["id"] == id;+ frames.push(frame);+ if done {+ return frames;+ }+ }+ }+ async fn initialize(&mut self, log: &mut Vec<AgentSessionLog>) -> Value {+ self.call(+ log,+ 1,+ "initialize",+ json!({"protocolVersion":1,"clientCapabilities":{}}),+ )+ .await+ .pop()+ .unwrap()+ }+ async fn session(&mut self, log: &mut Vec<AgentSessionLog>) -> String {+ self.call(+ log,+ 2,+ "session/new",+ json!({"cwd":"/workspace","mcpServers":[]}),+ )+ .await+ .last()+ .unwrap()["result"]["sessionId"]+ .as_str()+ .unwrap()+ .into()+ }+ async fn prompt(&mut self, log: &mut Vec<AgentSessionLog>, session: &str, id: u64, text: &str) {+ let frames = self+ .call(+ log,+ id,+ "session/prompt",+ json!({"sessionId":session,"prompt":[{"type":"text","text":text}]}),+ )+ .await;+ assert_eq!(frames.last().unwrap()["result"]["stopReason"], "end_turn");+ }+ async fn load(&mut self, log: &mut Vec<AgentSessionLog>, session: &str, id: u64) -> Vec<Value> {+ self.call(+ log,+ id,+ "session/load",+ json!({"sessionId":session,"cwd":"/workspace","mcpServers":[]}),+ )+ .await+ }+}+impl Drop for Client {+ fn drop(&mut self) {+ self.server.abort();+ }+}+fn entry(to_runtime: bool, value: Value) -> AgentSessionLog {+ let frame: RawJsonRpcMessage = serde_json::from_value(value).unwrap();+ AgentSessionLog {+ agent_session_id: AgentSessionId::new_from_uuid(uuid::Uuid::from_u128(0xA)),+ user_id: None,+ content: if to_runtime {+ Message::ToRuntime(ToRuntimeMessage::Acp(AcpMessage(frame)))+ } else {+ Message::ToServer(ToServerMessage::Acp(AcpMessage(frame)))+ },+ }+}+fn assert_fold(log: &[AgentSessionLog]) -> Vec<FoldedMessage> {+ let mut machine = FoldMachineImpl::new();+ let mut visible: Vec<FoldedMessage> = vec![];+ for (index, entry) in log.iter().enumerate() {+ for event in machine.push(entry.clone()) {+ match event {+ FoldEvent::MessagesReplaced(messages) => visible = messages.into_owned(),+ FoldEvent::NewMessage(message) => visible.push(message.into_owned()),+ FoldEvent::MessageUpdate(message) => {+ let position = visible+ .iter()+ .position(|old| old.id() == message.id())+ .unwrap();+ visible[position] = message.into_owned();+ }+ FoldEvent::MetadataUpdated(_) => {}+ }+ }+ assert_eq!(visible, machine.messages(), "machine prefix {index}");+ assert_eq!(+ visible,+ fold(log[..=index].iter().cloned()),+ "batch prefix {index}"+ );+ }+ visible+}+fn assert_turns(messages: &[FoldedMessage], turns: usize) {+ assert_eq!(+ messages.len(),+ turns * 2,+ "exactly one user and agent message per turn"+ );+ assert_eq!(+ messages+ .iter()+ .filter(|message| message.stop == Some(StopReason::EndTurn))+ .count(),+ turns,+ "one successful outcome per turn"+ );+ for (index, message) in messages.iter().enumerate() {+ assert_eq!(message.id.0 as usize, index / 2);+ }+}++#[tokio::test]+async fn recorded_missing_deltas_replay_restores_both_answers_once() {+ let runtime = Runtime::default();+ let journal = Journal::default();+ let mut client = Client::new(runtime.clone(), journal.clone());+ let mut log = vec![];+ client.initialize(&mut log).await;+ let session = client.session(&mut log).await;+ let recording: Vec<JournalEntry> =+ serde_json::from_str(include_str!("fixtures/missing_live_deltas.json")).unwrap();+ journal+ .entries+ .lock()+ .unwrap()+ .insert(session.clone(), recording);+ drop(client);++ let mut client = Client::new(runtime.clone(), journal);+ client.initialize(&mut log).await;+ let loaded = client.load(&mut log, &session, 3).await;+ assert!(loaded.last().unwrap().get("result").is_some());+ let messages = assert_fold(&log);+ assert_turns(&messages, 2);+ insta::assert_json_snapshot!("recorded_missing_deltas_replay", messages);+ let serialized = serde_json::to_string(&messages).unwrap();+ assert!(!serialized.contains("Final provider output"));+ assert!(!serialized.contains("Corrected provider message"));+ assert_eq!(serialized.matches("My name is **Codex**").count(), 1);+ assert_eq!(serialized.matches("## Hey! 👋").count(), 1);++ for request_id in [4, 5] {+ assert!(+ client+ .load(&mut log, &session, request_id)+ .await+ .last()+ .unwrap()+ .get("result")+ .is_some()+ );+ assert_eq!(+ assert_fold(&log),+ messages,+ "reloading must replace the transcript without duplicating text"+ );+ }+ assert_eq!(runtime.0.lock().unwrap().launches, 0);+}++#[tokio::test]+async fn partial_answer_is_withheld_while_working_and_final_snapshot_appears_once() {+ let runtime = Runtime::default();+ let mut client = Client::new(runtime.clone(), Journal::default());+ let mut log = Vec::new();+ client.initialize(&mut log).await;+ let session = client.session(&mut log).await;+ client+ .send(+ &mut log,+ json!({"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{+ "sessionId":session,"prompt":[{"type":"text","text":"hold"}]+ }}),+ )+ .await;+ loop {+ let mut line = String::new();+ tokio::time::timeout(Duration::from_secs(2), client.read.read_line(&mut line))+ .await+ .unwrap()+ .unwrap();+ let frame: Value = serde_json::from_str(&line).unwrap();+ assert!(frame.get("id").is_none(), "prompt must still be running");+ assert_ne!(+ frame["params"]["update"]["sessionUpdate"],+ "agent_message_chunk"+ );+ log.push(entry(false, frame.clone()));+ if frame["params"]["update"]["sessionUpdate"] == "agent_thought_chunk" {+ break;+ }+ }+ assert!(+ !serde_json::to_string(&assert_fold(&log))+ .unwrap()+ .contains("Incomplete answer")+ );+ {+ let mut calls = runtime.0.lock().unwrap();+ calls.holding = false;+ calls.final_only = true;+ }+ client.collect(&mut log, 3).await;+ let messages = assert_fold(&log);+ assert_turns(&messages, 1);+ let text = serde_json::to_string(&messages).unwrap();+ assert!(!text.contains("Incomplete answer"));+ assert_eq!(text.matches("Snapshot answer").count(), 1);+ client.load(&mut log, &session, 4).await;+ assert_eq!(assert_fold(&log), messages);+}++#[tokio::test]+async fn load_is_advertised_and_resume_is_not_implemented() {+ let mut client = Client::new(Runtime::default(), Journal::default());+ let mut log = vec![];+ let init = client.initialize(&mut log).await;+ assert_eq!(init["result"]["agentCapabilities"]["loadSession"], true);+ assert!(init["result"]["agentCapabilities"]["sessionCapabilities"]["resume"].is_null());+ let resumed = client+ .call(+ &mut log,+ 3,+ "session/resume",+ json!({"sessionId":"not-a-session","cwd":"/workspace","mcpServers":[]}),+ )+ .await;+ assert!(resumed.last().unwrap().get("error").is_some());+}++#[tokio::test]+async fn actual_live_reload_and_immediate_followup_replace_without_duplicate_turns() {+ let runtime = Runtime::default();+ let journal = Journal::default();+ let mut client = Client::new(runtime.clone(), journal.clone());+ let mut log = vec![];+ client.initialize(&mut log).await;+ let session = client.session(&mut log).await;+ client.prompt(&mut log, &session, 3, "First question").await;+ let first = assert_fold(&log);+ assert_turns(&first, 1);+ drop(client);+ let mut client = Client::new(runtime.clone(), journal);+ client.initialize(&mut log).await;+ for id in [4, 5] {+ let loaded = client.load(&mut log, &session, id).await;+ assert!(loaded.last().unwrap().get("result").is_some());+ assert_eq!(+ assert_fold(&log),+ first,+ "actual successful loads replace original messages"+ );+ }+ // No sleep: the immediately following request must observe released recovery ownership.+ client+ .prompt(&mut log, &session, 6, "Second question")+ .await;+ let second = assert_fold(&log);+ assert_turns(&second, 2);+ assert!(+ client+ .load(&mut log, &session, 7)+ .await+ .last()+ .unwrap()+ .get("result")+ .is_some()+ );+ assert_eq!(assert_fold(&log), second);+ let calls = runtime.0.lock().unwrap();+ assert_eq!(calls.launches, 1);+ assert_eq!(+ calls.followups,+ vec![(+ "task-fold".into(),+ "turn-1".into(),+ "Second question".into()+ )]+ );+}++#[tokio::test]+async fn incomplete_and_failed_actual_loads_preserve_prior_committed_messages() {+ let runtime = Runtime::default();+ let journal = Journal::default();+ let mut client = Client::new(runtime.clone(), journal.clone());+ let mut committed = vec![];+ client.initialize(&mut committed).await;+ let session = client.session(&mut committed).await;+ client+ .prompt(&mut committed, &session, 3, "Old question")+ .await;+ let old = assert_fold(&committed);+ // The durable conversation advances while this observer still shows the old turn.+ client+ .prompt(&mut vec![], &session, 4, "Newer question")+ .await;+ drop(client);+ let mut client = Client::new(runtime.clone(), journal.clone());+ client.initialize(&mut vec![]).await;+ let mut candidate = vec![];+ let loaded = client.load(&mut candidate, &session, 5).await;+ assert!(loaded.last().unwrap().get("result").is_some());+ let response = candidate.pop().unwrap();+ let mut interrupted = committed.clone();+ for frame in candidate {+ interrupted.push(frame);+ assert_eq!(+ assert_fold(&interrupted),+ old,+ "unacknowledged replay stays hidden"+ );+ }+ interrupted.push(response);+ assert_turns(&assert_fold(&interrupted), 2);+ drop(client);+ journal.fail_load.store(true, Ordering::SeqCst);+ let mut client = Client::new(runtime.clone(), journal.clone());+ client.initialize(&mut committed).await;+ let failed = client.load(&mut committed, &session, 6).await;+ assert!(failed.last().unwrap().get("error").is_some());+ assert_eq!(+ assert_fold(&committed),+ old,+ "failed load preserves the old conversation"+ );+ drop(client);+ journal.fail_load.store(false, Ordering::SeqCst);+ journal+ .entries+ .lock()+ .unwrap()+ .get_mut(&session)+ .unwrap()+ .remove(0);+ let mut client = Client::new(runtime, journal);+ client.initialize(&mut committed).await;+ let missing_boundary = client.load(&mut committed, &session, 7).await;+ assert!(+ missing_boundary.last().unwrap().get("error").is_some(),+ "native history without a complete beginning cannot be loaded"+ );+ assert_eq!(assert_fold(&committed), old);+}++#[tokio::test]+async fn cancelled_live_turn_keeps_one_cancelled_outcome_after_reload() {+ let runtime = Runtime::default();+ let journal = Journal::default();+ let mut client = Client::new(runtime.clone(), journal.clone());+ let mut log = vec![];+ client.initialize(&mut log).await;+ let session = client.session(&mut log).await;+ client.send(&mut log, json!({"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{"sessionId":session,"prompt":[{"type":"text","text":"hold"}]}})).await;+ loop {+ let mut line = String::new();+ tokio::time::timeout(Duration::from_secs(10), client.read.read_line(&mut line))+ .await+ .unwrap()+ .unwrap();+ let frame: Value = serde_json::from_str(&line).unwrap();+ assert_eq!(frame["method"], "session/update");+ let assistant = frame["params"]["update"]["sessionUpdate"] == "agent_thought_chunk";+ log.push(entry(false, frame));+ if assistant {+ break;+ }+ }+ client+ .send(+ &mut log,+ json!({"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":session}}),+ )+ .await;+ let stopped = client.collect(&mut log, 3).await;+ assert_eq!(stopped.last().unwrap()["result"]["stopReason"], "cancelled");+ let messages = assert_fold(&log);+ assert_eq!(+ messages.len(),+ 3,+ "live fold includes the accepted stop control"+ );+ assert_eq!(messages[1].stop, Some(StopReason::Cancelled));+ drop(client);+ let mut client = Client::new(runtime.clone(), journal);+ client.initialize(&mut log).await;+ assert!(+ client+ .load(&mut log, &session, 4)+ .await+ .last()+ .unwrap()+ .get("result")+ .is_some()+ );+ let replayed = assert_fold(&log);+ assert_eq!(+ replayed,+ messages[..2],+ "replay preserves conversation and cancellation outcome"+ );+ assert_eq!(runtime.0.lock().unwrap().launches, 1);+}++#[tokio::test]+async fn snapshot_only_answer_survives_repeated_loads_once() {+ let runtime = Runtime::default();+ runtime.0.lock().unwrap().final_only = true;+ let journal = Journal::default();+ let mut client = Client::new(runtime.clone(), journal.clone());+ let mut log = vec![];+ client.initialize(&mut log).await;+ let session = client.session(&mut log).await;+ client+ .prompt(&mut log, &session, 3, "Snapshot question")+ .await;+ let original = assert_fold(&log);+ assert_turns(&original, 1);+ drop(client);+ let mut client = Client::new(runtime.clone(), journal);+ client.initialize(&mut log).await;+ for id in 4..8 {+ assert!(+ client+ .load(&mut log, &session, id)+ .await+ .last()+ .unwrap()+ .get("result")+ .is_some()+ );+ assert_eq!(assert_fold(&log), original);+ }+ assert_eq!(runtime.0.lock().unwrap().launches, 1);+}++#[tokio::test]+async fn late_historical_records_are_silent_until_replacement_load() {+ let runtime = Runtime::default();+ let journal = Journal::default();+ let mut client = Client::new(runtime.clone(), journal.clone());+ let mut log = vec![];+ client.initialize(&mut log).await;+ let session = client.session(&mut log).await;+ client.prompt(&mut log, &session, 3, "Question").await;+ let original = assert_fold(&log);+ drop(client);+ runtime.0.lock().unwrap().late_record = true;+ let (send, mut receive) = tokio::sync::mpsc::unbounded_channel();+ let mut client = Client::with_reload(runtime.clone(), journal, Some(send));+ client.initialize(&mut log).await;+ assert!(+ client+ .load(&mut log, &session, 4)+ .await+ .last()+ .unwrap()+ .get("result")+ .is_some()+ );+ assert_eq!(assert_fold(&log), original);+ let requested = tokio::time::timeout(Duration::from_secs(10), receive.recv())+ .await+ .unwrap()+ .unwrap();+ assert_eq!(requested.to_string(), session);+ let mut unsolicited = String::new();+ assert!(+ tokio::time::timeout(+ Duration::from_millis(50),+ client.read.read_line(&mut unsolicited)+ )+ .await+ .is_err(),+ "historical recovery must not append ACP activity: {unsolicited}"+ );+ assert!(+ client+ .load(&mut log, &session, 5)+ .await+ .last()+ .unwrap()+ .get("result")+ .is_some()+ );+ let replaced = assert_fold(&log);+ assert_ne!(+ replaced, original,+ "successful reload includes newly recovered native history"+ );+ assert_turns(&replaced, 1);+ assert_eq!(replaced[1].stop, Some(StopReason::EndTurn));+ assert!(+ client+ .load(&mut log, &session, 6)+ .await+ .last()+ .unwrap()+ .get("result")+ .is_some()+ );+ assert_eq!(assert_fold(&log), replaced);+ assert_eq!(runtime.0.lock().unwrap().launches, 1);+}++fn associated_pr(turn: &str, repo: &str, number: u32) -> ExternalPullRequest {+ ExternalPullRequest {+ assistant_turn_id: TurnId::new(turn.into()).unwrap(),+ url: format!("https://github.com/{repo}/pull/{number}"),+ }+}++#[tokio::test]+async fn verified_pr_is_a_standard_completed_tool_in_live_and_replayed_history() {+ let runtime = Runtime::default();+ runtime.0.lock().unwrap().prs = vec![+ associated_pr("turn-1", "org/repo", 42),+ associated_pr("turn-1", "other/repo", 99),+ associated_pr("foreign-turn", "org/repo", 98),+ ];+ let mut client = Client::new(runtime.clone(), Journal::default());+ let mut log = vec![];+ client.initialize(&mut log).await;+ let session = client.session(&mut log).await;+ client+ .prompt(&mut log, &session, 3, "Inspect repository")+ .await;+ let messages = assert_fold(&log);+ assert_turns(&messages, 1);+ let serialized = serde_json::to_string(&messages).unwrap();+ assert_eq!(serialized.matches("Found pull request").count(), 1);+ assert!(serialized.contains("https://github.com/org/repo/pull/42"));+ assert!(!serialized.contains("other/repo"));+ assert!(!serialized.contains("/pull/98"));+ insta::assert_json_snapshot!("verified_pr_tool", messages);+ for id in [4, 5] {+ client.load(&mut log, &session, id).await;+ assert_eq!(assert_fold(&log), messages);+ }+ assert_eq!(runtime.0.lock().unwrap().launches, 1);+}++#[tokio::test]+async fn late_pr_metadata_replays_on_its_own_turn_without_duplicate_tools() {+ let runtime = Runtime::default();+ let journal = Journal::default();+ let mut client = Client::new(runtime.clone(), journal.clone());+ let mut log = vec![];+ client.initialize(&mut log).await;+ let session = client.session(&mut log).await;+ client.prompt(&mut log, &session, 3, "First turn").await;+ client.prompt(&mut log, &session, 4, "Second turn").await;+ drop(client);+ let mut snapshot = runtime.state().unwrap();+ snapshot.pull_requests = vec![associated_pr("turn-1", "org/repo", 42)];+ let sequence = journal.read(&session).await.unwrap().len() as i64;+ journal+ .append(+ &session,+ sequence,+ None,+ &JournalInput::Metadata {+ snapshot,+ native: None,+ },+ )+ .await+ .unwrap();+ let mut client = Client::new(runtime.clone(), journal);+ client.initialize(&mut log).await;+ client.load(&mut log, &session, 5).await;+ let messages = assert_fold(&log);+ assert_turns(&messages, 2);+ assert!(+ serde_json::to_string(&messages[1])+ .unwrap()+ .contains("Found pull request")+ );+ assert!(+ !serde_json::to_string(&messages[3])+ .unwrap()+ .contains("Found pull request")+ );+ for id in [6, 7] {+ client.load(&mut log, &session, id).await;+ assert_eq!(assert_fold(&log), messages);+ }+ assert_eq!(runtime.0.lock().unwrap().launches, 1);+ assert_eq!(runtime.0.lock().unwrap().followups.len(), 1);+}diff --git a/crates/codex_cloud_agents/tests/snapshots/fold__recorded_missing_deltas_replay.snap b/crates/codex_cloud_agents/tests/snapshots/fold__recorded_missing_deltas_replay.snapnew file mode 100644index 0000000000..5bbd808313--- /dev/null+++ b/crates/codex_cloud_agents/tests/snapshots/fold__recorded_missing_deltas_replay.snap@@ -0,0 +1,102 @@+---+source: crates/codex_cloud_agents/tests/fold.rs+expression: messages+---+[+ {+ "turn": 0,+ "author": {+ "kind": "user",+ "userId": null+ },+ "requestId": null,+ "parts": [+ {+ "kind": "text",+ "text": "wh atis this repo how is ti going man"+ }+ ],+ "stop": null+ },+ {+ "turn": 0,+ "author": {+ "kind": "agent"+ },+ "requestId": null,+ "parts": [+ {+ "kind": "thought",+ "text": "**Inspecting AGENTS and files****Inspecting hidden files and git history**"+ },+ {+ "kind": "tool_use",+ "id": "record_15",+ "name": {+ "kind": "native",+ "name": "/bin/bash -lc \"printf '%s\\\\n' '--- directory ---' && find . -maxdepth 2 -mindepth 1 -printf '%y %p\\\\n' | sort | sed -n '1,160p' && printf '%s\\\\n' '--- recent commits ---' && git log --oneline --decorate --all -10 && printf '%s\\\\n' '--- HEAD tree ---' && git ls-tree -r --name-only HEAD 2>&1 || true && printf '%s\\\\n' '--- remotes ---' && git remote -v\""+ },+ "status": "completed",+ "detail": {+ "kind": "terminal",+ "command": "/bin/bash -lc \"printf '%s\\\\n' '--- directory ---' && find . -maxdepth 2 -mindepth 1 -printf '%y %p\\\\n' | sort | sed -n '1,160p' && printf '%s\\\\n' '--- recent commits ---' && git log --oneline --decorate --all -10 && printf '%s\\\\n' '--- HEAD tree ---' && git ls-tree -r --name-only HEAD 2>&1 || true && printf '%s\\\\n' '--- remotes ---' && git remote -v\"",+ "output": null,+ "exitCode": null+ }+ },+ {+ "kind": "tool_use",+ "id": "record_106",+ "name": {+ "kind": "native",+ "name": "/bin/bash -lc \"pwd && printf '%s\\\\n' '--- AGENTS files ---' && find .. -name AGENTS.md -print && printf '%s\\\\n' '--- top-level files ---' && rg --files -g '\"'!node_modules'\"' | sed -n '1,120p' && printf '%s\\\\n' '--- git status ---' && git status --short --branch\""+ },+ "status": "completed",+ "detail": {+ "kind": "terminal",+ "command": "/bin/bash -lc \"pwd && printf '%s\\\\n' '--- AGENTS files ---' && find .. -name AGENTS.md -print && printf '%s\\\\n' '--- top-level files ---' && rg --files -g '\"'!node_modules'\"' | sed -n '1,120p' && printf '%s\\\\n' '--- git status ---' && git status --short --branch\"",+ "output": null,+ "exitCode": null+ }+ },+ {+ "kind": "text",+ "text": "## Hey! 👋\n\nI’m doing well, man—thanks for asking.\n\n## What is this repository?\n\nThis is currently an **empty temporary test repository**:\n\n- It contains no application source code, documentation, dependencies, or tests.\n- Its only tracked file is `.gitkeep`, which is commonly used to keep an otherwise empty directory in Git. \n\n\n- The repository has a single commit named **“Initialize repository.”**\n- You’re on the `work` branch.\n- No Git remote is configured, so it is not currently connected to a GitHub or other remote repository.\n\nIn short: **it’s just a blank sandbox that can be used to test changes or start a new project.**\n\n## Checks performed\n\n- ✅ `pwd`\n- ✅ `find .. -name AGENTS.md -print`\n- ✅ `rg --files -g '!node_modules'`\n- ✅ `git status --short --branch`\n- ✅ `find . -maxdepth 2 -mindepth 1 -printf '%y %p\\n'`\n- ✅ `git log --oneline --decorate --all -10`\n- ✅ `git ls-tree -r --name-only HEAD`\n- ✅ `git remote -v`\n\nI didn’t modify anything, so there was nothing to commit or open a pull request for."+ }+ ],+ "stop": {+ "kind": "end_turn"+ }+ },+ {+ "turn": 1,+ "author": {+ "kind": "user",+ "userId": null+ },+ "requestId": null,+ "parts": [+ {+ "kind": "text",+ "text": "what is your name"+ }+ ],+ "stop": null+ },+ {+ "turn": 1,+ "author": {+ "kind": "agent"+ },+ "requestId": null,+ "parts": [+ {+ "kind": "text",+ "text": "My name is **Codex**. I’m an AI coding assistant created by OpenAI."+ }+ ],+ "stop": {+ "kind": "end_turn"+ }+ }+]diff --git a/crates/codex_cloud_agents/tests/snapshots/fold__verified_pr_tool.snap b/crates/codex_cloud_agents/tests/snapshots/fold__verified_pr_tool.snapnew file mode 100644index 0000000000..4c613d33aa--- /dev/null+++ b/crates/codex_cloud_agents/tests/snapshots/fold__verified_pr_tool.snap@@ -0,0 +1,54 @@+---+source: crates/codex_cloud_agents/tests/fold.rs+expression: messages+---+[+ {+ "turn": 0,+ "author": {+ "kind": "user",+ "userId": null+ },+ "requestId": null,+ "parts": [+ {+ "kind": "text",+ "text": "Inspect repository"+ }+ ],+ "stop": null+ },+ {+ "turn": 0,+ "author": {+ "kind": "agent"+ },+ "requestId": null,+ "parts": [+ {+ "kind": "text",+ "text": "Answer for turn-1"+ },+ {+ "kind": "tool_use",+ "id": "codex-pr:turn-1:https://github.com/org/repo/pull/42",+ "name": {+ "kind": "native",+ "name": "Found pull request"+ },+ "status": "completed",+ "detail": {+ "kind": "other",+ "acpKind": "other",+ "output": "[View pull request](https://github.com/org/repo/pull/42)",+ "input": {+ "url": "https://github.com/org/repo/pull/42"+ }+ }+ }+ ],+ "stop": {+ "kind": "end_turn"+ }+ }+]diff --git a/crates/codex_cloud_agents/tests/snapshots/stdio__stdio_messages_followups_stop.snap b/crates/codex_cloud_agents/tests/snapshots/stdio__stdio_messages_followups_stop.snapnew file mode 100644index 0000000000..8d0639f223--- /dev/null+++ b/crates/codex_cloud_agents/tests/snapshots/stdio__stdio_messages_followups_stop.snap@@ -0,0 +1,115 @@+---+source: crates/codex_cloud_agents/tests/stdio.rs+expression: "normalize(&json!({\"initialize\":init,\"new\":new,\"first\":first,\"followup\":second,\"stop\":stopped}),\n&session)"+---+{+ "initialize": {+ "jsonrpc": "2.0",+ "id": 1,+ "result": {+ "protocolVersion": 1,+ "agentCapabilities": {+ "loadSession": true,+ "promptCapabilities": {+ "image": false,+ "audio": false,+ "embeddedContext": false+ },+ "mcpCapabilities": {+ "http": false,+ "sse": false+ },+ "sessionCapabilities": {},+ "auth": {}+ },+ "authMethods": [],+ "agentInfo": {+ "name": "codex_acp",+ "version": "0.1.0"+ }+ }+ },+ "new": [+ {+ "jsonrpc": "2.0",+ "id": 2,+ "result": {+ "sessionId": "SESSION"+ }+ }+ ],+ "first": [+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "sessionId": "SESSION",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "Hello 🌍"+ }+ }+ }+ },+ {+ "jsonrpc": "2.0",+ "id": 3,+ "result": {+ "stopReason": "end_turn"+ }+ }+ ],+ "followup": [+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "sessionId": "SESSION",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "Hello 🌍"+ }+ }+ }+ },+ {+ "jsonrpc": "2.0",+ "id": 4,+ "result": {+ "stopReason": "end_turn"+ }+ }+ ],+ "stop": [+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "sessionId": "SESSION",+ "update": {+ "sessionUpdate": "tool_call",+ "toolCallId": "running-tool",+ "title": "sleep 60",+ "kind": "execute",+ "status": "in_progress",+ "rawInput": {+ "id": "running-tool",+ "type": "commandExecution",+ "command": "sleep 60"+ }+ }+ }+ },+ {+ "jsonrpc": "2.0",+ "id": 5,+ "result": {+ "stopReason": "cancelled"+ }+ }+ ]+}diff --git a/crates/codex_cloud_agents/tests/snapshots/stdio__stdio_recorded_cloud_turn.snap b/crates/codex_cloud_agents/tests/snapshots/stdio__stdio_recorded_cloud_turn.snapnew file mode 100644index 0000000000..2f4ae276a3--- /dev/null+++ b/crates/codex_cloud_agents/tests/snapshots/stdio__stdio_recorded_cloud_turn.snap@@ -0,0 +1,68 @@+---+source: crates/codex_cloud_agents/tests/stdio.rs+expression: "normalize(&json!(frames), &session)"+---+[+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "sessionId": "SESSION",+ "update": {+ "sessionUpdate": "tool_call",+ "toolCallId": "recorded-id-7",+ "title": "printf \"safe-output\\n\"",+ "kind": "execute",+ "status": "completed",+ "content": [+ {+ "type": "content",+ "content": {+ "type": "text",+ "text": "safe-output\n"+ }+ }+ ],+ "rawInput": {+ "aggregatedOutput": "safe-output\n",+ "command": "printf \"safe-output\\n\"",+ "commandActions": [+ {+ "command": "printf \"safe-output\\n\"",+ "type": "unknown"+ }+ ],+ "cwd": "/workspace/example",+ "durationMs": 1000,+ "exitCode": 0,+ "id": "recorded-id-7",+ "processId": "recorded-id-8",+ "source": "unifiedExecStartup",+ "status": "completed",+ "type": "commandExecution"+ }+ }+ }+ },+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "sessionId": "SESSION",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "Safe text. Safe text. Safe text. Safe text. Safe text. Safe text. Safe text. Safe text. Safe text. Safe text. Safe text. "+ }+ }+ }+ },+ {+ "jsonrpc": "2.0",+ "id": 3,+ "result": {+ "stopReason": "end_turn"+ }+ }+]diff --git a/crates/codex_cloud_agents/tests/snapshots/stdio__stdio_unsupported_elicitation.snap b/crates/codex_cloud_agents/tests/snapshots/stdio__stdio_unsupported_elicitation.snapnew file mode 100644index 0000000000..cf069c739f--- /dev/null+++ b/crates/codex_cloud_agents/tests/snapshots/stdio__stdio_unsupported_elicitation.snap@@ -0,0 +1,14 @@+---+source: crates/codex_cloud_agents/tests/stdio.rs+expression: frames+---+[+ {+ "jsonrpc": "2.0",+ "id": 3,+ "error": {+ "code": -32603,+ "message": "cloud turn requested interactive input or approval unsupported by this adapter; remote cancellation requested"+ }+ }+]diff --git a/crates/codex_cloud_agents/tests/snapshots/stdio__stdio_unsupported_inputs.snap b/crates/codex_cloud_agents/tests/snapshots/stdio__stdio_unsupported_inputs.snapnew file mode 100644index 0000000000..d5e6487f6a--- /dev/null+++ b/crates/codex_cloud_agents/tests/snapshots/stdio__stdio_unsupported_inputs.snap@@ -0,0 +1,37 @@+---+source: crates/codex_cloud_agents/tests/stdio.rs+expression: "normalize(&json!({\"image\":image,\"empty\":empty,\"unsupported_mode\":unknown}),\n&session)"+---+{+ "image": [+ {+ "jsonrpc": "2.0",+ "id": 3,+ "error": {+ "code": -32602,+ "message": "Only text prompts are supported"+ }+ }+ ],+ "empty": [+ {+ "jsonrpc": "2.0",+ "id": 4,+ "error": {+ "code": -32602,+ "message": "Provide a nonempty text prompt (maximum 64 KiB)"+ }+ }+ ],+ "unsupported_mode": [+ {+ "jsonrpc": "2.0",+ "id": 5,+ "error": {+ "code": -32601,+ "message": "Method not found",+ "data": "session/set_mode"+ }+ }+ ]+}diff --git a/crates/codex_cloud_agents/tests/stdio.rs b/crates/codex_cloud_agents/tests/stdio.rsnew file mode 100644index 0000000000..b53c47bed9--- /dev/null+++ b/crates/codex_cloud_agents/tests/stdio.rs@@ -0,0 +1,504 @@+//! Byte-stream protocol regressions: exercise the same framing used by Zed.+use codex_cloud_agents::domain::acp_session::{SessionService, SessionStore, StoredSession};+use codex_cloud_agents::domain::cloud::*;+use codex_cloud_agents::domain::journal::{JournalEntry, JournalInput};+use codex_cloud_agents::domain::*;+use codex_cloud_agents::inbound::acp::serve;+use serde_json::{Value, json};+use std::collections::HashMap;+use std::sync::{+ Arc, Mutex,+ atomic::{AtomicBool, AtomicUsize, Ordering},+};+use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader, DuplexStream};++type Result<T> = std::result::Result<T, rootcause::Report>;+#[derive(Clone, Default)]+struct Journal(+ Arc<Mutex<HashMap<String, StoredSession>>>,+ Arc<Mutex<HashMap<String, Vec<JournalEntry>>>>,+);+impl SessionStore for Journal {+ async fn load(&self, id: &str) -> Result<Option<StoredSession>> {+ Ok(self.0.lock().unwrap().get(id).cloned())+ }+ async fn save(&self, id: &str, state: &StoredSession) -> Result<()> {+ self.0.lock().unwrap().insert(id.into(), state.clone());+ Ok(())+ }+ async fn read(&self, id: &str) -> std::result::Result<Vec<JournalEntry>, rootcause::Report> {+ Ok(self.1.lock().unwrap().get(id).cloned().unwrap_or_default())+ }+ async fn append(+ &self,+ id: &str,+ expected: i64,+ turn: Option<&TurnId>,+ input: &JournalInput,+ ) -> std::result::Result<JournalEntry, rootcause::Report> {+ let mut journals = self.1.lock().unwrap();+ let entries = journals.entry(id.to_owned()).or_default();+ if entries.len() as i64 != expected {+ return Err(rootcause::report!("stale sequence"));+ }+ let entry = JournalEntry {+ sequence: expected + 1,+ turn: turn.cloned(),+ input: input.clone(),+ };+ entries.push(entry.clone());+ Ok(entry)+ }+ async fn validate(&self) -> Result<()> {+ Ok(())+ }+}+struct Auth;+impl CredentialStore for Auth {+ fn load(&self) -> Result<Option<Credentials>> {+ Ok(Some(Credentials {+ version: 1,+ access_token: Secret::new("test-access".into())?,+ refresh_token: Secret::new("test-refresh".into())?,+ expires_at: u64::MAX,+ account_id: "test-account".into(),+ }))+ }+ fn save(&self, _: &Credentials) -> Result<()> {+ Ok(())+ }+ fn clear(&self) -> Result<()> {+ Ok(())+ }+}+#[derive(Default)]+struct Calls {+ creates: AtomicUsize,+ follows: AtomicUsize,+ cancels: AtomicUsize,+ turn: AtomicUsize,+ done: AtomicBool,+ hold: AtomicBool,+ input_request: AtomicBool,+ recorded: AtomicBool,+ cancelled: AtomicBool,+}+#[derive(Clone, Default)]+struct Provider(Arc<Calls>);+impl Provider {+ fn receipt(&self, prompt: &str) -> Result<CreatedTask> {+ let turn = self.0.turn.fetch_add(1, Ordering::SeqCst) + 1;+ self.0.done.store(false, Ordering::SeqCst);+ self.0+ .recorded+ .store(prompt.contains("recorded"), Ordering::SeqCst);+ self.0+ .input_request+ .store(prompt.contains("elicitation"), Ordering::SeqCst);+ self.0.cancelled.store(false, Ordering::SeqCst);+ self.0.hold.store(prompt.contains("hold"), Ordering::SeqCst);+ Ok(CreatedTask {+ task_id: CloudId::new("task-test".into())?,+ assistant_turn_id: Some(TurnId::new(format!("turn-{turn}"))?),+ url: "https://chatgpt.com/codex/tasks/task-test".into(),+ })+ }+ fn snapshot(&self) -> Result<TaskSnapshot> {+ let status = if self.0.cancelled.load(Ordering::SeqCst) {+ "cancelled"+ } else if self.0.done.load(Ordering::SeqCst) {+ "completed"+ } else {+ "in_progress"+ };+ Ok(TaskSnapshot {+ pull_requests: vec![],+ native: None,+ task_id: CloudId::new("task-test".into())?,+ title: Some("Test".into()),+ assistant_status: Some(status.into()),+ turns: vec![TurnSnapshot {+ source: "current_assistant_turn".into(),+ id: Some(format!("turn-{}", self.0.turn.load(Ordering::SeqCst))),+ messages: vec![],+ output_types: vec![],+ has_diff: false,+ }],+ })+ }+}+impl OAuth for Provider {+ async fn begin(&self) -> Result<DeviceLogin> {+ Err(rootcause::report!("login not expected"))+ }+ async fn poll(&self, _: &DeviceLogin) -> Result<LoginPoll> {+ Err(rootcause::report!("poll not expected"))+ }+ async fn refresh(&self, _: &Credentials) -> Result<Credentials> {+ Err(rootcause::report!("refresh not expected"))+ }+ async fn environments(&self, _: &Credentials) -> Result<Vec<Environment>> {+ Ok(vec![Environment {+ id: "env-test".into(),+ label: None,+ repositories: vec![],+ }])+ }+}+impl CloudTasks for Provider {+ async fn create(&self, _: &Credentials, request: &Launch) -> Result<CreatedTask> {+ self.0.creates.fetch_add(1, Ordering::SeqCst);+ self.receipt(&request.prompt)+ }+ async fn snapshot(&self, _: &Credentials, _: &CloudId) -> Result<TaskSnapshot> {+ self.snapshot()+ }+}+impl CloudConversation for Provider {+ async fn follow_up(+ &self,+ _: &Credentials,+ _: &CloudId,+ _: &TurnId,+ prompt: &str,+ ) -> Result<CreatedTask> {+ self.0.follows.fetch_add(1, Ordering::SeqCst);+ self.receipt(prompt)+ }+ async fn cancel(&self, _: &Credentials, _: &CloudId) -> Result<()> {+ self.0.cancels.fetch_add(1, Ordering::SeqCst);+ self.0.cancelled.store(true, Ordering::SeqCst);+ Ok(())+ }+ async fn turn(&self, _: &Credentials, _: &CloudId, _: &TurnId) -> Result<TaskSnapshot> {+ self.snapshot()+ }+ async fn stream(+ &self,+ _: &Credentials,+ _: &CloudId,+ turn: &TurnId,+ ) -> Result<CloudEventStream> {+ use futures::StreamExt as _;+ let id = turn.as_str();+ if self.0.recorded.load(Ordering::SeqCst) {+ let events: Vec<CloudEvent> =+ serde_json::from_str(include_str!("fixtures/recorded_cloud_turn.json")).unwrap();+ let calls = self.0.clone();+ return Ok(Box::pin(+ futures::stream::iter(+ events+ .into_iter()+ .map(|event| Ok(NativeRecord::from_event(event.clone()))),+ )+ .chain(futures::stream::once(async move {+ calls.done.store(true, Ordering::SeqCst);+ Ok(NativeRecord::from_event(CloudEvent {+ id: "fixture-end".into(),+ method: "turn/completed".into(),+ params: json!({}),+ }))+ })),+ ));+ }+ if self.0.input_request.load(Ordering::SeqCst) {+ return Ok(Box::pin(futures::stream::iter(vec![Ok(+ NativeRecord::from_event(CloudEvent {+ id: format!("{id}-input"),+ method: "item/tool/requestUserInput".into(),+ params: json!({"requestId":"question-1","questions":[{"id":"choice","question":"Choose a branch"}]}),+ }),+ )])));+ }+ let event = CloudEvent {+ id: format!("{id}-delta"),+ method: "item/agentMessage/delta".into(),+ params: json!({"threadId":"task-test","turnId":id,"itemId":format!("{id}-message"),"delta":"Hello 🌍"}),+ };+ let complete = CloudEvent {+ id: format!("{id}-complete"),+ method: "item/completed".into(),+ params: json!({"threadId":"task-test","turnId":id,"item":{"id":format!("{id}-message"),"type":"agentMessage","text":"Hello 🌍"}}),+ };+ if self.0.hold.load(Ordering::SeqCst) {+ let activity = CloudEvent {+ id: format!("{id}-tool"),+ method: "item/started".into(),+ params: json!({"item":{"id":"running-tool","type":"commandExecution","command":"sleep 60"}}),+ };+ return Ok(Box::pin(+ futures::stream::iter(vec![Ok(NativeRecord::from_event(activity))])+ .chain(futures::stream::pending()),+ ));+ }+ let calls = self.0.clone();+ Ok(Box::pin(+ futures::stream::iter(vec![+ Ok(NativeRecord::from_event(event.clone())),+ Ok(NativeRecord::from_event(event.clone())),+ Ok(NativeRecord::from_event(complete)),+ ])+ .chain(futures::stream::once(async move {+ calls.done.store(true, Ordering::SeqCst);+ Ok(NativeRecord::from_event(CloudEvent {+ id: format!("done-{}", calls.turn.load(Ordering::SeqCst)),+ method: "turn/completed".into(),+ params: json!({}),+ }))+ })),+ ))+ }+}+struct Client {+ read: BufReader<tokio::io::ReadHalf<DuplexStream>>,+ write: tokio::io::WriteHalf<DuplexStream>,+ server: tokio::task::JoinHandle<()>,+}+impl Client {+ async fn send(&mut self, frame: Value) {+ self.write+ .write_all(format!("{frame}\n").as_bytes())+ .await+ .unwrap();+ self.write.flush().await.unwrap();+ }+ async fn next(&mut self) -> Value {+ let mut line = String::new();+ let count = tokio::time::timeout(+ std::time::Duration::from_secs(15),+ self.read.read_line(&mut line),+ )+ .await+ .expect("ACP response timed out")+ .unwrap();+ assert_ne!(count, 0, "ACP unexpectedly closed");+ serde_json::from_str(&line).expect("stdout contains only JSON protocol frames")+ }+ async fn call(&mut self, id: i64, method: &str, params: Value) -> Vec<Value> {+ self.send(json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}))+ .await;+ let mut frames = vec![];+ loop {+ let frame = self.next().await;+ let done = frame["id"] == id;+ frames.push(frame);+ if done {+ return frames;+ }+ }+ }+}+impl Drop for Client {+ fn drop(&mut self) {+ self.server.abort();+ }+}+fn harness(provider: Provider, journal: Journal) -> Client {+ let service = Arc::new(SessionService::new(+ Arc::new(Probe::new(provider, Auth)),+ journal,+ Some(codex_cloud_agents::domain::runtime::CloudTarget {+ environment: CloudId::new("env-test".into()).unwrap(),+ branch: "main".into(),+ repository_url: None,+ }),+ ));+ let (client, agent) = tokio::io::duplex(128 * 1024);+ let (read, write) = tokio::io::split(client);+ let (agent_read, agent_write) = tokio::io::split(agent);+ let server = tokio::spawn(async move {+ let _ = serve(service, agent_read, agent_write, None).await;+ });+ Client {+ read: BufReader::new(read),+ write,+ server,+ }+}+async fn initialize(client: &mut Client) -> Value {+ client.call(1,"initialize",json!({"protocolVersion":1,"clientCapabilities":{},"clientInfo":{"name":"stdio-test","version":"1"}})).await.pop().unwrap()+}+fn normalize(value: &Value, session: &str) -> Value {+ match value {+ Value::String(text) => Value::String(text.replace(session, "SESSION")),+ Value::Array(items) => Value::Array(items.iter().map(|v| normalize(v, session)).collect()),+ Value::Object(items) => Value::Object(+ items+ .iter()+ .map(|(k, v)| (k.clone(), normalize(v, session)))+ .collect(),+ ),+ _ => value.clone(),+ }+}+#[tokio::test]+async fn stdio_messages_followups_and_stop_snapshot() {+ let provider = Provider::default();+ let mut client = harness(provider.clone(), Journal::default());+ let init = initialize(&mut client).await;+ let new = client+ .call(+ 2,+ "session/new",+ json!({"cwd":"/unrelated/local/repo","mcpServers":[]}),+ )+ .await;+ let session = new.last().unwrap()["result"]["sessionId"]+ .as_str()+ .unwrap()+ .to_owned();+ let first = client+ .call(+ 3,+ "session/prompt",+ json!({"sessionId":session,"prompt":[{"type":"text","text":"hello"}]}),+ )+ .await;+ let second = client+ .call(+ 4,+ "session/prompt",+ json!({"sessionId":session,"prompt":[{"type":"text","text":"again"}]}),+ )+ .await;+ client.send(json!({"jsonrpc":"2.0","id":5,"method":"session/prompt","params":{"sessionId":session,"prompt":[{"type":"text","text":"hold"}]}})).await;+ let mut stopped = vec![client.next().await];+ client+ .send(json!({"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":session}}))+ .await;+ loop {+ let frame = client.next().await;+ let done = frame["id"] == 5;+ stopped.push(frame);+ if done {+ break;+ }+ }+ assert_eq!(provider.0.creates.load(Ordering::SeqCst), 1);+ assert_eq!(provider.0.follows.load(Ordering::SeqCst), 2);+ assert!(provider.0.cancels.load(Ordering::SeqCst) >= 1);+ assert_eq!(first.last().unwrap()["result"]["stopReason"], "end_turn");+ assert_eq!(second.last().unwrap()["result"]["stopReason"], "end_turn");+ assert_eq!(stopped.last().unwrap()["result"]["stopReason"], "cancelled");+ insta::assert_json_snapshot!(+ "stdio_messages_followups_stop",+ normalize(+ &json!({"initialize":init,"new":new,"first":first,"followup":second,"stop":stopped}),+ &session+ )+ );+}+#[tokio::test]+async fn stdio_unsupported_inputs_do_not_launch_cloud_work() {+ let provider = Provider::default();+ let mut client = harness(provider.clone(), Journal::default());+ initialize(&mut client).await;+ let new = client+ .call(2, "session/new", json!({"cwd":"/tmp","mcpServers":[]}))+ .await;+ let session = new.last().unwrap()["result"]["sessionId"]+ .as_str()+ .unwrap()+ .to_owned();+ let image = client.call(3,"session/prompt",json!({"sessionId":session,"prompt":[{"type":"image","data":"AA==","mimeType":"image/png"}]})).await;+ let empty = client+ .call(+ 4,+ "session/prompt",+ json!({"sessionId":session,"prompt":[]}),+ )+ .await;+ let unknown = client+ .call(+ 5,+ "session/set_mode",+ json!({"sessionId":session,"modeId":"bypass"}),+ )+ .await;+ assert!(image.last().unwrap().get("error").is_some());+ assert!(empty.last().unwrap().get("error").is_some());+ assert!(unknown.last().unwrap().get("error").is_some());+ assert_eq!(provider.0.creates.load(Ordering::SeqCst), 0);+ insta::assert_json_snapshot!(+ "stdio_unsupported_inputs",+ normalize(+ &json!({"image":image,"empty":empty,"unsupported_mode":unknown}),+ &session+ )+ );+}++#[tokio::test]+async fn stdio_unsupported_elicitation_requests_remote_stop_without_fake_approval() {+ let provider = Provider::default();+ let mut client = harness(provider.clone(), Journal::default());+ initialize(&mut client).await;+ let new = client+ .call(2, "session/new", json!({"cwd":"/tmp","mcpServers":[]}))+ .await;+ let session = new.last().unwrap()["result"]["sessionId"]+ .as_str()+ .unwrap()+ .to_owned();+ let frames = client+ .call(+ 3,+ "session/prompt",+ json!({"sessionId":session,"prompt":[{"type":"text","text":"elicitation"}]}),+ )+ .await;+ assert!(frames.last().unwrap().get("error").is_some());+ assert_eq!(provider.0.cancels.load(Ordering::SeqCst), 1);+ assert!(+ !frames+ .iter()+ .any(|frame| frame["method"] == "session/request_permission")+ );+ // Keep source-location diagnostics out of fixture identity; the actionable sentence matters.+ let mut frames = normalize(&json!(frames), &session);+ for frame in frames.as_array_mut().unwrap() {+ if let Some(message) = frame.pointer_mut("/error/message") {+ let message_text = message.as_str().unwrap();+ let sentence = message_text+ .lines()+ .find(|line| line.contains("unsupported"))+ .unwrap_or(message_text);+ *message = json!(sentence.trim().trim_start_matches('●').trim());+ }+ }+ insta::assert_json_snapshot!("stdio_unsupported_elicitation", frames);+}++#[tokio::test]+async fn stdio_recorded_cloud_turn_snapshot() {+ let provider = Provider::default();+ let mut client = harness(provider.clone(), Journal::default());+ initialize(&mut client).await;+ let new = client+ .call(2, "session/new", json!({"cwd":"/tmp","mcpServers":[]}))+ .await;+ let session = new.last().unwrap()["result"]["sessionId"]+ .as_str()+ .unwrap()+ .to_owned();+ let frames = client+ .call(+ 3,+ "session/prompt",+ json!({"sessionId":session,"prompt":[{"type":"text","text":"recorded"}]}),+ )+ .await;+ assert_eq!(frames.last().unwrap()["result"]["stopReason"], "end_turn");+ assert!(frames.iter().any(|frame|frame.pointer("/params/update/sessionUpdate")==Some(&json!("tool_call"))));+ assert!(+ frames+ .iter()+ .any(|frame| frame.pointer("/params/update/sessionUpdate")+ == Some(&json!("agent_message_chunk")))+ );+ assert_eq!(provider.0.creates.load(Ordering::SeqCst), 1);+ insta::assert_json_snapshot!(+ "stdio_recorded_cloud_turn",+ normalize(&json!(frames), &session)+ );+}diff --git a/crates/codex_connection/Cargo.toml b/crates/codex_connection/Cargo.tomlnew file mode 100644index 0000000000..ebe180e6f1--- /dev/null+++ b/crates/codex_connection/Cargo.toml@@ -0,0 +1,25 @@+[package]+name = "codex_connection"+version = "0.1.0"+edition = "2024"+publish = false++[dependencies]+aes-gcm = { workspace = true }+async-trait = { workspace = true }+aws-sdk-kms = { workspace = true }+chrono = { workspace = true }+codex_cloud_agents = { path = "../codex_cloud_agents" }+macro_user_id = { path = "../macro_user_id" }+rootcause = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+sqlx = { workspace = true }+thiserror = { workspace = true }+tokio = { workspace = true }+uuid = { workspace = true }+zeroize = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+macro_db_migrator = { path = "../macro_db_migrator" }diff --git a/crates/codex_connection/src/domain.rs b/crates/codex_connection/src/domain.rsnew file mode 100644index 0000000000..ed2205a224--- /dev/null+++ b/crates/codex_connection/src/domain.rs@@ -0,0 +1,204 @@+//! Connection lifecycle policy independent of HTTP, PostgreSQL and KMS.++use async_trait::async_trait;+use chrono::{DateTime, Utc};+use codex_cloud_agents::domain::cloud::CloudId;+use codex_cloud_agents::domain::{Credentials, Environment, Secret};+use serde::{Deserialize, Serialize};+use uuid::Uuid;++mod service;+pub use service::ConnectionServiceImpl;++/// Errors contain no credentials or provider response bodies.+#[derive(Debug, thiserror::Error)]+pub enum ConnectionError {+ /// An operation requires an existing connection.+ #[error("connect Codex first")]+ NotConnected,+ /// Input cannot be accepted safely.+ #[error("invalid Codex connection input")]+ InvalidInput,+ /// The requested login attempt does not belong to this user or no longer exists.+ #[error("Codex login attempt not found")]+ NotFound,+ /// Account replacement requires explicit disconnect.+ #[error("Codex is already connected; disconnect before switching accounts")]+ AlreadyConnected,+ /// Provider access failed without revealing the underlying response.+ #[error("Codex is unavailable or authorization expired; reconnect if this persists")]+ Provider,+ /// A refresh must preserve the account to which the connection was bound.+ #[error("Codex account changed during refresh; reconnect")]+ AccountChanged,+ /// Persistence failed.+ #[error("could not persist Codex connection")]+ Storage,+ /// Envelope encryption or decryption failed.+ #[error("could not encrypt or decrypt Codex connection")]+ Encryption,+}++/// Safe connection metadata displayed in settings.+pub struct ConnectionStatus {+ /// Whether usable credentials are stored.+ pub connected: bool,+ /// Provider account identity, never a token.+ pub account_id: Option<String>,+ /// Selected environment, if configured.+ pub environment_id: Option<String>,+}++/// Information needed to complete device authorization in the browser.+pub struct StartedLogin {+ /// Owner-bound attempt identity.+ pub attempt_id: Uuid,+ /// Official provider device verification URL.+ pub verification_url: String,+ /// Short, expiring user code; never log this value.+ pub user_code: String,+ /// Absolute deadline.+ pub expires_at: DateTime<Utc>,+ /// Minimum interval between polling requests.+ pub poll_interval_seconds: u64,+}++/// Durable device authorization outcome.+#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum LoginStatus {+ /// Waiting for browser authorization.+ Pending,+ /// Credentials were atomically saved.+ Connected,+ /// Attempt deadline passed.+ Expired,+ /// Provider rejected the attempt; begin again.+ Failed,+}++/// Fresh owner credentials and the exact target a session must pin.+pub struct ResolvedConnection {+ /// New UUID for each successful connection, invalidating old bindings on reconnect.+ pub connection_id: Uuid,+ /// Current OAuth credentials; the caller must not retain them across operations.+ pub credentials: Credentials,+ /// Validated remote environment identity.+ pub environment_id: Option<CloudId>,+}++/// Owning service boundary used by auth handlers and cloud session runtimes.+#[async_trait]+pub trait ConnectionService: Send + Sync {+ /// Read safe connection metadata.+ async fn status(&self, owner: &str) -> Result<ConnectionStatus, ConnectionError>;+ /// Begin one durable owner-bound device authorization.+ async fn start_login(&self, owner: &str) -> Result<StartedLogin, ConnectionError>;+ /// Poll only the caller's current attempt and respect the provider interval.+ async fn poll_login(&self, owner: &str, attempt: Uuid) -> Result<LoginStatus, ConnectionError>;+ /// Cancel only a matching pending attempt.+ async fn cancel_login(&self, owner: &str, attempt: Uuid) -> Result<(), ConnectionError>;+ /// Delete credentials and invalidate pending attempts and prior session bindings.+ async fn disconnect(&self, owner: &str) -> Result<(), ConnectionError>;+ /// List environments using freshly rotated credentials.+ async fn environments(&self, owner: &str) -> Result<Vec<Environment>, ConnectionError>;+ /// Select a visible environment for subsequent sessions.+ async fn configure(+ &self,+ owner: &str,+ environment: &str,+ ) -> Result<ConnectionStatus, ConnectionError>;+ /// Resolve an authenticated connection, serializing refresh across service replicas.+ async fn resolve(&self, owner: &str) -> Result<ResolvedConnection, ConnectionError>;+}++/// Sensitive durable state; repository adapters must encrypt the entire serialized value.+#[derive(Default, Serialize, Deserialize)]+pub struct ConnectionState {+ /// The current completed connection, if any.+ pub connection: Option<StoredConnection>,+ /// Only the latest authorization attempt can become a connection.+ pub attempt: Option<LoginAttempt>,+}+/// Encrypted completed connection payload.+#[derive(Serialize, Deserialize)]+pub struct StoredConnection {+ /// Identity changes whenever an account reconnects.+ pub id: Uuid,+ /// Full provider tokens, never stored unencrypted.+ pub credentials: Credentials,+ /// Optional until the user chooses an environment.+ pub environment_id: Option<String>,+}+/// Encrypted device flow state; terminal attempts contain no device secret.+#[derive(Serialize, Deserialize)]+pub struct LoginAttempt {+ /// Owner-scoped attempt identity.+ pub id: Uuid,+ /// Current lifecycle outcome.+ pub status: LoginStatus,+ /// Deadline after which polling cannot exchange credentials.+ pub expires_at: DateTime<Utc>,+ /// Next allowed provider poll, enforced under the owner transaction lock.+ pub next_poll_at: DateTime<Utc>,+ /// Provider's minimum poll period.+ pub interval_seconds: u64,+ /// Cleared immediately on termination.+ pub device: Option<DeviceState>,+}+/// Sensitive device values needed for a later provider poll.+#[derive(Serialize, Deserialize)]+pub struct DeviceState {+ /// Provider's private poll handle.+ pub device_auth_id: Secret,+ /// Expiring browser code, encrypted alongside the handle.+ pub user_code: String,+ /// Fixed official verification URL returned at initiation.+ pub verification_url: String,+}++/// Repository lock spans credential reads, provider rotation and durable writes.+#[async_trait]+pub trait ConnectionRepository: Send + Sync {+ /// Acquire an exclusive per-owner lock across replicas and read decrypted state.+ async fn lock(&self, owner: &str) -> Result<Box<dyn ConnectionTransaction>, ConnectionError>;+}+/// Exclusive owner transaction; dropping it releases its lock and rolls back writes.+#[async_trait]+pub trait ConnectionTransaction: Send {+ /// Read the state loaded while acquiring the exclusive lock.+ fn state(&mut self) -> &mut ConnectionState;+ /// Atomically encrypt, write and commit the current state before releasing the lock.+ async fn commit(self: Box<Self>) -> Result<(), ConnectionError>;+}++/// Versioned authenticated envelope; only ciphertext is serializable outside domain state.+#[derive(Serialize, Deserialize)]+pub struct EncryptedState {+ /// Envelope format version.+ pub version: u8,+ /// AES-GCM payload ciphertext and tag.+ pub ciphertext: Vec<u8>,+ /// KMS-wrapped fresh AES data key.+ pub encrypted_data_key: Vec<u8>,+ /// Fresh random 96-bit AES-GCM nonce.+ pub nonce: Vec<u8>,+ /// CMK ARN returned by KMS.+ pub kms_key_id: String,+}+/// Cipher boundary binds every envelope to purpose and owner.+#[async_trait]+pub trait StateCipher: Send + Sync {+ /// Encrypt state without retaining plaintext bytes.+ async fn encrypt(+ &self,+ owner: &str,+ state: &ConnectionState,+ ) -> Result<EncryptedState, ConnectionError>;+ /// Decrypt only an envelope authenticated for this owner and feature.+ async fn decrypt(+ &self,+ owner: &str,+ envelope: &EncryptedState,+ ) -> Result<ConnectionState, ConnectionError>;+}diff --git a/crates/codex_connection/src/domain/service.rs b/crates/codex_connection/src/domain/service.rsnew file mode 100644index 0000000000..05b22de790--- /dev/null+++ b/crates/codex_connection/src/domain/service.rs@@ -0,0 +1,272 @@+//! Owner policy and device-flow orchestration over encrypted repository and OAuth ports.++use super::*;+use codex_cloud_agents::domain::{DeviceLogin, LoginPoll, OAuth};+use std::{sync::Arc, time::Duration};++/// Connection lifecycle implementation; only the composition root chooses adapters.+pub struct ConnectionServiceImpl<P> {+ repository: Arc<dyn ConnectionRepository>,+ provider: P,+}+impl<P: OAuth> ConnectionServiceImpl<P> {+ /// Compose a durable encrypted repository and the provider's OAuth implementation.+ pub fn new(repository: Arc<dyn ConnectionRepository>, provider: P) -> Self {+ Self {+ repository,+ provider,+ }+ }+ async fn lock(&self, owner: &str) -> Result<Box<dyn ConnectionTransaction>, ConnectionError> {+ macro_user_id::user_id::MacroUserIdStr::parse_from_str(owner)+ .map_err(|_| ConnectionError::InvalidInput)?;+ self.repository.lock(owner).await+ }+ async fn fresh(&self, owner: &str) -> Result<StoredConnection, ConnectionError> {+ let mut transaction = self.lock(owner).await?;+ let connection = transaction+ .state()+ .connection+ .as_mut()+ .ok_or(ConnectionError::NotConnected)?;+ connection+ .credentials+ .validate()+ .map_err(|_| ConnectionError::Encryption)?;+ let now = Utc::now().timestamp().max(0) as u64;+ let needs_refresh = connection.credentials.expires_at <= now.saturating_add(60);+ if needs_refresh {+ let refreshed = self+ .provider+ .refresh(&connection.credentials)+ .await+ .map_err(|_| ConnectionError::Provider)?;+ refreshed+ .validate()+ .map_err(|_| ConnectionError::Provider)?;+ if refreshed.account_id != connection.credentials.account_id {+ return Err(ConnectionError::AccountChanged);+ }+ connection.credentials = refreshed;+ }+ let result = StoredConnection {+ id: connection.id,+ credentials: copy_credentials(&connection.credentials)?,+ environment_id: connection.environment_id.clone(),+ };+ // Persist any rotated token before a downstream provider operation can fail.+ if needs_refresh {+ transaction.commit().await?;+ }+ Ok(result)+ }+}+fn copy_credentials(credentials: &Credentials) -> Result<Credentials, ConnectionError> {+ Ok(Credentials {+ version: credentials.version,+ access_token: Secret::new(credentials.access_token.expose().to_owned())+ .map_err(|_| ConnectionError::Encryption)?,+ refresh_token: Secret::new(credentials.refresh_token.expose().to_owned())+ .map_err(|_| ConnectionError::Encryption)?,+ expires_at: credentials.expires_at,+ account_id: credentials.account_id.clone(),+ })+}+fn status(state: &ConnectionState) -> ConnectionStatus {+ ConnectionStatus {+ connected: state.connection.is_some(),+ account_id: state+ .connection+ .as_ref()+ .map(|connection| connection.credentials.account_id.clone()),+ environment_id: state+ .connection+ .as_ref()+ .and_then(|connection| connection.environment_id.clone()),+ }+}++#[async_trait]+impl<P: OAuth + 'static> ConnectionService for ConnectionServiceImpl<P> {+ async fn status(&self, owner: &str) -> Result<ConnectionStatus, ConnectionError> {+ let mut transaction = self.lock(owner).await?;+ Ok(status(transaction.state()))+ }+ async fn start_login(&self, owner: &str) -> Result<StartedLogin, ConnectionError> {+ let mut transaction = self.lock(owner).await?;+ if transaction.state().connection.is_some() {+ return Err(ConnectionError::AlreadyConnected);+ }+ let login = self+ .provider+ .begin()+ .await+ .map_err(|_| ConnectionError::Provider)?;+ let now = Utc::now();+ let expires_at = now + chrono::Duration::seconds(login.timeout.as_secs().min(900) as i64);+ let interval_seconds = login.interval.as_secs().clamp(1, 900);+ let id = Uuid::now_v7();+ let result = StartedLogin {+ attempt_id: id,+ verification_url: login.verification_url.clone(),+ user_code: login.user_code.clone(),+ expires_at,+ poll_interval_seconds: interval_seconds,+ };+ transaction.state().attempt = Some(LoginAttempt {+ id,+ status: LoginStatus::Pending,+ expires_at,+ next_poll_at: now + chrono::Duration::seconds(interval_seconds as i64),+ interval_seconds,+ device: Some(DeviceState {+ device_auth_id: login.device_auth_id,+ user_code: login.user_code,+ verification_url: login.verification_url,+ }),+ });+ transaction.commit().await?;+ Ok(result)+ }+ async fn poll_login(&self, owner: &str, id: Uuid) -> Result<LoginStatus, ConnectionError> {+ let mut transaction = self.lock(owner).await?;+ let attempt = transaction+ .state()+ .attempt+ .as_mut()+ .filter(|attempt| attempt.id == id)+ .ok_or(ConnectionError::NotFound)?;+ if attempt.status != LoginStatus::Pending {+ return Ok(attempt.status);+ }+ let now = Utc::now();+ if now >= attempt.expires_at {+ attempt.status = LoginStatus::Expired;+ attempt.device = None;+ transaction.commit().await?;+ return Ok(LoginStatus::Expired);+ }+ if now < attempt.next_poll_at {+ return Ok(LoginStatus::Pending);+ }+ let device = attempt.device.as_ref().ok_or(ConnectionError::Encryption)?;+ let login = DeviceLogin {+ device_auth_id: Secret::new(device.device_auth_id.expose().to_owned())+ .map_err(|_| ConnectionError::Encryption)?,+ user_code: device.user_code.clone(),+ verification_url: device.verification_url.clone(),+ interval: Duration::from_secs(attempt.interval_seconds),+ timeout: Duration::from_secs((attempt.expires_at - now).num_seconds().max(0) as u64),+ };+ let polled = self.provider.poll(&login).await;+ if Utc::now() >= attempt.expires_at {+ attempt.status = LoginStatus::Expired;+ attempt.device = None;+ transaction.commit().await?;+ return Ok(LoginStatus::Expired);+ }+ // The lock remains held across exchange and persistence, preventing a second replica+ // from exchanging this attempt or replacing its credentials concurrently.+ let outcome = match polled {+ Ok(LoginPoll::Pending) => {+ attempt.next_poll_at =+ Utc::now() + chrono::Duration::seconds(attempt.interval_seconds as i64);+ LoginStatus::Pending+ }+ Ok(LoginPoll::Complete(credentials)) => {+ if credentials.validate().is_err() {+ attempt.status = LoginStatus::Failed;+ attempt.device = None;+ LoginStatus::Failed+ } else {+ attempt.status = LoginStatus::Connected;+ attempt.device = None;+ transaction.state().connection = Some(StoredConnection {+ id: Uuid::now_v7(),+ credentials,+ environment_id: None,+ });+ LoginStatus::Connected+ }+ }+ Err(_) => {+ attempt.status = LoginStatus::Failed;+ attempt.device = None;+ LoginStatus::Failed+ }+ };+ transaction.commit().await?;+ Ok(outcome)+ }+ async fn cancel_login(&self, owner: &str, id: Uuid) -> Result<(), ConnectionError> {+ let mut transaction = self.lock(owner).await?;+ let attempt = transaction+ .state()+ .attempt+ .as_ref()+ .filter(|attempt| attempt.id == id)+ .ok_or(ConnectionError::NotFound)?;+ // Cancelling an already completed login must not disconnect its credentials.+ if attempt.status == LoginStatus::Pending {+ transaction.state().attempt = None;+ transaction.commit().await?;+ }+ Ok(())+ }+ async fn disconnect(&self, owner: &str) -> Result<(), ConnectionError> {+ let mut transaction = self.lock(owner).await?;+ *transaction.state() = ConnectionState::default();+ transaction.commit().await+ }+ async fn environments(&self, owner: &str) -> Result<Vec<Environment>, ConnectionError> {+ let connection = self.fresh(owner).await?;+ self.provider+ .environments(&connection.credentials)+ .await+ .map_err(|_| ConnectionError::Provider)+ }+ async fn configure(+ &self,+ owner: &str,+ environment: &str,+ ) -> Result<ConnectionStatus, ConnectionError> {+ CloudId::new(environment.to_owned()).map_err(|_| ConnectionError::InvalidInput)?;+ let resolved = self.fresh(owner).await?;+ let environments = self+ .provider+ .environments(&resolved.credentials)+ .await+ .map_err(|_| ConnectionError::Provider)?;+ if !environments.iter().any(|item| item.id == environment) {+ return Err(ConnectionError::InvalidInput);+ }+ let mut transaction = self.lock(owner).await?;+ let connection = transaction+ .state()+ .connection+ .as_mut()+ .ok_or(ConnectionError::NotConnected)?;+ if connection.id != resolved.id {+ return Err(ConnectionError::AccountChanged);+ }+ connection.environment_id = Some(environment.to_owned());+ let result = status(transaction.state());+ transaction.commit().await?;+ Ok(result)+ }+ async fn resolve(&self, owner: &str) -> Result<ResolvedConnection, ConnectionError> {+ let connection = self.fresh(owner).await?;+ Ok(ResolvedConnection {+ connection_id: connection.id,+ credentials: connection.credentials,+ environment_id: connection+ .environment_id+ .map(CloudId::new)+ .transpose()+ .map_err(|_| ConnectionError::Encryption)?,+ })+ }+}++#[cfg(test)]+mod test;diff --git a/crates/codex_connection/src/domain/service/test.rs b/crates/codex_connection/src/domain/service/test.rsnew file mode 100644index 0000000000..29e78735ad--- /dev/null+++ b/crates/codex_connection/src/domain/service/test.rs@@ -0,0 +1,285 @@+use super::*;+use std::{+ collections::HashMap,+ sync::{+ Mutex,+ atomic::{AtomicUsize, Ordering},+ },+};++const OWNER: &str = "macro|[email protected]";+const OTHER: &str = "macro|[email protected]";+#[derive(Default)]+struct Repo(Mutex<HashMap<String, Arc<tokio::sync::Mutex<ConnectionState>>>>);+impl Repo {+ fn owner(&self, owner: &str) -> Arc<tokio::sync::Mutex<ConnectionState>> {+ self.0+ .lock()+ .unwrap()+ .entry(owner.into())+ .or_default()+ .clone()+ }+}+struct Tx {+ guard: tokio::sync::OwnedMutexGuard<ConnectionState>,+ state: ConnectionState,+}+#[async_trait]+impl ConnectionTransaction for Tx {+ fn state(&mut self) -> &mut ConnectionState {+ &mut self.state+ }+ async fn commit(mut self: Box<Self>) -> Result<(), ConnectionError> {+ *self.guard = std::mem::take(&mut self.state);+ Ok(())+ }+}+#[async_trait]+impl ConnectionRepository for Repo {+ async fn lock(&self, owner: &str) -> Result<Box<dyn ConnectionTransaction>, ConnectionError> {+ let guard = self.owner(owner).lock_owned().await;+ let state = serde_json::from_slice(&serde_json::to_vec(&*guard).unwrap()).unwrap();+ Ok(Box::new(Tx { guard, state }))+ }+}+#[derive(Default)]+struct Counts {+ polls: AtomicUsize,+ refresh: AtomicUsize,+ account_changed: bool,+}+struct Provider(Arc<Counts>);+fn credentials(account: &str, expiry: u64) -> Credentials {+ Credentials {+ version: 1,+ access_token: Secret::new("test-access".into()).unwrap(),+ refresh_token: Secret::new("test-refresh".into()).unwrap(),+ expires_at: expiry,+ account_id: account.into(),+ }+}+impl OAuth for Provider {+ async fn begin(&self) -> Result<DeviceLogin, rootcause::Report> {+ Ok(DeviceLogin {+ verification_url: "https://auth.openai.com/codex/device".into(),+ user_code: "TEST-CODE".into(),+ device_auth_id: Secret::new("test-device".into())?,+ interval: Duration::from_secs(5),+ timeout: Duration::from_secs(900),+ })+ }+ async fn poll(&self, _: &DeviceLogin) -> Result<LoginPoll, rootcause::Report> {+ self.0.polls.fetch_add(1, Ordering::SeqCst);+ Ok(LoginPoll::Complete(credentials("account-a", u64::MAX)))+ }+ async fn refresh(&self, _: &Credentials) -> Result<Credentials, rootcause::Report> {+ self.0.refresh.fetch_add(1, Ordering::SeqCst);+ tokio::task::yield_now().await;+ Ok(credentials(+ if self.0.account_changed {+ "account-b"+ } else {+ "account-a"+ },+ u64::MAX,+ ))+ }+ async fn environments(&self, _: &Credentials) -> Result<Vec<Environment>, rootcause::Report> {+ Ok(vec![Environment {+ repositories: vec![],+ id: "env-test".into(),+ label: Some("Test".into()),+ }])+ }+}+fn service() -> (ConnectionServiceImpl<Provider>, Arc<Repo>, Arc<Counts>) {+ let repo = Arc::new(Repo::default());+ let counts = Arc::new(Counts::default());+ (+ ConnectionServiceImpl::new(repo.clone(), Provider(counts.clone())),+ repo,+ counts,+ )+}+async fn ready(repo: &Repo, owner: &str) {+ let owner = repo.owner(owner);+ let mut state = owner.lock().await;+ state.attempt.as_mut().unwrap().next_poll_at = Utc::now() - chrono::Duration::seconds(1);+}+#[tokio::test]+async fn device_attempt_owner_binding_poll_throttle_and_atomic_connection() {+ let (service, repo, counts) = service();+ let login = service.start_login(OWNER).await.unwrap();+ assert!(matches!(+ service.poll_login(OTHER, login.attempt_id).await,+ Err(ConnectionError::NotFound)+ ));+ assert!(matches!(+ service.cancel_login(OTHER, login.attempt_id).await,+ Err(ConnectionError::NotFound)+ ));+ assert!(matches!(+ service.poll_login(OWNER, login.attempt_id).await.unwrap(),+ LoginStatus::Pending+ ));+ assert_eq!(counts.polls.load(Ordering::SeqCst), 0);+ ready(&repo, OWNER).await;+ assert!(matches!(+ service.poll_login(OWNER, login.attempt_id).await.unwrap(),+ LoginStatus::Connected+ ));+ assert!(service.status(OWNER).await.unwrap().connected);+ assert!(!service.status(OTHER).await.unwrap().connected);+ assert!(+ repo.owner(OWNER)+ .lock()+ .await+ .attempt+ .as_ref()+ .unwrap()+ .device+ .is_none()+ );+ assert!(matches!(+ service.start_login(OWNER).await,+ Err(ConnectionError::AlreadyConnected)+ ));+}+#[tokio::test]+async fn expired_and_cancelled_attempts_never_exchange_credentials() {+ let (service, repo, counts) = service();+ let login = service.start_login(OWNER).await.unwrap();+ repo.owner(OWNER)+ .lock()+ .await+ .attempt+ .as_mut()+ .unwrap()+ .expires_at = Utc::now() - chrono::Duration::seconds(1);+ assert!(matches!(+ service.poll_login(OWNER, login.attempt_id).await.unwrap(),+ LoginStatus::Expired+ ));+ let second = service.start_login(OWNER).await.unwrap();+ service+ .cancel_login(OWNER, second.attempt_id)+ .await+ .unwrap();+ assert!(matches!(+ service.poll_login(OWNER, second.attempt_id).await,+ Err(ConnectionError::NotFound)+ ));+ assert_eq!(counts.polls.load(Ordering::SeqCst), 0);+}+#[tokio::test]+async fn configuration_requires_visible_environment_and_refresh_is_serialized() {+ let (service, repo, counts) = service();+ let login = service.start_login(OWNER).await.unwrap();+ ready(&repo, OWNER).await;+ service.poll_login(OWNER, login.attempt_id).await.unwrap();+ assert!(+ service+ .resolve(OWNER)+ .await+ .unwrap()+ .environment_id+ .is_none()+ );+ assert!(matches!(+ service.configure(OWNER, "invisible").await,+ Err(ConnectionError::InvalidInput)+ ));+ service.configure(OWNER, "env-test").await.unwrap();+ repo.owner(OWNER)+ .lock()+ .await+ .connection+ .as_mut()+ .unwrap()+ .credentials+ .expires_at = 1;+ let (first, second) = tokio::join!(service.resolve(OWNER), service.resolve(OWNER));+ assert_eq!(first.unwrap().connection_id, second.unwrap().connection_id);+ assert_eq!(counts.refresh.load(Ordering::SeqCst), 1);+ service.disconnect(OWNER).await.unwrap();+ assert!(matches!(+ service.resolve(OWNER).await,+ Err(ConnectionError::NotConnected)+ ));+}+#[tokio::test]+async fn refresh_cannot_rebind_provider_account() {+ let repo = Arc::new(Repo::default());+ repo.owner(OWNER).lock().await.connection = Some(StoredConnection {+ id: Uuid::now_v7(),+ credentials: credentials("account-a", 1),+ environment_id: Some("env-test".into()),+ });+ let service = ConnectionServiceImpl::new(+ repo.clone(),+ Provider(Arc::new(Counts {+ account_changed: true,+ ..Default::default()+ })),+ );+ assert!(matches!(+ service.resolve(OWNER).await,+ Err(ConnectionError::AccountChanged)+ ));+ assert_eq!(+ repo.owner(OWNER)+ .lock()+ .await+ .connection+ .as_ref()+ .unwrap()+ .credentials+ .account_id,+ "account-a"+ );+}++#[tokio::test]+async fn configuration_requires_a_nonempty_visible_environment() {+ let (service, repo, _) = service();+ let login = service.start_login(OWNER).await.unwrap();+ ready(&repo, OWNER).await;+ service.poll_login(OWNER, login.attempt_id).await.unwrap();+ assert!(+ service+ .status(OWNER)+ .await+ .unwrap()+ .environment_id+ .is_none()+ );+ for environment in ["", " ", "unknown", "bad/environment"] {+ assert!(matches!(+ service.configure(OWNER, environment).await,+ Err(ConnectionError::InvalidInput)+ ));+ }+ let status = service.configure(OWNER, "env-test").await.unwrap();+ assert_eq!(status.environment_id.as_deref(), Some("env-test"));+ assert_eq!(+ service+ .resolve(OWNER)+ .await+ .unwrap()+ .environment_id+ .unwrap()+ .as_str(),+ "env-test"+ );+ assert!(service.configure(OWNER, "").await.is_err());+ assert_eq!(+ service+ .status(OWNER)+ .await+ .unwrap()+ .environment_id+ .as_deref(),+ Some("env-test")+ );+}diff --git a/crates/codex_connection/src/lib.rs b/crates/codex_connection/src/lib.rsnew file mode 100644index 0000000000..49c2fd6847--- /dev/null+++ b/crates/codex_connection/src/lib.rs@@ -0,0 +1,7 @@+#![deny(missing_docs)]+//! Owner-bound Codex OAuth connections, durable device login and encrypted credential rotation.++/// Connection policy and independently replaceable ports.+pub mod domain;+/// PostgreSQL storage and KMS envelope encryption.+pub mod outbound;diff --git a/crates/codex_connection/src/outbound.rs b/crates/codex_connection/src/outbound.rsnew file mode 100644index 0000000000..a1beaee50e--- /dev/null+++ b/crates/codex_connection/src/outbound.rs@@ -0,0 +1,6 @@+//! Provider-independent encrypted persistence implementations.++/// AWS KMS envelope encryption for arbitrarily sized OAuth payloads.+pub mod cipher;+/// PostgreSQL owner transaction locking and encrypted state persistence.+pub mod postgres;diff --git a/crates/codex_connection/src/outbound/cipher.rs b/crates/codex_connection/src/outbound/cipher.rsnew file mode 100644index 0000000000..6464b7a4d8--- /dev/null+++ b/crates/codex_connection/src/outbound/cipher.rs@@ -0,0 +1,189 @@+//! AES-256-GCM envelopes with a fresh owner-bound KMS data key per write.++use crate::domain::{ConnectionError, ConnectionState, EncryptedState, StateCipher};+use aes_gcm::{+ Aes256Gcm, Nonce,+ aead::{Aead, AeadCore, KeyInit, OsRng, Payload},+};+use async_trait::async_trait;+use aws_sdk_kms::{primitives::Blob, types::DataKeySpec};+use std::collections::HashMap;+use zeroize::Zeroizing;++const VERSION: u8 = 1;+const PURPOSE: &str = "codex-oauth-connection";+const MAX_PLAINTEXT_BYTES: usize = 512 * 1024;++/// KMS envelope cipher; data keys are never cached between operations.+pub struct EnvelopeCipher {+ keys: Box<dyn DataKeys>,+}+impl EnvelopeCipher {+ /// Create a cipher with a dedicated CMK. Requires GenerateDataKey and Decrypt.+ pub fn new(client: aws_sdk_kms::Client, key_id: String) -> Result<Self, ConnectionError> {+ if key_id.trim().is_empty() {+ return Err(ConnectionError::InvalidInput);+ }+ Ok(Self {+ keys: Box::new(KmsDataKeys { client, key_id }),+ })+ }+}+fn context(owner: &str) -> HashMap<String, String> {+ HashMap::from([+ ("purpose".into(), PURPOSE.into()),+ ("owner".into(), owner.into()),+ ("version".into(), VERSION.to_string()),+ ])+}+fn aad(owner: &str) -> Vec<u8> {+ // JSON encodes boundaries unambiguously even if an owner contains punctuation.+ serde_json::to_vec(&(PURPOSE, VERSION, owner)).expect("string tuple serialization cannot fail")+}+#[async_trait]+impl StateCipher for EnvelopeCipher {+ async fn encrypt(+ &self,+ owner: &str,+ state: &ConnectionState,+ ) -> Result<EncryptedState, ConnectionError> {+ let plaintext =+ Zeroizing::new(serde_json::to_vec(state).map_err(|_| ConnectionError::Encryption)?);+ if plaintext.len() > MAX_PLAINTEXT_BYTES {+ return Err(ConnectionError::Encryption);+ }+ let key = self.keys.generate(context(owner)).await?;+ let cipher =+ Aes256Gcm::new_from_slice(&key.plaintext).map_err(|_| ConnectionError::Encryption)?;+ let nonce = Aes256Gcm::generate_nonce(&mut OsRng);+ let ciphertext = cipher+ .encrypt(+ &nonce,+ Payload {+ msg: &plaintext,+ aad: &aad(owner),+ },+ )+ .map_err(|_| ConnectionError::Encryption)?;+ Ok(EncryptedState {+ version: VERSION,+ ciphertext,+ encrypted_data_key: key.encrypted,+ nonce: nonce.to_vec(),+ kms_key_id: key.key_id,+ })+ }+ async fn decrypt(+ &self,+ owner: &str,+ envelope: &EncryptedState,+ ) -> Result<ConnectionState, ConnectionError> {+ if envelope.version != VERSION+ || envelope.nonce.len() != 12+ || envelope.ciphertext.len() > MAX_PLAINTEXT_BYTES + 16+ || envelope.ciphertext.len() < 16+ || envelope.encrypted_data_key.is_empty()+ || envelope.encrypted_data_key.len() > 16 * 1024+ || envelope.kms_key_id.is_empty()+ {+ return Err(ConnectionError::Encryption);+ }+ let key = self+ .keys+ .decrypt(+ &envelope.kms_key_id,+ &envelope.encrypted_data_key,+ context(owner),+ )+ .await?;+ let cipher = Aes256Gcm::new_from_slice(&key).map_err(|_| ConnectionError::Encryption)?;+ let nonce_bytes: [u8; 12] = envelope+ .nonce+ .as_slice()+ .try_into()+ .map_err(|_| ConnectionError::Encryption)?;+ let plaintext = Zeroizing::new(+ cipher+ .decrypt(+ &Nonce::from(nonce_bytes),+ Payload {+ msg: &envelope.ciphertext,+ aad: &aad(owner),+ },+ )+ .map_err(|_| ConnectionError::Encryption)?,+ );+ serde_json::from_slice(&plaintext).map_err(|_| ConnectionError::Encryption)+ }+}+struct DataKey {+ plaintext: Zeroizing<Vec<u8>>,+ encrypted: Vec<u8>,+ key_id: String,+}+#[async_trait]+trait DataKeys: Send + Sync {+ async fn generate(&self, context: HashMap<String, String>) -> Result<DataKey, ConnectionError>;+ async fn decrypt(+ &self,+ key_id: &str,+ ciphertext: &[u8],+ context: HashMap<String, String>,+ ) -> Result<Zeroizing<Vec<u8>>, ConnectionError>;+}+struct KmsDataKeys {+ client: aws_sdk_kms::Client,+ key_id: String,+}+#[async_trait]+impl DataKeys for KmsDataKeys {+ async fn generate(&self, context: HashMap<String, String>) -> Result<DataKey, ConnectionError> {+ let output = self+ .client+ .generate_data_key()+ .key_id(&self.key_id)+ .key_spec(DataKeySpec::Aes256)+ .set_encryption_context(Some(context))+ .send()+ .await+ .map_err(|_| ConnectionError::Encryption)?;+ Ok(DataKey {+ plaintext: Zeroizing::new(+ output+ .plaintext+ .ok_or(ConnectionError::Encryption)?+ .into_inner(),+ ),+ encrypted: output+ .ciphertext_blob+ .ok_or(ConnectionError::Encryption)?+ .into_inner(),+ key_id: output.key_id.ok_or(ConnectionError::Encryption)?,+ })+ }+ async fn decrypt(+ &self,+ key_id: &str,+ ciphertext: &[u8],+ context: HashMap<String, String>,+ ) -> Result<Zeroizing<Vec<u8>>, ConnectionError> {+ let output = self+ .client+ .decrypt()+ .key_id(key_id)+ .ciphertext_blob(Blob::new(ciphertext))+ .set_encryption_context(Some(context))+ .send()+ .await+ .map_err(|_| ConnectionError::Encryption)?;+ Ok(Zeroizing::new(+ output+ .plaintext+ .ok_or(ConnectionError::Encryption)?+ .into_inner(),+ ))+ }+}++#[cfg(test)]+mod test;diff --git a/crates/codex_connection/src/outbound/cipher/test.rs b/crates/codex_connection/src/outbound/cipher/test.rsnew file mode 100644index 0000000000..4943d4323b--- /dev/null+++ b/crates/codex_connection/src/outbound/cipher/test.rs@@ -0,0 +1,76 @@+use super::*;+use crate::domain::StoredConnection;+use codex_cloud_agents::domain::{Credentials, Secret};++struct Keys;+#[async_trait]+impl DataKeys for Keys {+ async fn generate(&self, context: HashMap<String, String>) -> Result<DataKey, ConnectionError> {+ assert_eq!(context["purpose"], PURPOSE);+ Ok(DataKey {+ plaintext: Zeroizing::new(vec![7; 32]),+ encrypted: vec![3; 48],+ key_id: "test-key".into(),+ })+ }+ async fn decrypt(+ &self,+ _: &str,+ _: &[u8],+ _: HashMap<String, String>,+ ) -> Result<Zeroizing<Vec<u8>>, ConnectionError> {+ Ok(Zeroizing::new(vec![7; 32]))+ }+}+fn state() -> ConnectionState {+ ConnectionState {+ connection: Some(StoredConnection {+ id: uuid::Uuid::now_v7(),+ credentials: Credentials {+ version: 1,+ access_token: Secret::new("large-access-token".repeat(1000)).unwrap(),+ refresh_token: Secret::new("private-refresh-token".into()).unwrap(),+ expires_at: u64::MAX,+ account_id: "account-test".into(),+ },+ environment_id: Some("env-test".into()),+ }),+ attempt: None,+ }+}+#[tokio::test]+async fn large_oauth_payload_roundtrips_with_fresh_nonces_and_no_plaintext_at_rest() {+ let cipher = EnvelopeCipher {+ keys: Box::new(Keys),+ };+ let first = cipher.encrypt("owner-a", &state()).await.unwrap();+ let second = cipher.encrypt("owner-a", &state()).await.unwrap();+ assert_ne!(first.nonce, second.nonce);+ let serialized = serde_json::to_string(&first).unwrap();+ assert!(!serialized.contains("private-refresh-token"));+ let decrypted = cipher.decrypt("owner-a", &first).await.unwrap();+ assert_eq!(+ decrypted+ .connection+ .unwrap()+ .credentials+ .refresh_token+ .expose(),+ "private-refresh-token"+ );+}+#[tokio::test]+async fn owner_swaps_tampering_and_unknown_versions_fail_closed() {+ let cipher = EnvelopeCipher {+ keys: Box::new(Keys),+ };+ let mut encrypted = cipher.encrypt("owner-a", &state()).await.unwrap();+ assert!(cipher.decrypt("owner-b", &encrypted).await.is_err());+ encrypted.ciphertext[0] ^= 1;+ assert!(cipher.decrypt("owner-a", &encrypted).await.is_err());+ encrypted.version = 2;+ assert!(cipher.decrypt("owner-a", &encrypted).await.is_err());+ encrypted.version = 1;+ encrypted.nonce.clear();+ assert!(cipher.decrypt("owner-a", &encrypted).await.is_err());+}diff --git a/crates/codex_connection/src/outbound/postgres.rs b/crates/codex_connection/src/outbound/postgres.rsnew file mode 100644index 0000000000..f96eb7f4ed--- /dev/null+++ b/crates/codex_connection/src/outbound/postgres.rs@@ -0,0 +1,98 @@+//! Owner rows provide a cross-replica lock across token exchange and rotation.++use crate::domain::{+ ConnectionError, ConnectionRepository, ConnectionState, ConnectionTransaction, EncryptedState,+ StateCipher,+};+use async_trait::async_trait;+use sqlx::{PgPool, Postgres, Transaction};+use std::sync::Arc;++/// PostgreSQL storage holds only encrypted state and the owner's identity.+pub struct PostgresRepository {+ pool: PgPool,+ cipher: Arc<dyn StateCipher>,+}+impl PostgresRepository {+ /// Compose the SQL pool and envelope cipher in the application root.+ pub fn new(pool: PgPool, cipher: Arc<dyn StateCipher>) -> Self {+ Self { pool, cipher }+ }+}+struct OwnerTransaction {+ transaction: Transaction<'static, Postgres>,+ owner: String,+ state: ConnectionState,+ cipher: Arc<dyn StateCipher>,+}+#[async_trait]+impl ConnectionRepository for PostgresRepository {+ async fn lock(&self, owner: &str) -> Result<Box<dyn ConnectionTransaction>, ConnectionError> {+ let mut transaction = self+ .pool+ .begin()+ .await+ .map_err(|_| ConnectionError::Storage)?;+ // Insert-on-conflict and SELECT FOR UPDATE both serialize on the same natural key.+ // A disconnected row remains as a durable lock identity, with no stored secrets.+ sqlx::query!(+ "INSERT INTO codex_connections (user_id) VALUES ($1) ON CONFLICT (user_id) DO NOTHING",+ owner+ )+ .execute(&mut *transaction)+ .await+ .map_err(|_| ConnectionError::Storage)?;+ let row = sqlx::query!(+ "SELECT encrypted_state FROM codex_connections WHERE user_id = $1 FOR UPDATE",+ owner+ )+ .fetch_one(&mut *transaction)+ .await+ .map_err(|_| ConnectionError::Storage)?;+ let state = match row.encrypted_state {+ Some(value) => {+ let envelope: EncryptedState =+ serde_json::from_value(value).map_err(|_| ConnectionError::Encryption)?;+ self.cipher.decrypt(owner, &envelope).await?+ }+ None => ConnectionState::default(),+ };+ Ok(Box::new(OwnerTransaction {+ transaction,+ owner: owner.to_owned(),+ state,+ cipher: self.cipher.clone(),+ }))+ }+}+#[async_trait]+impl ConnectionTransaction for OwnerTransaction {+ fn state(&mut self) -> &mut ConnectionState {+ &mut self.state+ }+ async fn commit(self: Box<Self>) -> Result<(), ConnectionError> {+ let Self {+ mut transaction,+ owner,+ state,+ cipher,+ } = *self;+ let encrypted = if state.connection.is_none() && state.attempt.is_none() {+ None+ } else {+ Some(+ serde_json::to_value(cipher.encrypt(&owner, &state).await?)+ .map_err(|_| ConnectionError::Encryption)?,+ )+ };+ sqlx::query!("UPDATE codex_connections SET encrypted_state = $2, updated_at = NOW() WHERE user_id = $1", owner, encrypted)+ .execute(&mut *transaction).await.map_err(|_| ConnectionError::Storage)?;+ transaction+ .commit()+ .await+ .map_err(|_| ConnectionError::Storage)+ }+}++#[cfg(test)]+mod test;diff --git a/crates/codex_connection/src/outbound/postgres/test.rs b/crates/codex_connection/src/outbound/postgres/test.rsnew file mode 100644index 0000000000..1fcad414bd--- /dev/null+++ b/crates/codex_connection/src/outbound/postgres/test.rs@@ -0,0 +1,159 @@+use super::*;+use crate::domain::{LoginAttempt, LoginStatus};+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use std::collections::HashMap;+use tokio::sync::Mutex;+use uuid::Uuid;++// Store opaque handles in PostgreSQL while retaining plaintext solely inside this fake.+#[derive(Default)]+struct Cipher(Mutex<HashMap<Vec<u8>, Vec<u8>>>);+#[async_trait]+impl StateCipher for Cipher {+ async fn encrypt(+ &self,+ _: &str,+ state: &ConnectionState,+ ) -> Result<EncryptedState, ConnectionError> {+ let handle = Uuid::now_v7().as_bytes().to_vec();+ self.0+ .lock()+ .await+ .insert(handle.clone(), serde_json::to_vec(state).unwrap());+ Ok(EncryptedState {+ version: 1,+ ciphertext: handle,+ encrypted_data_key: vec![1],+ nonce: vec![0; 12],+ kms_key_id: "test".into(),+ })+ }+ async fn decrypt(+ &self,+ _: &str,+ envelope: &EncryptedState,+ ) -> Result<ConnectionState, ConnectionError> {+ Ok(serde_json::from_slice(self.0.lock().await.get(&envelope.ciphertext).unwrap()).unwrap())+ }+}+async fn user(pool: &PgPool, id: &str) {+ let uuid = Uuid::now_v7();+ let email = format!("{uuid}@example.com");+ sqlx::query!(r#"WITH created AS (INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1,$2,$2,$3) RETURNING id) INSERT INTO "User" ("id", "email", "macro_user_id") SELECT $4,$2,id FROM created"#,uuid,email,format!("stripe_{uuid}"),id).execute(pool).await.unwrap();+}+fn attempt() -> LoginAttempt {+ LoginAttempt {+ id: Uuid::now_v7(),+ status: LoginStatus::Expired,+ expires_at: chrono::Utc::now(),+ next_poll_at: chrono::Utc::now(),+ interval_seconds: 5,+ device: None,+ }+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn owner_transactions_serialize_and_preserve_isolation(pool: PgPool) {+ user(&pool, "owner-a").await;+ user(&pool, "owner-b").await;+ let repository = PostgresRepository::new(pool.clone(), Arc::new(Cipher::default()));+ let mut first = repository.lock("owner-a").await.unwrap();+ first.state().attempt = Some(attempt());+ let second = repository.lock("owner-a");+ tokio::pin!(second);+ // A different owner remains independently usable while owner A holds its lock.+ let mut other = tokio::time::timeout(+ std::time::Duration::from_secs(2),+ repository.lock("owner-b"),+ )+ .await+ .unwrap()+ .unwrap();+ assert!(other.state().attempt.is_none());+ assert!(+ tokio::time::timeout(std::time::Duration::from_millis(50), &mut second)+ .await+ .is_err()+ );+ let id = first.state().attempt.as_ref().unwrap().id;+ first.commit().await.unwrap();+ let mut second = tokio::time::timeout(std::time::Duration::from_secs(2), second)+ .await+ .unwrap()+ .unwrap();+ assert_eq!(second.state().attempt.as_ref().unwrap().id, id);+ second.state().attempt = None;+ second.commit().await.unwrap();+ let mut fetched = repository.lock("owner-a").await.unwrap();+ assert!(fetched.state().attempt.is_none());+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn dropped_transaction_does_not_publish_state(pool: PgPool) {+ user(&pool, "owner-a").await;+ let repository = PostgresRepository::new(pool, Arc::new(Cipher::default()));+ let mut pending = repository.lock("owner-a").await.unwrap();+ pending.state().attempt = Some(attempt());+ drop(pending);+ let mut fetched = repository.lock("owner-a").await.unwrap();+ assert!(fetched.state().attempt.is_none());+}++struct RotatingProvider(Arc<std::sync::atomic::AtomicUsize>);+impl codex_cloud_agents::domain::OAuth for RotatingProvider {+ async fn begin(&self) -> Result<codex_cloud_agents::domain::DeviceLogin, rootcause::Report> {+ unreachable!()+ }+ async fn poll(+ &self,+ _: &codex_cloud_agents::domain::DeviceLogin,+ ) -> Result<codex_cloud_agents::domain::LoginPoll, rootcause::Report> {+ unreachable!()+ }+ async fn refresh(+ &self,+ _: &codex_cloud_agents::domain::Credentials,+ ) -> Result<codex_cloud_agents::domain::Credentials, rootcause::Report> {+ self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ tokio::task::yield_now().await;+ Ok(credentials(u64::MAX))+ }+ async fn environments(+ &self,+ _: &codex_cloud_agents::domain::Credentials,+ ) -> Result<Vec<codex_cloud_agents::domain::Environment>, rootcause::Report> {+ unreachable!()+ }+}+fn credentials(expires_at: u64) -> codex_cloud_agents::domain::Credentials {+ use codex_cloud_agents::domain::{Credentials, Secret};+ Credentials {+ version: 1,+ access_token: Secret::new("test-access".into()).unwrap(),+ refresh_token: Secret::new("test-refresh".into()).unwrap(),+ expires_at,+ account_id: "account-a".into(),+ }+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn separate_service_replicas_rotate_one_owner_token_once(pool: PgPool) {+ use crate::domain::{ConnectionService, ConnectionServiceImpl, StoredConnection};+ let owner = "macro|[email protected]";+ user(&pool, owner).await;+ let cipher = Arc::new(Cipher::default());+ let repository = Arc::new(PostgresRepository::new(pool.clone(), cipher.clone()));+ let mut initial = repository.lock(owner).await.unwrap();+ initial.state().connection = Some(StoredConnection {+ id: Uuid::now_v7(),+ credentials: credentials(1),+ environment_id: Some("env-test".into()),+ });+ initial.commit().await.unwrap();+ let rotations = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let first = ConnectionServiceImpl::new(repository, RotatingProvider(rotations.clone()));+ let second = ConnectionServiceImpl::new(+ Arc::new(PostgresRepository::new(pool, cipher)),+ RotatingProvider(rotations.clone()),+ );+ let (one, two) = tokio::join!(first.resolve(owner), second.resolve(owner));+ assert_eq!(one.unwrap().connection_id, two.unwrap().connection_id);+ assert_eq!(rotations.load(std::sync::atomic::Ordering::SeqCst), 1);+}diff --git a/crates/macro_db_client/migrations/20260915231628_codex_connections.sql b/crates/macro_db_client/migrations/20260915231628_codex_connections.sqlnew file mode 100644index 0000000000..2c9eef66e6--- /dev/null+++ b/crates/macro_db_client/migrations/20260915231628_codex_connections.sql@@ -0,0 +1,11 @@+-- One encrypted credential + device-attempt payload per Macro user.+-- Row locks serialize provider refresh/exchange across replicas. Keeping the row on+-- disconnect preserves the lock identity; only the ciphertext is cleared.+CREATE TABLE codex_connections (+ user_id TEXT PRIMARY KEY REFERENCES "User"("id") ON DELETE CASCADE,+ encrypted_state JSONB,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ CONSTRAINT codex_connections_envelope_object CHECK (+ encrypted_state IS NULL OR jsonb_typeof(encrypted_state) = 'object'+ )+);diff --git a/crates/macro_db_client/migrations/20260915231629_codex_cloud_session_journal.sql b/crates/macro_db_client/migrations/20260915231629_codex_cloud_session_journal.sqlnew file mode 100644index 0000000000..f330354be5--- /dev/null+++ b/crates/macro_db_client/migrations/20260915231629_codex_cloud_session_journal.sql@@ -0,0 +1,5 @@+CREATE TABLE codex_cloud_sessions (+ agent_session_id uuid PRIMARY KEY REFERENCES agent_session(id) ON DELETE CASCADE,+ acp_session_id text NOT NULL,+ state jsonb NOT NULL+);diff --git a/crates/macro_db_client/migrations/20260915231630_codex_cloud_native_inputs.sql b/crates/macro_db_client/migrations/20260915231630_codex_cloud_native_inputs.sqlnew file mode 100644index 0000000000..0285adf95e--- /dev/null+++ b/crates/macro_db_client/migrations/20260915231630_codex_cloud_native_inputs.sql@@ -0,0 +1,10 @@+-- Native Codex observations, captured before interpretation in local session order.+-- Existing codex_cloud_sessions remains the metadata and task/turn receipt record.+-- Old projected history is deliberately not promoted into native input history.+CREATE TABLE codex_journal_input (+ agent_session_id UUID NOT NULL REFERENCES agent_session(id) ON DELETE CASCADE,+ sequence BIGINT NOT NULL CHECK (sequence > 0),+ turn_id TEXT,+ input JSONB NOT NULL,+ PRIMARY KEY (agent_session_id, sequence)+);diff --git a/crates/workspace-hack/Cargo.toml b/crates/workspace-hack/Cargo.tomlindex a28a1c70dd..61dc98cc23 100644--- a/crates/workspace-hack/Cargo.toml+++ b/crates/workspace-hack/Cargo.toml@@ -73,6 +73,7 @@ hyper-rustls-adf3d7031871b0af = { package = "hyper-rustls", version = "0.24", dehyper-util = { version = "0.1", features = ["client-legacy", "client-proxy", "http1", "http2", "server", "service"] }idna = { version = "1" }indexmap = { version = "2", features = ["serde"] }+insta = { version = "1", features = ["glob", "json"] }itertools = { version = "0.13" }lazy_static = { version = "1", default-features = false, features = ["spin_no_std"] }libc = { version = "0.2", features = ["extra_traits"] }@@ -207,6 +208,7 @@ hyper-rustls-adf3d7031871b0af = { package = "hyper-rustls", version = "0.24", dehyper-util = { version = "0.1", features = ["client-legacy", "client-proxy", "http1", "http2", "server", "service"] }idna = { version = "1" }indexmap = { version = "2", features = ["serde"] }+insta = { version = "1", features = ["glob", "json"] }itertools = { version = "0.13" }lazy_static = { version = "1", default-features = false, features = ["spin_no_std"] }libc = { version = "0.2", features = ["extra_traits"] }diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex e5e4d5a38a..8e5709e1bf 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -54,7 +54,7 @@ An accent **Create agent** button stays fixed to the right of the strip.It closes the session composer and opens the new-agent form at`/app/settings/agents?createAgent=true`; it does not create a session.Recents are remembered per user on this device. With no history, **Macro**-`@macro` (the default) and **Cursor** `@cursor` lead, followed by saved agents+`@macro` (the default), **Cursor** `@cursor`, and **Codex** `@codex` lead, followed by saved agentsthe caller can start: their own, team-shared personas, and selected-channelpersonas they can `@` mention.Without a connected Cursor API key, Cursor is a **Connect Cursor** button:@@ -62,6 +62,24 @@ clicking it closes the composer and opens Settings → Harness without creatinga session. It is keyboard-accessible; arrow navigation focuses it withoutactivating it. Connected Cursor remains a selectable agent. Setup navigationis disabled while a session is being created or its setup is being retried.+Codex composer choices and its Settings → Harness section require both+`enable-chat-v3-agents` and `enable-codex-agents`.+Codex shows **Set up Codex** until ChatGPT is connected and a cloud environment+is saved in Settings → Harness. New sessions use the saved environment and+always start from `main`. The composer hides model overrides for+Codex because this harness does not expose model selection. Codex assistant+text appears when the provider supplies a completed message or final snapshot.+Incomplete text fragments are withheld; tool activity and thinking still update+during the turn. Verified Codex PR associations appear as a completed **Found+pull request** activity containing the PR URL, alongside the clickable+PR chip. This reports an existing PR; it does not publish one. Opening a detached+session reads saved history; sending a message reattaches the runtime.+Codex file citations render as inline code with the path and+line range, such as `.gitkeep:1` or `src/main.rs:2-12`; they do not link to a local+file or a guessed remote revision. A recorded two-turn Codex conversation is+covered by ACP/fold snapshots and checked with the production Markdown renderer. Setup navigation,+selection, and the create/prompt payloads were verified in Chromium with mocked+app navigation and backend state; no remote session was created by that check.Each row shows its `@handle` beneath the name. There are no coding tags;default models appear only in the prompt's model selector.There is no search field or browse/expand control. Left/Right change the selecteddiff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex 92b100f177..97778aa7fc 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -72,7 +72,7 @@ event is created — no invitation goes out from the initial request. It cannotemail at all. The bot's prompt carries the current date and time in the mentioning user'sown time zone (their primary calendar's), so it resolves relative times ("tomorrow at 4","EOD") without asking; when no calendar is connected the prompt falls back to UTC and the-bot asks before scheduling a specific clock time. `@macro-new` / `@coder` / `@cursor` open+bot asks before scheduling a specific clock time. `@macro-new` / `@coder` / `@cursor` / `@codex` openan agent session; follow-up`@` mentions of that bot in the same thread route to it.The reply renders a Magic Chip: a rounded card of constant height that is present@@ -87,6 +87,16 @@ cropped at the chip's height with a fade at its foot; clicking it expands it inclicking again collapses it. Before anything is there to expand, clicking the area alsoopens the session.+`@codex` requires both `enable-chat-v3-agents` and `enable-codex-agents`.+It appears when the mentioning user has connected ChatGPT and saved a+cloud environment in Settings → Harness. New sessions use that environment on+`main`; there is no automatic repository selection. Follow-up mentions continue the same agent session. When+the provider URL arrives, the session header offers **Open in Codex**. Codex+assistant text appears as complete messages while tool activity and thinking+can continue updating during the turn. Mention+eligibility is covered by component/query tests; the channel interaction requires+a configured backend for end-to-end verification.+Cursor sessions choose a repository from the mentioning user's linked GitHub Appinstallations on their first prompt. A session without a repository can still useMacro and connected MCP tools, but cannot use the Git proxy. For a PR smoke test,@@ -103,8 +113,9 @@ service at `/mcp/internal` on its egress listener, separately from workspace MCPCursor, sandbox, and macrod sessions receive session-scoped credentials; themodel supplies only the URL. The tool records the link, not the GitHub PR itself.The shared Macro system instructions ask agents to register PRs when-`macro_internal.set_pull_request` is available. The instruction is not prepended-to individual user messages. Cursor+`macro_internal.set_pull_request` is available. Macro Internal MCP also advertises+this guidance in its server instructions. It is not prepended to individual user+messages. Cursorenables automatic PR creation when a repository is selected. Its returned URLis also recorded becauseautomatic creation can finish after the agent stops. Repeated registration is@@ -114,11 +125,19 @@ chips reload the current link; reconnecting also refreshes it. Multiple chipsfor the same session share its metadata, and loading it leaves the surroundingeditor visible.-When Cursor opens a pull request, the chip header shows its GitHub link as soon-as the run reports it, including after restoring a session. The link remains+When Cursor or Codex reports a pull request, the chip header shows its GitHub+link. Codex links can arrive after the assistant finishes; a session-update event+refreshes mounted chips without a new conversation message. Codex checks provider+PR metadata every 20 seconds while attached. Viewing a disconnected Codex session+reads saved history; sending a message reattaches the runtime. Refresh requires its original+ChatGPT connection to remain connected. The link remainsusable while the webhook mapping is loading or absent, then becomes a Macro PRentity link once synced. On narrow chips, long PR names truncate with an-ellipsis; hover the link to inspect the full title.+ellipsis; hover the link to inspect the full title. Codex delayed-link discovery,+duplicate and changed metadata updates, and opening the exact PR URL were verified+in Chromium with mocked session snapshots and realtime invalidation. This UI check+does not prove live provider discovery; backend tests separately cover delayed+provider metadata.When the agent stops to ask a question the question takes the area in the passage'splace, cropped and expandable the same way: the prompt, then what is asked - a form'sdiff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex 082868c59b..f792d7c1c2 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -418,9 +418,27 @@ a retryable error without hiding the other harnesses. Editing preserves a savedis no longer offered and labels it `saved, unavailable`. A macrod with no responding runtimecan remain loading until the 10-second discovery timeout; use Retry after reconnecting it.-`Harness` configures Cursor and paired macrod runtimes. Cursor's default-model picker uses+`Harness` configures Cursor, Codex, and paired macrod runtimes. Cursor's default-model picker usesthe same live model discovery and retains its existing save action.+The Codex row uses the OpenAI logo and the same icon, button, and status styling+as Cursor. Under **Codex**, choose **Connect with ChatGPT**, copy the displayed device code,+and use **Continue to ChatGPT** to finish sign-in in the provider tab. The Macro+page displays pending, expired, failed, and retryable error states; **Cancel+sign-in** cancels the attempt. After connecting, choose a **Cloud environment**+and click **Save Codex settings** before using Codex. Options show their+repositories. New sessions always use the `main` branch; there is no branch+picker or automatic repository selection. Changed selections display **Unsaved+changes** until the server confirms them. The save button is disabled until an+environment is selected, and when it matches the saved environment.+These choices apply to new sessions. **Disconnect** in the Codex row (accessible+name **Disconnect ChatGPT**) removes the connection. The UI never asks for an+OAuth token.++The Codex section and its auth/config requests were exercised in Chromium with+mocked backend responses on 2026-09-15. Provider login and a full deployed Macro+session were not exercised by that UI check.+## NotificationsToast regions are labeled `Notifications (alt+T)`; five empty live regions always exist indiff --git a/infra/packages/shared/src/index.ts b/infra/packages/shared/src/index.tsindex 20e0c1d133..3b2ea74b5f 100644--- a/infra/packages/shared/src/index.ts+++ b/infra/packages/shared/src/index.ts@@ -11,6 +11,9 @@ export const project = pulumi.getProject();export const stack = pulumi.getStack();+/** Stable alias shared by auth and the harness without a stack cycle. */+export const CODEX_OAUTH_KMS_ALIAS = `alias/authentication-service-codex-oauth-${stack}`;+export const config = new pulumi.Config();export const MACRO_ORG_NAME = 'macro-inc';diff --git a/infra/stacks/agent-harness-service/index.ts b/infra/stacks/agent-harness-service/index.tsindex a537590c61..9cef7be9a4 100644--- a/infra/stacks/agent-harness-service/index.ts+++ b/infra/stacks/agent-harness-service/index.ts@@ -2,6 +2,7 @@ import * as aws from '@pulumi/aws';import * as pulumi from '@pulumi/pulumi';import {config,+ CODEX_OAUTH_KMS_ALIAS,getAiToolsInfra,getMacroApiToken,getServiceUrl,@@ -86,6 +87,10 @@ const service = new AgentHarnessService(`agent-harness-service-${stack}`, {queueArns: [...aiTools.queueArns],bucketArns: [...aiTools.bucketArns],containerEnvVars: [+ {+ name: 'CODEX_OAUTH_KMS_KEY_ID',+ value: CODEX_OAUTH_KMS_ALIAS,+ },{name: 'ENVIRONMENT',value: stack,diff --git a/infra/stacks/authentication-service/index.ts b/infra/stacks/authentication-service/index.tsindex a62ac80991..4d87f70a02 100644--- a/infra/stacks/authentication-service/index.ts+++ b/infra/stacks/authentication-service/index.ts@@ -201,3 +201,4 @@ new UserLinkCleanupHandler('user-link-cleanup-handler', {});export const authenticationServiceUrl = pulumi.interpolate`${service.domain}`;+export const codexOauthKmsKeyArn = service.codexOauthKmsKeyArn;diff --git a/infra/stacks/authentication-service/service.ts b/infra/stacks/authentication-service/service.tsindex b04d617de1..1a42e0696b 100644--- a/infra/stacks/authentication-service/service.ts+++ b/infra/stacks/authentication-service/service.ts@@ -14,6 +14,7 @@ import { EcrImage } from '../../packages/service';import {BASE_DOMAIN,CLOUD_TRAIL_SNS_TOPIC_ARN,+ CODEX_OAUTH_KMS_ALIAS,DopplerEcsEnvironment,getGatewayAlb,GatewayService,@@ -35,6 +36,7 @@ const MICROSOFT_TOKEN_KMS_ACTIONS = ['kms:GenerateDataKey', 'kms:Decrypt'];// nothing here needs Decrypt.const CURSOR_API_KEY_KMS_WRITE_ACTIONS = ['kms:Encrypt'];const CURSOR_API_KEY_KMS_READ_ACTIONS = ['kms:Decrypt'];+const CODEX_OAUTH_KMS_ACTIONS = ['kms:GenerateDataKey', 'kms:Decrypt'];export const SERVICE_DOMAIN_NAME = `auth-service${stack === 'prod' ? '' : `-${stack}`@@ -79,6 +81,8 @@ export class AuthenticationService extends pulumi.ComponentResource {* needs it to grant itself Decrypt, and the service reads it as* `CURSOR_API_KEY_KMS_KEY_ID`. */public cursorApiKeyKmsKeyArn: pulumi.Output<string>;+ /** Dedicated envelope-encryption key for ChatGPT account connections. */+ public codexOauthKmsKeyArn: pulumi.Output<string>;constructor(name: string,@@ -356,6 +360,63 @@ export class AuthenticationService extends pulumi.ComponentResource {// what the service reads as CURSOR_API_KEY_KMS_KEY_ID.this.cursorApiKeyKmsKeyArn = cursorApiKeyKmsKey.arn;+ // Both services refresh OAuth credentials, so both need envelope read/write.+ // Direct role grants keep the harness independent of this stack's outputs.+ const codexOauthKmsKey = new aws.kms.Key(+ `${BASE_NAME}-codex-oauth-key`,+ {+ description: `ChatGPT OAuth connection encryption key for ${stack}`,+ deletionWindowInDays: cursorApiKeyKmsDeletionWindowInDays,+ enableKeyRotation: true,+ policy: aws.iam.getPolicyDocumentOutput({+ statements: [+ {+ sid: 'AllowAccountKeyAdministration',+ effect: 'Allow',+ principals: [{ type: 'AWS', identifiers: [accountRootArn] }],+ actions: [+ 'kms:CancelKeyDeletion',+ 'kms:Create*',+ 'kms:Delete*',+ 'kms:Describe*',+ 'kms:Disable*',+ 'kms:Enable*',+ 'kms:Get*',+ 'kms:List*',+ 'kms:Put*',+ 'kms:Revoke*',+ 'kms:ScheduleKeyDeletion',+ 'kms:TagResource',+ 'kms:UntagResource',+ 'kms:Update*',+ ],+ resources: ['*'],+ },+ {+ sid: 'AllowCodexConnectionEnvelopeEncryption',+ effect: 'Allow',+ principals: [+ {+ type: 'AWS',+ identifiers: [this.role.arn, ...cursorApiKeyReaderRoleArns],+ },+ ],+ actions: CODEX_OAUTH_KMS_ACTIONS,+ resources: ['*'],+ },+ ],+ }).json,+ tags: this.tags,+ },+ { parent: this, protect: stack === 'prod' }+ );+ new aws.kms.Alias(+ `${BASE_NAME}-codex-oauth-key-alias`,+ { name: CODEX_OAUTH_KMS_ALIAS, targetKeyId: codexOauthKmsKey.keyId },+ { parent: this }+ );+ this.codexOauthKmsKeyArn = codexOauthKmsKey.arn;+// ecr imageconst image = new EcrImage(`${BASE_NAME}-ecr-image-${stack}`,@@ -478,6 +539,10 @@ export class AuthenticationService extends pulumi.ComponentResource {name: 'CURSOR_API_KEY_KMS_KEY_ID',value: cursorApiKeyKmsKey.arn,},+ {+ name: 'CODEX_OAUTH_KMS_KEY_ID',+ value: codexOauthKmsKey.arn,+ },...(containerEnvVars ?? []),],secrets: [...dopplerEcsEnvironment.containerSecrets],diff --git a/packages/sdk/generated/auth/index.ts b/packages/sdk/generated/auth/index.tsindex e94a27a379..47dd41dee1 100644--- a/packages/sdk/generated/auth/index.ts+++ b/packages/sdk/generated/auth/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AbGroup, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, ClientOptions, CreateAccountMergeRequest, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreateUserData, CreateUserError, CreateUserErrors, CreateUserRequest, CreateUserResponse, CreateUserResponses, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestRef, GithubPullRequestStatus, GmailLinkStatusResponse, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, LinkShare, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StripeSessionResponse, Team, TeamInviteDetails, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';+export type { AbGroup, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreateUserData, CreateUserError, CreateUserErrors, CreateUserRequest, CreateUserResponse, CreateUserResponses, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestRef, GithubPullRequestStatus, GmailLinkStatusResponse, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StripeSessionResponse, Team, TeamInviteDetails, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';diff --git a/packages/sdk/generated/auth/sdk.gen.ts b/packages/sdk/generated/auth/sdk.gen.tsindex 773b0340ee..158cb4c5b1 100644--- a/packages/sdk/generated/auth/sdk.gen.ts+++ b/packages/sdk/generated/auth/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamResponses, CreateUserData, CreateUserErrors, CreateUserResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetTeamData, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';+import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamResponses, CreateUserData, CreateUserErrors, CreateUserResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetTeamData, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -57,6 +57,41 @@ export class Sdk extends HeyApiClient {Sdk.__registry.set(this, args?.key);}+ public disconnectCodex<ThrowOnError extends boolean = false>(options?: Options<DisconnectCodexData, ThrowOnError>): RequestResult<DisconnectCodexResponses, unknown, ThrowOnError> {+ return (options?.client ?? this.client).delete<DisconnectCodexResponses, unknown, ThrowOnError>({ url: '/codex', ...options });+ }++ public getCodexConnection<ThrowOnError extends boolean = false>(options?: Options<GetCodexConnectionData, ThrowOnError>): RequestResult<GetCodexConnectionResponses, unknown, ThrowOnError> {+ return (options?.client ?? this.client).get<GetCodexConnectionResponses, unknown, ThrowOnError>({ url: '/codex', ...options });+ }++ public configureCodex<ThrowOnError extends boolean = false>(options: Options<ConfigureCodexData, ThrowOnError>): RequestResult<ConfigureCodexResponses, unknown, ThrowOnError> {+ return (options.client ?? this.client).put<ConfigureCodexResponses, unknown, ThrowOnError>({+ url: '/codex/config',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ public listCodexEnvironments<ThrowOnError extends boolean = false>(options?: Options<ListCodexEnvironmentsData, ThrowOnError>): RequestResult<ListCodexEnvironmentsResponses, unknown, ThrowOnError> {+ return (options?.client ?? this.client).get<ListCodexEnvironmentsResponses, unknown, ThrowOnError>({ url: '/codex/environments', ...options });+ }++ public startCodexLogin<ThrowOnError extends boolean = false>(options?: Options<StartCodexLoginData, ThrowOnError>): RequestResult<StartCodexLoginResponses, unknown, ThrowOnError> {+ return (options?.client ?? this.client).post<StartCodexLoginResponses, unknown, ThrowOnError>({ url: '/codex/login', ...options });+ }++ public cancelCodexLogin<ThrowOnError extends boolean = false>(options: Options<CancelCodexLoginData, ThrowOnError>): RequestResult<CancelCodexLoginResponses, unknown, ThrowOnError> {+ return (options.client ?? this.client).delete<CancelCodexLoginResponses, unknown, ThrowOnError>({ url: '/codex/login/{attempt_id}', ...options });+ }++ public pollCodexLogin<ThrowOnError extends boolean = false>(options: Options<PollCodexLoginData, ThrowOnError>): RequestResult<PollCodexLoginResponses, unknown, ThrowOnError> {+ return (options.client ?? this.client).get<PollCodexLoginResponses, unknown, ThrowOnError>({ url: '/codex/login/{attempt_id}', ...options });+ }+/*** Forgets the caller's Cursor API key.*diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.tsindex a1f8cd4f17..53b0631419 100644--- a/packages/sdk/generated/auth/types.gen.ts+++ b/packages/sdk/generated/auth/types.gen.ts@@ -29,6 +29,115 @@ export type CheckoutSessionMetadata = {gaClientId?: string | null;};+/**+ * Explicit remote environment for future Codex sessions.+ */+export type CodexConfigRequest = {+ /**+ * An environment currently visible to this account.+ */+ environmentId: string;+};++/**+ * Safe connection metadata; no secret or masked token is returned.+ */+export type CodexConnectionStatus = {+ /**+ * Connected provider account identifier.+ */+ accountId?: string | null;+ /**+ * Whether the user has completed provider authorization.+ */+ connected: boolean;+ /**+ * Reserved until provider-verified email metadata is available.+ */+ email?: string | null;+ /**+ * Explicitly selected remote environment.+ */+ environmentId?: string | null;+};++/**+ * A cloud environment visible to the connected provider account.+ */+export type CodexEnvironment = {+ /**+ * Provider environment identity.+ */+ id: string;+ /**+ * Human-readable provider label.+ */+ label?: string | null;+ /**+ * Ordered safe repository identities from Codex.+ */+ repositories: Array<CodexEnvironmentRepository>;+};++/**+ * Safe repository metadata available to the connected Codex account.+ */+export type CodexEnvironmentRepository = {+ /**+ * Credential-free HTTPS clone URL.+ */+ cloneUrl: string;+ /**+ * Provider default branch.+ */+ defaultBranch: string;+ /**+ * Owner/repository identity.+ */+ fullName: string;+};++/**+ * Outcome of polling one attempt.+ */+export type CodexLoginPoll = {+ /**+ * Current attempt state.+ */+ status: CodexLoginState;+};++/**+ * Expiring browser authorization instructions.+ */+export type CodexLoginStart = {+ /**+ * Owner-bound attempt UUID.+ */+ attemptId: string;+ /**+ * UTC attempt deadline.+ */+ expiresAt: string;+ /**+ * Minimum browser polling interval.+ */+ pollIntervalSeconds: number;+ /**+ * Short expiring user code, not an API credential.+ */+ userCode: string;+ /**+ * Official provider verification URL.+ */+ verificationUrl: string;+};++/**+ * Device authorization state visible to its initiating user.+ */+export type CodexLoginState = 'pending' | 'connected' | 'expired' | 'failed';+export type CreateAccountMergeRequest = {/*** The email address to generate the merge link for.@@ -1029,6 +1138,101 @@ export type UserTokensResponse = {refresh_token: string;};+export type DisconnectCodexData = {+ body?: never;+ path?: never;+ query?: never;+ url: '/codex';+};++export type DisconnectCodexResponses = {+ 204: void;+};++export type DisconnectCodexResponse = DisconnectCodexResponses[keyof DisconnectCodexResponses];++export type GetCodexConnectionData = {+ body?: never;+ path?: never;+ query?: never;+ url: '/codex';+};++export type GetCodexConnectionResponses = {+ 200: CodexConnectionStatus;+};++export type GetCodexConnectionResponse = GetCodexConnectionResponses[keyof GetCodexConnectionResponses];++export type ConfigureCodexData = {+ body: CodexConfigRequest;+ path?: never;+ query?: never;+ url: '/codex/config';+};++export type ConfigureCodexResponses = {+ 200: CodexConnectionStatus;+};++export type ConfigureCodexResponse = ConfigureCodexResponses[keyof ConfigureCodexResponses];++export type ListCodexEnvironmentsData = {+ body?: never;+ path?: never;+ query?: never;+ url: '/codex/environments';+};++export type ListCodexEnvironmentsResponses = {+ 200: Array<CodexEnvironment>;+};++export type ListCodexEnvironmentsResponse = ListCodexEnvironmentsResponses[keyof ListCodexEnvironmentsResponses];++export type StartCodexLoginData = {+ body?: never;+ path?: never;+ query?: never;+ url: '/codex/login';+};++export type StartCodexLoginResponses = {+ 200: CodexLoginStart;+};++export type StartCodexLoginResponse = StartCodexLoginResponses[keyof StartCodexLoginResponses];++export type CancelCodexLoginData = {+ body?: never;+ path: {+ attempt_id: string;+ };+ query?: never;+ url: '/codex/login/{attempt_id}';+};++export type CancelCodexLoginResponses = {+ 204: void;+};++export type CancelCodexLoginResponse = CancelCodexLoginResponses[keyof CancelCodexLoginResponses];++export type PollCodexLoginData = {+ body?: never;+ path: {+ attempt_id: string;+ };+ query?: never;+ url: '/codex/login/{attempt_id}';+};++export type PollCodexLoginResponses = {+ 200: CodexLoginPoll;+};++export type PollCodexLoginResponse = PollCodexLoginResponses[keyof PollCodexLoginResponses];+export type DeleteCursorApiKeyData = {body?: never;path?: never;diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.jsonindex 20a615dc5d..97a7d9e24f 100644--- a/packages/sdk/specs/auth.json+++ b/packages/sdk/specs/auth.json@@ -10,6 +10,149 @@"version": "0.1.0"},"paths": {+ "/codex": {+ "get": {+ "tags": ["crate::api::codex"],+ "operationId": "get_codex_connection",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodexConnectionStatus"+ }+ }+ }+ }+ }+ },+ "delete": {+ "tags": ["crate::api::codex"],+ "operationId": "disconnect_codex",+ "responses": {+ "204": {+ "description": ""+ }+ }+ }+ },+ "/codex/config": {+ "put": {+ "tags": ["crate::api::codex"],+ "operationId": "configure_codex",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodexConfigRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodexConnectionStatus"+ }+ }+ }+ }+ }+ }+ },+ "/codex/environments": {+ "get": {+ "tags": ["crate::api::codex"],+ "operationId": "list_codex_environments",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CodexEnvironment"+ }+ }+ }+ }+ }+ }+ }+ },+ "/codex/login": {+ "post": {+ "tags": ["crate::api::codex"],+ "operationId": "start_codex_login",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodexLoginStart"+ }+ }+ }+ }+ }+ }+ },+ "/codex/login/{attempt_id}": {+ "get": {+ "tags": ["crate::api::codex"],+ "operationId": "poll_codex_login",+ "parameters": [+ {+ "name": "attempt_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodexLoginPoll"+ }+ }+ }+ }+ }+ },+ "delete": {+ "tags": ["crate::api::codex"],+ "operationId": "cancel_codex_login",+ "parameters": [+ {+ "name": "attempt_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "204": {+ "description": ""+ }+ }+ }+ },"/cursor-api-key": {"get": {"tags": ["crate::api::cursor_api_key::get_cursor_api_key"],@@ -3832,6 +3975,135 @@}}},+ "CodexConfigRequest": {+ "type": "object",+ "description": "Explicit remote environment for future Codex sessions.",+ "required": ["environmentId"],+ "properties": {+ "environmentId": {+ "type": "string",+ "description": "An environment currently visible to this account."+ }+ },+ "additionalProperties": false+ },+ "CodexConnectionStatus": {+ "type": "object",+ "description": "Safe connection metadata; no secret or masked token is returned.",+ "required": ["connected"],+ "properties": {+ "accountId": {+ "type": ["string", "null"],+ "description": "Connected provider account identifier."+ },+ "connected": {+ "type": "boolean",+ "description": "Whether the user has completed provider authorization."+ },+ "email": {+ "type": ["string", "null"],+ "description": "Reserved until provider-verified email metadata is available."+ },+ "environmentId": {+ "type": ["string", "null"],+ "description": "Explicitly selected remote environment."+ }+ }+ },+ "CodexEnvironment": {+ "type": "object",+ "description": "A cloud environment visible to the connected provider account.",+ "required": ["id", "repositories"],+ "properties": {+ "id": {+ "type": "string",+ "description": "Provider environment identity."+ },+ "label": {+ "type": ["string", "null"],+ "description": "Human-readable provider label."+ },+ "repositories": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CodexEnvironmentRepository"+ },+ "description": "Ordered safe repository identities from Codex."+ }+ }+ },+ "CodexEnvironmentRepository": {+ "type": "object",+ "description": "Safe repository metadata available to the connected Codex account.",+ "required": ["fullName", "cloneUrl", "defaultBranch"],+ "properties": {+ "cloneUrl": {+ "type": "string",+ "description": "Credential-free HTTPS clone URL."+ },+ "defaultBranch": {+ "type": "string",+ "description": "Provider default branch."+ },+ "fullName": {+ "type": "string",+ "description": "Owner/repository identity."+ }+ }+ },+ "CodexLoginPoll": {+ "type": "object",+ "description": "Outcome of polling one attempt.",+ "required": ["status"],+ "properties": {+ "status": {+ "$ref": "#/components/schemas/CodexLoginState",+ "description": "Current attempt state."+ }+ }+ },+ "CodexLoginStart": {+ "type": "object",+ "description": "Expiring browser authorization instructions.",+ "required": [+ "attemptId",+ "verificationUrl",+ "userCode",+ "expiresAt",+ "pollIntervalSeconds"+ ],+ "properties": {+ "attemptId": {+ "type": "string",+ "format": "uuid",+ "description": "Owner-bound attempt UUID."+ },+ "expiresAt": {+ "type": "string",+ "format": "date-time",+ "description": "UTC attempt deadline."+ },+ "pollIntervalSeconds": {+ "type": "integer",+ "format": "int64",+ "description": "Minimum browser polling interval.",+ "minimum": 0+ },+ "userCode": {+ "type": "string",+ "description": "Short expiring user code, not an API credential."+ },+ "verificationUrl": {+ "type": "string",+ "description": "Official provider verification URL."+ }+ }+ },+ "CodexLoginState": {+ "type": "string",+ "description": "Device authorization state visible to its initiating user.",+ "enum": ["pending", "connected", "expired", "failed"]+ },"CreateAccountMergeRequest": {"type": "object","required": ["email"],diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex 6f6dc128ec..ebeeeea585 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -33,8 +33,10 @@ export const agentHarnessBacklog =export const authExcluded = ['appleLogin',+ 'cancelCodexLogin','checkGithubLinkStatus','checkGmailLinkStatus',+ 'configureCodex','createCheckoutSessionV2','createInProgressLink','createMergeRequest',@@ -46,8 +48,10 @@ export const authExcluded = ['deleteTeam','deleteTeamInviteHandler','deleteUser',+ 'disconnectCodex','enrichGithubPullRequests','generateEmailLink',+ 'getCodexConnection','getCursorApiKey','getLegacyUserPermissions','getPermissions',@@ -66,6 +70,7 @@ export const authExcluded = ['initOutlookLink','inviteToTeam','joinTeam',+ 'listCodexEnvironments','listCursorModels','logout','oauth2Callback',@@ -78,6 +83,7 @@ export const authExcluded = ['patchUserGroup','patchUserOnboarding','patchUserTutorial',+ 'pollCodexLogin','postProfilePictures','putCursorApiKey','putCursorDefaultModel',@@ -92,6 +98,7 @@ export const authExcluded = ['sessionCreation','sessionLogin','ssoLogin',+ 'startCodexLogin','toggleTeamAutoJoinDomain','toggleTeamNonAdminInvites','verifyEmailLink',diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.tomlindex 57296f5153..ebdfe98b19 100644--- a/services/agent_harness_service/Cargo.toml+++ b/services/agent_harness_service/Cargo.toml@@ -17,6 +17,8 @@ name = "agent_harness_service_doppler_config"path = "src/doppler_config.rs"[dependencies]+codex_cloud_agents = { path = "../../crates/codex_cloud_agents" }+codex_connection = { path = "../../crates/codex_connection" }agent_egress = { path = "../../crates/agent_egress" }agent_fold = { path = "../../crates/agent_fold" }agent_harness = { path = "../../crates/agent_harness" }diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rsindex 1f7b3260b2..0120d04e1b 100644--- a/services/agent_harness_service/src/config.rs+++ b/services/agent_harness_service/src/config.rs@@ -35,6 +35,11 @@ macro_env_var::env_vars!(pub struct PipedreamProjectId;);+macro_env_var::maybe_env_vars!(+ /// Dedicated KMS key for encrypted per-owner Codex OAuth state.+ pub struct CodexOauthKmsKeyId;+);+/// The Pipedream project environment matching this deployment: production in/// prd, development everywhere else.fn default_pipedream_environment() -> String {@@ -51,6 +56,8 @@ pub struct Config {/// The environment we are in.#[macro_config_default(Environment::new_or_prod())]pub environment: Environment,+ /// Dedicated OAuth encryption key; absent deployments keep Codex unavailable.+ pub codex_oauth_kms_key_id: CodexOauthKmsKeyId,/// Comma-separated Kafka bootstrap servers.pub kafka_brokers: KafkaBrokers,/// MacroDB connection string; `agent_sessions` lives here.@@ -164,6 +171,17 @@ pub struct Config {}impl Config {+ /// Resolve the optional key from Doppler or the deployment-injected environment.+ pub fn codex_oauth_kms_key_id(&self) -> Option<String> {+ self.codex_oauth_kms_key_id+ .value()+ .map(str::to_owned)+ .or_else(|| {+ CodexOauthKmsKeyId::new().and_then(|value| value.value().map(str::to_owned))+ })+ .filter(|value| !value.trim().is_empty())+ }+/// Load the configuration from the environment.pub fn from_env() -> anyhow::Result<Self> {macro_config::ConfigLoader::load::<Config>()diff --git a/services/agent_harness_service/src/internal_mcp.rs b/services/agent_harness_service/src/internal_mcp.rsindex 53acb9f471..10f88bc73f 100644--- a/services/agent_harness_service/src/internal_mcp.rs+++ b/services/agent_harness_service/src/internal_mcp.rs@@ -81,6 +81,9 @@ impl ServerHandler for InternalTools {env!("CARGO_PKG_VERSION"),).with_title("Macro Internal MCP");+ info.instructions = Some(+ "When you create or start working on a pull request, register its URL with Macro using macro_internal.set_pull_request.".into(),+ );info}diff --git a/services/agent_harness_service/src/internal_mcp/test.rs b/services/agent_harness_service/src/internal_mcp/test.rsindex 0d1244314c..43634b21d2 100644--- a/services/agent_harness_service/src/internal_mcp/test.rs+++ b/services/agent_harness_service/src/internal_mcp/test.rs@@ -99,6 +99,21 @@ async fn each_harness_gets_only_internal_tools_and_writes_only_its_session() {.0,StatusCode::UNAUTHORIZED);+ let (status, initialized) = rpc(+ app.clone(),+ Some("secret"),+ "initialize",+ serde_json::json!({+ "protocolVersion": "2025-03-26",+ "capabilities": {},+ "clientInfo": { "name": "test", "version": "1.0.0" },+ }),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{initialized}");+ let instructions = initialized["result"]["instructions"].as_str().unwrap();+ assert!(instructions.contains("macro_internal.set_pull_request"));+ assert!(instructions.contains("register its URL"));let (status, listed) = rpc(app.clone(),Some("secret"),diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 05aa3e3751..55d2318c39 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -469,6 +469,59 @@ async fn run() -> anyhow::Result<()> {},pending_commands.clone(),)+ .with_pull_requests(session_pull_requests.clone());+ let codex_connections: Option<Arc<dyn codex_connection::domain::ConnectionService>> = config+ .codex_oauth_kms_key_id()+ .map(|key| {+ let cipher = codex_connection::outbound::cipher::EnvelopeCipher::new(+ aws_sdk_kms::Client::new(&aws_config),+ key,+ )?;+ let repository = codex_connection::outbound::postgres::PostgresRepository::new(+ pool.clone(),+ Arc::new(cipher),+ );+ let provider = codex_cloud_agents::outbound::openai::OpenAi::new()+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;+ Ok::<Arc<dyn codex_connection::domain::ConnectionService>, anyhow::Error>(Arc::new(+ codex_connection::domain::ConnectionServiceImpl::new(+ Arc::new(repository),+ provider,+ ),+ ))+ })+ .transpose()?;+ let codex_provider = codex_cloud_agents::outbound::openai::OpenAi::new()+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;+ let codex_journal_pool = pool.clone();+ let codex_manager = agent_harness::outbound::codex::CodexContainerManager::new(+ Arc::new(codex_provider),+ codex_connections,+ session_repo.clone(),+ Arc::new(move |id| {+ let journal = Arc::new(+ codex_cloud_agents::outbound::postgres_journal::PgCodexJournal::new(+ codex_journal_pool.clone(),+ id,+ replica,+ ),+ );+ let activated = journal.clone();+ (+ journal,+ Box::new(move |claim| {+ activated+ .activate(claim.session, claim.replica, claim.fence)+ .map_err(|e| {+ agent_runtime_protocol::domain::ports::TransportError::Client(+ e.to_string(),+ )+ .into()+ })+ }),+ )+ }),+ ).with_pull_requests(session_pull_requests);// Fixed system agents retain their deployment defaults. User/team agents// are resolved from agent_configs for every trigger so newly-created or@@ -503,6 +556,18 @@ async fn run() -> anyhow::Result<()> {mcp_servers: AgentMcpServers::OwnerConnections,},));+ fixed_runtimes.push((+ bot_id::CODEX_BOT_ID,+ AgentRuntimeConfig {+ kind: AgentKind::CodexCloud,+ model: String::new(),+ harness: "codex-cloud".into(),+ instructions: String::new(),+ mcp_servers: AgentMcpServers::Selected {+ servers: Vec::new(),+ },+ },+ ));let runtime_directory =PgAgentRuntimeDirectory::new(PgBotsRepo::new(pool.clone()), fixed_runtimes.clone());// Logged because the failure mode this replaced was silent: a harness that@@ -515,8 +580,12 @@ async fn run() -> anyhow::Result<()> {environment = %config.environment,"agent harness serving bots");- let containers =- RoutedContainerManager::new(sandbox_and_inmem, cursor_manager, session_repo.clone());+ let containers = RoutedContainerManager::new(+ sandbox_and_inmem,+ cursor_manager,+ codex_manager,+ session_repo.clone(),+ );let contacts_ingress = Arc::new(contacts::domain::service::SqsContactsIngress {queue: contacts::outbound::ingress::SqsContactsQueue::new(@@ -576,6 +645,15 @@ async fn run() -> anyhow::Result<()> {repo_url: config.harness_repo_url.clone(),},)+ .with_bot(+ bot_id::CODEX_BOT_ID,+ SessionDefaults {+ bot_id: bot_id::CODEX_BOT_ID,+ model: String::new(),+ harness: "codex-cloud".into(),+ repo_url: String::new(),+ },+ )// Sessions nothing names a bot for (the create menu's) run in-process;// explicitly selected coding agents keep their configured runtimes..with_managed_bot(inmem_bot);diff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.tomlindex 2d88b1b60d..2943abbabc 100644--- a/services/authentication_service/Cargo.toml+++ b/services/authentication_service/Cargo.toml@@ -31,6 +31,8 @@ rate_limit = []return_passwordless_code = [][dependencies]+codex_connection = { path = "../../crates/codex_connection" }+codex_cloud_agents = { path = "../../crates/codex_cloud_agents" }cursor_api_key = { path = "../../crates/cursor_api_key" }cursor_cloud_agents = { path = "../../crates/cursor_cloud_agents" }aes-gcm = { workspace = true }diff --git a/services/authentication_service/src/api.rs b/services/authentication_service/src/api.rsindex 2f312b3ef5..5d3b8c9717 100644--- a/services/authentication_service/src/api.rs+++ b/services/authentication_service/src/api.rs@@ -15,6 +15,7 @@ use utoipa_swagger_ui::SwaggerUi;pub(crate) mod context;// Routes+mod codex;mod cursor_api_key;#[allow(unused_imports)]mod email;@@ -117,6 +118,7 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {.nest("/user", user::router()).nest("/link", link::router()).nest("/cursor-api-key", cursor_api_key::router())+ .nest("/codex", codex::router()).nest("/github_pull_requests", github_pull_requests::router()).nest("/team",diff --git a/services/authentication_service/src/api/codex.rs b/services/authentication_service/src/api/codex.rsnew file mode 100644index 0000000000..1a6757b220--- /dev/null+++ b/services/authentication_service/src/api/codex.rs@@ -0,0 +1,282 @@+//! User-authenticated Codex connection endpoints; policy belongs to codex_connection.++use crate::api::context::{ApiContext, AuthorizationService};+use axum::{+ Json, Router,+ extract::{Path, State},+ http::StatusCode,+ response::{IntoResponse, Response},+ routing::{get, post, put},+};+use codex_connection::domain::{ConnectionError, ConnectionStatus, LoginStatus};+use macro_authorization::{MacroAuthorizationExtractor, UserOnly};+use serde::{Deserialize, Serialize};+use utoipa::ToSchema;+use uuid::Uuid;++type User = MacroAuthorizationExtractor<AuthorizationService, UserOnly>;++/// Safe connection metadata; no secret or masked token is returned.+#[derive(Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CodexConnectionStatus {+ /// Whether the user has completed provider authorization.+ pub connected: bool,+ /// Reserved until provider-verified email metadata is available.+ pub email: Option<String>,+ /// Connected provider account identifier.+ pub account_id: Option<String>,+ /// Explicitly selected remote environment.+ pub environment_id: Option<String>,+}+impl From<ConnectionStatus> for CodexConnectionStatus {+ fn from(status: ConnectionStatus) -> Self {+ Self {+ connected: status.connected,+ email: None,+ account_id: status.account_id,+ environment_id: status.environment_id,+ }+ }+}+/// Expiring browser authorization instructions.+#[derive(Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CodexLoginStart {+ /// Owner-bound attempt UUID.+ pub attempt_id: Uuid,+ /// Official provider verification URL.+ pub verification_url: String,+ /// Short expiring user code, not an API credential.+ pub user_code: String,+ /// UTC attempt deadline.+ pub expires_at: chrono::DateTime<chrono::Utc>,+ /// Minimum browser polling interval.+ pub poll_interval_seconds: u64,+}+/// Device authorization state visible to its initiating user.+#[derive(Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum CodexLoginState {+ /// Awaiting user authorization.+ Pending,+ /// Credentials were durably stored.+ Connected,+ /// Authorization deadline passed.+ Expired,+ /// Provider exchange failed; begin a new attempt.+ Failed,+}+/// Outcome of polling one attempt.+#[derive(Serialize, Deserialize, ToSchema)]+pub struct CodexLoginPoll {+ /// Current attempt state.+ pub status: CodexLoginState,+}+/// A cloud environment visible to the connected provider account.+#[derive(Serialize, Deserialize, ToSchema)]+pub struct CodexEnvironment {+ /// Provider environment identity.+ pub id: String,+ /// Human-readable provider label.+ pub label: Option<String>,+ /// Ordered safe repository identities from Codex.+ pub repositories: Vec<CodexEnvironmentRepository>,+}+/// Safe repository metadata available to the connected Codex account.+#[derive(Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CodexEnvironmentRepository {+ /// Owner/repository identity.+ pub full_name: String,+ /// Credential-free HTTPS clone URL.+ pub clone_url: String,+ /// Provider default branch.+ pub default_branch: String,+}+/// Explicit remote environment for future Codex sessions.+#[derive(Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct CodexConfigRequest {+ /// An environment currently visible to this account.+ pub environment_id: String,+}++pub enum ApiError {+ Connection(ConnectionError),+ Unavailable,+}+impl From<ConnectionError> for ApiError {+ fn from(error: ConnectionError) -> Self {+ Self::Connection(error)+ }+}+impl IntoResponse for ApiError {+ fn into_response(self) -> Response {+ let error = match self {+ Self::Unavailable => {+ return (+ StatusCode::SERVICE_UNAVAILABLE,+ Json(model::response::ErrorResponse {+ message: "Codex connection is unavailable in this deployment".into(),+ }),+ )+ .into_response();+ }+ Self::Connection(error) => error,+ };+ let code = match error {+ ConnectionError::InvalidInput => StatusCode::BAD_REQUEST,+ ConnectionError::NotFound => StatusCode::NOT_FOUND,+ ConnectionError::NotConnected+ | ConnectionError::AlreadyConnected+ | ConnectionError::AccountChanged => StatusCode::CONFLICT,+ ConnectionError::Provider => StatusCode::BAD_GATEWAY,+ ConnectionError::Storage | ConnectionError::Encryption => {+ StatusCode::INTERNAL_SERVER_ERROR+ }+ };+ (+ code,+ Json(model::response::ErrorResponse {+ message: error.to_string().into(),+ }),+ )+ .into_response()+ }+}++pub fn router() -> Router<ApiContext> {+ Router::new()+ .route("/", get(status).delete(disconnect))+ .route("/login", post(start_login))+ .route("/login/{attempt_id}", get(poll_login).delete(cancel_login))+ .route("/environments", get(environments))+ .route("/config", put(configure))+}++#[utoipa::path(get, path = "/codex", operation_id = "get_codex_connection", responses((status = 200, body = CodexConnectionStatus)))]+pub async fn status(+ State(ctx): State<ApiContext>,+ user: User,+) -> Result<Json<CodexConnectionStatus>, ApiError> {+ Ok(Json(+ ctx.codex_connection+ .as_ref()+ .ok_or(ApiError::Unavailable)?+ .status(user.authorization.macro_user_id.as_ref())+ .await?+ .into(),+ ))+}+#[utoipa::path(post, path = "/codex/login", operation_id = "start_codex_login", responses((status = 200, body = CodexLoginStart)))]+pub async fn start_login(+ State(ctx): State<ApiContext>,+ user: User,+) -> Result<Json<CodexLoginStart>, ApiError> {+ let started = ctx+ .codex_connection+ .as_ref()+ .ok_or(ApiError::Unavailable)?+ .start_login(user.authorization.macro_user_id.as_ref())+ .await?;+ Ok(Json(CodexLoginStart {+ attempt_id: started.attempt_id,+ verification_url: started.verification_url,+ user_code: started.user_code,+ expires_at: started.expires_at,+ poll_interval_seconds: started.poll_interval_seconds,+ }))+}+#[utoipa::path(get, path = "/codex/login/{attempt_id}", operation_id = "poll_codex_login", params(("attempt_id" = Uuid, Path)), responses((status = 200, body = CodexLoginPoll)))]+pub async fn poll_login(+ State(ctx): State<ApiContext>,+ user: User,+ Path(id): Path<Uuid>,+) -> Result<Json<CodexLoginPoll>, ApiError> {+ let status = ctx+ .codex_connection+ .as_ref()+ .ok_or(ApiError::Unavailable)?+ .poll_login(user.authorization.macro_user_id.as_ref(), id)+ .await?;+ Ok(Json(CodexLoginPoll {+ status: match status {+ LoginStatus::Pending => CodexLoginState::Pending,+ LoginStatus::Connected => CodexLoginState::Connected,+ LoginStatus::Expired => CodexLoginState::Expired,+ LoginStatus::Failed => CodexLoginState::Failed,+ },+ }))+}+#[utoipa::path(delete, path = "/codex/login/{attempt_id}", operation_id = "cancel_codex_login", params(("attempt_id" = Uuid, Path)), responses((status = 204)))]+pub async fn cancel_login(+ State(ctx): State<ApiContext>,+ user: User,+ Path(id): Path<Uuid>,+) -> Result<StatusCode, ApiError> {+ ctx.codex_connection+ .as_ref()+ .ok_or(ApiError::Unavailable)?+ .cancel_login(user.authorization.macro_user_id.as_ref(), id)+ .await?;+ Ok(StatusCode::NO_CONTENT)+}+#[utoipa::path(delete, path = "/codex", operation_id = "disconnect_codex", responses((status = 204)))]+pub async fn disconnect(State(ctx): State<ApiContext>, user: User) -> Result<StatusCode, ApiError> {+ ctx.codex_connection+ .as_ref()+ .ok_or(ApiError::Unavailable)?+ .disconnect(user.authorization.macro_user_id.as_ref())+ .await?;+ Ok(StatusCode::NO_CONTENT)+}+#[utoipa::path(get, path = "/codex/environments", operation_id = "list_codex_environments", responses((status = 200, body = Vec<CodexEnvironment>)))]+pub async fn environments(+ State(ctx): State<ApiContext>,+ user: User,+) -> Result<Json<Vec<CodexEnvironment>>, ApiError> {+ Ok(Json(+ ctx.codex_connection+ .as_ref()+ .ok_or(ApiError::Unavailable)?+ .environments(user.authorization.macro_user_id.as_ref())+ .await?+ .into_iter()+ .map(|environment| CodexEnvironment {+ id: environment.id,+ label: environment.label,+ repositories: environment+ .repositories+ .into_iter()+ .map(|repository| CodexEnvironmentRepository {+ full_name: repository.full_name,+ clone_url: repository.clone_url,+ default_branch: repository.default_branch,+ })+ .collect(),+ })+ .collect(),+ ))+}+#[utoipa::path(put, path = "/codex/config", operation_id = "configure_codex", request_body = CodexConfigRequest, responses((status = 200, body = CodexConnectionStatus)))]+pub async fn configure(+ State(ctx): State<ApiContext>,+ user: User,+ Json(request): Json<CodexConfigRequest>,+) -> Result<Json<CodexConnectionStatus>, ApiError> {+ Ok(Json(+ ctx.codex_connection+ .as_ref()+ .ok_or(ApiError::Unavailable)?+ .configure(+ user.authorization.macro_user_id.as_ref(),+ &request.environment_id,+ )+ .await?+ .into(),+ ))+}++#[cfg(test)]+mod test;diff --git a/services/authentication_service/src/api/codex/test.rs b/services/authentication_service/src/api/codex/test.rsnew file mode 100644index 0000000000..bac4ef2554--- /dev/null+++ b/services/authentication_service/src/api/codex/test.rs@@ -0,0 +1,130 @@+use super::*;++#[test]+fn connection_status_has_stable_safe_camel_case_shape() {+ let disconnected = CodexConnectionStatus::from(ConnectionStatus {+ connected: false,+ account_id: None,+ environment_id: None,+ });+ assert_eq!(+ serde_json::to_value(disconnected).unwrap(),+ serde_json::json!({+ "connected":false,"email":null,"accountId":null,"environmentId":null+ })+ );+ let configured = CodexConnectionStatus::from(ConnectionStatus {+ connected: true,+ account_id: Some("account-a".into()),+ environment_id: Some("env-a".into()),+ });+ assert_eq!(+ serde_json::to_value(configured).unwrap(),+ serde_json::json!({+ "connected":true,"email":null,"accountId":"account-a","environmentId":"env-a"+ })+ );+}+#[test]+fn login_instructions_expose_only_browser_values_and_deadline() {+ let id = Uuid::now_v7();+ let started = CodexLoginStart {+ attempt_id: id,+ verification_url: "https://auth.openai.com/codex/device".into(),+ user_code: "TEST-CODE".into(),+ expires_at: chrono::DateTime::from_timestamp(1_800_000_000, 0).unwrap(),+ poll_interval_seconds: 8,+ };+ let value = serde_json::to_value(started).unwrap();+ let keys: std::collections::BTreeSet<_> = value+ .as_object()+ .unwrap()+ .keys()+ .map(String::as_str)+ .collect();+ assert_eq!(+ keys,+ std::collections::BTreeSet::from([+ "attemptId",+ "verificationUrl",+ "userCode",+ "expiresAt",+ "pollIntervalSeconds"+ ])+ );+ assert_eq!(value["attemptId"], id.to_string());+ assert_eq!(value["pollIntervalSeconds"], 8);+ assert_eq!(+ serde_json::to_value(CodexLoginPoll {+ status: CodexLoginState::Failed+ })+ .unwrap(),+ serde_json::json!({"status":"failed"})+ );+}+#[tokio::test]+async fn deployment_unavailable_returns_503_without_exposing_operator_configuration() {+ let response = ApiError::Unavailable.into_response();+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);+ let body = axum::body::to_bytes(response.into_body(), 1024)+ .await+ .unwrap();+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(+ value,+ serde_json::json!({"message":"Codex connection is unavailable in this deployment"})+ );+}+#[tokio::test]+async fn domain_errors_have_distinct_http_status_and_only_safe_message() {+ for (error, expected) in [+ (ConnectionError::InvalidInput, StatusCode::BAD_REQUEST),+ (ConnectionError::NotFound, StatusCode::NOT_FOUND),+ (ConnectionError::NotConnected, StatusCode::CONFLICT),+ (ConnectionError::AlreadyConnected, StatusCode::CONFLICT),+ (ConnectionError::Provider, StatusCode::BAD_GATEWAY),+ (ConnectionError::Storage, StatusCode::INTERNAL_SERVER_ERROR),+ (+ ConnectionError::Encryption,+ StatusCode::INTERNAL_SERVER_ERROR,+ ),+ ] {+ let message = error.to_string();+ let response = ApiError::from(error).into_response();+ assert_eq!(response.status(), expected);+ let body = axum::body::to_bytes(response.into_body(), 1024)+ .await+ .unwrap();+ assert_eq!(+ serde_json::from_slice::<serde_json::Value>(&body).unwrap(),+ serde_json::json!({"message":message})+ );+ }+}++#[test]+fn explicit_environment_configuration_and_repository_metadata_wire_contract() {+ for invalid in [+ serde_json::json!({}),+ serde_json::json!({"environmentId":null}),+ serde_json::json!({"environmentId":"env-a","branch":"other"}),+ ] {+ assert!(serde_json::from_value::<CodexConfigRequest>(invalid).is_err());+ }+ let request: CodexConfigRequest =+ serde_json::from_value(serde_json::json!({"environmentId":"env-a"})).unwrap();+ assert_eq!(request.environment_id, "env-a");+ let environment = CodexEnvironment {+ id: "env-a".into(),+ label: None,+ repositories: vec![CodexEnvironmentRepository {+ full_name: "owner/repo".into(),+ clone_url: "https://github.com/owner/repo.git".into(),+ default_branch: "trunk".into(),+ }],+ };+ assert_eq!(+ serde_json::to_value(environment).unwrap(),+ serde_json::json!({"id":"env-a","label":null,"repositories":[{"fullName":"owner/repo","cloneUrl":"https://github.com/owner/repo.git","defaultBranch":"trunk"}]})+ );+}diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rsindex 603a2c5fb3..55e330a0dc 100644--- a/services/authentication_service/src/api/context.rs+++ b/services/authentication_service/src/api/context.rs@@ -118,6 +118,8 @@ pub(crate) struct ApiContext {pub microsoft_token_cipher: Option<Arc<dyn MicrosoftTokenCipher>>,/// Encrypts users' Cursor API keys.pub cursor_api_key_cipher: Arc<dyn CursorApiKeyCipher>,+ /// Owner-bound Codex OAuth lifecycle and cloud target settings.+ pub codex_connection: Option<Arc<dyn codex_connection::domain::ConnectionService>>,pub macro_cache_client: Arc<MacroCache>,pub stripe_client: Arc<stripe::Client>,pub document_storage_service_client:diff --git a/services/authentication_service/src/api/swagger.rs b/services/authentication_service/src/api/swagger.rsindex 7843be8c69..05fd3b3388 100644--- a/services/authentication_service/src/api/swagger.rs+++ b/services/authentication_service/src/api/swagger.rs@@ -87,6 +87,13 @@ use model::user::{// Cursor API key (settings -> Connections). Fully qualified:// the `cursor_api_key` crate shadows the module of the same// name in this path position.+ crate::api::codex::status,+ crate::api::codex::start_login,+ crate::api::codex::poll_login,+ crate::api::codex::cancel_login,+ crate::api::codex::disconnect,+ crate::api::codex::environments,+ crate::api::codex::configure,crate::api::cursor_api_key::get_cursor_api_key::handler,crate::api::cursor_api_key::put_cursor_api_key::handler,crate::api::cursor_api_key::delete_cursor_api_key::handler,diff --git a/services/authentication_service/src/config.rs b/services/authentication_service/src/config.rsindex b29f395b4f..ef5f48dac7 100644--- a/services/authentication_service/src/config.rs+++ b/services/authentication_service/src/config.rs@@ -53,6 +53,8 @@ maybe_env_vars! {/// process environment because `MacroConfig` does not fall back to it/// when `APP_SECRETS_JSON` is present.pub struct CursorApiKeyKmsKeyId;+ /// Dedicated CMK for encrypted Codex OAuth envelopes, injected by infrastructure.+ pub struct CodexOauthKmsKeyId;pub struct GaMeasurementId;pub struct GaApiSecret;pub struct MetaPixelId;@@ -110,6 +112,8 @@ pub struct Config {/// read through [`Config::cursor_api_key_kms_key_id`], which refuses an/// absent or blank value at startup.pub cursor_api_key_kms_key_id: CursorApiKeyKmsKeyId,+ /// Dedicated Codex envelope encryption CMK; absent deployments return 503 for Codex.+ pub codex_oauth_kms_key_id: CodexOauthKmsKeyId,/// Stripe secret keypub stripe_secret_key: StripeSecretKey,/// The port to listen for HTTP requests on.@@ -194,6 +198,19 @@ impl Config {)}+ /// Resolve the dedicated CMK, including Pulumi-injected process environment.+ pub(crate) fn codex_oauth_kms_key_id(&self) -> Option<String> {+ let process = CodexOauthKmsKeyId::new();+ nonblank_value(self.codex_oauth_kms_key_id.value())+ .or_else(|| {+ process+ .as_ref()+ .and_then(CodexOauthKmsKeyId::value)+ .and_then(|value| nonblank_value(Some(value)))+ })+ .map(str::to_owned)+ }+/// Resolves Microsoft credentials, enforcing that all values are configured together.pub(crate) fn microsoft_credentials(&self) -> anyhow::Result<Option<MicrosoftCredentials>> {resolve_microsoft_credentials(diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rsindex f3c95ded73..b7b6f22bcc 100644--- a/services/authentication_service/src/main.rs+++ b/services/authentication_service/src/main.rs@@ -438,6 +438,25 @@ async fn main() -> anyhow::Result<()> {notification_ingress: notification_ingress_service.clone(),};+ let codex_connection = if let Some(key_id) = config.codex_oauth_kms_key_id() {+ let cipher = Arc::new(codex_connection::outbound::cipher::EnvelopeCipher::new(+ aws_sdk_kms::Client::new(&aws_config),+ key_id,+ )?);+ let repository = Arc::new(+ codex_connection::outbound::postgres::PostgresRepository::new(db.clone(), cipher),+ );+ let provider = codex_cloud_agents::outbound::openai::OpenAi::new()+ .map_err(|_| anyhow::anyhow!("failed to initialize Codex OAuth client"))?;+ Some(+ Arc::new(codex_connection::domain::ConnectionServiceImpl::new(+ repository, provider,+ )) as Arc<dyn codex_connection::domain::ConnectionService>,+ )+ } else {+ None+ };+let server_result = api::setup_and_serve(ApiContext {db,@@ -445,6 +464,7 @@ async fn main() -> anyhow::Result<()> {auth_client: Arc::new(auth_client),microsoft_token_cipher,cursor_api_key_cipher,+ codex_connection,macro_cache_client: Arc::new(macro_cache_client),stripe_client: Arc::new(stripe_client),document_storage_service_client: Arc::new(document_storage_service_client),diff --git a/tooling/just/check.just b/tooling/just/check.justindex 1e39ff64ea..4a78beb258 100644--- a/tooling/just/check.just+++ b/tooling/just/check.just@@ -28,7 +28,8 @@ check *ARGS:if [ -z "$changed" ]; then echo "no changed files — nothing to check"; exit 0; firs=$(grep -E '^(crates|services|tooling)/.*\.rs$' <<<"$changed" || true)- js=$(grep -E '^(apps/web|packages|services/(analytics-proxy|ai-editing-worker|lexical-service|websocket-service))/.*\.(ts|tsx)$' <<<"$changed" || true)+ # Match packages/sdk/biome.jsonc: preserve generator output verbatim.+ js=$(grep -E '^(apps/web|packages|services/(analytics-proxy|ai-editing-worker|lexical-service|websocket-service))/.*\.(ts|tsx)$' <<<"$changed" | grep -v '^packages/sdk/generated/' || true)sg=$(grep -E '^(apps|crates|packages|services|tooling)/.*\.(rs|ts|tsx)$' <<<"$changed" || true)fail=0diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env.rs b/tooling/xtask/crates/xtask_local/src/local/local_env.rsindex 9728a138da..4fccf8ff92 100644--- a/tooling/xtask/crates/xtask_local/src/local/local_env.rs+++ b/tooling/xtask/crates/xtask_local/src/local/local_env.rs@@ -205,6 +205,10 @@ impl InfraEnv {"CURSOR_API_KEY_KMS_KEY_ID".into(),resources::CURSOR_API_KEY_KMS_ALIAS.into(),);+ env.insert(+ "CODEX_OAUTH_KMS_KEY_ID".into(),+ resources::CODEX_OAUTH_KMS_ALIAS.into(),+ );// Dummy creds: the SDK talks to LocalStack, never real AWS.env.insert("AWS_ACCESS_KEY_ID".into(), "test".into());env.insert("AWS_SECRET_ACCESS_KEY".into(), "test".into());diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rsindex 99b271a045..04b2f76816 100644--- a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs+++ b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs@@ -297,6 +297,10 @@ fn the_agent_harness_uses_local_containers_and_wipes_daytona() {// No `CURSOR_API_KEY`: `@cursor` sessions run on the key each user// registers in settings, so there is no deployment-wide one to stub.assert!(!env.contains_key("CURSOR_API_KEY"));+ assert_eq!(+ env.get("CODEX_OAUTH_KMS_KEY_ID").map(String::as_str),+ Some(resources::CODEX_OAUTH_KMS_ALIAS)+ );}/// Sandboxes and the harness are both containers, so they reach each other on adiff --git a/tooling/xtask/crates/xtask_local/src/local/localstack.rs b/tooling/xtask/crates/xtask_local/src/local/localstack.rsindex 80fa351d76..283b303abc 100644--- a/tooling/xtask/crates/xtask_local/src/local/localstack.rs+++ b/tooling/xtask/crates/xtask_local/src/local/localstack.rs@@ -70,40 +70,49 @@ async fn provision_async(url: &str) -> Result<()> {/// stops one user's ciphertext decrypting under another user's id is live/// locally too, and a local stack is a fair test of it.async fn create_kms_keys(kms: &aws_sdk_kms::Client) -> Result<()> {- let alias = resources::CURSOR_API_KEY_KMS_ALIAS;let existing = kms.list_aliases().send().await.context("listing kms aliases")?;- if existing- .aliases()- .iter()- .any(|entry| entry.alias_name() == Some(alias))- {- return Ok(());- }-- let key = kms- .create_key()- .description("Cursor API key encryption key (local)")- .send()- .await- .context("creating the cursor api key kms key")?;- let key_id = key- .key_metadata()- .map(|metadata| metadata.key_id())- .context("kms create_key returned no key metadata")?;-- ignore_exists(- kms.create_alias()- .alias_name(alias)- .target_key_id(key_id)+ for (alias, description) in [+ (+ resources::CURSOR_API_KEY_KMS_ALIAS,+ "Cursor API key encryption key (local)",+ ),+ (+ resources::CODEX_OAUTH_KMS_ALIAS,+ "ChatGPT OAuth envelope encryption key (local)",+ ),+ ] {+ if existing+ .aliases()+ .iter()+ .any(|entry| entry.alias_name() == Some(alias))+ {+ continue;+ }+ let key = kms+ .create_key()+ .description(description).send().await- .map(|_| ()),- &format!("kms alias {alias}"),- )+ .context("creating local kms key")?;+ let key_id = key+ .key_metadata()+ .map(|metadata| metadata.key_id())+ .context("kms create_key returned no key metadata")?;+ ignore_exists(+ kms.create_alias()+ .alias_name(alias)+ .target_key_id(key_id)+ .send()+ .await+ .map(|_| ()),+ &format!("kms alias {alias}"),+ )?;+ }+ Ok(())}async fn create_queues(sqs: &aws_sdk_sqs::Client) -> Result<()> {diff --git a/tooling/xtask/crates/xtask_local/src/local/resources.rs b/tooling/xtask/crates/xtask_local/src/local/resources.rsindex d2cc125879..69b14a50dd 100644--- a/tooling/xtask/crates/xtask_local/src/local/resources.rs+++ b/tooling/xtask/crates/xtask_local/src/local/resources.rs@@ -40,6 +40,9 @@ pub const STATIC_FILE_TABLE: &str = "static-file-metadata";/// stable and KMS accepts one anywhere a key id goes.pub const CURSOR_API_KEY_KMS_ALIAS: &str = "alias/macro-local-cursor-api-key";+/// Dedicated envelope-encryption key for local ChatGPT account connections.+pub const CODEX_OAUTH_KMS_ALIAS: &str = "alias/macro-local-codex-oauth";+/// The full LocalStack URL for `queue` (docker-network host — services run in/// containers and reach LocalStack by its compose alias).pub fn queue_url(queue: &str) -> String {