From 950b702fe7e5743a1d4841c60581277873bf99e6 Mon Sep 17 00:00:00 2001 From: Rohit Arunachalam Date: Wed, 24 Jun 2026 20:51:29 -0700 Subject: [PATCH] Support external clock sleeps --- .../schema/json/ServerNotification.json | 43 +++++ .../codex_app_server_protocol.schemas.json | 45 +++++ .../codex_app_server_protocol.v2.schemas.json | 45 +++++ .../json/v2/CurrentTimeSleepNotification.json | 24 +++ .../schema/typescript/ServerNotification.ts | 3 +- .../v2/CurrentTimeSleepNotification.ts | 9 + .../schema/typescript/v2/index.ts | 1 + .../src/protocol/common.rs | 11 ++ .../src/protocol/v2/current_time.rs | 24 +++ codex-rs/app-server/README.md | 2 + codex-rs/app-server/src/current_time.rs | 175 +++++++++++++++--- codex-rs/app-server/src/message_processor.rs | 13 +- .../app-server/tests/suite/v2/current_time.rs | 152 +++++++++++++-- .../tui/src/app/app_server_event_targets.rs | 1 + codex-rs/tui/src/chatwidget/protocol.rs | 1 + 15 files changed, 505 insertions(+), 44 deletions(-) create mode 100644 codex-rs/app-server-protocol/schema/json/v2/CurrentTimeSleepNotification.json create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/CurrentTimeSleepNotification.ts diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index a3d07c24a0..3384f3d45e 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -1062,6 +1062,28 @@ ], "type": "object" }, + "CurrentTimeSleepNotification": { + "properties": { + "durationMs": { + "description": "Duration to wait on the external clock.", + "format": "uint64", + "minimum": 0.0, + "type": "integer" + }, + "sleepId": { + "type": "string" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "durationMs", + "sleepId", + "threadId" + ], + "type": "object" + }, "DeprecationNoticeNotification": { "properties": { "details": { @@ -5930,6 +5952,27 @@ "title": "Thread/tokenUsage/updatedNotification", "type": "object" }, + { + "description": "Register a sleep with an external clock owned by the client.", + "properties": { + "method": { + "enum": [ + "currentTime/sleep" + ], + "title": "CurrentTime/sleepNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/CurrentTimeSleepNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "CurrentTime/sleepNotification", + "type": "object" + }, { "properties": { "method": { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 4d417ffb2f..4e421ba881 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -4368,6 +4368,27 @@ "title": "Thread/tokenUsage/updatedNotification", "type": "object" }, + { + "description": "Register a sleep with an external clock owned by the client.", + "properties": { + "method": { + "enum": [ + "currentTime/sleep" + ], + "title": "CurrentTime/sleepNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/CurrentTimeSleepNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "CurrentTime/sleepNotification", + "type": "object" + }, { "properties": { "method": { @@ -8823,6 +8844,30 @@ ], "type": "object" }, + "CurrentTimeSleepNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "durationMs": { + "description": "Duration to wait on the external clock.", + "format": "uint64", + "minimum": 0.0, + "type": "integer" + }, + "sleepId": { + "type": "string" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "durationMs", + "sleepId", + "threadId" + ], + "title": "CurrentTimeSleepNotification", + "type": "object" + }, "DeprecationNoticeNotification": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 0df923a0f4..57637d6a5f 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -5063,6 +5063,30 @@ ], "type": "object" }, + "CurrentTimeSleepNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "durationMs": { + "description": "Duration to wait on the external clock.", + "format": "uint64", + "minimum": 0.0, + "type": "integer" + }, + "sleepId": { + "type": "string" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "durationMs", + "sleepId", + "threadId" + ], + "title": "CurrentTimeSleepNotification", + "type": "object" + }, "DeprecationNoticeNotification": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { @@ -12794,6 +12818,27 @@ "title": "Thread/tokenUsage/updatedNotification", "type": "object" }, + { + "description": "Register a sleep with an external clock owned by the client.", + "properties": { + "method": { + "enum": [ + "currentTime/sleep" + ], + "title": "CurrentTime/sleepNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/CurrentTimeSleepNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "CurrentTime/sleepNotification", + "type": "object" + }, { "properties": { "method": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/CurrentTimeSleepNotification.json b/codex-rs/app-server-protocol/schema/json/v2/CurrentTimeSleepNotification.json new file mode 100644 index 0000000000..913b61215f --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/CurrentTimeSleepNotification.json @@ -0,0 +1,24 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "durationMs": { + "description": "Duration to wait on the external clock.", + "format": "uint64", + "minimum": 0.0, + "type": "integer" + }, + "sleepId": { + "type": "string" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "durationMs", + "sleepId", + "threadId" + ], + "title": "CurrentTimeSleepNotification", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts b/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts index f3f828b8ac..a0c7fb6ad5 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts @@ -12,6 +12,7 @@ import type { CommandExecOutputDeltaNotification } from "./v2/CommandExecOutputD import type { CommandExecutionOutputDeltaNotification } from "./v2/CommandExecutionOutputDeltaNotification"; import type { ConfigWarningNotification } from "./v2/ConfigWarningNotification"; import type { ContextCompactedNotification } from "./v2/ContextCompactedNotification"; +import type { CurrentTimeSleepNotification } from "./v2/CurrentTimeSleepNotification"; import type { DeprecationNoticeNotification } from "./v2/DeprecationNoticeNotification"; import type { ErrorNotification } from "./v2/ErrorNotification"; import type { ExternalAgentConfigImportCompletedNotification } from "./v2/ExternalAgentConfigImportCompletedNotification"; @@ -74,4 +75,4 @@ import type { WindowsWorldWritableWarningNotification } from "./v2/WindowsWorldW /** * Notification sent from the server to the client. */ -export type ServerNotification = { "method": "error", "params": ErrorNotification } | { "method": "thread/started", "params": ThreadStartedNotification } | { "method": "thread/status/changed", "params": ThreadStatusChangedNotification } | { "method": "thread/archived", "params": ThreadArchivedNotification } | { "method": "thread/deleted", "params": ThreadDeletedNotification } | { "method": "thread/unarchived", "params": ThreadUnarchivedNotification } | { "method": "thread/closed", "params": ThreadClosedNotification } | { "method": "skills/changed", "params": SkillsChangedNotification } | { "method": "thread/name/updated", "params": ThreadNameUpdatedNotification } | { "method": "thread/goal/updated", "params": ThreadGoalUpdatedNotification } | { "method": "thread/goal/cleared", "params": ThreadGoalClearedNotification } | { "method": "thread/settings/updated", "params": ThreadSettingsUpdatedNotification } | { "method": "thread/tokenUsage/updated", "params": ThreadTokenUsageUpdatedNotification } | { "method": "turn/started", "params": TurnStartedNotification } | { "method": "hook/started", "params": HookStartedNotification } | { "method": "turn/completed", "params": TurnCompletedNotification } | { "method": "hook/completed", "params": HookCompletedNotification } | { "method": "turn/diff/updated", "params": TurnDiffUpdatedNotification } | { "method": "turn/plan/updated", "params": TurnPlanUpdatedNotification } | { "method": "item/started", "params": ItemStartedNotification } | { "method": "item/autoApprovalReview/started", "params": ItemGuardianApprovalReviewStartedNotification } | { "method": "item/autoApprovalReview/completed", "params": ItemGuardianApprovalReviewCompletedNotification } | { "method": "item/completed", "params": ItemCompletedNotification } | { "method": "rawResponseItem/completed", "params": RawResponseItemCompletedNotification } | { "method": "item/agentMessage/delta", "params": AgentMessageDeltaNotification } | { "method": "item/plan/delta", "params": PlanDeltaNotification } | { "method": "command/exec/outputDelta", "params": CommandExecOutputDeltaNotification } | { "method": "process/outputDelta", "params": ProcessOutputDeltaNotification } | { "method": "process/exited", "params": ProcessExitedNotification } | { "method": "item/commandExecution/outputDelta", "params": CommandExecutionOutputDeltaNotification } | { "method": "item/commandExecution/terminalInteraction", "params": TerminalInteractionNotification } | { "method": "item/fileChange/outputDelta", "params": FileChangeOutputDeltaNotification } | { "method": "item/fileChange/patchUpdated", "params": FileChangePatchUpdatedNotification } | { "method": "serverRequest/resolved", "params": ServerRequestResolvedNotification } | { "method": "item/mcpToolCall/progress", "params": McpToolCallProgressNotification } | { "method": "mcpServer/oauthLogin/completed", "params": McpServerOauthLoginCompletedNotification } | { "method": "mcpServer/startupStatus/updated", "params": McpServerStatusUpdatedNotification } | { "method": "account/updated", "params": AccountUpdatedNotification } | { "method": "account/rateLimits/updated", "params": AccountRateLimitsUpdatedNotification } | { "method": "app/list/updated", "params": AppListUpdatedNotification } | { "method": "remoteControl/status/changed", "params": RemoteControlStatusChangedNotification } | { "method": "externalAgentConfig/import/progress", "params": ExternalAgentConfigImportProgressNotification } | { "method": "externalAgentConfig/import/completed", "params": ExternalAgentConfigImportCompletedNotification } | { "method": "fs/changed", "params": FsChangedNotification } | { "method": "item/reasoning/summaryTextDelta", "params": ReasoningSummaryTextDeltaNotification } | { "method": "item/reasoning/summaryPartAdded", "params": ReasoningSummaryPartAddedNotification } | { "method": "item/reasoning/textDelta", "params": ReasoningTextDeltaNotification } | { "method": "thread/compacted", "params": ContextCompactedNotification } | { "method": "model/rerouted", "params": ModelReroutedNotification } | { "method": "model/verification", "params": ModelVerificationNotification } | { "method": "turn/moderationMetadata", "params": TurnModerationMetadataNotification } | { "method": "model/safetyBuffering/updated", "params": ModelSafetyBufferingUpdatedNotification } | { "method": "warning", "params": WarningNotification } | { "method": "guardianWarning", "params": GuardianWarningNotification } | { "method": "deprecationNotice", "params": DeprecationNoticeNotification } | { "method": "configWarning", "params": ConfigWarningNotification } | { "method": "fuzzyFileSearch/sessionUpdated", "params": FuzzyFileSearchSessionUpdatedNotification } | { "method": "fuzzyFileSearch/sessionCompleted", "params": FuzzyFileSearchSessionCompletedNotification } | { "method": "thread/realtime/started", "params": ThreadRealtimeStartedNotification } | { "method": "thread/realtime/itemAdded", "params": ThreadRealtimeItemAddedNotification } | { "method": "thread/realtime/transcript/delta", "params": ThreadRealtimeTranscriptDeltaNotification } | { "method": "thread/realtime/transcript/done", "params": ThreadRealtimeTranscriptDoneNotification } | { "method": "thread/realtime/outputAudio/delta", "params": ThreadRealtimeOutputAudioDeltaNotification } | { "method": "thread/realtime/sdp", "params": ThreadRealtimeSdpNotification } | { "method": "thread/realtime/error", "params": ThreadRealtimeErrorNotification } | { "method": "thread/realtime/closed", "params": ThreadRealtimeClosedNotification } | { "method": "windows/worldWritableWarning", "params": WindowsWorldWritableWarningNotification } | { "method": "windowsSandbox/setupCompleted", "params": WindowsSandboxSetupCompletedNotification } | { "method": "account/login/completed", "params": AccountLoginCompletedNotification }; +export type ServerNotification = { "method": "error", "params": ErrorNotification } | { "method": "thread/started", "params": ThreadStartedNotification } | { "method": "thread/status/changed", "params": ThreadStatusChangedNotification } | { "method": "thread/archived", "params": ThreadArchivedNotification } | { "method": "thread/deleted", "params": ThreadDeletedNotification } | { "method": "thread/unarchived", "params": ThreadUnarchivedNotification } | { "method": "thread/closed", "params": ThreadClosedNotification } | { "method": "skills/changed", "params": SkillsChangedNotification } | { "method": "thread/name/updated", "params": ThreadNameUpdatedNotification } | { "method": "thread/goal/updated", "params": ThreadGoalUpdatedNotification } | { "method": "thread/goal/cleared", "params": ThreadGoalClearedNotification } | { "method": "thread/settings/updated", "params": ThreadSettingsUpdatedNotification } | { "method": "thread/tokenUsage/updated", "params": ThreadTokenUsageUpdatedNotification } | { "method": "currentTime/sleep", "params": CurrentTimeSleepNotification } | { "method": "turn/started", "params": TurnStartedNotification } | { "method": "hook/started", "params": HookStartedNotification } | { "method": "turn/completed", "params": TurnCompletedNotification } | { "method": "hook/completed", "params": HookCompletedNotification } | { "method": "turn/diff/updated", "params": TurnDiffUpdatedNotification } | { "method": "turn/plan/updated", "params": TurnPlanUpdatedNotification } | { "method": "item/started", "params": ItemStartedNotification } | { "method": "item/autoApprovalReview/started", "params": ItemGuardianApprovalReviewStartedNotification } | { "method": "item/autoApprovalReview/completed", "params": ItemGuardianApprovalReviewCompletedNotification } | { "method": "item/completed", "params": ItemCompletedNotification } | { "method": "rawResponseItem/completed", "params": RawResponseItemCompletedNotification } | { "method": "item/agentMessage/delta", "params": AgentMessageDeltaNotification } | { "method": "item/plan/delta", "params": PlanDeltaNotification } | { "method": "command/exec/outputDelta", "params": CommandExecOutputDeltaNotification } | { "method": "process/outputDelta", "params": ProcessOutputDeltaNotification } | { "method": "process/exited", "params": ProcessExitedNotification } | { "method": "item/commandExecution/outputDelta", "params": CommandExecutionOutputDeltaNotification } | { "method": "item/commandExecution/terminalInteraction", "params": TerminalInteractionNotification } | { "method": "item/fileChange/outputDelta", "params": FileChangeOutputDeltaNotification } | { "method": "item/fileChange/patchUpdated", "params": FileChangePatchUpdatedNotification } | { "method": "serverRequest/resolved", "params": ServerRequestResolvedNotification } | { "method": "item/mcpToolCall/progress", "params": McpToolCallProgressNotification } | { "method": "mcpServer/oauthLogin/completed", "params": McpServerOauthLoginCompletedNotification } | { "method": "mcpServer/startupStatus/updated", "params": McpServerStatusUpdatedNotification } | { "method": "account/updated", "params": AccountUpdatedNotification } | { "method": "account/rateLimits/updated", "params": AccountRateLimitsUpdatedNotification } | { "method": "app/list/updated", "params": AppListUpdatedNotification } | { "method": "remoteControl/status/changed", "params": RemoteControlStatusChangedNotification } | { "method": "externalAgentConfig/import/progress", "params": ExternalAgentConfigImportProgressNotification } | { "method": "externalAgentConfig/import/completed", "params": ExternalAgentConfigImportCompletedNotification } | { "method": "fs/changed", "params": FsChangedNotification } | { "method": "item/reasoning/summaryTextDelta", "params": ReasoningSummaryTextDeltaNotification } | { "method": "item/reasoning/summaryPartAdded", "params": ReasoningSummaryPartAddedNotification } | { "method": "item/reasoning/textDelta", "params": ReasoningTextDeltaNotification } | { "method": "thread/compacted", "params": ContextCompactedNotification } | { "method": "model/rerouted", "params": ModelReroutedNotification } | { "method": "model/verification", "params": ModelVerificationNotification } | { "method": "turn/moderationMetadata", "params": TurnModerationMetadataNotification } | { "method": "model/safetyBuffering/updated", "params": ModelSafetyBufferingUpdatedNotification } | { "method": "warning", "params": WarningNotification } | { "method": "guardianWarning", "params": GuardianWarningNotification } | { "method": "deprecationNotice", "params": DeprecationNoticeNotification } | { "method": "configWarning", "params": ConfigWarningNotification } | { "method": "fuzzyFileSearch/sessionUpdated", "params": FuzzyFileSearchSessionUpdatedNotification } | { "method": "fuzzyFileSearch/sessionCompleted", "params": FuzzyFileSearchSessionCompletedNotification } | { "method": "thread/realtime/started", "params": ThreadRealtimeStartedNotification } | { "method": "thread/realtime/itemAdded", "params": ThreadRealtimeItemAddedNotification } | { "method": "thread/realtime/transcript/delta", "params": ThreadRealtimeTranscriptDeltaNotification } | { "method": "thread/realtime/transcript/done", "params": ThreadRealtimeTranscriptDoneNotification } | { "method": "thread/realtime/outputAudio/delta", "params": ThreadRealtimeOutputAudioDeltaNotification } | { "method": "thread/realtime/sdp", "params": ThreadRealtimeSdpNotification } | { "method": "thread/realtime/error", "params": ThreadRealtimeErrorNotification } | { "method": "thread/realtime/closed", "params": ThreadRealtimeClosedNotification } | { "method": "windows/worldWritableWarning", "params": WindowsWorldWritableWarningNotification } | { "method": "windowsSandbox/setupCompleted", "params": WindowsSandboxSetupCompletedNotification } | { "method": "account/login/completed", "params": AccountLoginCompletedNotification }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/CurrentTimeSleepNotification.ts b/codex-rs/app-server-protocol/schema/typescript/v2/CurrentTimeSleepNotification.ts new file mode 100644 index 0000000000..2407d40534 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/CurrentTimeSleepNotification.ts @@ -0,0 +1,9 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type CurrentTimeSleepNotification = { threadId: string, sleepId: string, +/** + * Duration to wait on the external clock. + */ +durationMs: number, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index ff7df9e9ec..5640ce449d 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -90,6 +90,7 @@ export type { ConsumeAccountRateLimitResetCreditParams } from "./ConsumeAccountR export type { ConsumeAccountRateLimitResetCreditResponse } from "./ConsumeAccountRateLimitResetCreditResponse"; export type { ContextCompactedNotification } from "./ContextCompactedNotification"; export type { CreditsSnapshot } from "./CreditsSnapshot"; +export type { CurrentTimeSleepNotification } from "./CurrentTimeSleepNotification"; export type { DeprecationNoticeNotification } from "./DeprecationNoticeNotification"; export type { DynamicToolCallOutputContentItem } from "./DynamicToolCallOutputContentItem"; export type { DynamicToolCallParams } from "./DynamicToolCallParams"; diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 51a37fbaa9..e712e9c35c 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -1139,6 +1139,14 @@ client_request_definitions! { response: v2::GetAccountResponse, }, + #[experimental("currentTime/wake")] + /// Wake a pending sleep registered with an external clock. + CurrentTimeWake => "currentTime/wake" { + params: v2::CurrentTimeWakeParams, + serialization: None, + response: v2::CurrentTimeWakeResponse, + }, + /// DEPRECATED APIs below GetConversationSummary { params: v1::GetConversationSummaryParams, @@ -1613,6 +1621,9 @@ server_notification_definitions! { #[experimental("thread/settings/updated")] ThreadSettingsUpdated => "thread/settings/updated" (v2::ThreadSettingsUpdatedNotification), ThreadTokenUsageUpdated => "thread/tokenUsage/updated" (v2::ThreadTokenUsageUpdatedNotification), + #[experimental("currentTime/sleep")] + /// Register a sleep with an external clock owned by the client. + CurrentTimeSleep => "currentTime/sleep" (v2::CurrentTimeSleepNotification), TurnStarted => "turn/started" (v2::TurnStartedNotification), HookStarted => "hook/started" (v2::HookStartedNotification), TurnCompleted => "turn/completed" (v2::TurnCompletedNotification), diff --git a/codex-rs/app-server-protocol/src/protocol/v2/current_time.rs b/codex-rs/app-server-protocol/src/protocol/v2/current_time.rs index 9fd23f7981..58e77ddefb 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/current_time.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/current_time.rs @@ -18,3 +18,27 @@ pub struct CurrentTimeReadResponse { #[ts(type = "number")] pub current_time_at: i64, } + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct CurrentTimeSleepNotification { + pub thread_id: String, + pub sleep_id: String, + /// Duration to wait on the external clock. + #[ts(type = "number")] + pub duration_ms: u64, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct CurrentTimeWakeParams { + pub thread_id: String, + pub sleep_id: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct CurrentTimeWakeResponse {} diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 246b2bb0c0..8e6730cb8b 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -1481,6 +1481,8 @@ Desktop hosts that provide upstream attestation should set `capabilities.request When `[features.current_time_reminder]` is enabled with `clock_source = "external"`, app-server sends the client subscribed to the thread an experimental `currentTime/read` request with `{ "threadId": "thr_123" }` when a time reminder is due. The client responds with `{ "currentTimeAt": 1781717655 }`, where `currentTimeAt` is an integer Unix timestamp in seconds. A failed, canceled, timed-out, or malformed response stops the turn before the model request is sent. +When the same feature enables `sleep_tool`, `clock.sleep` sends an experimental `currentTime/sleep` notification with `{ "threadId": "thr_123", "sleepId": "sleep_123", "durationMs": 30000 }`. The client later wakes the waiting tool by sending `currentTime/wake` with the same `threadId` and `sleepId`. The client should update its external clock before waking so later `currentTime/read` requests observe the completed sleep. App-server responds with `{}` and ignores wakes for sleeps that are no longer pending. + ### MCP server elicitations MCP servers can interrupt a turn and ask the client for structured input via `mcpServer/elicitation/request`. diff --git a/codex-rs/app-server/src/current_time.rs b/codex-rs/app-server/src/current_time.rs index 205068be2b..3a01ae3071 100644 --- a/codex-rs/app-server/src/current_time.rs +++ b/codex-rs/app-server/src/current_time.rs @@ -1,4 +1,6 @@ +use std::collections::HashMap; use std::sync::Arc; +use std::sync::Mutex; use std::sync::Weak; use anyhow::Context; @@ -9,34 +11,104 @@ use chrono::DateTime; use chrono::Utc; use codex_app_server_protocol::CurrentTimeReadParams; use codex_app_server_protocol::CurrentTimeReadResponse; +use codex_app_server_protocol::CurrentTimeSleepNotification; +use codex_app_server_protocol::CurrentTimeWakeParams; +use codex_app_server_protocol::CurrentTimeWakeResponse; +use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequestPayload; use codex_core::SleepFuture; use codex_core::TimeFuture; use codex_core::TimeProvider; use codex_protocol::ThreadId; +use tokio::sync::oneshot; use tokio::time::Duration; use tokio::time::Instant; use tokio::time::timeout_at; +use uuid::Uuid; use crate::outgoing_message::ConnectionId; use crate::outgoing_message::OutgoingMessageSender; use crate::thread_state::ThreadStateManager; -const CURRENT_TIME_REQUEST_TIMEOUT: Duration = Duration::from_secs(5); +const EXTERNAL_CLOCK_REQUEST_TIMEOUT: Duration = Duration::from_secs(5); pub(crate) fn app_server_time_provider( outgoing: Arc, thread_state_manager: ThreadStateManager, -) -> Arc { +) -> Arc { Arc::new(AppServerTimeProvider { outgoing: Arc::downgrade(&outgoing), thread_state_manager, + pending_sleeps: Arc::new(PendingSleeps::default()), }) } -struct AppServerTimeProvider { +pub(crate) struct AppServerTimeProvider { outgoing: Weak, thread_state_manager: ThreadStateManager, + pending_sleeps: Arc, +} + +#[derive(Clone, Eq, Hash, PartialEq)] +struct SleepKey { + thread_id: String, + sleep_id: String, +} + +#[derive(Default)] +struct PendingSleeps { + // Dropping a canceled sleep future removes its waiter synchronously. + wake_senders: Mutex>>, +} + +impl PendingSleeps { + fn register(&self, key: SleepKey) -> oneshot::Receiver<()> { + let (tx, rx) = oneshot::channel(); + self.wake_senders + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert(key, tx); + rx + } + + fn wake(&self, key: &SleepKey) { + let sender = self + .wake_senders + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .remove(key); + if let Some(sender) = sender { + let _ = sender.send(()); + } + } + + fn remove(&self, key: &SleepKey) { + self.wake_senders + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .remove(key); + } +} + +struct PendingSleepGuard { + pending_sleeps: Arc, + key: SleepKey, +} + +impl Drop for PendingSleepGuard { + fn drop(&mut self) { + self.pending_sleeps.remove(&self.key); + } +} + +impl AppServerTimeProvider { + pub(crate) fn wake(&self, params: CurrentTimeWakeParams) -> CurrentTimeWakeResponse { + self.pending_sleeps.wake(&SleepKey { + thread_id: params.thread_id, + sleep_id: params.sleep_id, + }); + CurrentTimeWakeResponse {} + } } impl TimeProvider for AppServerTimeProvider { @@ -51,9 +123,36 @@ impl TimeProvider for AppServerTimeProvider { }) } - fn sleep(&self, _thread_id: ThreadId, duration: Duration) -> SleepFuture<'_> { + fn sleep(&self, thread_id: ThreadId, duration: Duration) -> SleepFuture<'_> { + let outgoing = self.outgoing.clone(); + let thread_state_manager = self.thread_state_manager.clone(); + let pending_sleeps = Arc::clone(&self.pending_sleeps); Box::pin(async move { - tokio::time::sleep(duration).await; + let outgoing = outgoing + .upgrade() + .context("app-server current-time provider is unavailable")?; + let duration_ms = u64::try_from(duration.as_millis()) + .context("external sleep duration exceeds the supported range")?; + let sleep_id = Uuid::now_v7().to_string(); + let key = SleepKey { + thread_id: thread_id.to_string(), + sleep_id: sleep_id.clone(), + }; + // Register before notifying so an eager wake cannot race with the notification. + let wake_rx = pending_sleeps.register(key.clone()); + let _guard = PendingSleepGuard { + pending_sleeps, + key, + }; + notify_external_sleep( + outgoing, + thread_state_manager, + thread_id, + sleep_id, + duration_ms, + ) + .await?; + wake_rx.await.context("external sleep was canceled")?; Ok(()) }) } @@ -64,22 +163,9 @@ async fn request_current_time( thread_state_manager: ThreadStateManager, thread_id: ThreadId, ) -> Result> { - let deadline = Instant::now() + CURRENT_TIME_REQUEST_TIMEOUT; - timeout_at( - deadline, - thread_state_manager.wait_for_thread_subscriber(thread_id), - ) - .await - .map_err(|_| { - anyhow!( - "timed out waiting for a client to subscribe to the thread after {}s", - CURRENT_TIME_REQUEST_TIMEOUT.as_secs() - ) - })?; - let connection_ids = thread_state_manager - .subscribed_connection_ids(thread_id) - .await; - let connection_id = require_single_current_time_connection(&connection_ids)?; + let deadline = Instant::now() + EXTERNAL_CLOCK_REQUEST_TIMEOUT; + let connection_id = + wait_for_current_time_connection(thread_state_manager, thread_id, deadline).await?; let connection_ids = [connection_id]; let (request_id, rx) = outgoing .send_request_to_connections( @@ -105,7 +191,7 @@ async fn request_current_time( let _canceled = outgoing.cancel_request(&request_id).await; bail!( "current-time request timed out after {}s", - CURRENT_TIME_REQUEST_TIMEOUT.as_secs() + EXTERNAL_CLOCK_REQUEST_TIMEOUT.as_secs() ); } }; @@ -116,6 +202,51 @@ async fn request_current_time( .ok_or_else(|| anyhow!("current-time response is outside the supported range")) } +async fn notify_external_sleep( + outgoing: Arc, + thread_state_manager: ThreadStateManager, + thread_id: ThreadId, + sleep_id: String, + duration_ms: u64, +) -> Result<()> { + let deadline = Instant::now() + EXTERNAL_CLOCK_REQUEST_TIMEOUT; + let connection_id = + wait_for_current_time_connection(thread_state_manager, thread_id, deadline).await?; + outgoing + .send_server_notification_to_connections( + &[connection_id], + ServerNotification::CurrentTimeSleep(CurrentTimeSleepNotification { + thread_id: thread_id.to_string(), + sleep_id, + duration_ms, + }), + ) + .await; + Ok(()) +} + +async fn wait_for_current_time_connection( + thread_state_manager: ThreadStateManager, + thread_id: ThreadId, + deadline: Instant, +) -> Result { + timeout_at( + deadline, + thread_state_manager.wait_for_thread_subscriber(thread_id), + ) + .await + .map_err(|_| { + anyhow!( + "timed out waiting for a client to subscribe to the thread after {}s", + EXTERNAL_CLOCK_REQUEST_TIMEOUT.as_secs() + ) + })?; + let connection_ids = thread_state_manager + .subscribed_connection_ids(thread_id) + .await; + require_single_current_time_connection(&connection_ids) +} + fn require_single_current_time_connection(connection_ids: &[ConnectionId]) -> Result { // External clocks are not interchangeable, so do not choose one silently. match connection_ids { diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 41ecbfe561..5bacf78fbf 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -7,6 +7,7 @@ use std::sync::atomic::AtomicBool; use crate::attestation::app_server_attestation_provider; use crate::config_manager::ConfigManager; use crate::connection_rpc_gate::ConnectionRpcGate; +use crate::current_time::AppServerTimeProvider; use crate::current_time::app_server_time_provider; use crate::error_code::invalid_request; use crate::extensions::ThreadExtensionDependencies; @@ -185,6 +186,7 @@ impl ExternalAuth for ExternalAuthRefreshBridge { pub(crate) struct MessageProcessor { outgoing: Arc, + current_time_provider: Arc, models_refresh_worker: ModelsRefreshWorker, skills_watcher: Arc, account_processor: AccountRequestProcessor, @@ -345,6 +347,8 @@ impl MessageProcessor { ), ); let goal_service = Arc::new(GoalService::new()); + let current_time_provider = + app_server_time_provider(outgoing.clone(), thread_state_manager.clone()); let thread_manager = Arc::new_cyclic(|thread_manager| { ThreadManager::new( config.as_ref(), @@ -379,10 +383,7 @@ impl MessageProcessor { outgoing.clone(), thread_state_manager.clone(), )), - Some(app_server_time_provider( - outgoing.clone(), - thread_state_manager.clone(), - )), + Some(current_time_provider.clone()), ) }); let models_manager = thread_manager.get_models_manager(); @@ -554,6 +555,7 @@ impl MessageProcessor { Self { outgoing, + current_time_provider, models_refresh_worker, skills_watcher, account_processor, @@ -953,6 +955,9 @@ impl MessageProcessor { ClientRequest::Initialize { .. } => { panic!("Initialize should be handled before initialized request dispatch"); } + ClientRequest::CurrentTimeWake { params, .. } => { + Ok(Some(self.current_time_provider.wake(params).into())) + } ClientRequest::ConfigRead { params, .. } => self .config_processor .read(params) diff --git a/codex-rs/app-server/tests/suite/v2/current_time.rs b/codex-rs/app-server/tests/suite/v2/current_time.rs index d4a3a58e40..f6e4b9f0de 100644 --- a/codex-rs/app-server/tests/suite/v2/current_time.rs +++ b/codex-rs/app-server/tests/suite/v2/current_time.rs @@ -5,6 +5,9 @@ use app_test_support::TestAppServer; use app_test_support::create_final_assistant_message_sse_response; use app_test_support::to_response; use codex_app_server_protocol::CurrentTimeReadResponse; +use codex_app_server_protocol::CurrentTimeSleepNotification; +use codex_app_server_protocol::CurrentTimeWakeParams; +use codex_app_server_protocol::CurrentTimeWakeResponse; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ServerRequest; @@ -26,6 +29,7 @@ const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(25); const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10); const CURRENT_TIME_AT: i64 = 1_781_717_655; const CURRENT_TIME_REMINDER: &str = "It is 2026-06-17 17:34:15 UTC."; +const TWELVE_HOURS_MS: u64 = 12 * 60 * 60 * 1000; #[tokio::test] async fn current_time_read_round_trip_adds_reminder_to_model_input() -> Result<()> { @@ -70,23 +74,7 @@ async fn current_time_read_round_trip_adds_reminder_to_model_input() -> Result<( .await??; let _: TurnStartResponse = to_response(turn_response)?; - let server_request = timeout( - DEFAULT_READ_TIMEOUT, - app_server.read_stream_until_request_message(), - ) - .await??; - let ServerRequest::CurrentTimeRead { request_id, params } = server_request else { - panic!("expected CurrentTimeRead request, got: {server_request:?}"); - }; - assert_eq!(params.thread_id, thread.id); - app_server - .send_response( - request_id, - serde_json::to_value(CurrentTimeReadResponse { - current_time_at: CURRENT_TIME_AT, - })?, - ) - .await?; + respond_to_current_time_read(&mut app_server, &thread.id, CURRENT_TIME_AT).await?; timeout( DEFAULT_READ_TIMEOUT, app_server.read_stream_until_notification_message("turn/completed"), @@ -103,6 +91,135 @@ async fn current_time_read_round_trip_adds_reminder_to_model_input() -> Result<( Ok(()) } +#[tokio::test] +async fn external_sleep_notification_waits_for_wake_and_ignores_stale_wakes() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = responses::start_mock_server().await; + responses::mount_sse_sequence( + &server, + vec![ + responses::sse(vec![ + responses::ev_response_created("resp-1"), + responses::ev_function_call_with_namespace( + "sleep-call", + "clock", + "sleep", + &serde_json::json!({ "duration_ms": TWELVE_HOURS_MS }).to_string(), + ), + responses::ev_completed("resp-1"), + ]), + create_final_assistant_message_sse_response("Done")?, + ], + ) + .await; + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri())?; + + let mut app_server = TestAppServer::new_with_auto_env(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, app_server.initialize()).await??; + + let thread_request_id = app_server + .send_thread_start_request_with_auto_env(ThreadStartParams::default()) + .await?; + let thread_response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + app_server.read_stream_until_response_message(RequestId::Integer(thread_request_id)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response(thread_response)?; + + let turn_request_id = app_server + .send_turn_start_request(TurnStartParams { + thread_id: thread.id.clone(), + input: vec![UserInput::Text { + text: "Sleep".to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + let turn_response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + app_server.read_stream_until_response_message(RequestId::Integer(turn_request_id)), + ) + .await??; + let _: TurnStartResponse = to_response(turn_response)?; + + respond_to_current_time_read(&mut app_server, &thread.id, CURRENT_TIME_AT).await?; + + let sleep_notification = timeout( + DEFAULT_READ_TIMEOUT, + app_server.read_stream_until_notification_message("currentTime/sleep"), + ) + .await??; + let params: CurrentTimeSleepNotification = + serde_json::from_value(sleep_notification.params.expect("currentTime/sleep params"))?; + assert_eq!(params.thread_id, thread.id); + assert_eq!(params.duration_ms, TWELVE_HOURS_MS); + assert!(!params.sleep_id.is_empty()); + let sleep_id = params.sleep_id; + + let wake_params = CurrentTimeWakeParams { + thread_id: thread.id.clone(), + sleep_id, + }; + let wake_request_id = app_server + .send_raw_request( + "currentTime/wake", + Some(serde_json::to_value(wake_params.clone())?), + ) + .await?; + let wake_response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + app_server.read_stream_until_response_message(RequestId::Integer(wake_request_id)), + ) + .await??; + let _: CurrentTimeWakeResponse = to_response(wake_response)?; + + respond_to_current_time_read(&mut app_server, &thread.id, CURRENT_TIME_AT + 1).await?; + + timeout( + DEFAULT_READ_TIMEOUT, + app_server.read_stream_until_notification_message("turn/completed"), + ) + .await??; + + let stale_wake_request_id = app_server + .send_raw_request("currentTime/wake", Some(serde_json::to_value(wake_params)?)) + .await?; + let stale_wake_response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + app_server.read_stream_until_response_message(RequestId::Integer(stale_wake_request_id)), + ) + .await??; + let _: CurrentTimeWakeResponse = to_response(stale_wake_response)?; + Ok(()) +} + +async fn respond_to_current_time_read( + app_server: &mut TestAppServer, + thread_id: &str, + current_time_at: i64, +) -> Result<()> { + let server_request = timeout( + DEFAULT_READ_TIMEOUT, + app_server.read_stream_until_request_message(), + ) + .await??; + let ServerRequest::CurrentTimeRead { request_id, params } = server_request else { + panic!("expected CurrentTimeRead request, got: {server_request:?}"); + }; + assert_eq!(params.thread_id, thread_id); + app_server + .send_response( + request_id, + serde_json::to_value(CurrentTimeReadResponse { current_time_at })?, + ) + .await?; + Ok(()) +} + fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { std::fs::write( codex_home.join("config.toml"), @@ -117,6 +234,7 @@ model_provider = "mock_provider" enabled = true reminder_interval_seconds = 1 clock_source = "external" +sleep_tool = true [model_providers.mock_provider] name = "Mock provider for test" diff --git a/codex-rs/tui/src/app/app_server_event_targets.rs b/codex-rs/tui/src/app/app_server_event_targets.rs index 212c45b4be..a31f0d7d8b 100644 --- a/codex-rs/tui/src/app/app_server_event_targets.rs +++ b/codex-rs/tui/src/app/app_server_event_targets.rs @@ -61,6 +61,7 @@ pub(super) fn server_notification_thread_target( ServerNotification::ThreadTokenUsageUpdated(notification) => { Some(notification.thread_id.as_str()) } + ServerNotification::CurrentTimeSleep(notification) => Some(notification.thread_id.as_str()), ServerNotification::ThreadGoalUpdated(notification) => { Some(notification.thread_id.as_str()) } diff --git a/codex-rs/tui/src/chatwidget/protocol.rs b/codex-rs/tui/src/chatwidget/protocol.rs index 0c5b0ed3ee..6e6f8eccef 100644 --- a/codex-rs/tui/src/chatwidget/protocol.rs +++ b/codex-rs/tui/src/chatwidget/protocol.rs @@ -196,6 +196,7 @@ impl ChatWidget { | ServerNotification::AccountRateLimitsUpdated(_) | ServerNotification::ThreadStarted(_) | ServerNotification::ThreadStatusChanged(_) + | ServerNotification::CurrentTimeSleep(_) | ServerNotification::ThreadArchived(_) | ServerNotification::ThreadDeleted(_) | ServerNotification::ThreadUnarchived(_)