From 2f0a7c0c907aff53447a2cc74cead0362633843d Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Tue, 7 Apr 2026 18:50:46 -0700 Subject: [PATCH] Add timer tool --- MODULE.bazel.lock | 4 + codex-rs/Cargo.lock | 45 +- codex-rs/Cargo.toml | 2 + .../schema/json/ClientRequest.json | 64 ++ .../schema/json/ServerNotification.json | 179 ++++ .../codex_app_server_protocol.schemas.json | 183 ++++ .../codex_app_server_protocol.v2.schemas.json | 183 ++++ .../json/v2/ThreadTimerFiredNotification.json | 125 +++ .../v2/ThreadTimerUpdatedNotification.json | 128 +++ .../schema/typescript/ServerNotification.ts | 4 +- .../schema/typescript/v2/ThreadTimer.ts | 7 + .../v2/ThreadTimerFiredNotification.ts | 6 + .../v2/ThreadTimerUpdatedNotification.ts | 6 + .../schema/typescript/v2/TimerDelivery.ts | 5 + .../schema/typescript/v2/TimerTrigger.ts | 5 + .../schema/typescript/v2/index.ts | 5 + .../src/protocol/common.rs | 19 + .../app-server-protocol/src/protocol/v2.rs | 106 +++ codex-rs/app-server/README.md | 5 + .../app-server/src/bespoke_event_handling.rs | 63 ++ .../app-server/src/codex_message_processor.rs | 188 +++- .../tests/suite/v2/turn_interrupt.rs | 2 +- .../app-server/tests/suite/v2/turn_start.rs | 2 +- codex-rs/core/Cargo.toml | 2 + codex-rs/core/config.schema.json | 6 + codex-rs/core/src/codex.rs | 339 ++++++- codex-rs/core/src/codex_tests.rs | 174 ++++ codex-rs/core/src/codex_thread.rs | 23 + codex-rs/core/src/lib.rs | 2 + codex-rs/core/src/tasks/mod.rs | 16 +- codex-rs/core/src/timer_trigger.rs | 691 ++++++++++++++ codex-rs/core/src/timers.rs | 864 ++++++++++++++++++ codex-rs/core/src/tools/handlers/mod.rs | 6 +- codex-rs/core/src/tools/handlers/timers.rs | 108 +++ codex-rs/core/src/tools/spec.rs | 12 + .../core/templates/timers/one_shot_prompt.md | 13 + .../core/templates/timers/recurring_prompt.md | 15 + codex-rs/core/tests/suite/mod.rs | 1 + codex-rs/core/tests/suite/timers.rs | 106 +++ codex-rs/features/src/lib.rs | 8 + codex-rs/rollout/src/lib.rs | 1 + codex-rs/rollout/src/list.rs | 11 +- codex-rs/rollout/src/recorder_tests.rs | 119 ++- codex-rs/rollout/src/timer_sidecar.rs | 20 + codex-rs/tools/src/lib.rs | 4 + codex-rs/tools/src/timer_tool.rs | 135 +++ codex-rs/tools/src/timer_tool_tests.rs | 31 + codex-rs/tools/src/tool_config.rs | 6 + codex-rs/tools/src/tool_registry_plan.rs | 24 + .../tools/src/tool_registry_plan_types.rs | 3 + codex-rs/tui/src/app.rs | 125 ++- codex-rs/tui/src/app/app_server_adapter.rs | 4 + codex-rs/tui/src/app_event.rs | 25 + codex-rs/tui/src/app_server_session.rs | 93 ++ codex-rs/tui/src/bottom_pane/chat_composer.rs | 9 + codex-rs/tui/src/bottom_pane/command_popup.rs | 7 + codex-rs/tui/src/bottom_pane/mod.rs | 5 + .../tui/src/bottom_pane/slash_commands.rs | 3 + codex-rs/tui/src/chatwidget.rs | 194 ++++ codex-rs/tui/src/chatwidget/tests.rs | 1 + codex-rs/tui/src/chatwidget/tests/helpers.rs | 1 + ...p_keeps_selected_timer_prompt_visible.snap | 11 + ...up_renders_schedule_triggers_readably.snap | 12 + codex-rs/tui/src/chatwidget/tests/timers.rs | 112 +++ codex-rs/tui/src/lib.rs | 1 + codex-rs/tui/src/resume_picker.rs | 56 +- codex-rs/tui/src/slash_command.rs | 4 + codex-rs/tui/src/timer_scheduler.rs | 595 ++++++++++++ 68 files changed, 5292 insertions(+), 42 deletions(-) create mode 100644 codex-rs/app-server-protocol/schema/json/v2/ThreadTimerFiredNotification.json create mode 100644 codex-rs/app-server-protocol/schema/json/v2/ThreadTimerUpdatedNotification.json create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/ThreadTimer.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/ThreadTimerFiredNotification.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/ThreadTimerUpdatedNotification.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/TimerDelivery.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/TimerTrigger.ts create mode 100644 codex-rs/core/src/timer_trigger.rs create mode 100644 codex-rs/core/src/timers.rs create mode 100644 codex-rs/core/src/tools/handlers/timers.rs create mode 100644 codex-rs/core/templates/timers/one_shot_prompt.md create mode 100644 codex-rs/core/templates/timers/recurring_prompt.md create mode 100644 codex-rs/core/tests/suite/timers.rs create mode 100644 codex-rs/rollout/src/timer_sidecar.rs create mode 100644 codex-rs/tools/src/timer_tool.rs create mode 100644 codex-rs/tools/src/timer_tool_tests.rs create mode 100644 codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__timers__thread_timers_popup_keeps_selected_timer_prompt_visible.snap create mode 100644 codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__timers__thread_timers_popup_renders_schedule_triggers_readably.snap create mode 100644 codex-rs/tui/src/chatwidget/tests/timers.rs create mode 100644 codex-rs/tui/src/timer_scheduler.rs diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 746679af39..ecbe3b49d2 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -698,6 +698,7 @@ "chacha20_0.9.1": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1\"},{\"name\":\"cipher\",\"req\":\"^0.4.4\"},{\"features\":[\"dev\"],\"kind\":\"dev\",\"name\":\"cipher\",\"req\":\"^0.4.4\"},{\"name\":\"cpufeatures\",\"req\":\"^0.2\",\"target\":\"cfg(any(target_arch = \\\"x86_64\\\", target_arch = \\\"x86\\\"))\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.3.3\"}],\"features\":{\"std\":[\"cipher/std\"],\"zeroize\":[\"cipher/zeroize\"]}}", "chacha20poly1305_0.10.1": "{\"dependencies\":[{\"default_features\":false,\"name\":\"aead\",\"req\":\"^0.5\"},{\"default_features\":false,\"features\":[\"dev\"],\"kind\":\"dev\",\"name\":\"aead\",\"req\":\"^0.5\"},{\"features\":[\"zeroize\"],\"name\":\"chacha20\",\"req\":\"^0.9\"},{\"name\":\"cipher\",\"req\":\"^0.4\"},{\"name\":\"poly1305\",\"req\":\"^0.8\"},{\"default_features\":false,\"name\":\"zeroize\",\"req\":\"^1.5\"}],\"features\":{\"alloc\":[\"aead/alloc\"],\"default\":[\"alloc\",\"getrandom\"],\"getrandom\":[\"aead/getrandom\",\"rand_core\"],\"heapless\":[\"aead/heapless\"],\"rand_core\":[\"aead/rand_core\"],\"reduced-round\":[],\"std\":[\"aead/std\",\"alloc\"],\"stream\":[\"aead/stream\"]}}", "chardetng_0.1.17": "{\"dependencies\":[{\"name\":\"arrayvec\",\"optional\":true,\"req\":\"^0.5.1\"},{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"detone\",\"req\":\"^1.0.0\"},{\"default_features\":false,\"name\":\"encoding_rs\",\"req\":\"^0.8.29\"},{\"default_features\":false,\"name\":\"memchr\",\"req\":\"^2.2.0\"},{\"name\":\"rayon\",\"optional\":true,\"req\":\"^1.3.0\"}],\"features\":{\"multithreading\":[\"rayon\",\"arrayvec\"],\"testing-only-no-semver-guarantees-do-not-use\":[]}}", + "chrono-tz_0.10.4": "{\"dependencies\":[{\"features\":[\"derive\"],\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.2\"},{\"default_features\":false,\"name\":\"chrono\",\"req\":\"^0.4.25\"},{\"default_features\":false,\"features\":[\"alloc\"],\"kind\":\"dev\",\"name\":\"chrono\",\"req\":\"^0.4\"},{\"kind\":\"build\",\"name\":\"chrono-tz-build\",\"optional\":true,\"req\":\"^0.5\"},{\"kind\":\"dev\",\"name\":\"chrono-tz-build\",\"req\":\"^0.5\"},{\"default_features\":false,\"name\":\"phf\",\"req\":\"^0.12\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.99\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tzfile\",\"req\":\"^0.1\"},{\"default_features\":false,\"name\":\"uncased\",\"optional\":true,\"req\":\"^0.9\"}],\"features\":{\"case-insensitive\":[\"dep:uncased\",\"chrono-tz-build\",\"chrono-tz-build/case-insensitive\",\"phf/uncased\"],\"default\":[\"std\"],\"filter-by-regex\":[\"chrono-tz-build\",\"chrono-tz-build/filter-by-regex\"],\"serde\":[\"dep:serde\"],\"std\":[]}}", "chrono_0.4.43": "{\"dependencies\":[{\"features\":[\"derive\"],\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.0\"},{\"name\":\"defmt\",\"optional\":true,\"req\":\"^1.0.1\"},{\"features\":[\"fallback\"],\"name\":\"iana-time-zone\",\"optional\":true,\"req\":\"^0.1.45\",\"target\":\"cfg(unix)\"},{\"name\":\"js-sys\",\"optional\":true,\"req\":\"^0.3\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", not(any(target_os = \\\"emscripten\\\", target_os = \\\"wasi\\\"))))\"},{\"default_features\":false,\"name\":\"num-traits\",\"req\":\"^0.2\"},{\"name\":\"pure-rust-locales\",\"optional\":true,\"req\":\"^0.8.2\"},{\"default_features\":false,\"name\":\"rkyv\",\"optional\":true,\"req\":\"^0.7.43\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.99\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"similar-asserts\",\"req\":\"^1.6.1\"},{\"name\":\"wasm-bindgen\",\"optional\":true,\"req\":\"^0.2\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", not(any(target_os = \\\"emscripten\\\", target_os = \\\"wasi\\\"))))\"},{\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", not(any(target_os = \\\"emscripten\\\", target_os = \\\"wasi\\\"))))\"},{\"kind\":\"dev\",\"name\":\"windows-bindgen\",\"req\":\"^0.66\"},{\"name\":\"windows-link\",\"optional\":true,\"req\":\"^0.2\",\"target\":\"cfg(windows)\"}],\"features\":{\"__internal_bench\":[],\"alloc\":[],\"clock\":[\"winapi\",\"iana-time-zone\",\"now\"],\"core-error\":[],\"default\":[\"clock\",\"std\",\"oldtime\",\"wasmbind\"],\"defmt\":[\"dep:defmt\",\"pure-rust-locales?/defmt\"],\"libc\":[],\"now\":[\"std\"],\"oldtime\":[],\"rkyv\":[\"dep:rkyv\",\"rkyv/size_32\"],\"rkyv-16\":[\"dep:rkyv\",\"rkyv?/size_16\"],\"rkyv-32\":[\"dep:rkyv\",\"rkyv?/size_32\"],\"rkyv-64\":[\"dep:rkyv\",\"rkyv?/size_64\"],\"rkyv-validation\":[\"rkyv?/validation\"],\"std\":[\"alloc\"],\"unstable-locales\":[\"pure-rust-locales\"],\"wasmbind\":[\"wasm-bindgen\",\"js-sys\"],\"winapi\":[\"windows-link\"]}}", "chunked_transfer_1.5.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3\"}],\"features\":{}}", "cipher_0.4.4": "{\"dependencies\":[{\"name\":\"blobby\",\"optional\":true,\"req\":\"^0.3\"},{\"name\":\"crypto-common\",\"req\":\"^0.1.6\"},{\"name\":\"inout\",\"req\":\"^0.1\"},{\"default_features\":false,\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1.5\"}],\"features\":{\"alloc\":[],\"block-padding\":[\"inout/block-padding\"],\"dev\":[\"blobby\"],\"rand_core\":[\"crypto-common/rand_core\"],\"std\":[\"alloc\",\"crypto-common/std\",\"inout/std\"]}}", @@ -1138,7 +1139,9 @@ "percent-encoding_2.3.2": "{\"dependencies\":[],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"std\":[\"alloc\"]}}", "petgraph_0.6.5": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"ahash\",\"req\":\"^0.7.2\"},{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.3\"},{\"kind\":\"dev\",\"name\":\"defmac\",\"req\":\"^0.2.1\"},{\"default_features\":false,\"name\":\"fixedbitset\",\"req\":\"^0.4.0\"},{\"kind\":\"dev\",\"name\":\"fxhash\",\"req\":\"^0.2.1\"},{\"name\":\"indexmap\",\"req\":\"^2.0\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"itertools\",\"req\":\"^0.12.1\"},{\"kind\":\"dev\",\"name\":\"odds\",\"req\":\"^0.4.0\"},{\"default_features\":false,\"name\":\"quickcheck\",\"optional\":true,\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.5.5\"},{\"name\":\"rayon\",\"optional\":true,\"req\":\"^1.5.3\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_derive\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"all\":[\"unstable\",\"quickcheck\",\"matrix_graph\",\"stable_graph\",\"graphmap\",\"rayon\"],\"default\":[\"graphmap\",\"stable_graph\",\"matrix_graph\"],\"generate\":[],\"graphmap\":[],\"matrix_graph\":[],\"rayon\":[\"dep:rayon\",\"indexmap/rayon\"],\"serde-1\":[\"serde\",\"serde_derive\"],\"stable_graph\":[],\"unstable\":[\"generate\"]}}", "petgraph_0.8.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"ahash\",\"req\":\"^0.7.2\"},{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.3\"},{\"kind\":\"dev\",\"name\":\"defmac\",\"req\":\"^0.2.1\"},{\"name\":\"dot-parser\",\"optional\":true,\"req\":\"^0.5.1\"},{\"name\":\"dot-parser-macros\",\"optional\":true,\"req\":\"^0.5.1\"},{\"default_features\":false,\"name\":\"fixedbitset\",\"req\":\"^0.5.7\"},{\"kind\":\"dev\",\"name\":\"fxhash\",\"req\":\"^0.2.1\"},{\"default_features\":false,\"features\":[\"default-hasher\",\"inline-more\"],\"name\":\"hashbrown\",\"req\":\"^0.15.0\"},{\"default_features\":false,\"name\":\"indexmap\",\"req\":\"^2.5.0\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"itertools\",\"req\":\"^0.12.1\"},{\"kind\":\"dev\",\"name\":\"odds\",\"req\":\"^0.4.0\"},{\"default_features\":false,\"name\":\"quickcheck\",\"optional\":true,\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.5.5\"},{\"name\":\"rayon\",\"optional\":true,\"req\":\"^1.5.3\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"serde_derive\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"all\":[\"unstable\",\"quickcheck\",\"matrix_graph\",\"stable_graph\",\"graphmap\",\"rayon\",\"dot_parser\"],\"default\":[\"std\",\"graphmap\",\"stable_graph\",\"matrix_graph\"],\"dot_parser\":[\"std\",\"dep:dot-parser\",\"dep:dot-parser-macros\"],\"generate\":[],\"graphmap\":[],\"matrix_graph\":[],\"quickcheck\":[\"std\",\"dep:quickcheck\",\"graphmap\",\"stable_graph\"],\"rayon\":[\"std\",\"dep:rayon\",\"indexmap/rayon\",\"hashbrown/rayon\"],\"serde-1\":[\"serde\",\"serde_derive\"],\"stable_graph\":[\"serde?/alloc\"],\"std\":[\"indexmap/std\"],\"unstable\":[\"generate\"]}}", + "phf_0.12.1": "{\"dependencies\":[{\"name\":\"phf_macros\",\"optional\":true,\"req\":\"^0.12.0\"},{\"default_features\":false,\"name\":\"phf_shared\",\"req\":\"^0.12.0\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"macros\":[\"phf_macros\"],\"std\":[\"phf_shared/std\",\"serde?/std\"],\"uncased\":[\"phf_macros?/uncased\",\"phf_shared/uncased\"],\"unicase\":[\"phf_macros?/unicase\",\"phf_shared/unicase\"]}}", "phf_shared_0.11.3": "{\"dependencies\":[{\"name\":\"siphasher\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"uncased\",\"optional\":true,\"req\":\"^0.9.9\"},{\"name\":\"unicase\",\"optional\":true,\"req\":\"^2.4.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", + "phf_shared_0.12.1": "{\"dependencies\":[{\"name\":\"siphasher\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"uncased\",\"optional\":true,\"req\":\"^0.9.9\"},{\"name\":\"unicase\",\"optional\":true,\"req\":\"^2.4.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "pin-project-internal_1.1.10": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1.0.60\"},{\"name\":\"quote\",\"req\":\"^1.0.25\"},{\"default_features\":false,\"features\":[\"parsing\",\"printing\",\"clone-impls\",\"proc-macro\",\"full\",\"visit-mut\"],\"name\":\"syn\",\"req\":\"^2.0.1\"}],\"features\":{}}", "pin-project-lite_0.2.16": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1\"}],\"features\":{}}", "pin-project-lite_0.2.17": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1\"}],\"features\":{}}", @@ -1236,6 +1239,7 @@ "ring_0.17.14": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.2.8\"},{\"default_features\":false,\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"name\":\"getrandom\",\"req\":\"^0.2.10\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.148\",\"target\":\"cfg(all(any(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), all(target_arch = \\\"arm\\\", target_endian = \\\"little\\\")), any(target_os = \\\"android\\\", target_os = \\\"linux\\\")))\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.155\",\"target\":\"cfg(all(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), target_vendor = \\\"apple\\\", any(target_os = \\\"ios\\\", target_os = \\\"macos\\\", target_os = \\\"tvos\\\", target_os = \\\"visionos\\\", target_os = \\\"watchos\\\")))\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2.148\",\"target\":\"cfg(any(unix, windows, target_os = \\\"wasi\\\"))\"},{\"name\":\"untrusted\",\"req\":\"^0.9\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3.37\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", target_os = \\\"unknown\\\"))\"},{\"features\":[\"Win32_Foundation\",\"Win32_System_Threading\"],\"name\":\"windows-sys\",\"req\":\"^0.52\",\"target\":\"cfg(all(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), target_os = \\\"windows\\\"))\"}],\"features\":{\"alloc\":[],\"default\":[\"alloc\",\"dev_urandom_fallback\"],\"dev_urandom_fallback\":[],\"less-safe-getrandom-custom-or-rdrand\":[],\"less-safe-getrandom-espidf\":[],\"slow_tests\":[],\"std\":[\"alloc\"],\"test_logging\":[],\"unstable-testing-arm-no-hw\":[],\"unstable-testing-arm-no-neon\":[],\"wasm32_unknown_unknown_js\":[\"getrandom/js\"]}}", "rmcp-macros_0.15.0": "{\"dependencies\":[{\"name\":\"darling\",\"req\":\"^0.23\"},{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{}}", "rmcp_0.15.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0\"},{\"name\":\"async-trait\",\"req\":\"^0.1.89\"},{\"kind\":\"dev\",\"name\":\"async-trait\",\"req\":\"^0.1\"},{\"name\":\"axum\",\"optional\":true,\"req\":\"^0.8\"},{\"name\":\"base64\",\"optional\":true,\"req\":\"^0.22\"},{\"name\":\"bytes\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"serde\",\"clock\",\"std\",\"oldtime\"],\"name\":\"chrono\",\"req\":\"^0.4.38\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\"))\"},{\"features\":[\"serde\"],\"name\":\"chrono\",\"req\":\"^0.4.38\",\"target\":\"cfg(not(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\")))\"},{\"name\":\"futures\",\"req\":\"^0.3\"},{\"name\":\"http\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"http-body\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"http-body-util\",\"optional\":true,\"req\":\"^0.1\"},{\"default_features\":false,\"features\":[\"reqwest\"],\"name\":\"oauth2\",\"optional\":true,\"req\":\"^5.0\"},{\"name\":\"pastey\",\"optional\":true,\"req\":\"^0.2.0\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"features\":[\"tokio1\"],\"name\":\"process-wrap\",\"optional\":true,\"req\":\"^9.0\"},{\"name\":\"rand\",\"optional\":true,\"req\":\"^0.9\"},{\"default_features\":false,\"features\":[\"json\",\"stream\"],\"name\":\"reqwest\",\"optional\":true,\"req\":\"^0.12\"},{\"name\":\"rmcp-macros\",\"optional\":true,\"req\":\"^0.15.0\"},{\"features\":[\"chrono04\"],\"name\":\"schemars\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"chrono04\"],\"kind\":\"dev\",\"name\":\"schemars\",\"req\":\"^1.1.0\"},{\"features\":[\"derive\",\"rc\"],\"name\":\"serde\",\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"sse-stream\",\"optional\":true,\"req\":\"^0.2\"},{\"name\":\"thiserror\",\"req\":\"^2\"},{\"features\":[\"sync\",\"macros\",\"rt\",\"time\"],\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"name\":\"tokio-stream\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"tokio-util\",\"req\":\"^0.7\"},{\"name\":\"tower-service\",\"optional\":true,\"req\":\"^0.3\"},{\"name\":\"tracing\",\"req\":\"^0.1\"},{\"features\":[\"env-filter\",\"std\",\"fmt\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"name\":\"url\",\"optional\":true,\"req\":\"^2.4\"},{\"features\":[\"v4\"],\"name\":\"uuid\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"__reqwest\":[\"dep:reqwest\"],\"auth\":[\"dep:oauth2\",\"__reqwest\",\"dep:url\"],\"client\":[\"dep:tokio-stream\"],\"client-side-sse\":[\"dep:sse-stream\",\"dep:http\"],\"default\":[\"base64\",\"macros\",\"server\"],\"elicitation\":[\"dep:url\"],\"macros\":[\"dep:rmcp-macros\",\"dep:pastey\"],\"reqwest\":[\"__reqwest\",\"reqwest?/rustls-tls\"],\"reqwest-native-tls\":[\"__reqwest\",\"reqwest?/native-tls\"],\"reqwest-tls-no-provider\":[\"__reqwest\",\"reqwest?/rustls-tls-no-provider\"],\"schemars\":[\"dep:schemars\"],\"server\":[\"transport-async-rw\",\"dep:schemars\",\"dep:pastey\"],\"server-side-http\":[\"uuid\",\"dep:rand\",\"dep:tokio-stream\",\"dep:http\",\"dep:http-body\",\"dep:http-body-util\",\"dep:bytes\",\"dep:sse-stream\",\"dep:axum\",\"tower\"],\"tower\":[\"dep:tower-service\"],\"transport-async-rw\":[\"tokio/io-util\",\"tokio-util/codec\"],\"transport-child-process\":[\"transport-async-rw\",\"tokio/process\",\"dep:process-wrap\"],\"transport-io\":[\"transport-async-rw\",\"tokio/io-std\"],\"transport-streamable-http-client\":[\"client-side-sse\",\"transport-worker\"],\"transport-streamable-http-client-reqwest\":[\"transport-streamable-http-client\",\"__reqwest\"],\"transport-streamable-http-server\":[\"transport-streamable-http-server-session\",\"server-side-http\",\"transport-worker\"],\"transport-streamable-http-server-session\":[\"transport-async-rw\",\"dep:tokio-stream\"],\"transport-worker\":[\"dep:tokio-stream\"]}}", + "rrule_0.14.0": "{\"dependencies\":[{\"name\":\"chrono\",\"req\":\"^0.4.39\"},{\"name\":\"chrono-tz\",\"req\":\"^0.10.1\"},{\"features\":[\"derive\"],\"name\":\"clap\",\"optional\":true,\"req\":\"^4.5.26\"},{\"name\":\"log\",\"req\":\"^0.4.25\"},{\"default_features\":false,\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"orig_serde\",\"package\":\"serde\",\"req\":\"^1.0.217\"},{\"default_features\":false,\"features\":[\"perf\",\"std\"],\"name\":\"regex\",\"req\":\"^1.11.1\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.135\"},{\"name\":\"serde_with\",\"optional\":true,\"req\":\"^3.12.0\"},{\"name\":\"thiserror\",\"req\":\"^2.0.11\"}],\"features\":{\"by-easter\":[],\"cli-tool\":[\"clap\"],\"default\":[],\"exrule\":[],\"serde\":[\"serde_with\",\"chrono/serde\",\"chrono-tz/serde\"]}}", "rsa_0.9.10": "{\"dependencies\":[{\"features\":[\"alloc\"],\"kind\":\"dev\",\"name\":\"base64ct\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"const-oid\",\"req\":\"^0.9\"},{\"default_features\":false,\"features\":[\"alloc\",\"oid\"],\"name\":\"digest\",\"req\":\"^0.10.5\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4.1\"},{\"default_features\":false,\"features\":[\"i128\",\"prime\",\"zeroize\"],\"name\":\"num-bigint\",\"package\":\"num-bigint-dig\",\"req\":\"^0.8.6\"},{\"default_features\":false,\"name\":\"num-integer\",\"req\":\"^0.1.39\"},{\"default_features\":false,\"features\":[\"libm\"],\"name\":\"num-traits\",\"req\":\"^0.2.9\"},{\"default_features\":false,\"features\":[\"alloc\",\"pkcs8\"],\"name\":\"pkcs1\",\"req\":\"^0.7.5\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"pkcs8\",\"req\":\"^0.10.2\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rand_chacha\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"rand_core\",\"req\":\"^0.6.4\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"rand_core\",\"req\":\"^0.6\"},{\"kind\":\"dev\",\"name\":\"rand_xorshift\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.184\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0.89\"},{\"default_features\":false,\"features\":[\"oid\"],\"name\":\"sha1\",\"optional\":true,\"req\":\"^0.10.5\"},{\"default_features\":false,\"features\":[\"oid\"],\"kind\":\"dev\",\"name\":\"sha1\",\"req\":\"^0.10.5\"},{\"default_features\":false,\"features\":[\"oid\"],\"name\":\"sha2\",\"optional\":true,\"req\":\"^0.10.6\"},{\"default_features\":false,\"features\":[\"oid\"],\"kind\":\"dev\",\"name\":\"sha2\",\"req\":\"^0.10.6\"},{\"default_features\":false,\"features\":[\"oid\"],\"kind\":\"dev\",\"name\":\"sha3\",\"req\":\"^0.10.7\"},{\"default_features\":false,\"features\":[\"alloc\",\"digest\",\"rand_core\"],\"name\":\"signature\",\"req\":\">2.0, <2.3\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"spki\",\"req\":\"^0.7.3\"},{\"default_features\":false,\"name\":\"subtle\",\"req\":\"^2.1.1\"},{\"features\":[\"alloc\"],\"name\":\"zeroize\",\"req\":\"^1.5\"}],\"features\":{\"default\":[\"std\",\"pem\",\"u64_digit\"],\"getrandom\":[\"rand_core/getrandom\"],\"hazmat\":[],\"nightly\":[\"num-bigint/nightly\"],\"pem\":[\"pkcs1/pem\",\"pkcs8/pem\"],\"pkcs5\":[\"pkcs8/encryption\"],\"serde\":[\"dep:serde\",\"num-bigint/serde\"],\"std\":[\"digest/std\",\"pkcs1/std\",\"pkcs8/std\",\"rand_core/std\",\"signature/std\"],\"u64_digit\":[\"num-bigint/u64_digit\"]}}", "rust-embed-impl_8.11.0": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"name\":\"rust-embed-utils\",\"req\":\"^8.11.0\"},{\"name\":\"shellexpand\",\"optional\":true,\"req\":\"^3\"},{\"default_features\":false,\"features\":[\"derive\",\"parsing\",\"proc-macro\",\"printing\"],\"name\":\"syn\",\"req\":\"^2\"},{\"name\":\"walkdir\",\"req\":\"^2.3.1\"}],\"features\":{\"compression\":[],\"debug-embed\":[],\"deterministic-timestamps\":[],\"include-exclude\":[\"rust-embed-utils/include-exclude\"],\"interpolate-folder-path\":[\"shellexpand\"],\"mime-guess\":[\"rust-embed-utils/mime-guess\"]}}", "rust-embed-utils_8.11.0": "{\"dependencies\":[{\"name\":\"globset\",\"optional\":true,\"req\":\"^0.4.8\"},{\"name\":\"mime_guess\",\"optional\":true,\"req\":\"^2.0.4\"},{\"name\":\"sha2\",\"req\":\"^0.10.5\"},{\"name\":\"walkdir\",\"req\":\"^2.3.1\"}],\"features\":{\"debug-embed\":[],\"include-exclude\":[\"globset\"],\"mime-guess\":[\"mime_guess\"]}}", diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index b109d64430..8499e684e6 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1233,6 +1233,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "chrono-tz" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3" +dependencies = [ + "chrono", + "phf", +] + [[package]] name = "chunked_transfer" version = "1.5.0" @@ -1862,6 +1872,7 @@ dependencies = [ "base64 0.22.1", "bm25", "chrono", + "chrono-tz", "clap", "codex-analytics", "codex-api", @@ -1939,6 +1950,7 @@ dependencies = [ "regex-lite", "reqwest", "rmcp", + "rrule", "serde", "serde_json", "serial_test", @@ -7199,6 +7211,15 @@ dependencies = [ "indexmap 2.13.0", ] +[[package]] +name = "phf" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7" +dependencies = [ + "phf_shared 0.12.1", +] + [[package]] name = "phf_shared" version = "0.11.3" @@ -7208,6 +7229,15 @@ dependencies = [ "siphasher", ] +[[package]] +name = "phf_shared" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project" version = "1.1.10" @@ -8358,6 +8388,19 @@ dependencies = [ "syn 2.0.114", ] +[[package]] +name = "rrule" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "720acfb4980b9d8a6a430f6d7a11933e701ebbeba5eee39cc9d8c5f932aaff74" +dependencies = [ + "chrono", + "chrono-tz", + "log", + "regex", + "thiserror 2.0.18", +] + [[package]] name = "rsa" version = "0.9.10" @@ -9704,7 +9747,7 @@ checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f" dependencies = [ "new_debug_unreachable", "parking_lot", - "phf_shared", + "phf_shared 0.11.3", "precomputed-hash", ] diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 16329276cd..9ef6984052 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -208,6 +208,7 @@ bm25 = "2.3.2" bytes = "1.10.1" chardetng = "0.1.17" chrono = "0.4.43" +chrono-tz = "0.10.4" clap = "4" clap_complete = "4" color-eyre = "0.6.3" @@ -275,6 +276,7 @@ ratatui-macros = "0.6.0" regex = "1.12.3" regex-lite = "0.1.8" reqwest = "0.12" +rrule = "0.14.0" rmcp = { version = "0.15.0", default-features = false } runfiles = { git = "https://github.com/dzbarsky/rules_rust", rev = "b56cbaa8465e74127f1ea216f813cd377295ad81" } rustls = { version = "0.23", default-features = false, features = [ diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 4ca884cb55..a158e3eda5 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -3212,6 +3212,70 @@ ], "type": "object" }, + "TimerDelivery": { + "enum": [ + "after-turn", + "steer-current-turn" + ], + "type": "string" + }, + "TimerTrigger": { + "oneOf": [ + { + "properties": { + "kind": { + "enum": [ + "delay" + ], + "type": "string" + }, + "repeat": { + "type": [ + "boolean", + "null" + ] + }, + "seconds": { + "format": "uint64", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "kind", + "seconds" + ], + "type": "object" + }, + { + "properties": { + "dtstart": { + "type": [ + "string", + "null" + ] + }, + "kind": { + "enum": [ + "schedule" + ], + "type": "string" + }, + "rrule": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "kind" + ], + "title": "KindTimerTrigger", + "type": "object" + } + ] + }, "TurnInterruptParams": { "properties": { "threadId": { diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 07049e08cf..9f3ae7e348 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -3463,6 +3463,81 @@ ], "type": "object" }, + "ThreadTimer": { + "properties": { + "createdAt": { + "format": "int64", + "type": "integer" + }, + "delivery": { + "$ref": "#/definitions/TimerDelivery" + }, + "id": { + "type": "string" + }, + "lastRunAt": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "nextRunAt": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "prompt": { + "type": "string" + }, + "trigger": { + "$ref": "#/definitions/TimerTrigger" + } + }, + "required": [ + "createdAt", + "delivery", + "id", + "prompt", + "trigger" + ], + "type": "object" + }, + "ThreadTimerFiredNotification": { + "properties": { + "threadId": { + "type": "string" + }, + "timer": { + "$ref": "#/definitions/ThreadTimer" + } + }, + "required": [ + "threadId", + "timer" + ], + "type": "object" + }, + "ThreadTimerUpdatedNotification": { + "properties": { + "threadId": { + "type": "string" + }, + "timers": { + "items": { + "$ref": "#/definitions/ThreadTimer" + }, + "type": "array" + } + }, + "required": [ + "threadId", + "timers" + ], + "type": "object" + }, "ThreadTokenUsage": { "properties": { "last": { @@ -3515,6 +3590,70 @@ ], "type": "object" }, + "TimerDelivery": { + "enum": [ + "after-turn", + "steer-current-turn" + ], + "type": "string" + }, + "TimerTrigger": { + "oneOf": [ + { + "properties": { + "kind": { + "enum": [ + "delay" + ], + "type": "string" + }, + "repeat": { + "type": [ + "boolean", + "null" + ] + }, + "seconds": { + "format": "uint64", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "kind", + "seconds" + ], + "type": "object" + }, + { + "properties": { + "dtstart": { + "type": [ + "string", + "null" + ] + }, + "kind": { + "enum": [ + "schedule" + ], + "type": "string" + }, + "rrule": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "kind" + ], + "title": "KindTimerTrigger", + "type": "object" + } + ] + }, "TokenUsageBreakdown": { "properties": { "cachedInputTokens": { @@ -4180,6 +4319,46 @@ "title": "Thread/name/updatedNotification", "type": "object" }, + { + "properties": { + "method": { + "enum": [ + "thread/timer/updated" + ], + "title": "Thread/timer/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadTimerUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/timer/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/timer/fired" + ], + "title": "Thread/timer/firedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadTimerFiredNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/timer/firedNotification", + "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 2d81f62684..4531e7b0e2 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 @@ -3572,6 +3572,46 @@ "title": "Thread/name/updatedNotification", "type": "object" }, + { + "properties": { + "method": { + "enum": [ + "thread/timer/updated" + ], + "title": "Thread/timer/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/ThreadTimerUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/timer/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/timer/fired" + ], + "title": "Thread/timer/firedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/ThreadTimerFiredNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/timer/firedNotification", + "type": "object" + }, { "properties": { "method": { @@ -14339,6 +14379,85 @@ "title": "ThreadStatusChangedNotification", "type": "object" }, + "ThreadTimer": { + "properties": { + "createdAt": { + "format": "int64", + "type": "integer" + }, + "delivery": { + "$ref": "#/definitions/v2/TimerDelivery" + }, + "id": { + "type": "string" + }, + "lastRunAt": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "nextRunAt": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "prompt": { + "type": "string" + }, + "trigger": { + "$ref": "#/definitions/v2/TimerTrigger" + } + }, + "required": [ + "createdAt", + "delivery", + "id", + "prompt", + "trigger" + ], + "type": "object" + }, + "ThreadTimerFiredNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + }, + "timer": { + "$ref": "#/definitions/v2/ThreadTimer" + } + }, + "required": [ + "threadId", + "timer" + ], + "title": "ThreadTimerFiredNotification", + "type": "object" + }, + "ThreadTimerUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + }, + "timers": { + "items": { + "$ref": "#/definitions/v2/ThreadTimer" + }, + "type": "array" + } + }, + "required": [ + "threadId", + "timers" + ], + "title": "ThreadTimerUpdatedNotification", + "type": "object" + }, "ThreadTokenUsage": { "properties": { "last": { @@ -14455,6 +14574,70 @@ ], "type": "string" }, + "TimerDelivery": { + "enum": [ + "after-turn", + "steer-current-turn" + ], + "type": "string" + }, + "TimerTrigger": { + "oneOf": [ + { + "properties": { + "kind": { + "enum": [ + "delay" + ], + "type": "string" + }, + "repeat": { + "type": [ + "boolean", + "null" + ] + }, + "seconds": { + "format": "uint64", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "kind", + "seconds" + ], + "type": "object" + }, + { + "properties": { + "dtstart": { + "type": [ + "string", + "null" + ] + }, + "kind": { + "enum": [ + "schedule" + ], + "type": "string" + }, + "rrule": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "kind" + ], + "title": "KindTimerTrigger", + "type": "object" + } + ] + }, "TokenUsageBreakdown": { "properties": { "cachedInputTokens": { 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 c58326c6f8..fa5fe68c12 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 @@ -8673,6 +8673,46 @@ "title": "Thread/name/updatedNotification", "type": "object" }, + { + "properties": { + "method": { + "enum": [ + "thread/timer/updated" + ], + "title": "Thread/timer/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadTimerUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/timer/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/timer/fired" + ], + "title": "Thread/timer/firedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadTimerFiredNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/timer/firedNotification", + "type": "object" + }, { "properties": { "method": { @@ -12194,6 +12234,85 @@ "title": "ThreadStatusChangedNotification", "type": "object" }, + "ThreadTimer": { + "properties": { + "createdAt": { + "format": "int64", + "type": "integer" + }, + "delivery": { + "$ref": "#/definitions/TimerDelivery" + }, + "id": { + "type": "string" + }, + "lastRunAt": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "nextRunAt": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "prompt": { + "type": "string" + }, + "trigger": { + "$ref": "#/definitions/TimerTrigger" + } + }, + "required": [ + "createdAt", + "delivery", + "id", + "prompt", + "trigger" + ], + "type": "object" + }, + "ThreadTimerFiredNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + }, + "timer": { + "$ref": "#/definitions/ThreadTimer" + } + }, + "required": [ + "threadId", + "timer" + ], + "title": "ThreadTimerFiredNotification", + "type": "object" + }, + "ThreadTimerUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + }, + "timers": { + "items": { + "$ref": "#/definitions/ThreadTimer" + }, + "type": "array" + } + }, + "required": [ + "threadId", + "timers" + ], + "title": "ThreadTimerUpdatedNotification", + "type": "object" + }, "ThreadTokenUsage": { "properties": { "last": { @@ -12310,6 +12429,70 @@ ], "type": "string" }, + "TimerDelivery": { + "enum": [ + "after-turn", + "steer-current-turn" + ], + "type": "string" + }, + "TimerTrigger": { + "oneOf": [ + { + "properties": { + "kind": { + "enum": [ + "delay" + ], + "type": "string" + }, + "repeat": { + "type": [ + "boolean", + "null" + ] + }, + "seconds": { + "format": "uint64", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "kind", + "seconds" + ], + "type": "object" + }, + { + "properties": { + "dtstart": { + "type": [ + "string", + "null" + ] + }, + "kind": { + "enum": [ + "schedule" + ], + "type": "string" + }, + "rrule": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "kind" + ], + "title": "KindTimerTrigger", + "type": "object" + } + ] + }, "TokenUsageBreakdown": { "properties": { "cachedInputTokens": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadTimerFiredNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadTimerFiredNotification.json new file mode 100644 index 0000000000..98d74d4da0 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadTimerFiredNotification.json @@ -0,0 +1,125 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "ThreadTimer": { + "properties": { + "createdAt": { + "format": "int64", + "type": "integer" + }, + "delivery": { + "$ref": "#/definitions/TimerDelivery" + }, + "id": { + "type": "string" + }, + "lastRunAt": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "nextRunAt": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "prompt": { + "type": "string" + }, + "trigger": { + "$ref": "#/definitions/TimerTrigger" + } + }, + "required": [ + "createdAt", + "delivery", + "id", + "prompt", + "trigger" + ], + "type": "object" + }, + "TimerDelivery": { + "enum": [ + "after-turn", + "steer-current-turn" + ], + "type": "string" + }, + "TimerTrigger": { + "oneOf": [ + { + "properties": { + "kind": { + "enum": [ + "delay" + ], + "type": "string" + }, + "repeat": { + "type": [ + "boolean", + "null" + ] + }, + "seconds": { + "format": "uint64", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "kind", + "seconds" + ], + "type": "object" + }, + { + "properties": { + "dtstart": { + "type": [ + "string", + "null" + ] + }, + "kind": { + "enum": [ + "schedule" + ], + "type": "string" + }, + "rrule": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "kind" + ], + "title": "KindTimerTrigger", + "type": "object" + } + ] + } + }, + "properties": { + "threadId": { + "type": "string" + }, + "timer": { + "$ref": "#/definitions/ThreadTimer" + } + }, + "required": [ + "threadId", + "timer" + ], + "title": "ThreadTimerFiredNotification", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadTimerUpdatedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadTimerUpdatedNotification.json new file mode 100644 index 0000000000..afa5a9677a --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadTimerUpdatedNotification.json @@ -0,0 +1,128 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "ThreadTimer": { + "properties": { + "createdAt": { + "format": "int64", + "type": "integer" + }, + "delivery": { + "$ref": "#/definitions/TimerDelivery" + }, + "id": { + "type": "string" + }, + "lastRunAt": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "nextRunAt": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "prompt": { + "type": "string" + }, + "trigger": { + "$ref": "#/definitions/TimerTrigger" + } + }, + "required": [ + "createdAt", + "delivery", + "id", + "prompt", + "trigger" + ], + "type": "object" + }, + "TimerDelivery": { + "enum": [ + "after-turn", + "steer-current-turn" + ], + "type": "string" + }, + "TimerTrigger": { + "oneOf": [ + { + "properties": { + "kind": { + "enum": [ + "delay" + ], + "type": "string" + }, + "repeat": { + "type": [ + "boolean", + "null" + ] + }, + "seconds": { + "format": "uint64", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "kind", + "seconds" + ], + "type": "object" + }, + { + "properties": { + "dtstart": { + "type": [ + "string", + "null" + ] + }, + "kind": { + "enum": [ + "schedule" + ], + "type": "string" + }, + "rrule": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "kind" + ], + "title": "KindTimerTrigger", + "type": "object" + } + ] + } + }, + "properties": { + "threadId": { + "type": "string" + }, + "timers": { + "items": { + "$ref": "#/definitions/ThreadTimer" + }, + "type": "array" + } + }, + "required": [ + "threadId", + "timers" + ], + "title": "ThreadTimerUpdatedNotification", + "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 a985914134..64f370821f 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts @@ -46,6 +46,8 @@ import type { ThreadRealtimeStartedNotification } from "./v2/ThreadRealtimeStart import type { ThreadRealtimeTranscriptUpdatedNotification } from "./v2/ThreadRealtimeTranscriptUpdatedNotification"; import type { ThreadStartedNotification } from "./v2/ThreadStartedNotification"; import type { ThreadStatusChangedNotification } from "./v2/ThreadStatusChangedNotification"; +import type { ThreadTimerFiredNotification } from "./v2/ThreadTimerFiredNotification"; +import type { ThreadTimerUpdatedNotification } from "./v2/ThreadTimerUpdatedNotification"; import type { ThreadTokenUsageUpdatedNotification } from "./v2/ThreadTokenUsageUpdatedNotification"; import type { ThreadUnarchivedNotification } from "./v2/ThreadUnarchivedNotification"; import type { TurnCompletedNotification } from "./v2/TurnCompletedNotification"; @@ -58,4 +60,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/unarchived", "params": ThreadUnarchivedNotification } | { "method": "thread/closed", "params": ThreadClosedNotification } | { "method": "skills/changed", "params": SkillsChangedNotification } | { "method": "thread/name/updated", "params": ThreadNameUpdatedNotification } | { "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": "item/commandExecution/outputDelta", "params": CommandExecutionOutputDeltaNotification } | { "method": "item/commandExecution/terminalInteraction", "params": TerminalInteractionNotification } | { "method": "item/fileChange/outputDelta", "params": FileChangeOutputDeltaNotification } | { "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": "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": "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/transcriptUpdated", "params": ThreadRealtimeTranscriptUpdatedNotification } | { "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/unarchived", "params": ThreadUnarchivedNotification } | { "method": "thread/closed", "params": ThreadClosedNotification } | { "method": "skills/changed", "params": SkillsChangedNotification } | { "method": "thread/name/updated", "params": ThreadNameUpdatedNotification } | { "method": "thread/timer/updated", "params": ThreadTimerUpdatedNotification } | { "method": "thread/timer/fired", "params": ThreadTimerFiredNotification } | { "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": "item/commandExecution/outputDelta", "params": CommandExecutionOutputDeltaNotification } | { "method": "item/commandExecution/terminalInteraction", "params": TerminalInteractionNotification } | { "method": "item/fileChange/outputDelta", "params": FileChangeOutputDeltaNotification } | { "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": "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": "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/transcriptUpdated", "params": ThreadRealtimeTranscriptUpdatedNotification } | { "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/ThreadTimer.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadTimer.ts new file mode 100644 index 0000000000..f84498e513 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadTimer.ts @@ -0,0 +1,7 @@ +// 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. +import type { TimerDelivery } from "./TimerDelivery"; +import type { TimerTrigger } from "./TimerTrigger"; + +export type ThreadTimer = { id: string, trigger: TimerTrigger, prompt: string, delivery: TimerDelivery, createdAt: number, nextRunAt: number | null, lastRunAt: number | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadTimerFiredNotification.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadTimerFiredNotification.ts new file mode 100644 index 0000000000..839e4e29f5 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadTimerFiredNotification.ts @@ -0,0 +1,6 @@ +// 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. +import type { ThreadTimer } from "./ThreadTimer"; + +export type ThreadTimerFiredNotification = { threadId: string, timer: ThreadTimer, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadTimerUpdatedNotification.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadTimerUpdatedNotification.ts new file mode 100644 index 0000000000..cbf2ea2fc2 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadTimerUpdatedNotification.ts @@ -0,0 +1,6 @@ +// 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. +import type { ThreadTimer } from "./ThreadTimer"; + +export type ThreadTimerUpdatedNotification = { threadId: string, timers: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/TimerDelivery.ts b/codex-rs/app-server-protocol/schema/typescript/v2/TimerDelivery.ts new file mode 100644 index 0000000000..fbd0aeb35e --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/TimerDelivery.ts @@ -0,0 +1,5 @@ +// 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 TimerDelivery = "after-turn" | "steer-current-turn"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/TimerTrigger.ts b/codex-rs/app-server-protocol/schema/typescript/v2/TimerTrigger.ts new file mode 100644 index 0000000000..e75abec6be --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/TimerTrigger.ts @@ -0,0 +1,5 @@ +// 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 TimerTrigger = { "kind": "delay", seconds: number, repeat: boolean | null, } | { "kind": "schedule", dtstart: string | null, rrule: string | null, }; 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 3874280e47..eb2e06fa75 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -313,6 +313,9 @@ export type { ThreadStartResponse } from "./ThreadStartResponse"; export type { ThreadStartedNotification } from "./ThreadStartedNotification"; export type { ThreadStatus } from "./ThreadStatus"; export type { ThreadStatusChangedNotification } from "./ThreadStatusChangedNotification"; +export type { ThreadTimer } from "./ThreadTimer"; +export type { ThreadTimerFiredNotification } from "./ThreadTimerFiredNotification"; +export type { ThreadTimerUpdatedNotification } from "./ThreadTimerUpdatedNotification"; export type { ThreadTokenUsage } from "./ThreadTokenUsage"; export type { ThreadTokenUsageUpdatedNotification } from "./ThreadTokenUsageUpdatedNotification"; export type { ThreadUnarchiveParams } from "./ThreadUnarchiveParams"; @@ -321,6 +324,8 @@ export type { ThreadUnarchivedNotification } from "./ThreadUnarchivedNotificatio export type { ThreadUnsubscribeParams } from "./ThreadUnsubscribeParams"; export type { ThreadUnsubscribeResponse } from "./ThreadUnsubscribeResponse"; export type { ThreadUnsubscribeStatus } from "./ThreadUnsubscribeStatus"; +export type { TimerDelivery } from "./TimerDelivery"; +export type { TimerTrigger } from "./TimerTrigger"; export type { TokenUsageBreakdown } from "./TokenUsageBreakdown"; export type { ToolRequestUserInputAnswer } from "./ToolRequestUserInputAnswer"; export type { ToolRequestUserInputOption } from "./ToolRequestUserInputOption"; diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 0f02f9bf7e..ee80e1b14e 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -317,6 +317,21 @@ client_request_definitions! { params: v2::ThreadReadParams, response: v2::ThreadReadResponse, }, + #[experimental("thread/timer/create")] + ThreadTimerCreate => "thread/timer/create" { + params: v2::ThreadTimerCreateParams, + response: v2::ThreadTimerCreateResponse, + }, + #[experimental("thread/timer/delete")] + ThreadTimerDelete => "thread/timer/delete" { + params: v2::ThreadTimerDeleteParams, + response: v2::ThreadTimerDeleteResponse, + }, + #[experimental("thread/timer/list")] + ThreadTimerList => "thread/timer/list" { + params: v2::ThreadTimerListParams, + response: v2::ThreadTimerListResponse, + }, SkillsList => "skills/list" { params: v2::SkillsListParams, response: v2::SkillsListResponse, @@ -958,6 +973,10 @@ server_notification_definitions! { ThreadClosed => "thread/closed" (v2::ThreadClosedNotification), SkillsChanged => "skills/changed" (v2::SkillsChangedNotification), ThreadNameUpdated => "thread/name/updated" (v2::ThreadNameUpdatedNotification), + #[experimental("thread/timer/updated")] + ThreadTimerUpdated => "thread/timer/updated" (v2::ThreadTimerUpdatedNotification), + #[experimental("thread/timer/fired")] + ThreadTimerFired => "thread/timer/fired" (v2::ThreadTimerFiredNotification), ThreadTokenUsageUpdated => "thread/tokenUsage/updated" (v2::ThreadTokenUsageUpdatedNotification), TurnStarted => "turn/started" (v2::TurnStartedNotification), HookStarted => "hook/started" (v2::HookStartedNotification), diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 2bf04a2655..20db1ab828 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -3183,6 +3183,112 @@ pub struct ThreadReadResponse { pub thread: Thread, } +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "kebab-case")] +#[ts(rename_all = "kebab-case", export_to = "v2/")] +pub enum TimerDelivery { + AfterTurn, + SteerCurrentTurn, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(tag = "kind", rename_all = "camelCase")] +#[ts(tag = "kind")] +#[ts(export_to = "v2/")] +pub enum TimerTrigger { + #[serde(rename_all = "camelCase")] + #[ts(rename_all = "camelCase")] + Delay { + #[ts(type = "number")] + seconds: u64, + repeat: Option, + }, + #[serde(rename_all = "camelCase")] + #[ts(rename_all = "camelCase")] + Schedule { + dtstart: Option, + rrule: Option, + }, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadTimer { + pub id: String, + pub trigger: TimerTrigger, + pub prompt: String, + pub delivery: TimerDelivery, + #[ts(type = "number")] + pub created_at: i64, + #[ts(type = "number | null")] + pub next_run_at: Option, + #[ts(type = "number | null")] + pub last_run_at: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadTimerCreateParams { + pub thread_id: String, + pub trigger: TimerTrigger, + pub prompt: String, + pub delivery: TimerDelivery, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadTimerCreateResponse { + pub timer: ThreadTimer, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadTimerDeleteParams { + pub thread_id: String, + pub id: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadTimerDeleteResponse { + pub deleted: bool, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadTimerListParams { + pub thread_id: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadTimerListResponse { + pub data: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadTimerUpdatedNotification { + pub thread_id: String, + pub timers: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadTimerFiredNotification { + pub thread_id: String, + pub timer: ThreadTimer, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 69176b0b26..4bac512946 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -145,6 +145,11 @@ Example with notification opt-out: - `thread/unsubscribe` — unsubscribe this connection from thread turn/item events. If this was the last subscriber, the server shuts down and unloads the thread, then emits `thread/closed`. - `thread/name/set` — set or update a thread’s user-facing name for either a loaded thread or a persisted rollout; returns `{}` on success and emits `thread/name/updated` to initialized, opted-in clients. Thread names are not required to be unique; name lookups resolve to the most recently updated thread. - `thread/unarchive` — move an archived rollout file back into the sessions directory; returns the restored `thread` on success and emits `thread/unarchived`. +- `thread/timer/create` — create a runtime timer on a loaded thread; accepts a structured `trigger`, `prompt`, and `delivery`, returns the created timer, and requires the under-development feature flag `timer_tool` to be enabled for that thread. Delay triggers use `seconds` plus optional `repeat`; `seconds: 0, repeat: true` means run whenever the thread is idle. Schedule triggers use optional `dtstart` and/or `rrule`. +- `thread/timer/delete` — delete one runtime timer from a loaded thread by id; returns `{ deleted }` and requires `timer_tool`. +- `thread/timer/list` — list runtime timers for a loaded thread; returns `{ data }` and requires `timer_tool`. +- `thread/timer/updated` — notification emitted when a loaded thread’s timer list changes, including one-shot timers deleting themselves after execution or timers restored from disk. +- `thread/timer/fired` — notification emitted when a thread timer fires, either for a synthetic follow-on turn or a same-turn steer delivery. - `thread/compact/start` — trigger conversation history compaction for a thread; returns `{}` immediately while progress streams through standard turn/item notifications. - `thread/shellCommand` — run a user-initiated `!` shell command against a thread; this runs unsandboxed with full access rather than inheriting the thread sandbox policy. Returns `{}` immediately while progress streams through standard turn/item notifications and any active turn receives the formatted output in its message stream. - `thread/backgroundTerminals/clean` — terminate all running background terminals for a thread (experimental; requires `capabilities.experimentalApi`); returns `{}` when the cleanup request is accepted. diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index 976518465b..ea00593570 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -84,8 +84,12 @@ use codex_app_server_protocol::ThreadRealtimeSdpNotification; use codex_app_server_protocol::ThreadRealtimeStartedNotification; use codex_app_server_protocol::ThreadRealtimeTranscriptUpdatedNotification; use codex_app_server_protocol::ThreadRollbackResponse; +use codex_app_server_protocol::ThreadTimer; +use codex_app_server_protocol::ThreadTimerFiredNotification; +use codex_app_server_protocol::ThreadTimerUpdatedNotification; use codex_app_server_protocol::ThreadTokenUsage; use codex_app_server_protocol::ThreadTokenUsageUpdatedNotification; +use codex_app_server_protocol::TimerTrigger; use codex_app_server_protocol::ToolRequestUserInputOption; use codex_app_server_protocol::ToolRequestUserInputParams; use codex_app_server_protocol::ToolRequestUserInputQuestion; @@ -112,6 +116,8 @@ use codex_core::ThreadManager; use codex_core::find_thread_name_by_id; use codex_core::review_format::format_review_findings_block; use codex_core::review_prompts; +use codex_core::timers::TIMER_FIRED_BACKGROUND_EVENT_PREFIX; +use codex_core::timers::TIMER_UPDATED_BACKGROUND_EVENT_PREFIX; use codex_protocol::ThreadId; use codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem as CoreDynamicToolCallOutputContentItem; use codex_protocol::dynamic_tools::DynamicToolResponse as CoreDynamicToolResponse; @@ -161,6 +167,35 @@ struct CommandExecutionCompletionItem { command_actions: Vec, } +fn thread_timer_from_core(value: codex_core::timers::ThreadTimer) -> ThreadTimer { + ThreadTimer { + id: value.id, + trigger: timer_trigger_from_core(value.trigger), + prompt: value.prompt, + delivery: match value.delivery { + codex_core::timers::TimerDelivery::AfterTurn => { + codex_app_server_protocol::TimerDelivery::AfterTurn + } + codex_core::timers::TimerDelivery::SteerCurrentTurn => { + codex_app_server_protocol::TimerDelivery::SteerCurrentTurn + } + }, + created_at: value.created_at, + next_run_at: value.next_run_at, + last_run_at: value.last_run_at, + } +} + +fn timer_trigger_from_core(value: codex_core::timers::ThreadTimerTrigger) -> TimerTrigger { + match value { + codex_core::timers::ThreadTimerTrigger::Delay { seconds, repeat } => { + TimerTrigger::Delay { seconds, repeat } + } + codex_core::timers::ThreadTimerTrigger::Schedule { dtstart, rrule } => { + TimerTrigger::Schedule { dtstart, rrule } + } + } +} #[allow(clippy::too_many_arguments)] pub(crate) async fn apply_bespoke_event_handling( event: Event, @@ -1305,6 +1340,34 @@ pub(crate) async fn apply_bespoke_event_handling( .send_server_notification(ServerNotification::DeprecationNotice(notification)) .await; } + EventMsg::BackgroundEvent(event) => { + if let Some(payload) = event + .message + .strip_prefix(TIMER_UPDATED_BACKGROUND_EVENT_PREFIX) + && let Ok(timers) = + serde_json::from_str::>(payload) + { + let notification = ThreadTimerUpdatedNotification { + thread_id: conversation_id.to_string(), + timers: timers.into_iter().map(thread_timer_from_core).collect(), + }; + outgoing + .send_server_notification(ServerNotification::ThreadTimerUpdated(notification)) + .await; + } else if let Some(payload) = event + .message + .strip_prefix(TIMER_FIRED_BACKGROUND_EVENT_PREFIX) + && let Ok(timer) = serde_json::from_str::(payload) + { + let notification = ThreadTimerFiredNotification { + thread_id: conversation_id.to_string(), + timer: thread_timer_from_core(timer), + }; + outgoing + .send_server_notification(ServerNotification::ThreadTimerFired(notification)) + .await; + } + } EventMsg::ReasoningContentDelta(event) => { let notification = ReasoningSummaryTextDeltaNotification { thread_id: conversation_id.to_string(), diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 1e10a5696d..bb86058042 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -162,12 +162,21 @@ use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; use codex_app_server_protocol::ThreadStartedNotification; use codex_app_server_protocol::ThreadStatus; +use codex_app_server_protocol::ThreadTimer as ApiThreadTimer; +use codex_app_server_protocol::ThreadTimerCreateParams; +use codex_app_server_protocol::ThreadTimerCreateResponse; +use codex_app_server_protocol::ThreadTimerDeleteParams; +use codex_app_server_protocol::ThreadTimerDeleteResponse; +use codex_app_server_protocol::ThreadTimerListParams; +use codex_app_server_protocol::ThreadTimerListResponse; use codex_app_server_protocol::ThreadUnarchiveParams; use codex_app_server_protocol::ThreadUnarchiveResponse; use codex_app_server_protocol::ThreadUnarchivedNotification; use codex_app_server_protocol::ThreadUnsubscribeParams; use codex_app_server_protocol::ThreadUnsubscribeResponse; use codex_app_server_protocol::ThreadUnsubscribeStatus; +use codex_app_server_protocol::TimerDelivery as ApiTimerDelivery; +use codex_app_server_protocol::TimerTrigger as ApiTimerTrigger; use codex_app_server_protocol::Turn; use codex_app_server_protocol::TurnError; use codex_app_server_protocol::TurnInterruptParams; @@ -774,6 +783,18 @@ impl CodexMessageProcessor { self.thread_read(to_connection_request_id(request_id), params) .await; } + ClientRequest::ThreadTimerCreate { request_id, params } => { + self.thread_timer_create(to_connection_request_id(request_id), params) + .await; + } + ClientRequest::ThreadTimerDelete { request_id, params } => { + self.thread_timer_delete(to_connection_request_id(request_id), params) + .await; + } + ClientRequest::ThreadTimerList { request_id, params } => { + self.thread_timer_list(to_connection_request_id(request_id), params) + .await; + } ClientRequest::ThreadShellCommand { request_id, params } => { self.thread_shell_command(to_connection_request_id(request_id), params) .await; @@ -3126,7 +3147,7 @@ impl CodexMessageProcessor { message: format!("failed to unarchive thread: {err}"), data: None, })?; - tokio::fs::rename(&canonical_rollout_path, &restored_path) + rename_rollout_with_timer_sidecar(&canonical_rollout_path, &restored_path) .await .map_err(|err| JSONRPCErrorError { code: INTERNAL_ERROR_CODE, @@ -3678,6 +3699,106 @@ impl CodexMessageProcessor { self.outgoing.send_response(request_id, response).await; } + async fn thread_timer_create( + &mut self, + request_id: ConnectionRequestId, + params: ThreadTimerCreateParams, + ) { + let ThreadTimerCreateParams { + thread_id, + trigger, + prompt, + delivery, + } = params; + let Some(thread) = self.load_timer_thread(request_id.clone(), &thread_id).await else { + return; + }; + match thread + .create_timer( + timer_trigger_to_core(trigger), + prompt, + timer_delivery_to_core(delivery), + ) + .await + { + Ok(timer) => { + self.outgoing + .send_response( + request_id, + ThreadTimerCreateResponse { + timer: api_thread_timer_from_core(timer), + }, + ) + .await; + } + Err(err) => self.send_invalid_request_error(request_id, err).await, + } + } + + async fn thread_timer_delete( + &mut self, + request_id: ConnectionRequestId, + params: ThreadTimerDeleteParams, + ) { + let ThreadTimerDeleteParams { thread_id, id } = params; + let Some(thread) = self.load_timer_thread(request_id.clone(), &thread_id).await else { + return; + }; + let deleted = match thread.delete_timer(&id).await { + Ok(deleted) => deleted, + Err(err) => { + self.send_invalid_request_error(request_id, err).await; + return; + } + }; + self.outgoing + .send_response(request_id, ThreadTimerDeleteResponse { deleted }) + .await; + } + + async fn thread_timer_list( + &mut self, + request_id: ConnectionRequestId, + params: ThreadTimerListParams, + ) { + let ThreadTimerListParams { thread_id } = params; + let Some(thread) = self.load_timer_thread(request_id.clone(), &thread_id).await else { + return; + }; + let data = thread + .list_timers() + .await + .into_iter() + .map(api_thread_timer_from_core) + .collect(); + self.outgoing + .send_response(request_id, ThreadTimerListResponse { data }) + .await; + } + + async fn load_timer_thread( + &mut self, + request_id: ConnectionRequestId, + thread_id: &str, + ) -> Option> { + let (_, thread) = match self.load_thread(thread_id).await { + Ok(value) => value, + Err(error) => { + self.outgoing.send_error(request_id, error).await; + return None; + } + }; + if !thread.enabled(Feature::TimerScheduler) { + self.send_invalid_request_error( + request_id, + format!("thread {thread_id} does not support timer scheduling"), + ) + .await; + return None; + } + Some(thread) + } + pub(crate) fn thread_created_receiver(&self) -> broadcast::Receiver { self.thread_manager.subscribe_thread_created() } @@ -5652,7 +5773,7 @@ impl CodexMessageProcessor { .join(codex_core::ARCHIVED_SESSIONS_SUBDIR); tokio::fs::create_dir_all(&archive_folder).await?; let archived_path = archive_folder.join(&file_name); - tokio::fs::rename(&canonical_rollout_path, &archived_path).await?; + rename_rollout_with_timer_sidecar(&canonical_rollout_path, &archived_path).await?; if let Some(ctx) = state_db_ctx { let _ = ctx .mark_archived(thread_id, archived_path.as_path(), Utc::now()) @@ -7910,6 +8031,21 @@ impl CodexMessageProcessor { } } +async fn rename_rollout_with_timer_sidecar(from: &Path, to: &Path) -> std::io::Result<()> { + tokio::fs::rename(from, to).await?; + + let from_sidecar = codex_core::timers::timer_sidecar_path_for_rollout(from); + let to_sidecar = codex_core::timers::timer_sidecar_path_for_rollout(to); + match tokio::fs::rename(&from_sidecar, &to_sidecar).await { + Ok(()) => Ok(()), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(err) => { + let _ = tokio::fs::rename(to, from).await; + Err(err) + } + } +} + fn normalize_thread_list_cwd_filter( cwd: Option, ) -> Result, JSONRPCErrorError> { @@ -9055,6 +9191,54 @@ fn build_thread_from_snapshot( } } +fn timer_delivery_to_core(value: ApiTimerDelivery) -> codex_core::timers::TimerDelivery { + match value { + ApiTimerDelivery::AfterTurn => codex_core::timers::TimerDelivery::AfterTurn, + ApiTimerDelivery::SteerCurrentTurn => codex_core::timers::TimerDelivery::SteerCurrentTurn, + } +} + +fn api_timer_delivery_from_core(value: codex_core::timers::TimerDelivery) -> ApiTimerDelivery { + match value { + codex_core::timers::TimerDelivery::AfterTurn => ApiTimerDelivery::AfterTurn, + codex_core::timers::TimerDelivery::SteerCurrentTurn => ApiTimerDelivery::SteerCurrentTurn, + } +} + +fn timer_trigger_to_core(value: ApiTimerTrigger) -> codex_core::timers::ThreadTimerTrigger { + match value { + ApiTimerTrigger::Delay { seconds, repeat } => { + codex_core::timers::ThreadTimerTrigger::Delay { seconds, repeat } + } + ApiTimerTrigger::Schedule { dtstart, rrule } => { + codex_core::timers::ThreadTimerTrigger::Schedule { dtstart, rrule } + } + } +} + +fn api_timer_trigger_from_core(value: codex_core::timers::ThreadTimerTrigger) -> ApiTimerTrigger { + match value { + codex_core::timers::ThreadTimerTrigger::Delay { seconds, repeat } => { + ApiTimerTrigger::Delay { seconds, repeat } + } + codex_core::timers::ThreadTimerTrigger::Schedule { dtstart, rrule } => { + ApiTimerTrigger::Schedule { dtstart, rrule } + } + } +} + +fn api_thread_timer_from_core(value: codex_core::timers::ThreadTimer) -> ApiThreadTimer { + ApiThreadTimer { + id: value.id, + trigger: api_timer_trigger_from_core(value.trigger), + prompt: value.prompt, + delivery: api_timer_delivery_from_core(value.delivery), + created_at: value.created_at, + next_run_at: value.next_run_at, + last_run_at: value.last_run_at, + } +} + pub(crate) fn summary_to_thread(summary: ConversationSummary) -> Thread { let ConversationSummary { conversation_id, diff --git a/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs b/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs index 2850c7b74f..8f305b1c38 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs @@ -22,7 +22,7 @@ use codex_app_server_protocol::UserInput as V2UserInput; use tempfile::TempDir; use tokio::time::timeout; -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); +const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20); #[tokio::test] async fn turn_interrupt_aborts_running_turn() -> Result<()> { diff --git a/codex-rs/app-server/tests/suite/v2/turn_start.rs b/codex-rs/app-server/tests/suite/v2/turn_start.rs index 59591dd0d1..3d9470861f 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -67,7 +67,7 @@ use tokio::time::timeout; #[cfg(windows)] const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25); #[cfg(not(windows))] -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); +const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20); const TEST_ORIGINATOR: &str = "codex_vscode"; const LOCAL_PRAGMATIC_TEMPLATE: &str = "You are a deeply pragmatic, effective software engineer."; diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index d2cbad83ef..7d8bc1dcb8 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -24,6 +24,7 @@ async-trait = { workspace = true } base64 = { workspace = true } bm25 = { workspace = true } chrono = { workspace = true, features = ["serde"] } +chrono-tz = { workspace = true } clap = { workspace = true, features = ["derive"] } codex-analytics = { workspace = true } codex-api = { workspace = true } @@ -87,6 +88,7 @@ once_cell = { workspace = true } rand = { workspace = true } regex-lite = { workspace = true } reqwest = { workspace = true, features = ["json", "stream"] } +rrule = { workspace = true } rmcp = { workspace = true, default-features = false, features = [ "base64", "macros", diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index e4e7ff85b7..60a95db391 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -488,6 +488,9 @@ "steer": { "type": "boolean" }, + "timer_tool": { + "type": "boolean" + }, "tool_call_mcp_elicitation": { "type": "boolean" }, @@ -2201,6 +2204,9 @@ "steer": { "type": "boolean" }, + "timer_tool": { + "type": "boolean" + }, "tool_call_mcp_elicitation": { "type": "boolean" }, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 66f7c020a5..c8601b1d5b 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -1,6 +1,7 @@ use std::collections::HashMap; use std::collections::HashSet; use std::fmt::Debug; +use std::future::Future; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; @@ -303,6 +304,19 @@ use crate::tasks::GhostSnapshotTask; use crate::tasks::ReviewTask; use crate::tasks::SessionTask; use crate::tasks::SessionTaskContext; +use crate::timers::ClaimedTimer; +use crate::timers::CreateTimer; +use crate::timers::PersistedTimer; +use crate::timers::TIMER_FIRED_BACKGROUND_EVENT_PREFIX; +use crate::timers::TIMER_UPDATED_BACKGROUND_EVENT_PREFIX; +use crate::timers::ThreadTimer; +use crate::timers::ThreadTimerTrigger; +use crate::timers::TimerDelivery; +use crate::timers::TimerTaskSpec; +use crate::timers::TimersState; +use crate::timers::load_timer_sidecar; +use crate::timers::timer_prompt_input_item; +use crate::timers::write_timer_sidecar; use crate::tools::ToolRouter; use crate::tools::context::SharedTurnDiffTracker; use crate::tools::js_repl::JsReplHandle; @@ -821,15 +835,29 @@ pub(crate) struct Session { pending_mcp_server_refresh_config: Mutex>, pub(crate) conversation: Arc, pub(crate) active_turn: Mutex>, + /// Prevents concurrent timers from claiming multiple timers before a + /// newly started turn becomes the active turn. + timer_start_in_progress: Mutex, + /// Serializes timer sidecar snapshots and file writes so stale timer state + /// cannot overwrite newer persisted state. + timer_sidecar_write_lock: Mutex<()>, mailbox: Mailbox, mailbox_rx: Mutex, idle_pending_input: Mutex>, // TODO (jif) merge with mailbox! + timers: Mutex, + timer_tasks_cancellation_token: CancellationToken, pub(crate) guardian_review_session: GuardianReviewSessionManager, pub(crate) services: SessionServices, js_repl: Arc, next_internal_sub_id: AtomicU64, } +impl Drop for Session { + fn drop(&mut self) { + self.timer_tasks_cancellation_token.cancel(); + } +} + #[derive(Clone, Debug)] pub(crate) struct TurnSkillsContext { pub(crate) outcome: Arc, @@ -1985,9 +2013,13 @@ impl Session { pending_mcp_server_refresh_config: Mutex::new(None), conversation: Arc::new(RealtimeConversationManager::new()), active_turn: Mutex::new(None), + timer_start_in_progress: Mutex::new(false), + timer_sidecar_write_lock: Mutex::new(()), mailbox, mailbox_rx: Mutex::new(mailbox_rx), idle_pending_input: Mutex::new(Vec::new()), + timers: Mutex::new(TimersState::default()), + timer_tasks_cancellation_token: CancellationToken::new(), guardian_review_session: GuardianReviewSessionManager::default(), services, js_repl, @@ -2025,6 +2057,7 @@ impl Session { for event in events { sess.send_event_raw(event).await; } + sess.restore_timers_from_sidecar().await; // Start the watcher after SessionConfigured so it cannot emit earlier events. sess.start_skills_watcher_listener(); @@ -2667,6 +2700,310 @@ impl Session { .await } + pub(crate) async fn list_timers(&self) -> Vec { + self.timers.lock().await.list_timers() + } + + pub(crate) async fn create_timer( + self: &Arc, + trigger: ThreadTimerTrigger, + prompt: String, + delivery: TimerDelivery, + ) -> Result { + self.ensure_rollout_materialized().await; + let Some(rollout_path) = self.current_rollout_path().await else { + return Err("timers require a persisted rollout path for restoration".to_string()); + }; + + let timer_cancel = CancellationToken::new(); + let id = uuid::Uuid::new_v4().to_string(); + let (timer, timer_spec) = { + let mut timers = self.timers.lock().await; + timers.create_timer( + CreateTimer { + id: id.clone(), + trigger, + prompt, + delivery, + now: Utc::now(), + }, + Some(timer_cancel.clone()), + )? + }; + if let Err(err) = self.persist_timers_to_rollout_sidecar(&rollout_path).await { + if let Some(runtime) = self.timers.lock().await.remove_timer(&id) { + TimersState::cancel_runtime(&runtime); + } + return Err(err); + } + + if let Some(timer_spec) = timer_spec { + self.spawn_timer_task(id, timer_spec, timer_cancel); + } + self.emit_timer_updated_notification().await; + self.maybe_start_pending_timer().await; + Ok(timer) + } + + pub(crate) async fn delete_timer(&self, id: &str) -> Result { + let Some(runtime) = self.timers.lock().await.remove_timer(id) else { + return Ok(false); + }; + let Some(rollout_path) = self.current_rollout_path().await else { + self.timers.lock().await.restore_runtime(runtime); + return Err("timers require a persisted rollout path for restoration".to_string()); + }; + if let Err(err) = self.persist_timers_to_rollout_sidecar(&rollout_path).await { + self.timers.lock().await.restore_runtime(runtime); + return Err(err); + } + TimersState::cancel_runtime(&runtime); + self.emit_timer_updated_notification().await; + Ok(true) + } + + pub(crate) async fn maybe_start_pending_timer(self: &Arc) { + let Some(ClaimedTimer { + timer, + context, + deleted_one_shot_timer, + }) = self.claim_next_timer_for_delivery().await + else { + return; + }; + + self.emit_timer_fired_notification(&timer).await; + if deleted_one_shot_timer { + self.emit_timer_updated_notification().await; + } + self.persist_timers_sidecar_best_effort().await; + + let input_item = timer_prompt_input_item(&context); + match context.delivery { + TimerDelivery::SteerCurrentTurn => { + if !self.inject_timer_into_active_turn(input_item.clone()).await { + self.queue_response_items_for_next_turn(vec![input_item]) + .await; + self.maybe_start_turn_for_pending_work().await; + } + } + TimerDelivery::AfterTurn => { + self.queue_response_items_for_next_turn(vec![input_item]) + .await; + self.maybe_start_turn_for_pending_work().await; + } + } + *self.timer_start_in_progress.lock().await = false; + } + + async fn claim_next_timer_for_delivery(self: &Arc) -> Option { + let mut timer_start_in_progress = self.timer_start_in_progress.lock().await; + if *timer_start_in_progress { + return None; + } + *timer_start_in_progress = true; + drop(timer_start_in_progress); + + let has_pending_turn_inputs = self.has_queued_response_items_for_next_turn().await + || self.has_trigger_turn_mailbox_items().await; + + let (has_active_turn, active_turn_is_regular) = { + let active_turn = self.active_turn.lock().await; + let has_active_turn = active_turn.is_some(); + let active_turn_is_regular = active_turn + .as_ref() + .and_then(|turn| turn.tasks.first()) + .is_some_and(|(_, task)| matches!(task.kind, crate::state::TaskKind::Regular)); + (has_active_turn, active_turn_is_regular) + }; + let can_after_turn = !has_active_turn && !has_pending_turn_inputs; + let claimed = self.timers.lock().await.claim_next_timer( + Utc::now(), + can_after_turn, + active_turn_is_regular, + ); + if claimed.is_none() { + *self.timer_start_in_progress.lock().await = false; + } + claimed + } + + async fn inject_timer_into_active_turn(&self, item: ResponseInputItem) -> bool { + let turn_state = { + let active = self.active_turn.lock().await; + let Some(active_turn) = active.as_ref() else { + return false; + }; + + match active_turn.tasks.first().map(|(_, task)| task.kind) { + Some(crate::state::TaskKind::Regular) => Arc::clone(&active_turn.turn_state), + Some(crate::state::TaskKind::Review | crate::state::TaskKind::Compact) | None => { + return false; + } + } + }; + + let mut turn_state = turn_state.lock().await; + turn_state.push_pending_input(item); + true + } + + fn spawn_timer_task( + self: &Arc, + id: String, + timer_spec: TimerTaskSpec, + cancellation_token: CancellationToken, + ) { + let weak = Arc::downgrade(self); + let session_cancel = self.timer_tasks_cancellation_token.clone(); + tokio::spawn(async move { + let mut delay = timer_spec.delay; + loop { + tokio::select! { + _ = session_cancel.cancelled() => break, + _ = cancellation_token.cancelled() => break, + _ = tokio::time::sleep(delay) => {} + } + let Some(session) = weak.upgrade() else { + break; + }; + let changed = session.timers.lock().await.mark_timer_due(&id, Utc::now()); + if changed { + session.persist_timers_sidecar_best_effort().await; + } + session.maybe_start_pending_timer().await; + let next_timer_spec = session + .timers + .lock() + .await + .timer_spec_for_timer(&id, Utc::now()); + let Some(next_timer_spec) = next_timer_spec else { + break; + }; + delay = next_timer_spec.delay; + } + }); + } + + async fn persist_timers_to_rollout_sidecar(&self, rollout_path: &Path) -> Result<(), String> { + let rollout_path = rollout_path.to_path_buf(); + self.persist_timers_sidecar_with_writer(|timers| async move { + write_timer_sidecar(&rollout_path, &timers).await + }) + .await + } + + async fn persist_timers_sidecar_with_writer( + &self, + write_sidecar: W, + ) -> Result<(), String> + where + W: FnOnce(Vec) -> Fut, + Fut: Future>, + { + let _write_lock = self.timer_sidecar_write_lock.lock().await; + let timers = self.timers.lock().await.persisted_timers(); + write_sidecar(timers).await + } + + async fn persist_timers_sidecar_best_effort(&self) { + let Some(rollout_path) = self.current_rollout_path().await else { + return; + }; + if let Err(err) = self.persist_timers_to_rollout_sidecar(&rollout_path).await { + warn!("failed to persist timers sidecar: {err}"); + } + } + + async fn restore_timers_from_sidecar(self: &Arc) { + if !self.features.enabled(Feature::TimerScheduler) { + return; + } + let Some(rollout_path) = self.current_rollout_path().await else { + return; + }; + let persisted = match load_timer_sidecar(&rollout_path).await { + Ok(persisted) => persisted, + Err(err) => { + warn!("{err}"); + return; + } + }; + if persisted.is_empty() { + return; + } + + { + let _write_lock = self.timer_sidecar_write_lock.lock().await; + let mut normalized = Vec::::new(); + for persisted_timer in persisted { + let timer_cancel = CancellationToken::new(); + let timer_spec = { + let mut timers = self.timers.lock().await; + match timers.restore_timer( + persisted_timer.clone(), + Utc::now(), + Some(timer_cancel.clone()), + ) { + Ok(timer_spec) => { + normalized = timers.persisted_timers(); + timer_spec + } + Err(err) => { + warn!( + "skipping invalid persisted timer {}: {err}", + persisted_timer.timer.id + ); + continue; + } + } + }; + if let Some(timer_spec) = timer_spec { + self.spawn_timer_task( + persisted_timer.timer.id.clone(), + timer_spec, + timer_cancel, + ); + } + } + + if let Err(err) = write_timer_sidecar(&rollout_path, &normalized).await { + warn!("failed to rewrite normalized timer sidecar: {err}"); + } + } + self.emit_timer_updated_notification().await; + self.maybe_start_pending_timer().await; + } + + async fn emit_timer_updated_notification(&self) { + let timers = self.list_timers().await; + let Ok(payload) = serde_json::to_string(&timers) else { + warn!("failed to serialize timer update payload"); + return; + }; + self.send_event_raw(Event { + id: INITIAL_SUBMIT_ID.to_owned(), + msg: EventMsg::BackgroundEvent(BackgroundEventEvent { + message: format!("{TIMER_UPDATED_BACKGROUND_EVENT_PREFIX}{payload}"), + }), + }) + .await; + } + + async fn emit_timer_fired_notification(&self, timer: &ThreadTimer) { + let Ok(payload) = serde_json::to_string(timer) else { + warn!("failed to serialize timer fired payload"); + return; + }; + self.send_event_raw(Event { + id: INITIAL_SUBMIT_ID.to_owned(), + msg: EventMsg::BackgroundEvent(BackgroundEventEvent { + message: format!("{TIMER_FIRED_BACKGROUND_EVENT_PREFIX}{payload}"), + }), + }) + .await; + } + async fn build_settings_update_items( &self, reference_context_item: Option<&TurnContextItem>, @@ -4199,8 +4536,6 @@ impl Session { } } - /// Queue response items to be injected into the next active turn created for this session. - #[cfg(test)] pub(crate) async fn queue_response_items_for_next_turn(&self, items: Vec) { if items.is_empty() { return; diff --git a/codex-rs/core/src/codex_tests.rs b/codex-rs/core/src/codex_tests.rs index d57d92c1ec..7988a5a09a 100644 --- a/codex-rs/core/src/codex_tests.rs +++ b/codex-rs/core/src/codex_tests.rs @@ -11,6 +11,11 @@ use crate::config_loader::Sourced; use crate::exec::ExecCapturePolicy; use crate::function_tool::FunctionCallError; use crate::shell::default_user_shell; +use crate::timers::ThreadTimerTrigger; +use crate::timers::TimerDelivery; +use crate::timers::TimersState; +use crate::timers::load_timer_sidecar; +use crate::timers::write_timer_sidecar; use crate::tools::format_exec_output_str; use codex_features::Features; @@ -115,6 +120,8 @@ use serde_json::json; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration as StdDuration; +use tempfile::TempDir; +use tokio::sync::Notify; #[path = "codex_tests_guardian.rs"] mod guardian_tests; @@ -2815,9 +2822,13 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { pending_mcp_server_refresh_config: Mutex::new(None), conversation: Arc::new(RealtimeConversationManager::new()), active_turn: Mutex::new(None), + timer_start_in_progress: Mutex::new(false), + timer_sidecar_write_lock: Mutex::new(()), mailbox, mailbox_rx: Mutex::new(mailbox_rx), idle_pending_input: Mutex::new(Vec::new()), + timers: Mutex::new(TimersState::default()), + timer_tasks_cancellation_token: CancellationToken::new(), guardian_review_session: crate::guardian::GuardianReviewSessionManager::default(), services, js_repl, @@ -3656,9 +3667,13 @@ pub(crate) async fn make_session_and_context_with_dynamic_tools_and_rx( pending_mcp_server_refresh_config: Mutex::new(None), conversation: Arc::new(RealtimeConversationManager::new()), active_turn: Mutex::new(None), + timer_start_in_progress: Mutex::new(false), + timer_sidecar_write_lock: Mutex::new(()), mailbox, mailbox_rx: Mutex::new(mailbox_rx), idle_pending_input: Mutex::new(Vec::new()), + timers: Mutex::new(TimersState::default()), + timer_tasks_cancellation_token: CancellationToken::new(), guardian_review_session: crate::guardian::GuardianReviewSessionManager::default(), services, js_repl, @@ -3678,6 +3693,165 @@ pub(crate) async fn make_session_and_context_with_rx() -> ( make_session_and_context_with_dynamic_tools_and_rx(Vec::new()).await } +#[tokio::test] +async fn dropping_session_cancels_timer_tasks() { + let (session, _, _) = make_session_and_context_with_rx().await; + let cancel_token = session.timer_tasks_cancellation_token.clone(); + + drop(session); + + assert!(cancel_token.is_cancelled()); +} + +#[tokio::test] +async fn maybe_start_pending_timer_claims_only_one_timer_while_start_is_in_progress() { + let (session, _, _) = make_session_and_context_with_rx().await; + let now = chrono::Utc::now(); + { + let mut timers = session.timers.lock().await; + timers + .create_timer( + crate::timers::CreateTimer { + id: "timer-1".to_string(), + trigger: ThreadTimerTrigger::Delay { + seconds: 10, + repeat: Some(true), + }, + prompt: "first".to_string(), + delivery: TimerDelivery::AfterTurn, + now, + }, + /*timer_cancel*/ None, + ) + .expect("first timer should be created"); + timers + .create_timer( + crate::timers::CreateTimer { + id: "timer-2".to_string(), + trigger: ThreadTimerTrigger::Delay { + seconds: 10, + repeat: Some(true), + }, + prompt: "second".to_string(), + delivery: TimerDelivery::AfterTurn, + now, + }, + /*timer_cancel*/ None, + ) + .expect("second timer should be created"); + timers.mark_timer_due("timer-1", now); + timers.mark_timer_due("timer-2", now); + } + + let first = Arc::clone(&session); + let second = Arc::clone(&session); + tokio::join!( + first.maybe_start_pending_timer(), + second.maybe_start_pending_timer() + ); + + let timers = session.timers.lock().await.list_timers(); + assert_eq!( + timers + .iter() + .filter(|timer| timer.last_run_at.is_some()) + .count(), + 1 + ); +} + +#[tokio::test] +async fn timer_sidecar_persistence_serializes_stale_and_newer_snapshots() { + let (session, _, _) = make_session_and_context_with_rx().await; + let tempdir = TempDir::new().expect("tempdir"); + let rollout_path = tempdir.path().join("rollout.jsonl"); + let now = chrono::Utc::now(); + { + let mut timers = session.timers.lock().await; + timers + .create_timer( + crate::timers::CreateTimer { + id: "timer-1".to_string(), + trigger: ThreadTimerTrigger::Delay { + seconds: 10, + repeat: Some(true), + }, + prompt: "first".to_string(), + delivery: TimerDelivery::AfterTurn, + now, + }, + /*timer_cancel*/ None, + ) + .expect("first timer should be created"); + } + + let first_snapshot_taken = Arc::new(Notify::new()); + let allow_first_write = Arc::new(Notify::new()); + let first_session = Arc::clone(&session); + let first_rollout_path = rollout_path.clone(); + let first_snapshot_taken_for_task = Arc::clone(&first_snapshot_taken); + let allow_first_write_for_task = Arc::clone(&allow_first_write); + let first_write = tokio::spawn(async move { + first_session + .persist_timers_sidecar_with_writer(|timers| async move { + first_snapshot_taken_for_task.notify_one(); + allow_first_write_for_task.notified().await; + write_timer_sidecar(&first_rollout_path, &timers).await + }) + .await + .expect("first persist should succeed"); + }); + first_snapshot_taken.notified().await; + + { + let mut timers = session.timers.lock().await; + let removed = timers + .remove_timer("timer-1") + .expect("first timer should be removable"); + TimersState::cancel_runtime(&removed); + timers + .create_timer( + crate::timers::CreateTimer { + id: "timer-2".to_string(), + trigger: ThreadTimerTrigger::Delay { + seconds: 10, + repeat: Some(true), + }, + prompt: "second".to_string(), + delivery: TimerDelivery::AfterTurn, + now, + }, + /*timer_cancel*/ None, + ) + .expect("second timer should be created"); + } + + let second_session = Arc::clone(&session); + let second_rollout_path = rollout_path.clone(); + let second_write = tokio::spawn(async move { + second_session + .persist_timers_sidecar_with_writer(|timers| async move { + write_timer_sidecar(&second_rollout_path, &timers).await + }) + .await + .expect("second persist should succeed"); + }); + + allow_first_write.notify_one(); + first_write + .await + .expect("first persist task should complete"); + second_write + .await + .expect("second persist task should complete"); + + let loaded = load_timer_sidecar(&rollout_path) + .await + .expect("timer sidecar should load"); + let persisted = session.timers.lock().await.persisted_timers(); + assert_eq!(loaded, persisted); +} + #[tokio::test] async fn refresh_mcp_servers_is_deferred_until_next_turn() { let (session, turn_context) = make_session_and_context().await; diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index 9727cc208a..ab6c7f0ad4 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -27,6 +27,9 @@ use std::path::PathBuf; use tokio::sync::Mutex; use tokio::sync::watch; +use crate::timers::ThreadTimer; +use crate::timers::ThreadTimerTrigger; +use crate::timers::TimerDelivery; use codex_rollout::state_db::StateDbHandle; #[derive(Clone, Debug)] @@ -258,6 +261,26 @@ impl CodexThread { Ok(*guard) } + + pub async fn create_timer( + &self, + trigger: ThreadTimerTrigger, + prompt: String, + delivery: TimerDelivery, + ) -> Result { + self.codex + .session + .create_timer(trigger, prompt, delivery) + .await + } + + pub async fn delete_timer(&self, id: &str) -> Result { + self.codex.session.delete_timer(id).await + } + + pub async fn list_timers(&self) -> Vec { + self.codex.session.list_timers().await + } } fn pending_message_input_item(message: &ResponseItem) -> CodexResult { diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 83232de734..488acfaf44 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -41,6 +41,8 @@ mod hook_runtime; mod installation_id; pub(crate) mod instructions; pub(crate) mod landlock; +mod timer_trigger; +pub mod timers; pub use landlock::spawn_command_under_linux_sandbox; pub(crate) mod mcp; mod mcp_skill_dependencies; diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index 5da3650bf8..aa7d063823 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -235,7 +235,7 @@ impl Session { self.start_task(turn_context, input, task).await; } - async fn start_task( + pub(crate) async fn start_task( self: &Arc, turn_context: Arc, input: Vec, @@ -522,15 +522,15 @@ impl Session { duration_ms, }); self.send_event(turn_context.as_ref(), event).await; - - if should_clear_active_turn { - let session = Arc::clone(self); - let _scheduler = tokio::task::spawn_blocking(move || { - tokio::runtime::Handle::current().block_on(async move { + let session = Arc::clone(self); + let _scheduler = tokio::task::spawn_blocking(move || { + tokio::runtime::Handle::current().block_on(async move { + session.maybe_start_pending_timer().await; + if should_clear_active_turn { session.maybe_start_turn_for_pending_work().await; - }); + } }); - } + }); } async fn take_active_turn(&self) -> Option { diff --git a/codex-rs/core/src/timer_trigger.rs b/codex-rs/core/src/timer_trigger.rs new file mode 100644 index 0000000000..2bae1bf1d3 --- /dev/null +++ b/codex-rs/core/src/timer_trigger.rs @@ -0,0 +1,691 @@ +//! Trigger validation and next-fire calculation for persistent thread timers. +//! +//! This module keeps calendar and delay scheduling details out of `timers.rs`. +//! It owns the persisted trigger shape, local wall-clock schedule normalization, +//! and RRULE-backed recurrence evaluation. + +use chrono::DateTime; +use chrono::Duration as ChronoDuration; +use chrono::LocalResult; +use chrono::NaiveDateTime; +use chrono::TimeZone; +use chrono::Utc; +use rrule::RRuleSet; +use rrule::Tz; +use serde::Deserialize; +use serde::Serialize; +use std::time::Duration; + +const LOCAL_DATE_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S"; +const RRULE_DATE_TIME_FORMAT: &str = "%Y%m%dT%H%M%S"; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "kebab-case")] +pub enum TimerTrigger { + Delay { + seconds: u64, + repeat: Option, + }, + Schedule { + dtstart: Option, + rrule: Option, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct TriggerTiming { + pub(crate) trigger: TimerTrigger, + pub(crate) pending_run: bool, + pub(crate) next_run_at: Option, + pub(crate) timer_delay: Option, +} + +impl TimerTrigger { + pub(crate) fn is_recurring(&self) -> bool { + match self { + Self::Delay { repeat, .. } => repeat.unwrap_or(false), + Self::Schedule { rrule, .. } => rrule.as_ref().is_some_and(|rrule| !rrule.is_empty()), + } + } + + pub(crate) fn is_idle_recurring(&self) -> bool { + matches!( + self, + Self::Delay { + seconds: 0, + repeat: Some(true), + } + ) + } + + pub(crate) fn display(&self) -> String { + match self { + Self::Delay { seconds, repeat } => { + let suffix = if repeat.unwrap_or(false) { + ", repeat" + } else { + "" + }; + format!("delay {seconds}s{suffix}") + } + Self::Schedule { dtstart, rrule } => match (dtstart, rrule) { + (Some(dtstart), Some(rrule)) => format!("schedule {dtstart}; {rrule}"), + (Some(dtstart), None) => format!("schedule {dtstart}"), + (None, Some(rrule)) => format!("schedule {rrule}"), + (None, None) => "invalid schedule".to_string(), + }, + } + } +} + +pub(crate) fn timing_for_new_trigger( + trigger: TimerTrigger, + created_at: DateTime, + now: DateTime, +) -> Result { + let timezone = local_timezone(); + timing_for_new_trigger_with_timezone(trigger, created_at, now, timezone) +} + +pub(crate) fn timing_for_restored_trigger( + trigger: TimerTrigger, + created_at: i64, + persisted_pending_run: bool, + persisted_next_run_at: Option, + now: DateTime, +) -> Result { + let timezone = local_timezone(); + timing_for_restored_trigger_with_timezone( + trigger, + created_at, + persisted_pending_run, + persisted_next_run_at, + now, + timezone, + ) +} + +pub(crate) fn next_run_after_due( + trigger: &TimerTrigger, + created_at: i64, + now: DateTime, +) -> Result, String> { + let timezone = local_timezone(); + next_run_after_due_with_timezone(trigger, created_at, now, timezone) +} + +fn timing_for_new_trigger_with_timezone( + trigger: TimerTrigger, + created_at: DateTime, + now: DateTime, + timezone: Tz, +) -> Result { + let normalized = normalize_trigger(trigger, now, timezone)?; + match &normalized { + TimerTrigger::Delay { seconds, repeat } => { + let repeat = repeat.unwrap_or(false); + if repeat && *seconds == 0 { + return Ok(timing( + normalized, /*pending_run*/ true, /*next_run_at*/ None, now, + )); + } + let next_run_at = checked_add_seconds(created_at, *seconds)?; + let pending_run = next_run_at <= now; + let next_run_at = if repeat { + if pending_run { + next_delay_recurring_run_at(created_at, *seconds, now)? + } else { + Some(next_run_at.timestamp()) + } + } else { + Some(next_run_at.timestamp()) + }; + Ok(timing(normalized, pending_run, next_run_at, now)) + } + TimerTrigger::Schedule { rrule: None, .. } => { + let due_at = schedule_dtstart_utc(&normalized, timezone)?; + Ok(timing( + normalized, + due_at <= now, + Some(due_at.timestamp()), + now, + )) + } + TimerTrigger::Schedule { rrule: Some(_), .. } => { + let due_or_next = next_schedule_occurrence_at_or_after(&normalized, now, timezone)?; + let Some(due_or_next) = due_or_next else { + return Ok(timing( + normalized, /*pending_run*/ false, /*next_run_at*/ None, now, + )); + }; + let pending_run = due_or_next <= now.timestamp(); + let next_run_at = if pending_run { + next_schedule_occurrence_after(&normalized, now, timezone)? + } else { + Some(due_or_next) + }; + Ok(timing(normalized, pending_run, next_run_at, now)) + } + } +} + +fn timing_for_restored_trigger_with_timezone( + trigger: TimerTrigger, + created_at: i64, + persisted_pending_run: bool, + persisted_next_run_at: Option, + now: DateTime, + timezone: Tz, +) -> Result { + let normalized = normalize_trigger(trigger, now, timezone)?; + match &normalized { + TimerTrigger::Delay { seconds, repeat } => { + let repeat = repeat.unwrap_or(false); + if repeat && *seconds == 0 { + return Ok(timing( + normalized, /*pending_run*/ true, /*next_run_at*/ None, now, + )); + } + let next_run_at = persisted_next_run_at + .or_else(|| next_delay_run_at(created_at, *seconds)) + .ok_or_else(|| "delay next run time is out of range".to_string())?; + let due = next_run_at <= now.timestamp(); + let pending_run = persisted_pending_run || due; + let next_run_at = if repeat && due { + next_delay_recurring_run_at_from_timestamp(created_at, *seconds, now)? + } else { + Some(next_run_at) + }; + Ok(timing(normalized, pending_run, next_run_at, now)) + } + TimerTrigger::Schedule { rrule: None, .. } => { + let next_run_at = persisted_next_run_at + .or_else(|| { + schedule_dtstart_utc(&normalized, timezone) + .ok() + .map(|dt| dt.timestamp()) + }) + .ok_or_else(|| "schedule next run time is out of range".to_string())?; + Ok(timing( + normalized, + persisted_pending_run || next_run_at <= now.timestamp(), + Some(next_run_at), + now, + )) + } + TimerTrigger::Schedule { rrule: Some(_), .. } => { + let due = persisted_next_run_at.is_none_or(|next| next <= now.timestamp()); + let pending_run = persisted_pending_run || due; + let next_run_at = if due { + next_schedule_occurrence_after(&normalized, now, timezone)? + } else { + persisted_next_run_at + }; + Ok(timing(normalized, pending_run, next_run_at, now)) + } + } +} + +fn next_run_after_due_with_timezone( + trigger: &TimerTrigger, + created_at: i64, + now: DateTime, + timezone: Tz, +) -> Result, String> { + match trigger { + TimerTrigger::Delay { seconds, repeat } => { + if repeat.unwrap_or(false) { + if *seconds == 0 { + return Ok(None); + } + next_delay_recurring_run_at_from_timestamp(created_at, *seconds, now) + } else { + Ok(None) + } + } + TimerTrigger::Schedule { rrule: None, .. } => Ok(None), + TimerTrigger::Schedule { rrule: Some(_), .. } => { + next_schedule_occurrence_after(trigger, now, timezone) + } + } +} + +fn normalize_trigger( + trigger: TimerTrigger, + now: DateTime, + timezone: Tz, +) -> Result { + match trigger { + TimerTrigger::Delay { seconds, repeat } => Ok(TimerTrigger::Delay { seconds, repeat }), + TimerTrigger::Schedule { dtstart, rrule } => { + let dtstart = normalize_optional_string(dtstart); + let rrule = normalize_optional_string(rrule); + if dtstart.is_none() && rrule.is_none() { + return Err("schedule trigger requires dtstart, rrule, or both".to_string()); + } + let dtstart = match (dtstart, rrule.as_ref()) { + (Some(dtstart), _) => { + validate_dtstart(&dtstart, timezone)?; + Some(dtstart) + } + (None, Some(_)) => Some(format_local_dtstart(now, timezone)), + (None, None) => None, + }; + let normalized = TimerTrigger::Schedule { dtstart, rrule }; + if matches!(normalized, TimerTrigger::Schedule { rrule: Some(_), .. }) { + parse_rrule_set(&normalized, timezone)?; + } + Ok(normalized) + } + } +} + +fn timing( + trigger: TimerTrigger, + pending_run: bool, + next_run_at: Option, + now: DateTime, +) -> TriggerTiming { + let keep_timer_for_pending = trigger.is_recurring(); + let timer_delay = next_run_at + .filter(|_| !pending_run || keep_timer_for_pending) + .and_then(|next| timer_delay(next, now)); + TriggerTiming { + trigger, + pending_run, + next_run_at, + timer_delay, + } +} + +fn normalize_optional_string(value: Option) -> Option { + value + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) +} + +fn checked_add_seconds(start: DateTime, seconds: u64) -> Result, String> { + let seconds = i64::try_from(seconds) + .map_err(|_| "delay seconds value is too large to schedule".to_string())?; + start + .checked_add_signed(ChronoDuration::seconds(seconds)) + .ok_or_else(|| "delay next run time is out of range".to_string()) +} + +fn next_delay_run_at(created_at: i64, seconds: u64) -> Option { + let seconds = i64::try_from(seconds).ok()?; + created_at.checked_add(seconds) +} + +fn next_delay_recurring_run_at( + created_at: DateTime, + seconds: u64, + now: DateTime, +) -> Result, String> { + next_delay_recurring_run_at_from_timestamp(created_at.timestamp(), seconds, now) +} + +fn next_delay_recurring_run_at_from_timestamp( + created_at: i64, + seconds: u64, + now: DateTime, +) -> Result, String> { + let seconds = i64::try_from(seconds) + .map_err(|_| "delay seconds value is too large to schedule".to_string())?; + if seconds <= 0 { + return Err("delay.repeat requires seconds to be greater than 0".to_string()); + } + let elapsed = now.timestamp().saturating_sub(created_at); + let completed_intervals = elapsed.div_euclid(seconds) + 1; + created_at + .checked_add( + completed_intervals + .checked_mul(seconds) + .ok_or_else(|| "delay next run time is out of range".to_string())?, + ) + .map(Some) + .ok_or_else(|| "delay next run time is out of range".to_string()) +} + +fn timer_delay(next_run_at: i64, now: DateTime) -> Option { + if next_run_at <= now.timestamp() { + return Some(Duration::ZERO); + } + u64::try_from(next_run_at - now.timestamp()) + .ok() + .map(Duration::from_secs) +} + +fn schedule_dtstart_utc(trigger: &TimerTrigger, timezone: Tz) -> Result, String> { + let TimerTrigger::Schedule { + dtstart: Some(dtstart), + .. + } = trigger + else { + return Err("schedule trigger requires dtstart".to_string()); + }; + local_dtstart_to_utc(dtstart, timezone) +} + +fn next_schedule_occurrence_after( + trigger: &TimerTrigger, + after: DateTime, + timezone: Tz, +) -> Result, String> { + let set = parse_rrule_set(trigger, timezone)?; + let after = after + .checked_add_signed(ChronoDuration::seconds(1)) + .unwrap_or(after); + let result = set.after(after.with_timezone(&timezone)).all(1); + Ok(result + .dates + .into_iter() + .next() + .map(|next| next.with_timezone(&Utc).timestamp())) +} + +fn next_schedule_occurrence_at_or_after( + trigger: &TimerTrigger, + at: DateTime, + timezone: Tz, +) -> Result, String> { + let after = at + .checked_sub_signed(ChronoDuration::seconds(1)) + .unwrap_or(at); + next_schedule_occurrence_after(trigger, after, timezone) +} + +fn parse_rrule_set(trigger: &TimerTrigger, timezone: Tz) -> Result { + let TimerTrigger::Schedule { + dtstart: Some(dtstart), + rrule: Some(rrule), + } = trigger + else { + return Err("schedule trigger requires dtstart and rrule".to_string()); + }; + let naive = parse_dtstart(dtstart)?; + let raw_rrule = rrule + .strip_prefix("RRULE:") + .or_else(|| rrule.strip_prefix("rrule:")) + .unwrap_or(rrule); + let rrule_set = format!( + "DTSTART;TZID={}:{}\nRRULE:{}", + timezone.name(), + naive.format(RRULE_DATE_TIME_FORMAT), + raw_rrule + ); + rrule_set + .parse::() + .map_err(|err| format!("invalid schedule rrule `{rrule}`: {err}")) +} + +fn validate_dtstart(dtstart: &str, timezone: Tz) -> Result<(), String> { + local_dtstart_to_utc(dtstart, timezone).map(|_| ()) +} + +fn local_dtstart_to_utc(dtstart: &str, timezone: Tz) -> Result, String> { + let naive = parse_dtstart(dtstart)?; + match timezone.from_local_datetime(&naive) { + LocalResult::Single(dt) => Ok(dt.with_timezone(&Utc)), + LocalResult::Ambiguous(earliest, _) => Ok(earliest.with_timezone(&Utc)), + LocalResult::None => Err(format!( + "schedule dtstart `{dtstart}` does not exist in local timezone {timezone}" + )), + } +} + +fn parse_dtstart(dtstart: &str) -> Result { + NaiveDateTime::parse_from_str(dtstart, LOCAL_DATE_TIME_FORMAT) + .map_err(|_| format!("schedule dtstart `{dtstart}` must use format YYYY-MM-DDTHH:MM:SS")) +} + +fn format_local_dtstart(now: DateTime, timezone: Tz) -> String { + now.with_timezone(&timezone) + .naive_local() + .format(LOCAL_DATE_TIME_FORMAT) + .to_string() +} + +fn local_timezone() -> Tz { + iana_time_zone::get_timezone() + .ok() + .and_then(|timezone| timezone.parse::().ok()) + .map(Tz::Tz) + .unwrap_or(Tz::UTC) +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::TimeZone; + use pretty_assertions::assert_eq; + + const TS_1: i64 = 1; + const TS_100: i64 = 100; + const TS_135: i64 = 135; + const TS_1_700_000_000: i64 = 1_700_000_000; + + fn utc(timestamp: i64) -> DateTime { + Utc.timestamp_opt(timestamp, 0) + .single() + .expect("valid timestamp") + } + + fn utc_datetime(datetime: &str) -> DateTime { + Utc.from_utc_datetime( + &NaiveDateTime::parse_from_str(datetime, LOCAL_DATE_TIME_FORMAT) + .expect("valid datetime"), + ) + } + + #[test] + fn delay_one_shot_becomes_pending_when_due() { + let timing = timing_for_new_trigger_with_timezone( + TimerTrigger::Delay { + seconds: 0, + repeat: None, + }, + utc(TS_100), + utc(TS_100), + Tz::UTC, + ) + .expect("trigger should be valid"); + assert_eq!( + timing, + TriggerTiming { + trigger: TimerTrigger::Delay { + seconds: 0, + repeat: None, + }, + pending_run: true, + next_run_at: Some(100), + timer_delay: None, + } + ); + } + + #[test] + fn delay_repeat_zero_is_idle_recurring() { + let timing = timing_for_new_trigger_with_timezone( + TimerTrigger::Delay { + seconds: 0, + repeat: Some(true), + }, + utc(TS_100), + utc(TS_100), + Tz::UTC, + ) + .expect("zero repeat should be a valid idle-recurring trigger"); + assert_eq!( + timing, + TriggerTiming { + trigger: TimerTrigger::Delay { + seconds: 0, + repeat: Some(true), + }, + pending_run: true, + next_run_at: None, + timer_delay: None, + } + ); + assert_eq!( + next_run_after_due_with_timezone( + &TimerTrigger::Delay { + seconds: 0, + repeat: Some(true), + }, + /*created_at*/ 100, + utc(TS_100), + Tz::UTC, + ) + .expect("zero repeat should remain timer-free"), + None + ); + } + + #[test] + fn delay_repeat_coalesces_overdue_runs() { + let timing = timing_for_restored_trigger_with_timezone( + TimerTrigger::Delay { + seconds: 10, + repeat: Some(true), + }, + /*created_at*/ 100, + /*persisted_pending_run*/ false, + Some(110), + utc(TS_135), + Tz::UTC, + ) + .expect("trigger should be valid"); + assert_eq!(timing.pending_run, true); + assert_eq!(timing.next_run_at, Some(140)); + } + + #[test] + fn schedule_rrule_only_resolves_dtstart_to_now() { + let timing = timing_for_new_trigger_with_timezone( + TimerTrigger::Schedule { + dtstart: None, + rrule: Some("FREQ=HOURLY;BYMINUTE=0;BYSECOND=0".to_string()), + }, + utc(TS_1_700_000_000), + utc(TS_1_700_000_000), + Tz::UTC, + ) + .expect("trigger should be valid"); + assert_eq!( + timing.trigger, + TimerTrigger::Schedule { + dtstart: Some("2023-11-14T22:13:20".to_string()), + rrule: Some("FREQ=HOURLY;BYMINUTE=0;BYSECOND=0".to_string()), + } + ); + assert_eq!(timing.pending_run, false); + assert_eq!(timing.next_run_at, Some(1_700_002_800)); + } + + #[test] + fn schedule_dtstart_only_is_one_shot() { + let timing = timing_for_new_trigger_with_timezone( + TimerTrigger::Schedule { + dtstart: Some("2024-01-01T09:00:00".to_string()), + rrule: None, + }, + utc(TS_1), + utc(TS_1), + Tz::UTC, + ) + .expect("trigger should be valid"); + assert_eq!(timing.pending_run, false); + assert_eq!(timing.next_run_at, Some(1_704_099_600)); + } + + #[test] + fn schedule_recurring_historical_dtstart_waits_for_next_future_occurrence() { + let timing = timing_for_new_trigger_with_timezone( + TimerTrigger::Schedule { + dtstart: Some("2024-01-01T09:00:00".to_string()), + rrule: Some("FREQ=DAILY;BYHOUR=9;BYMINUTE=0;BYSECOND=0".to_string()), + }, + utc_datetime("2024-01-02T08:00:00"), + utc_datetime("2024-01-02T08:00:00"), + Tz::UTC, + ) + .expect("trigger should be valid"); + assert_eq!(timing.pending_run, false); + assert_eq!( + timing.next_run_at, + Some(utc_datetime("2024-01-02T09:00:00").timestamp()) + ); + } + + #[test] + fn schedule_recurring_due_now_becomes_pending() { + let timing = timing_for_new_trigger_with_timezone( + TimerTrigger::Schedule { + dtstart: Some("2024-01-01T09:00:00".to_string()), + rrule: Some("FREQ=DAILY;BYHOUR=9;BYMINUTE=0;BYSECOND=0".to_string()), + }, + utc_datetime("2024-01-02T09:00:00"), + utc_datetime("2024-01-02T09:00:00"), + Tz::UTC, + ) + .expect("trigger should be valid"); + assert_eq!(timing.pending_run, true); + assert_eq!( + timing.next_run_at, + Some(utc_datetime("2024-01-03T09:00:00").timestamp()) + ); + } + + #[test] + fn schedule_rejects_neither_dtstart_nor_rrule() { + assert_eq!( + timing_for_new_trigger_with_timezone( + TimerTrigger::Schedule { + dtstart: None, + rrule: None, + }, + utc(TS_1), + utc(TS_1), + Tz::UTC, + ) + .expect_err("empty schedule should be invalid"), + "schedule trigger requires dtstart, rrule, or both" + ); + } + + #[test] + fn schedule_rejects_invalid_dtstart() { + assert_eq!( + timing_for_new_trigger_with_timezone( + TimerTrigger::Schedule { + dtstart: Some("2024-01-01 09:00:00".to_string()), + rrule: None, + }, + utc(TS_1), + utc(TS_1), + Tz::UTC, + ) + .expect_err("bad dtstart should be invalid"), + "schedule dtstart `2024-01-01 09:00:00` must use format YYYY-MM-DDTHH:MM:SS" + ); + } + + #[test] + fn schedule_rejects_invalid_rrule() { + assert!( + timing_for_new_trigger_with_timezone( + TimerTrigger::Schedule { + dtstart: Some("2024-01-01T09:00:00".to_string()), + rrule: Some("FREQ=NEVER".to_string()), + }, + utc(TS_1), + utc(TS_1), + Tz::UTC, + ) + .expect_err("bad rrule should be invalid") + .contains("invalid schedule rrule") + ); + } +} diff --git a/codex-rs/core/src/timers.rs b/codex-rs/core/src/timers.rs new file mode 100644 index 0000000000..3e77ddd9a3 --- /dev/null +++ b/codex-rs/core/src/timers.rs @@ -0,0 +1,864 @@ +//! Persistent thread-local timer scheduling for follow-on turns and same-turn steer delivery. +//! +//! This module owns the in-memory timer registry, trigger evaluation, the user +//! message injected when a timer fires, and the JSON sidecar format used to +//! restore timers after a harness restart. + +use crate::timer_trigger::TimerTrigger; +use crate::timer_trigger::TriggerTiming; +use crate::timer_trigger::next_run_after_due; +use crate::timer_trigger::timing_for_new_trigger; +use crate::timer_trigger::timing_for_restored_trigger; +use chrono::Utc; +use codex_protocol::models::ContentItem; +use codex_protocol::models::ResponseInputItem; +use serde::Deserialize; +use serde::Serialize; +use std::collections::HashMap; +use std::io::ErrorKind; +use std::path::Path; +use std::path::PathBuf; +use tokio_util::sync::CancellationToken; +use uuid::Uuid; + +pub const TIMER_UPDATED_BACKGROUND_EVENT_PREFIX: &str = "timer_updated:"; +pub const TIMER_FIRED_BACKGROUND_EVENT_PREFIX: &str = "timer_fired:"; +pub const MAX_ACTIVE_TIMERS_PER_THREAD: usize = 256; +const ONE_SHOT_TIMER_PROMPT: &str = include_str!("../templates/timers/one_shot_prompt.md"); +const RECURRING_TIMER_PROMPT: &str = include_str!("../templates/timers/recurring_prompt.md"); + +pub use crate::timer_trigger::TimerTrigger as ThreadTimerTrigger; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum TimerDelivery { + AfterTurn, + SteerCurrentTurn, +} + +impl TimerDelivery { + pub fn as_str(self) -> &'static str { + match self { + Self::AfterTurn => "after-turn", + Self::SteerCurrentTurn => "steer-current-turn", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ThreadTimer { + pub id: String, + pub trigger: TimerTrigger, + pub prompt: String, + pub delivery: TimerDelivery, + pub created_at: i64, + pub next_run_at: Option, + pub last_run_at: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct TimerInvocationContext { + pub(crate) current_timer_id: String, + pub(crate) trigger: TimerTrigger, + pub(crate) prompt: String, + pub(crate) recurring: bool, + pub(crate) delivery: TimerDelivery, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct ClaimedTimer { + pub(crate) timer: ThreadTimer, + pub(crate) context: TimerInvocationContext, + pub(crate) deleted_one_shot_timer: bool, +} + +#[derive(Debug)] +pub(crate) struct CreateTimer { + pub(crate) id: String, + pub(crate) trigger: TimerTrigger, + pub(crate) prompt: String, + pub(crate) delivery: TimerDelivery, + pub(crate) now: chrono::DateTime, +} + +#[derive(Debug, Default)] +pub(crate) struct TimersState { + timers: HashMap, +} + +#[derive(Debug)] +pub(crate) struct TimerRuntime { + pub(crate) timer: ThreadTimer, + pending_run: bool, + pub(crate) timer_cancel: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct PersistedTimer { + pub(crate) timer: ThreadTimer, + pub(crate) pending_run: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct TimerTaskSpec { + pub(crate) delay: std::time::Duration, +} + +impl TimersState { + pub(crate) fn list_timers(&self) -> Vec { + let mut timers = self + .timers + .values() + .map(|runtime| runtime.timer.clone()) + .collect::>(); + timers.sort_by(|left, right| { + left.created_at + .cmp(&right.created_at) + .then_with(|| left.id.cmp(&right.id)) + }); + timers + } + + pub(crate) fn persisted_timers(&self) -> Vec { + let mut timers = self + .timers + .values() + .map(|runtime| PersistedTimer { + timer: runtime.timer.clone(), + pending_run: runtime.pending_run, + }) + .collect::>(); + timers.sort_by(|left, right| { + left.timer + .created_at + .cmp(&right.timer.created_at) + .then_with(|| left.timer.id.cmp(&right.timer.id)) + }); + timers + } + + pub(crate) fn create_timer( + &mut self, + create_timer: CreateTimer, + timer_cancel: Option, + ) -> Result<(ThreadTimer, Option), String> { + if self.timers.len() >= MAX_ACTIVE_TIMERS_PER_THREAD { + return Err(format!( + "too many active timers; each thread supports at most {MAX_ACTIVE_TIMERS_PER_THREAD} timers" + )); + } + let CreateTimer { + id, + trigger, + prompt, + delivery, + now, + } = create_timer; + let TriggerTiming { + trigger, + pending_run, + next_run_at, + timer_delay, + } = timing_for_new_trigger(trigger, now, now)?; + let timer = ThreadTimer { + id: id.clone(), + trigger, + prompt, + delivery, + created_at: now.timestamp(), + next_run_at, + last_run_at: None, + }; + self.timers.insert( + id, + TimerRuntime { + timer: timer.clone(), + pending_run, + timer_cancel, + }, + ); + Ok((timer, timer_delay.map(|delay| TimerTaskSpec { delay }))) + } + + pub(crate) fn restore_timer( + &mut self, + persisted: PersistedTimer, + now: chrono::DateTime, + timer_cancel: Option, + ) -> Result, String> { + if self.timers.len() >= MAX_ACTIVE_TIMERS_PER_THREAD { + return Err(format!( + "too many persisted timers; each thread supports at most {MAX_ACTIVE_TIMERS_PER_THREAD} timers" + )); + } + let PersistedTimer { + timer, + pending_run: persisted_pending_run, + } = persisted; + let TriggerTiming { + trigger, + pending_run, + next_run_at, + timer_delay, + } = timing_for_restored_trigger( + timer.trigger, + timer.created_at, + persisted_pending_run, + timer.next_run_at, + now, + )?; + let timer = ThreadTimer { + trigger, + next_run_at, + ..timer + }; + let id = timer.id.clone(); + self.timers.insert( + id, + TimerRuntime { + timer, + pending_run, + timer_cancel, + }, + ); + Ok(timer_delay.map(|delay| TimerTaskSpec { delay })) + } + + pub(crate) fn remove_timer(&mut self, id: &str) -> Option { + self.timers.remove(id) + } + + pub(crate) fn restore_runtime(&mut self, runtime: TimerRuntime) { + self.timers.insert(runtime.timer.id.clone(), runtime); + } + + pub(crate) fn cancel_runtime(runtime: &TimerRuntime) { + if let Some(cancel) = runtime.timer_cancel.as_ref() { + cancel.cancel(); + } + } + + pub(crate) fn mark_timer_due(&mut self, id: &str, now: chrono::DateTime) -> bool { + let Some(runtime) = self.timers.get_mut(id) else { + return false; + }; + let mut changed = !runtime.pending_run; + runtime.pending_run = true; + match next_run_after_due(&runtime.timer.trigger, runtime.timer.created_at, now) { + Ok(next_run_at) if runtime.timer.next_run_at != next_run_at => { + runtime.timer.next_run_at = next_run_at; + changed = true; + } + Ok(_) => {} + Err(err) => { + tracing::warn!( + "failed to advance timer {} trigger: {err}", + runtime.timer.id + ); + } + } + changed + } + + pub(crate) fn timer_spec_for_timer( + &self, + id: &str, + now: chrono::DateTime, + ) -> Option { + let runtime = self.timers.get(id)?; + let next_run_at = runtime.timer.next_run_at?; + if runtime.pending_run && !runtime.timer.trigger.is_recurring() { + return None; + } + Some(TimerTaskSpec { + delay: if next_run_at <= now.timestamp() { + std::time::Duration::ZERO + } else { + let delay = u64::try_from(next_run_at - now.timestamp()).ok()?; + std::time::Duration::from_secs(delay) + }, + }) + } + + pub(crate) fn claim_next_timer( + &mut self, + now: chrono::DateTime, + can_after_turn: bool, + can_steer_current_turn: bool, + ) -> Option { + let (next_timer_id, actual_delivery) = self + .timers + .values() + .filter(|runtime| runtime.pending_run) + .filter_map(|runtime| { + if runtime.timer.trigger.is_idle_recurring() { + if can_after_turn { + return Some((runtime, TimerDelivery::AfterTurn)); + } + return None; + } + let actual_delivery = match runtime.timer.delivery { + TimerDelivery::AfterTurn if can_after_turn => TimerDelivery::AfterTurn, + TimerDelivery::AfterTurn => return None, + TimerDelivery::SteerCurrentTurn if can_steer_current_turn => { + TimerDelivery::SteerCurrentTurn + } + TimerDelivery::SteerCurrentTurn if can_after_turn => TimerDelivery::AfterTurn, + TimerDelivery::SteerCurrentTurn => return None, + }; + Some((runtime, actual_delivery)) + }) + .min_by(|(left, _), (right, _)| { + left.timer + .last_run_at + .unwrap_or(left.timer.created_at) + .cmp(&right.timer.last_run_at.unwrap_or(right.timer.created_at)) + .then_with(|| left.timer.created_at.cmp(&right.timer.created_at)) + .then_with(|| left.timer.id.cmp(&right.timer.id)) + }) + .map(|(runtime, actual_delivery)| (runtime.timer.id.clone(), actual_delivery))?; + + let runtime = self.timers.remove(&next_timer_id)?; + let TimerRuntime { + mut timer, + pending_run: _, + timer_cancel, + } = runtime; + let is_recurring = timer.trigger.is_recurring(); + let deleted_one_shot_timer = !is_recurring; + if deleted_one_shot_timer { + if let Some(cancel) = timer_cancel.as_ref() { + cancel.cancel(); + } + } else { + timer.last_run_at = Some(now.timestamp()); + let pending_run = timer.trigger.is_idle_recurring(); + self.timers.insert( + timer.id.clone(), + TimerRuntime { + timer: timer.clone(), + pending_run, + timer_cancel, + }, + ); + } + Some(ClaimedTimer { + timer: timer.clone(), + context: TimerInvocationContext { + current_timer_id: timer.id, + trigger: timer.trigger, + prompt: timer.prompt, + recurring: is_recurring, + delivery: actual_delivery, + }, + deleted_one_shot_timer, + }) + } +} + +pub(crate) fn timer_prompt_input_item(timer: &TimerInvocationContext) -> ResponseInputItem { + let text = if timer.recurring { + render_timer_prompt_template(RECURRING_TIMER_PROMPT, timer) + } else { + render_timer_prompt_template(ONE_SHOT_TIMER_PROMPT, timer) + }; + ResponseInputItem::Message { + role: "user".to_string(), + content: vec![ContentItem::InputText { text }], + } +} + +fn render_timer_prompt_template(template: &str, timer: &TimerInvocationContext) -> String { + template + .replace("\r\n", "\n") + .replace("{{CURRENT_TIMER_ID}}", &timer.current_timer_id) + .replace("{{TRIGGER}}", &timer.trigger.display()) + .replace("{{PROMPT}}", &timer.prompt) + .replace("{{DELIVERY}}", timer.delivery.as_str()) + .trim_end() + .to_string() +} + +pub fn timer_sidecar_path_for_rollout(rollout_path: &Path) -> PathBuf { + PathBuf::from(format!("{}.timers.json", rollout_path.display())) +} + +pub(crate) async fn load_timer_sidecar(rollout_path: &Path) -> Result, String> { + let sidecar_path = timer_sidecar_path_for_rollout(rollout_path); + let bytes = match tokio::fs::read(&sidecar_path).await { + Ok(bytes) => bytes, + Err(err) if err.kind() == ErrorKind::NotFound => return Ok(Vec::new()), + Err(err) => { + return Err(format!( + "failed to read timer sidecar `{}`: {err}", + sidecar_path.display() + )); + } + }; + let raw_timers: Vec = serde_json::from_slice(&bytes).map_err(|err| { + format!( + "failed to parse timer sidecar `{}`: {err}", + sidecar_path.display() + ) + })?; + let mut timers = Vec::new(); + for raw_timer in raw_timers { + match serde_json::from_value::(raw_timer) { + Ok(timer) => timers.push(timer), + Err(err) => { + tracing::warn!( + "skipping invalid persisted timer from `{}`: {err}", + sidecar_path.display() + ); + } + } + } + Ok(timers) +} + +pub(crate) async fn write_timer_sidecar( + rollout_path: &Path, + timers: &[PersistedTimer], +) -> Result<(), String> { + let sidecar_path = timer_sidecar_path_for_rollout(rollout_path); + if timers.is_empty() { + match tokio::fs::remove_file(&sidecar_path).await { + Ok(()) => return Ok(()), + Err(err) if err.kind() == ErrorKind::NotFound => return Ok(()), + Err(err) => { + return Err(format!( + "failed to remove empty timer sidecar `{}`: {err}", + sidecar_path.display() + )); + } + } + } + + let bytes = serde_json::to_vec_pretty(timers).map_err(|err| { + format!( + "failed to serialize timer sidecar `{}`: {err}", + sidecar_path.display() + ) + })?; + let tmp_path = PathBuf::from(format!("{}.tmp-{}", sidecar_path.display(), Uuid::new_v4())); + tokio::fs::write(&tmp_path, bytes).await.map_err(|err| { + format!( + "failed to write temporary timer sidecar `{}`: {err}", + tmp_path.display() + ) + })?; + match tokio::fs::rename(&tmp_path, &sidecar_path).await { + Ok(()) => Ok(()), + Err(initial_error) => { + #[cfg(target_os = "windows")] + { + match tokio::fs::remove_file(&sidecar_path).await { + Ok(()) => { + tokio::fs::rename(&tmp_path, &sidecar_path) + .await + .map_err(|err| { + format!( + "failed to replace timer sidecar `{}` with `{}`: {err}", + sidecar_path.display(), + tmp_path.display() + ) + })?; + return Ok(()); + } + Err(err) if err.kind() == ErrorKind::NotFound => {} + Err(err) => { + let _ = tokio::fs::remove_file(&tmp_path).await; + return Err(format!( + "failed to remove existing timer sidecar `{}` before replace: {err}", + sidecar_path.display() + )); + } + } + } + + let _ = tokio::fs::remove_file(&tmp_path).await; + Err(format!( + "failed to atomically replace timer sidecar `{}` with `{}`: {initial_error}", + sidecar_path.display(), + tmp_path.display() + )) + } + } +} + +#[cfg(test)] +mod tests { + use super::CreateTimer; + use super::MAX_ACTIVE_TIMERS_PER_THREAD; + use super::PersistedTimer; + use super::ThreadTimer; + use super::TimerDelivery; + use super::TimerInvocationContext; + use super::TimersState; + use super::load_timer_sidecar; + use super::timer_prompt_input_item; + use super::timer_sidecar_path_for_rollout; + use super::write_timer_sidecar; + use crate::timer_trigger::TimerTrigger; + use chrono::TimeZone; + use chrono::Utc; + use codex_protocol::models::ContentItem; + use codex_protocol::models::ResponseInputItem; + use pretty_assertions::assert_eq; + use tempfile::TempDir; + + const ZERO_SECONDS: u64 = 0; + const TEN_SECONDS: u64 = 10; + const SIXTY_SECONDS: u64 = 60; + + fn delay(seconds: u64, repeat: Option) -> TimerTrigger { + TimerTrigger::Delay { seconds, repeat } + } + + #[test] + fn claim_one_shot_timer_removes_it() { + let now = Utc.timestamp_opt(100, 0).single().expect("valid timestamp"); + let mut timers = TimersState::default(); + let (timer, timer_spec) = timers + .create_timer( + CreateTimer { + id: "timer-1".to_string(), + trigger: delay(ZERO_SECONDS, /*repeat*/ None), + prompt: "run tests".to_string(), + delivery: TimerDelivery::AfterTurn, + now, + }, + /*timer_cancel*/ None, + ) + .expect("timer should be created"); + assert_eq!(timer_spec, None); + assert_eq!(timers.list_timers(), vec![timer]); + + let claimed = timers + .claim_next_timer( + now, /*can_after_turn*/ true, /*can_steer_current_turn*/ true, + ) + .expect("timer should be claimed"); + assert_eq!(claimed.context.current_timer_id, "timer-1"); + assert!(claimed.deleted_one_shot_timer); + assert!(timers.list_timers().is_empty()); + } + + #[test] + fn claim_next_timer_prefers_pending_timer_that_ran_least_recently() { + let create_first = Utc.timestamp_opt(100, 0).single().expect("valid timestamp"); + let create_second = Utc.timestamp_opt(101, 0).single().expect("valid timestamp"); + let first_claimed_at = Utc.timestamp_opt(110, 0).single().expect("valid timestamp"); + let second_claimed_at = Utc.timestamp_opt(111, 0).single().expect("valid timestamp"); + let mut timers = TimersState::default(); + timers + .create_timer( + CreateTimer { + id: "timer-1".to_string(), + trigger: delay(TEN_SECONDS, Some(true)), + prompt: "older recurring timer".to_string(), + delivery: TimerDelivery::AfterTurn, + now: create_first, + }, + /*timer_cancel*/ None, + ) + .expect("timer should be created"); + timers + .create_timer( + CreateTimer { + id: "timer-2".to_string(), + trigger: delay(TEN_SECONDS, Some(true)), + prompt: "newer recurring timer".to_string(), + delivery: TimerDelivery::AfterTurn, + now: create_second, + }, + /*timer_cancel*/ None, + ) + .expect("timer should be created"); + timers.mark_timer_due("timer-1", first_claimed_at); + timers.mark_timer_due("timer-2", first_claimed_at); + + let first = timers + .claim_next_timer( + first_claimed_at, + /*can_after_turn*/ true, + /*can_steer_current_turn*/ true, + ) + .expect("first timer should be claimed"); + assert_eq!(first.context.current_timer_id, "timer-1"); + + let second = timers + .claim_next_timer( + second_claimed_at, + /*can_after_turn*/ true, + /*can_steer_current_turn*/ true, + ) + .expect("second timer should be claimed"); + assert_eq!(second.context.current_timer_id, "timer-2"); + } + + #[test] + fn idle_recurring_timer_remains_pending_after_claim() { + let now = Utc.timestamp_opt(100, 0).single().expect("valid timestamp"); + let mut timers = TimersState::default(); + let (timer, timer_spec) = timers + .create_timer( + CreateTimer { + id: "timer-1".to_string(), + trigger: delay(ZERO_SECONDS, Some(true)), + prompt: "keep going".to_string(), + delivery: TimerDelivery::AfterTurn, + now, + }, + /*timer_cancel*/ None, + ) + .expect("timer should be created"); + assert_eq!(timer_spec, None); + + let claimed = timers + .claim_next_timer( + now, /*can_after_turn*/ true, /*can_steer_current_turn*/ true, + ) + .expect("timer should be claimed"); + assert!(!claimed.deleted_one_shot_timer); + assert_eq!( + timers.persisted_timers(), + vec![PersistedTimer { + timer: ThreadTimer { + last_run_at: Some(100), + ..timer + }, + pending_run: true, + }] + ); + } + + #[test] + fn idle_recurring_timer_waits_for_idle_even_if_delivery_requests_steer() { + let now = Utc.timestamp_opt(100, 0).single().expect("valid timestamp"); + let mut timers = TimersState::default(); + timers + .create_timer( + CreateTimer { + id: "timer-1".to_string(), + trigger: delay(ZERO_SECONDS, Some(true)), + prompt: "keep going".to_string(), + delivery: TimerDelivery::SteerCurrentTurn, + now, + }, + /*timer_cancel*/ None, + ) + .expect("timer should be created"); + + assert_eq!( + timers.claim_next_timer( + now, /*can_after_turn*/ false, /*can_steer_current_turn*/ true, + ), + None + ); + let claimed = timers + .claim_next_timer( + now, /*can_after_turn*/ true, /*can_steer_current_turn*/ false, + ) + .expect("timer should be claimed when idle"); + assert_eq!(claimed.context.delivery, TimerDelivery::AfterTurn); + } + + #[test] + fn create_timer_rejects_more_than_maximum_active_timers() { + let now = Utc.timestamp_opt(100, 0).single().expect("valid timestamp"); + let mut timers = TimersState::default(); + for index in 0..MAX_ACTIVE_TIMERS_PER_THREAD { + timers + .create_timer( + CreateTimer { + id: format!("timer-{index}"), + trigger: delay(SIXTY_SECONDS, Some(true)), + prompt: format!("prompt-{index}"), + delivery: TimerDelivery::AfterTurn, + now, + }, + /*timer_cancel*/ None, + ) + .expect("timer should be created"); + } + + let result = timers.create_timer( + CreateTimer { + id: "timer-overflow".to_string(), + trigger: delay(SIXTY_SECONDS, Some(true)), + prompt: "overflow".to_string(), + delivery: TimerDelivery::AfterTurn, + now, + }, + /*timer_cancel*/ None, + ); + + assert_eq!( + result, + Err(format!( + "too many active timers; each thread supports at most {MAX_ACTIVE_TIMERS_PER_THREAD} timers" + )) + ); + } + + #[test] + fn timer_prompt_input_is_visible_user_input() { + let item = timer_prompt_input_item(&TimerInvocationContext { + current_timer_id: "timer-1".to_string(), + trigger: delay(TEN_SECONDS, Some(true)), + prompt: "run tests".to_string(), + recurring: true, + delivery: TimerDelivery::SteerCurrentTurn, + }); + assert_eq!( + item, + ResponseInputItem::Message { + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "\ntimer-1\ndelay 10s, repeat\nsteer-current-turn\ntrue\n\nrun tests\n\n\nThis timer should keep running on its schedule after this invocation.\nDo not call TimerDelete just because you completed this invocation.\nCall TimerDelete with {\"id\":\"timer-1\"} only if the user's timer prompt included an explicit stop condition, such as \"until\", \"stop when\", or \"while\", and that condition is now satisfied.\nDo not expose scheduler internals unless they matter to the user.\n\n".to_string(), + }], + } + ); + } + + #[test] + fn one_shot_timer_prompt_input_omits_delete_instruction() { + let item = timer_prompt_input_item(&TimerInvocationContext { + current_timer_id: "timer-1".to_string(), + trigger: delay(ZERO_SECONDS, /*repeat*/ None), + prompt: "run tests once".to_string(), + recurring: false, + delivery: TimerDelivery::AfterTurn, + }); + assert_eq!( + item, + ResponseInputItem::Message { + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "\ntimer-1\ndelay 0s\nafter-turn\nfalse\n\nrun tests once\n\n\nThis one-shot timer has already been removed from the schedule, so you do not need to call TimerDelete.\nDo not expose scheduler internals unless they matter to the user.\n\n".to_string(), + }], + } + ); + } + + #[tokio::test] + async fn timer_sidecar_round_trips_persisted_timers() { + let tempdir = TempDir::new().expect("tempdir"); + let rollout_path = tempdir.path().join("rollout.jsonl"); + let persisted = vec![PersistedTimer { + timer: super::ThreadTimer { + id: "timer-1".to_string(), + trigger: delay(ZERO_SECONDS, /*repeat*/ None), + prompt: "run tests".to_string(), + delivery: TimerDelivery::AfterTurn, + created_at: 1, + next_run_at: None, + last_run_at: None, + }, + pending_run: true, + }]; + + write_timer_sidecar(&rollout_path, &persisted) + .await + .expect("write sidecar"); + let loaded = load_timer_sidecar(&rollout_path) + .await + .expect("load sidecar"); + + assert_eq!(loaded, persisted); + assert_eq!( + timer_sidecar_path_for_rollout(&rollout_path), + tempdir.path().join("rollout.jsonl.timers.json") + ); + } + + #[tokio::test] + async fn timer_sidecar_overwrites_existing_file() { + let tempdir = TempDir::new().expect("tempdir"); + let rollout_path = tempdir.path().join("rollout.jsonl"); + let original = vec![PersistedTimer { + timer: super::ThreadTimer { + id: "timer-1".to_string(), + trigger: delay(ZERO_SECONDS, /*repeat*/ None), + prompt: "run tests".to_string(), + delivery: TimerDelivery::AfterTurn, + created_at: 1, + next_run_at: None, + last_run_at: None, + }, + pending_run: true, + }]; + let replacement = vec![PersistedTimer { + timer: super::ThreadTimer { + id: "timer-2".to_string(), + trigger: delay(SIXTY_SECONDS, Some(true)), + prompt: "run different tests".to_string(), + delivery: TimerDelivery::SteerCurrentTurn, + created_at: 2, + next_run_at: None, + last_run_at: Some(3), + }, + pending_run: false, + }]; + + write_timer_sidecar(&rollout_path, &original) + .await + .expect("write original sidecar"); + write_timer_sidecar(&rollout_path, &replacement) + .await + .expect("overwrite sidecar"); + + let loaded = load_timer_sidecar(&rollout_path) + .await + .expect("load overwritten sidecar"); + assert_eq!(loaded, replacement); + } + + #[tokio::test] + async fn timer_sidecar_skips_invalid_entries() { + let tempdir = TempDir::new().expect("tempdir"); + let rollout_path = tempdir.path().join("rollout.jsonl"); + let sidecar_path = timer_sidecar_path_for_rollout(&rollout_path); + tokio::fs::write( + &sidecar_path, + r#"[ + { "timer": { "id": "old", "cronExpression": "@after-turn" }, "pending_run": true }, + { + "timer": { + "id": "timer-1", + "trigger": { "kind": "delay", "seconds": 0, "repeat": null }, + "prompt": "run tests", + "delivery": "after-turn", + "created_at": 1, + "next_run_at": null, + "last_run_at": null + }, + "pending_run": true + } + ]"#, + ) + .await + .expect("write sidecar"); + + let loaded = load_timer_sidecar(&rollout_path) + .await + .expect("load sidecar"); + + assert_eq!( + loaded, + vec![PersistedTimer { + timer: super::ThreadTimer { + id: "timer-1".to_string(), + trigger: delay(ZERO_SECONDS, /*repeat*/ None), + prompt: "run tests".to_string(), + delivery: TimerDelivery::AfterTurn, + created_at: 1, + next_run_at: None, + last_run_at: None, + }, + pending_run: true, + }] + ); + } +} diff --git a/codex-rs/core/src/tools/handlers/mod.rs b/codex-rs/core/src/tools/handlers/mod.rs index ec6fc02cfa..124e5d0a4c 100644 --- a/codex-rs/core/src/tools/handlers/mod.rs +++ b/codex-rs/core/src/tools/handlers/mod.rs @@ -1,5 +1,5 @@ pub(crate) mod agent_jobs; -pub(crate) mod apply_patch; +pub mod apply_patch; mod dynamic; mod js_repl; mod list_dir; @@ -13,6 +13,7 @@ mod request_permissions; mod request_user_input; mod shell; mod test_sync; +mod timers; mod tool_search; mod tool_suggest; pub(crate) mod unified_exec; @@ -47,6 +48,9 @@ pub use request_user_input::RequestUserInputHandler; pub use shell::ShellCommandHandler; pub use shell::ShellHandler; pub use test_sync::TestSyncHandler; +pub use timers::TimerCreateHandler; +pub use timers::TimerDeleteHandler; +pub use timers::TimerListHandler; pub use tool_search::ToolSearchHandler; pub use tool_suggest::ToolSuggestHandler; pub use unified_exec::UnifiedExecHandler; diff --git a/codex-rs/core/src/tools/handlers/timers.rs b/codex-rs/core/src/tools/handlers/timers.rs new file mode 100644 index 0000000000..f6874ecfb7 --- /dev/null +++ b/codex-rs/core/src/tools/handlers/timers.rs @@ -0,0 +1,108 @@ +//! Built-in tool handlers for thread-local persistent timer management. +//! +//! These handlers bridge `TimerCreate`, `TimerDelete`, and `TimerList` tool +//! calls onto the current thread session's timer registry. + +use serde::Deserialize; + +use crate::function_tool::FunctionCallError; +use crate::timers::ThreadTimerTrigger; +use crate::timers::TimerDelivery; +use crate::tools::context::FunctionToolOutput; +use crate::tools::context::ToolInvocation; +use crate::tools::context::ToolPayload; +use crate::tools::handlers::parse_arguments; +use crate::tools::registry::ToolHandler; +use crate::tools::registry::ToolKind; + +#[derive(Deserialize)] +struct TimerCreateArgs { + trigger: ThreadTimerTrigger, + prompt: String, + delivery: TimerDelivery, +} + +#[derive(Deserialize)] +struct TimerDeleteArgs { + id: String, +} + +pub struct TimerCreateHandler; + +impl ToolHandler for TimerCreateHandler { + type Output = FunctionToolOutput; + + fn kind(&self) -> ToolKind { + ToolKind::Function + } + + async fn handle(&self, invocation: ToolInvocation) -> Result { + let ToolPayload::Function { arguments } = invocation.payload else { + return Err(FunctionCallError::RespondToModel( + "TimerCreate received unsupported payload".to_string(), + )); + }; + let args: TimerCreateArgs = parse_arguments(&arguments)?; + let timer = invocation + .session + .create_timer(args.trigger, args.prompt, args.delivery) + .await + .map_err(FunctionCallError::RespondToModel)?; + let content = serde_json::to_string(&timer).map_err(|err| { + FunctionCallError::Fatal(format!("failed to serialize TimerCreate response: {err}")) + })?; + Ok(FunctionToolOutput::from_text(content, Some(true))) + } +} + +pub struct TimerDeleteHandler; + +impl ToolHandler for TimerDeleteHandler { + type Output = FunctionToolOutput; + + fn kind(&self) -> ToolKind { + ToolKind::Function + } + + async fn handle(&self, invocation: ToolInvocation) -> Result { + let ToolPayload::Function { arguments } = invocation.payload else { + return Err(FunctionCallError::RespondToModel( + "TimerDelete received unsupported payload".to_string(), + )); + }; + let args: TimerDeleteArgs = parse_arguments(&arguments)?; + let deleted = invocation + .session + .delete_timer(&args.id) + .await + .map_err(FunctionCallError::RespondToModel)?; + let content = serde_json::json!({ "deleted": deleted }).to_string(); + Ok(FunctionToolOutput::from_text(content, Some(deleted))) + } +} + +pub struct TimerListHandler; + +impl ToolHandler for TimerListHandler { + type Output = FunctionToolOutput; + + fn kind(&self) -> ToolKind { + ToolKind::Function + } + + async fn handle(&self, invocation: ToolInvocation) -> Result { + match invocation.payload { + ToolPayload::Function { .. } => {} + _ => { + return Err(FunctionCallError::RespondToModel( + "TimerList received unsupported payload".to_string(), + )); + } + } + let timers = invocation.session.list_timers().await; + let content = serde_json::to_string(&timers).map_err(|err| { + FunctionCallError::Fatal(format!("failed to serialize TimerList response: {err}")) + })?; + Ok(FunctionToolOutput::from_text(content, Some(true))) + } +} diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 37a68d4081..80262ce12d 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -1,5 +1,8 @@ use crate::shell::Shell; use crate::shell::ShellType; +use crate::tools::handlers::TimerCreateHandler; +use crate::tools::handlers::TimerDeleteHandler; +use crate::tools::handlers::TimerListHandler; use crate::tools::handlers::agent_jobs::BatchJobHandler; use crate::tools::handlers::multi_agents_common::DEFAULT_WAIT_TIMEOUT_MS; use crate::tools::handlers::multi_agents_common::MAX_WAIT_TIMEOUT_MS; @@ -130,6 +133,15 @@ pub(crate) fn build_specs_with_discoverable_tools( for handler in plan.handlers { match handler.kind { + ToolHandlerKind::TimerCreate => { + builder.register_handler(handler.name, Arc::new(TimerCreateHandler)); + } + ToolHandlerKind::TimerDelete => { + builder.register_handler(handler.name, Arc::new(TimerDeleteHandler)); + } + ToolHandlerKind::TimerList => { + builder.register_handler(handler.name, Arc::new(TimerListHandler)); + } ToolHandlerKind::AgentJobs => { builder.register_handler(handler.name, Arc::new(BatchJobHandler)); } diff --git a/codex-rs/core/templates/timers/one_shot_prompt.md b/codex-rs/core/templates/timers/one_shot_prompt.md new file mode 100644 index 0000000000..a453d5884f --- /dev/null +++ b/codex-rs/core/templates/timers/one_shot_prompt.md @@ -0,0 +1,13 @@ + +{{CURRENT_TIMER_ID}} +{{TRIGGER}} +{{DELIVERY}} +false + +{{PROMPT}} + + +This one-shot timer has already been removed from the schedule, so you do not need to call TimerDelete. +Do not expose scheduler internals unless they matter to the user. + + diff --git a/codex-rs/core/templates/timers/recurring_prompt.md b/codex-rs/core/templates/timers/recurring_prompt.md new file mode 100644 index 0000000000..1da7bc0f2c --- /dev/null +++ b/codex-rs/core/templates/timers/recurring_prompt.md @@ -0,0 +1,15 @@ + +{{CURRENT_TIMER_ID}} +{{TRIGGER}} +{{DELIVERY}} +true + +{{PROMPT}} + + +This timer should keep running on its schedule after this invocation. +Do not call TimerDelete just because you completed this invocation. +Call TimerDelete with {"id":"{{CURRENT_TIMER_ID}}"} only if the user's timer prompt included an explicit stop condition, such as "until", "stop when", or "while", and that condition is now satisfied. +Do not expose scheduler internals unless they matter to the user. + + diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index 78dcf748a3..52235e540f 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -142,6 +142,7 @@ mod sqlite_state; mod stream_error_allows_next_turn; mod stream_no_completed; mod subagent_notifications; +mod timers; mod tool_harness; mod tool_parallelism; mod tool_suggest; diff --git a/codex-rs/core/tests/suite/timers.rs b/codex-rs/core/tests/suite/timers.rs new file mode 100644 index 0000000000..f105319a28 --- /dev/null +++ b/codex-rs/core/tests/suite/timers.rs @@ -0,0 +1,106 @@ +use anyhow::Result; +use anyhow::anyhow; +use codex_core::timers::TIMER_FIRED_BACKGROUND_EVENT_PREFIX; +use codex_core::timers::ThreadTimer; +use codex_core::timers::ThreadTimerTrigger; +use codex_core::timers::TimerDelivery; +use codex_features::Feature; +use codex_protocol::protocol::EventMsg; +use core_test_support::responses::ev_assistant_message; +use core_test_support::responses::ev_completed; +use core_test_support::responses::ev_response_created; +use core_test_support::responses::mount_sse_once; +use core_test_support::responses::sse; +use core_test_support::responses::start_mock_server; +use core_test_support::test_codex::test_codex; +use core_test_support::wait_for_event; +use core_test_support::wait_for_event_match; +use pretty_assertions::assert_eq; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn create_timer_emits_fired_background_event_when_timer_starts() -> Result<()> { + assert_after_turn_timer_starts_and_emits_fired_event().await +} + +#[tokio::test(flavor = "current_thread")] +async fn create_timer_starts_on_current_thread_runtime() -> Result<()> { + assert_after_turn_timer_starts_and_emits_fired_event().await +} + +async fn assert_after_turn_timer_starts_and_emits_fired_event() -> Result<()> { + let server = start_mock_server().await; + let mock = mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-1"), + ev_assistant_message("msg-1", "timer ran"), + ev_completed("resp-1"), + ]), + ) + .await; + + let mut builder = test_codex().with_config(|config| { + config + .features + .enable(Feature::TimerScheduler) + .unwrap_or_else(|err| panic!("test config should allow feature update: {err}")); + }); + let test = builder.build(&server).await?; + + let created = test + .codex + .create_timer( + ThreadTimerTrigger::Delay { + seconds: 0, + repeat: None, + }, + "run timer".to_string(), + TimerDelivery::AfterTurn, + ) + .await + .map_err(|err| anyhow!("{err}"))?; + + let payload = wait_for_event_match(&test.codex, |event| match event { + EventMsg::BackgroundEvent(event) => event + .message + .strip_prefix(TIMER_FIRED_BACKGROUND_EVENT_PREFIX) + .map(str::to_owned), + _ => None, + }) + .await; + let fired: ThreadTimer = serde_json::from_str(&payload)?; + assert_eq!(fired, created); + + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + + let user_messages = mock.single_request().message_input_texts("user"); + let expected_timer_input = format!( + " +{} +delay 0s +after-turn +false + +run timer + + +This one-shot timer has already been removed from the schedule, so you do not need to call TimerDelete. +Do not expose scheduler internals unless they matter to the user. + +", + created.id + ); + assert_eq!( + user_messages + .iter() + .filter(|message| message.contains("")) + .map(String::as_str) + .collect::>(), + vec![expected_timer_input.as_str()] + ); + + Ok(()) +} diff --git a/codex-rs/features/src/lib.rs b/codex-rs/features/src/lib.rs index 23c23c9916..01ba780598 100644 --- a/codex-rs/features/src/lib.rs +++ b/codex-rs/features/src/lib.rs @@ -172,6 +172,8 @@ pub enum Feature { Personality, /// Enable native artifact tools. Artifact, + /// Enable per-thread persistent timer scheduling tools and APIs. + TimerScheduler, /// Enable Fast mode selection in the TUI and request layer. FastMode, /// Enable experimental realtime voice conversation mode in the TUI. @@ -808,6 +810,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::UnderDevelopment, default_enabled: false, }, + FeatureSpec { + id: Feature::TimerScheduler, + key: "timer_tool", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::FastMode, key: "fast_mode", diff --git a/codex-rs/rollout/src/lib.rs b/codex-rs/rollout/src/lib.rs index 6acf2c3be4..3b5f7618a8 100644 --- a/codex-rs/rollout/src/lib.rs +++ b/codex-rs/rollout/src/lib.rs @@ -11,6 +11,7 @@ pub(crate) mod policy; pub(crate) mod recorder; pub(crate) mod session_index; pub mod state_db; +mod timer_sidecar; pub(crate) mod default_client { pub use codex_login::default_client::*; diff --git a/codex-rs/rollout/src/list.rs b/codex-rs/rollout/src/list.rs index e7d3dae5de..869792fc0d 100644 --- a/codex-rs/rollout/src/list.rs +++ b/codex-rs/rollout/src/list.rs @@ -17,6 +17,7 @@ use uuid::Uuid; use super::ARCHIVED_SESSIONS_SUBDIR; use super::SESSIONS_SUBDIR; +use super::timer_sidecar::thread_preview_from_timer_sidecar; use crate::protocol::EventMsg; use crate::state_db; use codex_file_search as file_search; @@ -713,8 +714,12 @@ async fn build_thread_item( { return None; } - // Apply filters: must have session meta and at least one user message event - if summary.saw_session_meta && summary.saw_user_event { + let timer_preview = if summary.saw_user_event { + None + } else { + thread_preview_from_timer_sidecar(&path).await + }; + if summary.saw_session_meta && (summary.saw_user_event || timer_preview.is_some()) { let HeadTailSummary { thread_id, first_user_message, @@ -737,7 +742,7 @@ async fn build_thread_item( return Some(ThreadItem { path, thread_id, - first_user_message, + first_user_message: first_user_message.or(timer_preview), cwd, git_branch, git_sha, diff --git a/codex-rs/rollout/src/recorder_tests.rs b/codex-rs/rollout/src/recorder_tests.rs index 163c8a1ee8..0dbac0e51e 100644 --- a/codex-rs/rollout/src/recorder_tests.rs +++ b/codex-rs/rollout/src/recorder_tests.rs @@ -31,6 +31,23 @@ fn test_config(codex_home: &Path) -> RolloutConfig { } fn write_session_file(root: &Path, ts: &str, uuid: Uuid) -> std::io::Result { + write_session_file_with_user_message(root, ts, uuid, /*include_user_message*/ true) +} + +fn write_session_file_without_user_message( + root: &Path, + ts: &str, + uuid: Uuid, +) -> std::io::Result { + write_session_file_with_user_message(root, ts, uuid, /*include_user_message*/ false) +} + +fn write_session_file_with_user_message( + root: &Path, + ts: &str, + uuid: Uuid, + include_user_message: bool, +) -> std::io::Result { let day_dir = root.join("sessions/2025/01/03"); fs::create_dir_all(&day_dir)?; let path = day_dir.join(format!("rollout-{ts}-{uuid}.jsonl")); @@ -49,16 +66,18 @@ fn write_session_file(root: &Path, ts: &str, uuid: Uuid) -> std::io::Result std::io::Resul Ok(()) } +#[tokio::test] +async fn list_threads_db_enabled_fills_page_after_filtering_empty_threads() -> std::io::Result<()> { + let home = TempDir::new().expect("temp dir"); + let config = test_config(home.path()); + + let empty_uuid = Uuid::from_u128(9015); + let valid_uuid = Uuid::from_u128(9016); + let empty_thread_id = + ThreadId::from_string(&empty_uuid.to_string()).expect("valid empty thread id"); + let valid_thread_id = ThreadId::from_string(&valid_uuid.to_string()).expect("valid thread id"); + let empty_path = + write_session_file_without_user_message(home.path(), "2025-01-03T15-00-00", empty_uuid)?; + let valid_path = write_session_file(home.path(), "2025-01-03T14-00-00", valid_uuid)?; + + let runtime = codex_state::StateRuntime::init( + home.path().to_path_buf(), + config.model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + runtime + .mark_backfill_complete(/*last_watermark*/ None) + .await + .expect("backfill should be complete"); + + let empty_created_at = chrono::Utc + .with_ymd_and_hms(2025, 1, 3, 15, 0, 0) + .single() + .expect("valid empty thread datetime"); + let mut empty_builder = codex_state::ThreadMetadataBuilder::new( + empty_thread_id, + empty_path, + empty_created_at, + SessionSource::Cli, + ); + empty_builder.model_provider = Some(config.model_provider_id.clone()); + empty_builder.cwd = home.path().to_path_buf(); + let empty_metadata = empty_builder.build(config.model_provider_id.as_str()); + runtime + .upsert_thread(&empty_metadata) + .await + .expect("state db empty upsert should succeed"); + + let valid_created_at = chrono::Utc + .with_ymd_and_hms(2025, 1, 3, 14, 0, 0) + .single() + .expect("valid thread datetime"); + let mut valid_builder = codex_state::ThreadMetadataBuilder::new( + valid_thread_id, + valid_path.clone(), + valid_created_at, + SessionSource::Cli, + ); + valid_builder.model_provider = Some(config.model_provider_id.clone()); + valid_builder.cwd = home.path().to_path_buf(); + let mut valid_metadata = valid_builder.build(config.model_provider_id.as_str()); + valid_metadata.first_user_message = Some("Hello from user".to_string()); + runtime + .upsert_thread(&valid_metadata) + .await + .expect("state db valid upsert should succeed"); + + let default_provider = config.model_provider_id.clone(); + let page = RolloutRecorder::list_threads( + &config, + /*page_size*/ 1, + /*cursor*/ None, + ThreadSortKey::CreatedAt, + &[], + /*model_providers*/ None, + default_provider.as_str(), + /*search_term*/ None, + ) + .await?; + assert_eq!(page.items.len(), 1); + assert_eq!(page.items[0].path, valid_path); + assert!(page.next_cursor.is_none()); + Ok(()) +} + #[tokio::test] async fn resume_candidate_matches_cwd_reads_latest_turn_context() -> std::io::Result<()> { let home = TempDir::new().expect("temp dir"); diff --git a/codex-rs/rollout/src/timer_sidecar.rs b/codex-rs/rollout/src/timer_sidecar.rs new file mode 100644 index 0000000000..af1997b85d --- /dev/null +++ b/codex-rs/rollout/src/timer_sidecar.rs @@ -0,0 +1,20 @@ +//! Helpers for locating timer sidecars and surfacing scheduler-only threads in +//! session listings. + +use std::path::Path; +use std::path::PathBuf; + +const TIMER_THREAD_PREVIEW: &str = "(timer configured)"; + +pub(crate) fn timer_sidecar_path_for_rollout(rollout_path: &Path) -> PathBuf { + PathBuf::from(format!("{}.timers.json", rollout_path.display())) +} + +pub(crate) async fn thread_preview_from_timer_sidecar(rollout_path: &Path) -> Option { + let sidecar_path = timer_sidecar_path_for_rollout(rollout_path); + tokio::fs::try_exists(sidecar_path) + .await + .ok() + .filter(|exists| *exists) + .map(|_| TIMER_THREAD_PREVIEW.to_string()) +} diff --git a/codex-rs/tools/src/lib.rs b/codex-rs/tools/src/lib.rs index 16e84700bb..18367c21de 100644 --- a/codex-rs/tools/src/lib.rs +++ b/codex-rs/tools/src/lib.rs @@ -15,6 +15,7 @@ mod mcp_tool; mod plan_tool; mod request_user_input_tool; mod responses_api; +mod timer_tool; mod tool_config; mod tool_definition; mod tool_discovery; @@ -85,6 +86,9 @@ pub use responses_api::dynamic_tool_to_responses_api_tool; pub use responses_api::mcp_tool_to_deferred_responses_api_tool; pub use responses_api::mcp_tool_to_responses_api_tool; pub use responses_api::tool_definition_to_responses_api_tool; +pub use timer_tool::create_timer_create_tool; +pub use timer_tool::create_timer_delete_tool; +pub use timer_tool::create_timer_list_tool; pub use tool_config::ShellCommandBackendConfig; pub use tool_config::ToolUserShellType; pub use tool_config::ToolsConfig; diff --git a/codex-rs/tools/src/timer_tool.rs b/codex-rs/tools/src/timer_tool.rs new file mode 100644 index 0000000000..bcbb39259b --- /dev/null +++ b/codex-rs/tools/src/timer_tool.rs @@ -0,0 +1,135 @@ +//! Responses API tool specs for thread-local persistent timer management. +//! +//! These specs expose the `TimerCreate`, `TimerDelete`, and `TimerList` +//! built-in tools so models can create, inspect, and delete timers on the +//! current thread. + +use crate::JsonSchema; +use crate::ResponsesApiTool; +use crate::ToolSpec; +use std::collections::BTreeMap; + +pub fn create_timer_create_tool() -> ToolSpec { + let trigger_properties = BTreeMap::from([ + ( + "kind".to_string(), + JsonSchema::String { + description: Some("Trigger kind. Use `delay` or `schedule`.".to_string()), + }, + ), + ( + "seconds".to_string(), + JsonSchema::Number { + description: Some("Delay trigger seconds from creation time.".to_string()), + }, + ), + ( + "repeat".to_string(), + JsonSchema::Boolean { + description: Some( + "Delay trigger recurrence flag. With seconds 0, repeat means run whenever the thread is idle." + .to_string(), + ), + }, + ), + ( + "dtstart".to_string(), + JsonSchema::String { + description: Some( + "Schedule trigger floating local datetime in YYYY-MM-DDTHH:MM:SS format." + .to_string(), + ), + }, + ), + ( + "rrule".to_string(), + JsonSchema::String { + description: Some("Schedule trigger RRULE string.".to_string()), + }, + ), + ]); + let properties = BTreeMap::from([ + ( + "trigger".to_string(), + JsonSchema::Object { + properties: trigger_properties, + required: Some(vec!["kind".to_string()]), + additional_properties: Some(false.into()), + }, + ), + ( + "prompt".to_string(), + JsonSchema::String { + description: Some("Prompt to execute when the timer fires.".to_string()), + }, + ), + ( + "delivery".to_string(), + JsonSchema::String { + description: Some( + "Delivery mode for the timer. Use `after-turn` or `steer-current-turn`." + .to_string(), + ), + }, + ), + ]); + + ToolSpec::Function(ResponsesApiTool { + name: "TimerCreate".to_string(), + description: "Create a thread timer using a structured trigger, prompt, and delivery mode." + .to_string(), + strict: false, + defer_loading: None, + parameters: JsonSchema::Object { + properties, + required: Some(vec![ + "trigger".to_string(), + "prompt".to_string(), + "delivery".to_string(), + ]), + additional_properties: Some(false.into()), + }, + output_schema: None, + }) +} + +pub fn create_timer_delete_tool() -> ToolSpec { + let properties = BTreeMap::from([( + "id".to_string(), + JsonSchema::String { + description: Some("Identifier of the timer to delete.".to_string()), + }, + )]); + + ToolSpec::Function(ResponsesApiTool { + name: "TimerDelete".to_string(), + description: "Delete a thread timer by id.".to_string(), + strict: false, + defer_loading: None, + parameters: JsonSchema::Object { + properties, + required: Some(vec!["id".to_string()]), + additional_properties: Some(false.into()), + }, + output_schema: None, + }) +} + +pub fn create_timer_list_tool() -> ToolSpec { + ToolSpec::Function(ResponsesApiTool { + name: "TimerList".to_string(), + description: "List thread timers for the current thread.".to_string(), + strict: false, + defer_loading: None, + parameters: JsonSchema::Object { + properties: BTreeMap::new(), + required: None, + additional_properties: Some(false.into()), + }, + output_schema: None, + }) +} + +#[cfg(test)] +#[path = "timer_tool_tests.rs"] +mod tests; diff --git a/codex-rs/tools/src/timer_tool_tests.rs b/codex-rs/tools/src/timer_tool_tests.rs new file mode 100644 index 0000000000..130171e5ed --- /dev/null +++ b/codex-rs/tools/src/timer_tool_tests.rs @@ -0,0 +1,31 @@ +use crate::ResponsesApiTool; +use crate::ToolSpec; +use pretty_assertions::assert_eq; + +use super::create_timer_create_tool; +use super::create_timer_delete_tool; +use super::create_timer_list_tool; + +#[test] +fn timer_create_tool_uses_expected_name() { + let ToolSpec::Function(ResponsesApiTool { name, .. }) = create_timer_create_tool() else { + panic!("expected function tool"); + }; + assert_eq!(name, "TimerCreate"); +} + +#[test] +fn timer_delete_tool_uses_expected_name() { + let ToolSpec::Function(ResponsesApiTool { name, .. }) = create_timer_delete_tool() else { + panic!("expected function tool"); + }; + assert_eq!(name, "TimerDelete"); +} + +#[test] +fn timer_list_tool_uses_expected_name() { + let ToolSpec::Function(ResponsesApiTool { name, .. }) = create_timer_list_tool() else { + panic!("expected function tool"); + }; + assert_eq!(name, "TimerList"); +} diff --git a/codex-rs/tools/src/tool_config.rs b/codex-rs/tools/src/tool_config.rs index 1b55d2c4f4..39853d514e 100644 --- a/codex-rs/tools/src/tool_config.rs +++ b/codex-rs/tools/src/tool_config.rs @@ -105,6 +105,8 @@ pub struct ToolsConfig { pub collab_tools: bool, pub multi_agent_v2: bool, pub hide_spawn_agent_metadata: bool, + pub request_user_input: bool, + pub timer_scheduler: bool, pub default_mode_request_user_input: bool, pub experimental_supported_tools: Vec, pub agent_jobs_tools: bool, @@ -143,6 +145,8 @@ impl ToolsConfig { let include_multi_agent_v2 = features.enabled(Feature::MultiAgentV2); let hide_spawn_agent_metadata = features.enabled(Feature::DebugHideSpawnAgentMetadata); let include_agent_jobs = features.enabled(Feature::SpawnCsv); + let include_request_user_input = !matches!(session_source, SessionSource::SubAgent(_)); + let include_timer_scheduler = features.enabled(Feature::TimerScheduler); let include_default_mode_request_user_input = features.enabled(Feature::DefaultModeRequestUserInput); let include_search_tool = @@ -220,6 +224,8 @@ impl ToolsConfig { collab_tools: include_collab_tools, multi_agent_v2: include_multi_agent_v2, hide_spawn_agent_metadata, + request_user_input: include_request_user_input, + timer_scheduler: include_timer_scheduler, default_mode_request_user_input: include_default_mode_request_user_input, experimental_supported_tools: model_info.experimental_supported_tools.clone(), agent_jobs_tools: include_agent_jobs, diff --git a/codex-rs/tools/src/tool_registry_plan.rs b/codex-rs/tools/src/tool_registry_plan.rs index dc76c12d36..9497f31d6e 100644 --- a/codex-rs/tools/src/tool_registry_plan.rs +++ b/codex-rs/tools/src/tool_registry_plan.rs @@ -44,6 +44,9 @@ use crate::create_spawn_agent_tool_v1; use crate::create_spawn_agent_tool_v2; use crate::create_spawn_agents_on_csv_tool; use crate::create_test_sync_tool; +use crate::create_timer_create_tool; +use crate::create_timer_delete_tool; +use crate::create_timer_list_tool; use crate::create_tool_search_tool; use crate::create_tool_suggest_tool; use crate::create_update_plan_tool; @@ -227,6 +230,27 @@ pub fn build_tool_registry_plan( plan.register_handler("request_permissions", ToolHandlerKind::RequestPermissions); } + if config.timer_scheduler { + plan.push_spec( + create_timer_create_tool(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.push_spec( + create_timer_delete_tool(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.push_spec( + create_timer_list_tool(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.register_handler("TimerCreate", ToolHandlerKind::TimerCreate); + plan.register_handler("TimerDelete", ToolHandlerKind::TimerDelete); + plan.register_handler("TimerList", ToolHandlerKind::TimerList); + } + if config.search_tool && let Some(app_tools) = params.app_tools { diff --git a/codex-rs/tools/src/tool_registry_plan_types.rs b/codex-rs/tools/src/tool_registry_plan_types.rs index d15cf15d5a..62e639c270 100644 --- a/codex-rs/tools/src/tool_registry_plan_types.rs +++ b/codex-rs/tools/src/tool_registry_plan_types.rs @@ -10,6 +10,9 @@ use std::collections::HashMap; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ToolHandlerKind { + TimerCreate, + TimerDelete, + TimerList, AgentJobs, ApplyPatch, CloseAgentV1, diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index dad10fa766..0f24156c06 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -48,6 +48,8 @@ use crate::render::renderable::Renderable; use crate::resume_picker::SessionSelection; #[cfg(test)] use crate::test_support::PathBufExt; +use crate::timer_scheduler::format_timer_summary; +use crate::timer_scheduler::parse_timer_spec; use crate::tui; use crate::tui::TuiEvent; use crate::update_action::UpdateAction; @@ -1983,6 +1985,26 @@ impl App { }); } + fn parse_thread_timer_spec(&mut self, thread_id: ThreadId, spec: String) { + let config = self.config.clone(); + let target = match self.remote_app_server_url.clone() { + Some(websocket_url) => crate::AppServerTarget::Remote { + websocket_url, + auth_token: self.remote_app_server_auth_token.clone(), + }, + None => crate::AppServerTarget::Embedded, + }; + let app_event_tx = self.app_event_tx.clone(); + tokio::spawn(async move { + let result = parse_timer_spec(config, target, spec.clone()).await; + app_event_tx.send(AppEvent::ThreadTimerSpecParsed { + thread_id, + spec, + result, + }); + }); + } + fn submit_feedback( &mut self, app_server: &AppServerSession, @@ -2100,7 +2122,6 @@ impl App { self.handle_feedback_thread_event(event); } } - /// Process the completed MCP inventory fetch: clear the loading spinner, then /// render either the full tool/resource listing or an error into chat history. /// @@ -3329,11 +3350,20 @@ impl App { app_server: &mut AppServerSession, started: AppServerStartedThread, ) -> Result<()> { + let thread_id = started.session.thread_id; self.reset_thread_event_state(); let init = self.chatwidget_init_for_forked_or_resumed_thread(tui, self.config.clone()); self.replace_chat_widget(ChatWidget::new_with_app_event(init)); self.enqueue_primary_thread_session(started.session, started.turns) .await?; + if self.config.features.enabled(Feature::TimerScheduler) { + match app_server.thread_timer_list(thread_id).await { + Ok(timers) => self.chat_widget.on_thread_timers_updated(timers), + Err(err) => { + tracing::warn!(%err, "failed to load thread timers while attaching thread"); + } + } + } self.backfill_loaded_subagent_threads(app_server).await; Ok(()) } @@ -4216,6 +4246,87 @@ impl App { tui.frame_requester().schedule_frame(); } + AppEvent::OpenThreadTimers { thread_id } => { + match app_server.thread_timer_list(thread_id).await { + Ok(timers) => { + if self.chat_widget.thread_id() == Some(thread_id) { + self.chat_widget.open_thread_timers_popup(thread_id, timers); + } + } + Err(err) => { + if self.chat_widget.thread_id() == Some(thread_id) { + self.chat_widget + .add_error_message(format!("Failed to load thread timers: {err}")); + } + } + } + } + AppEvent::CreateThreadTimerFromSpec { thread_id, spec } => { + self.parse_thread_timer_spec(thread_id, spec); + } + AppEvent::ThreadTimerSpecParsed { + thread_id, + spec, + result, + } => match result { + Ok(parsed) => match app_server + .thread_timer_create( + thread_id, + parsed.trigger.clone(), + parsed.prompt.clone(), + parsed.delivery, + ) + .await + { + Ok(timer) => { + if self.chat_widget.thread_id() == Some(thread_id) { + let summary = + format_timer_summary(&timer.trigger, timer.delivery, &timer.prompt); + self.chat_widget.add_info_message( + format!("Created thread timer from `/loop {spec}`."), + Some(summary), + ); + } + } + Err(err) => { + if self.chat_widget.thread_id() == Some(thread_id) { + self.chat_widget + .add_error_message(format!("Failed to create thread timer: {err}")); + } + } + }, + Err(err) => { + if self.chat_widget.thread_id() == Some(thread_id) { + self.chat_widget + .add_error_message(format!("Failed to parse `/loop {spec}`: {err}")); + } + } + }, + AppEvent::DeleteThreadTimer { thread_id, id } => { + match app_server.thread_timer_delete(thread_id, id.clone()).await { + Ok(true) => { + if self.chat_widget.thread_id() == Some(thread_id) { + self.chat_widget.add_info_message( + format!("Deleted thread timer `{id}`."), + /*hint*/ None, + ); + } + } + Ok(false) => { + if self.chat_widget.thread_id() == Some(thread_id) { + self.chat_widget + .add_error_message(format!("No thread timer matched `{id}`.")); + } + } + Err(err) => { + if self.chat_widget.thread_id() == Some(thread_id) { + self.chat_widget.add_error_message(format!( + "Failed to delete thread timer `{id}`: {err}" + )); + } + } + } + } AppEvent::InsertHistoryCell(cell) => { let cell: Arc = cell.into(); if let Some(Overlay::Transcript(t)) = &mut self.overlay { @@ -7731,6 +7842,14 @@ mod tests { let codex_home = tempdir()?; app.config.codex_home = codex_home.path().to_path_buf(); let guardian_approvals = guardian_approvals_mode(); + app.config + .features + .set_enabled(Feature::GuardianApproval, /*enabled*/ false)?; + app.chat_widget + .set_feature_enabled(Feature::GuardianApproval, /*enabled*/ false); + app.config.approvals_reviewer = ApprovalsReviewer::User; + app.chat_widget + .set_approvals_reviewer(ApprovalsReviewer::User); app.update_feature_flags(vec![(Feature::GuardianApproval, true)]) .await; @@ -7818,9 +7937,7 @@ mod tests { let config_toml = "approvals_reviewer = \"guardian_subagent\"\napproval_policy = \"on-request\"\nsandbox_mode = \"workspace-write\"\n\n[features]\nguardian_approval = true\n"; std::fs::write(config_toml_path.as_path(), config_toml)?; let user_config = toml::from_str::(config_toml)?; - app.config.config_layer_stack = app - .config - .config_layer_stack + app.config.config_layer_stack = codex_core::config_loader::ConfigLayerStack::default() .with_user_config(&config_toml_path, user_config); app.config .features diff --git a/codex-rs/tui/src/app/app_server_adapter.rs b/codex-rs/tui/src/app/app_server_adapter.rs index 0bd78f353a..c0defe4086 100644 --- a/codex-rs/tui/src/app/app_server_adapter.rs +++ b/codex-rs/tui/src/app/app_server_adapter.rs @@ -329,6 +329,10 @@ fn server_notification_thread_target( ServerNotification::ThreadNameUpdated(notification) => { Some(notification.thread_id.as_str()) } + ServerNotification::ThreadTimerFired(notification) => Some(notification.thread_id.as_str()), + ServerNotification::ThreadTimerUpdated(notification) => { + Some(notification.thread_id.as_str()) + } ServerNotification::ThreadTokenUsageUpdated(notification) => { Some(notification.thread_id.as_str()) } diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index d727963f0d..68fd1bab4a 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -30,6 +30,7 @@ use crate::bottom_pane::ApprovalRequest; use crate::bottom_pane::StatusLineItem; use crate::bottom_pane::TerminalTitleItem; use crate::history_cell::HistoryCell; +use crate::timer_scheduler::ParsedTimerSpec; use codex_config::types::ApprovalsReviewer; use codex_features::Feature; @@ -108,6 +109,30 @@ pub(crate) enum AppEvent { /// Fork the current session into a new thread. ForkCurrentSession, + /// List timers for the specified thread and open the management UI. + OpenThreadTimers { + thread_id: ThreadId, + }, + + /// Parse a `/loop ` input into structured timer params. + CreateThreadTimerFromSpec { + thread_id: ThreadId, + spec: String, + }, + + /// Result of parsing a `/loop ` input. + ThreadTimerSpecParsed { + thread_id: ThreadId, + spec: String, + result: Result, + }, + + /// Delete one timer from the specified thread. + DeleteThreadTimer { + thread_id: ThreadId, + id: String, + }, + /// Request to exit the application. /// /// Use `ShutdownFirst` for user-initiated quits so core cleanup runs and the diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs index 9f3a4d83dd..03a726bfc0 100644 --- a/codex-rs/tui/src/app_server_session.rs +++ b/codex-rs/tui/src/app_server_session.rs @@ -55,8 +55,17 @@ use codex_app_server_protocol::ThreadShellCommandParams; use codex_app_server_protocol::ThreadShellCommandResponse; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; +use codex_app_server_protocol::ThreadTimer; +use codex_app_server_protocol::ThreadTimerCreateParams; +use codex_app_server_protocol::ThreadTimerCreateResponse; +use codex_app_server_protocol::ThreadTimerDeleteParams; +use codex_app_server_protocol::ThreadTimerDeleteResponse; +use codex_app_server_protocol::ThreadTimerListParams; +use codex_app_server_protocol::ThreadTimerListResponse; use codex_app_server_protocol::ThreadUnsubscribeParams; use codex_app_server_protocol::ThreadUnsubscribeResponse; +use codex_app_server_protocol::TimerDelivery; +use codex_app_server_protocol::TimerTrigger; use codex_app_server_protocol::Turn; use codex_app_server_protocol::TurnInterruptParams; use codex_app_server_protocol::TurnInterruptResponse; @@ -316,6 +325,28 @@ impl AppServerSession { started_thread_from_start_response(response, config).await } + pub(crate) async fn start_ephemeral_thread_with_base_instructions( + &mut self, + config: &Config, + base_instructions: String, + ) -> Result { + let request_id = self.next_request_id(); + let mut params = thread_start_params_from_config( + config, + self.thread_params_mode(), + self.remote_cwd_override.as_deref(), + ); + params.ephemeral = Some(true); + params.persist_extended_history = false; + params.base_instructions = Some(base_instructions); + let response: ThreadStartResponse = self + .client + .request_typed(ClientRequest::ThreadStart { request_id, params }) + .await + .wrap_err("thread/start failed during timer spec parsing")?; + started_thread_from_start_response(response, config).await + } + pub(crate) async fn resume_thread( &mut self, config: Config, @@ -414,6 +445,68 @@ impl AppServerSession { Ok(response.thread) } + pub(crate) async fn thread_timer_create( + &mut self, + thread_id: ThreadId, + trigger: TimerTrigger, + prompt: String, + delivery: TimerDelivery, + ) -> Result { + let request_id = self.next_request_id(); + let response: ThreadTimerCreateResponse = self + .client + .request_typed(ClientRequest::ThreadTimerCreate { + request_id, + params: ThreadTimerCreateParams { + thread_id: thread_id.to_string(), + trigger, + prompt, + delivery, + }, + }) + .await + .wrap_err("thread/timer/create failed in TUI")?; + Ok(response.timer) + } + + pub(crate) async fn thread_timer_delete( + &mut self, + thread_id: ThreadId, + id: String, + ) -> Result { + let request_id = self.next_request_id(); + let response: ThreadTimerDeleteResponse = self + .client + .request_typed(ClientRequest::ThreadTimerDelete { + request_id, + params: ThreadTimerDeleteParams { + thread_id: thread_id.to_string(), + id, + }, + }) + .await + .wrap_err("thread/timer/delete failed in TUI")?; + Ok(response.deleted) + } + + pub(crate) async fn thread_timer_list( + &mut self, + thread_id: ThreadId, + ) -> Result> { + let request_id = self.next_request_id(); + let response: ThreadTimerListResponse = self + .client + .request_typed(ClientRequest::ThreadTimerList { + request_id, + params: ThreadTimerListParams { + thread_id: thread_id.to_string(), + }, + }) + .await + .wrap_err("thread/timer/list failed in TUI")?; + Ok(response.data) + } + #[allow(clippy::too_many_arguments)] pub(crate) async fn turn_start( &mut self, diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 6cf6c18d32..03c39810fa 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -328,6 +328,7 @@ pub(crate) struct ChatComposer { collaboration_mode_indicator: Option, connectors_enabled: bool, plugins_command_enabled: bool, + timer_scheduler_command_enabled: bool, fast_command_enabled: bool, personality_command_enabled: bool, realtime_conversation_enabled: bool, @@ -368,6 +369,7 @@ impl ChatComposer { collaboration_modes_enabled: self.collaboration_modes_enabled, connectors_enabled: self.connectors_enabled, plugins_command_enabled: self.plugins_command_enabled, + timer_scheduler_command_enabled: self.timer_scheduler_command_enabled, fast_command_enabled: self.fast_command_enabled, personality_command_enabled: self.personality_command_enabled, realtime_conversation_enabled: self.realtime_conversation_enabled, @@ -450,6 +452,7 @@ impl ChatComposer { collaboration_mode_indicator: None, connectors_enabled: false, plugins_command_enabled: false, + timer_scheduler_command_enabled: false, fast_command_enabled: false, personality_command_enabled: false, realtime_conversation_enabled: false, @@ -489,6 +492,10 @@ impl ChatComposer { self.plugins_command_enabled = enabled; } + pub fn set_timer_scheduler_command_enabled(&mut self, enabled: bool) { + self.timer_scheduler_command_enabled = enabled; + } + /// Toggle composer-side image paste handling. /// /// This only affects whether image-like paste content is converted into attachments; the @@ -3065,6 +3072,7 @@ impl ChatComposer { let collaboration_modes_enabled = self.collaboration_modes_enabled; let connectors_enabled = self.connectors_enabled; let plugins_command_enabled = self.plugins_command_enabled; + let timer_scheduler_command_enabled = self.timer_scheduler_command_enabled; let fast_command_enabled = self.fast_command_enabled; let personality_command_enabled = self.personality_command_enabled; let realtime_conversation_enabled = self.realtime_conversation_enabled; @@ -3073,6 +3081,7 @@ impl ChatComposer { collaboration_modes_enabled, connectors_enabled, plugins_command_enabled, + timer_scheduler_command_enabled, fast_command_enabled, personality_command_enabled, realtime_conversation_enabled, diff --git a/codex-rs/tui/src/bottom_pane/command_popup.rs b/codex-rs/tui/src/bottom_pane/command_popup.rs index 8bef8ddbc8..01d02582f8 100644 --- a/codex-rs/tui/src/bottom_pane/command_popup.rs +++ b/codex-rs/tui/src/bottom_pane/command_popup.rs @@ -33,6 +33,7 @@ pub(crate) struct CommandPopupFlags { pub(crate) collaboration_modes_enabled: bool, pub(crate) connectors_enabled: bool, pub(crate) plugins_command_enabled: bool, + pub(crate) timer_scheduler_command_enabled: bool, pub(crate) fast_command_enabled: bool, pub(crate) personality_command_enabled: bool, pub(crate) realtime_conversation_enabled: bool, @@ -46,6 +47,7 @@ impl From for slash_commands::BuiltinCommandFlags { collaboration_modes_enabled: value.collaboration_modes_enabled, connectors_enabled: value.connectors_enabled, plugins_command_enabled: value.plugins_command_enabled, + timer_scheduler_command_enabled: value.timer_scheduler_command_enabled, fast_command_enabled: value.fast_command_enabled, personality_command_enabled: value.personality_command_enabled, realtime_conversation_enabled: value.realtime_conversation_enabled, @@ -355,6 +357,7 @@ mod tests { connectors_enabled: false, plugins_command_enabled: false, fast_command_enabled: false, + timer_scheduler_command_enabled: false, personality_command_enabled: true, realtime_conversation_enabled: false, audio_device_selection_enabled: false, @@ -375,6 +378,7 @@ mod tests { connectors_enabled: false, plugins_command_enabled: false, fast_command_enabled: false, + timer_scheduler_command_enabled: false, personality_command_enabled: true, realtime_conversation_enabled: false, audio_device_selection_enabled: false, @@ -395,6 +399,7 @@ mod tests { connectors_enabled: false, plugins_command_enabled: false, fast_command_enabled: false, + timer_scheduler_command_enabled: false, personality_command_enabled: false, realtime_conversation_enabled: false, audio_device_selection_enabled: false, @@ -422,6 +427,7 @@ mod tests { connectors_enabled: false, plugins_command_enabled: false, fast_command_enabled: false, + timer_scheduler_command_enabled: false, personality_command_enabled: true, realtime_conversation_enabled: false, audio_device_selection_enabled: false, @@ -442,6 +448,7 @@ mod tests { connectors_enabled: false, plugins_command_enabled: false, fast_command_enabled: false, + timer_scheduler_command_enabled: false, personality_command_enabled: true, realtime_conversation_enabled: true, audio_device_selection_enabled: false, diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index cbb698e3a2..bd2eac90c2 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -272,6 +272,11 @@ impl BottomPane { self.request_redraw(); } + pub fn set_timer_scheduler_command_enabled(&mut self, enabled: bool) { + self.composer.set_timer_scheduler_command_enabled(enabled); + self.request_redraw(); + } + pub fn take_mention_bindings(&mut self) -> Vec { self.composer.take_mention_bindings() } diff --git a/codex-rs/tui/src/bottom_pane/slash_commands.rs b/codex-rs/tui/src/bottom_pane/slash_commands.rs index 54b1a8cf4e..70f5652aba 100644 --- a/codex-rs/tui/src/bottom_pane/slash_commands.rs +++ b/codex-rs/tui/src/bottom_pane/slash_commands.rs @@ -15,6 +15,7 @@ pub(crate) struct BuiltinCommandFlags { pub(crate) collaboration_modes_enabled: bool, pub(crate) connectors_enabled: bool, pub(crate) plugins_command_enabled: bool, + pub(crate) timer_scheduler_command_enabled: bool, pub(crate) fast_command_enabled: bool, pub(crate) personality_command_enabled: bool, pub(crate) realtime_conversation_enabled: bool, @@ -33,6 +34,7 @@ pub(crate) fn builtins_for_input(flags: BuiltinCommandFlags) -> Vec<(&'static st }) .filter(|(_, cmd)| flags.connectors_enabled || *cmd != SlashCommand::Apps) .filter(|(_, cmd)| flags.plugins_command_enabled || *cmd != SlashCommand::Plugins) + .filter(|(_, cmd)| flags.timer_scheduler_command_enabled || *cmd != SlashCommand::Loop) .filter(|(_, cmd)| flags.fast_command_enabled || *cmd != SlashCommand::Fast) .filter(|(_, cmd)| flags.personality_command_enabled || *cmd != SlashCommand::Personality) .filter(|(_, cmd)| flags.realtime_conversation_enabled || *cmd != SlashCommand::Realtime) @@ -66,6 +68,7 @@ mod tests { collaboration_modes_enabled: true, connectors_enabled: true, plugins_command_enabled: true, + timer_scheduler_command_enabled: true, fast_command_enabled: true, personality_command_enabled: true, realtime_conversation_enabled: true, diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 040adc5a8f..2b698201ce 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -66,6 +66,8 @@ use crate::terminal_title::SetTerminalTitleResult; use crate::terminal_title::clear_terminal_title; use crate::terminal_title::set_terminal_title; use crate::text_formatting::proper_join; +use crate::timer_scheduler::format_timer_trigger; +use crate::timer_scheduler::trigger_is_recurring; use crate::version::CODEX_CLI_VERSION; use codex_app_server_protocol::AppSummary; use codex_app_server_protocol::CodexErrorInfo as AppServerCodexErrorInfo; @@ -348,6 +350,7 @@ use crate::status_indicator_widget::STATUS_DETAILS_DEFAULT_MAX_LINES; use crate::status_indicator_widget::StatusDetailsCapitalization; use crate::text_formatting::truncate_text; use crate::tui::FrameRequester; +use codex_app_server_protocol::ThreadTimer; mod interrupts; use self::interrupts::InterruptManager; mod session_header; @@ -843,6 +846,7 @@ pub(crate) struct ChatWidget { thread_id: Option, thread_name: Option, forked_from: Option, + thread_timers: Vec, frame_requester: FrameRequester, // Whether to include the initial welcome banner on session configured show_welcome_banner: bool, @@ -1072,6 +1076,71 @@ impl From<&str> for UserMessage { } } +#[derive(Debug, Clone, PartialEq, Eq)] +struct TimerFiredUserMessage { + prompt: String, + trigger: Option, + delivery: Option, + recurring: bool, +} + +impl TimerFiredUserMessage { + fn schedule(&self) -> String { + let mut parts = vec!["Running thread timer".to_string()]; + if let Some(trigger) = self + .trigger + .as_deref() + .filter(|trigger| !trigger.is_empty()) + { + parts.push(trigger.to_string()); + } + if !self.recurring { + parts.push("one-shot".to_string()); + } + if let Some(delivery) = self + .delivery + .as_deref() + .filter(|delivery| !delivery.is_empty()) + { + parts.push(delivery.to_string()); + } + parts.join(" • ") + } +} + +fn parse_timer_fired_user_message(message: &str) -> Option { + let trimmed = message.trim(); + if !trimmed.starts_with("") || !trimmed.ends_with("") { + return None; + } + + let prompt = extract_timer_fired_tag(trimmed, "prompt") + .unwrap_or_default() + .trim_matches('\n') + .to_string(); + let trigger = extract_timer_fired_tag(trimmed, "trigger").map(|text| text.trim().to_string()); + let delivery = extract_timer_fired_tag(trimmed, "delivery").map(|text| text.trim().to_string()); + let recurring = extract_timer_fired_tag(trimmed, "recurring") + .as_deref() + .map(str::trim) + == Some("true"); + + Some(TimerFiredUserMessage { + prompt, + trigger, + delivery, + recurring, + }) +} + +fn extract_timer_fired_tag(message: &str, tag: &str) -> Option { + let open = format!("<{tag}>"); + let close = format!(""); + let after_open = message.split_once(&open)?.1; + let value = after_open.split_once(&close)?.0; + Some(value.to_string()) +} + struct PendingSteer { user_message: UserMessage, compare_key: PendingSteerCompareKey, @@ -1939,6 +2008,7 @@ impl ChatWidget { self.thread_id = Some(event.session_id); self.thread_name = event.thread_name.clone(); self.forked_from = event.forked_from_id; + self.thread_timers.clear(); self.current_rollout_path = event.rollout_path.clone(); self.current_cwd = Some(event.cwd.clone()); match AbsolutePathBuf::try_from(event.cwd.clone()) { @@ -1986,6 +2056,7 @@ impl ChatWidget { self.refresh_model_display(); self.refresh_status_surfaces(); self.sync_fast_command_enabled(); + self.sync_timer_scheduler_command_enabled(); self.sync_personality_command_enabled(); self.sync_plugins_command_enabled(); self.refresh_plugin_mentions(); @@ -2380,6 +2451,9 @@ impl ChatWidget { if self.has_queued_follow_up_messages() { return; } + if !self.thread_timers.is_empty() { + return; + } if self.active_mode_kind() != ModeKind::Plan { return; } @@ -4674,6 +4748,7 @@ impl ChatWidget { thread_id: None, thread_name: None, forked_from: None, + thread_timers: Vec::new(), queued_user_messages: VecDeque::new(), rejected_steers_queue: VecDeque::new(), pending_steers: VecDeque::new(), @@ -4731,6 +4806,7 @@ impl ChatWidget { .bottom_pane .set_collaboration_modes_enabled(/*enabled*/ true); widget.sync_fast_command_enabled(); + widget.sync_timer_scheduler_command_enabled(); widget.sync_personality_command_enabled(); widget.sync_plugins_command_enabled(); widget @@ -5049,6 +5125,14 @@ impl ChatWidget { SlashCommand::Review => { self.open_review_popup(); } + SlashCommand::Loop => { + let Some(thread_id) = self.thread_id else { + self.add_error_message("No active thread is available.".to_string()); + return; + }; + self.app_event_tx + .send(AppEvent::OpenThreadTimers { thread_id }); + } SlashCommand::Rename => { self.session_telemetry .counter("codex.thread.rename", /*inc*/ 1, &[]); @@ -5450,6 +5534,27 @@ impl ChatWidget { })); self.bottom_pane.drain_pending_submission_state(); } + SlashCommand::Loop if !trimmed.is_empty() => { + let Some(thread_id) = self.thread_id else { + self.add_error_message("No active thread is available.".to_string()); + return; + }; + let Some((prepared_args, _prepared_elements)) = self + .bottom_pane + .prepare_inline_args_submission(/*record_history*/ false) + else { + return; + }; + self.add_info_message( + format!("Scheduling `/loop {prepared_args}`..."), + Some("Parsing the spec and creating the thread timer.".to_string()), + ); + self.app_event_tx.send(AppEvent::CreateThreadTimerFromSpec { + thread_id, + spec: prepared_args, + }); + self.bottom_pane.drain_pending_submission_state(); + } SlashCommand::SandboxReadRoot if !trimmed.is_empty() => { let Some((prepared_args, _prepared_elements)) = self .bottom_pane @@ -6316,6 +6421,12 @@ impl ChatWidget { } } } + ServerNotification::ThreadTimerUpdated(notification) => { + self.on_thread_timers_updated(notification.timers); + } + ServerNotification::ThreadTimerFired(notification) => { + self.on_thread_timer_fired(notification.timer); + } ServerNotification::TurnStarted(_) => { self.last_non_retry_error = None; if !matches!(replay_kind, Some(ReplayKind::ResumeInitialMessages)) { @@ -7153,6 +7264,16 @@ impl ChatWidget { fn on_user_message_event(&mut self, event: UserMessageEvent) { self.last_rendered_user_message_event = Some(Self::rendered_user_message_event_from_event(&event)); + if event.images.as_ref().is_none_or(Vec::is_empty) + && event.local_images.is_empty() + && event.text_elements.is_empty() + && let Some(timer) = parse_timer_fired_user_message(&event.message) + { + let schedule = timer.schedule(); + self.add_info_message(timer.prompt, Some(schedule)); + self.needs_final_message_separator = false; + return; + } let remote_image_urls = event.images.unwrap_or_default(); if !event.message.trim().is_empty() || !event.text_elements.is_empty() @@ -9344,6 +9465,9 @@ impl ChatWidget { if feature == Feature::FastMode { self.sync_fast_command_enabled(); } + if feature == Feature::TimerScheduler { + self.sync_timer_scheduler_command_enabled(); + } if feature == Feature::Personality { self.sync_personality_command_enabled(); } @@ -9584,6 +9708,12 @@ impl ChatWidget { .set_fast_command_enabled(self.fast_mode_enabled()); } + fn sync_timer_scheduler_command_enabled(&mut self) { + self.bottom_pane.set_timer_scheduler_command_enabled( + self.config.features.enabled(Feature::TimerScheduler), + ); + } + fn sync_personality_command_enabled(&mut self) { self.bottom_pane .set_personality_command_enabled(self.config.features.enabled(Feature::Personality)); @@ -9905,6 +10035,70 @@ impl ChatWidget { self.request_redraw(); } + pub(crate) fn on_thread_timers_updated(&mut self, timers: Vec) { + self.thread_timers = timers; + } + + pub(crate) fn on_thread_timer_fired(&mut self, timer: ThreadTimer) { + // The transcript row is rendered from the visible user + // message, so the fire notification only needs to refresh the viewport. + let _ = timer; + self.request_redraw(); + } + + pub(crate) fn open_thread_timers_popup( + &mut self, + thread_id: ThreadId, + timers: Vec, + ) { + self.thread_timers = timers.clone(); + if timers.is_empty() { + self.add_info_message( + "No thread timers are currently scheduled.".to_string(), + Some("Use `/loop ` to create one.".to_string()), + ); + return; + } + + let items = timers + .into_iter() + .map(|timer| { + let timer_id = timer.id.clone(); + let actions: Vec = vec![Box::new(move |tx| { + tx.send(AppEvent::DeleteThreadTimer { + thread_id, + id: timer_id.clone(), + }); + })]; + let trigger = format_timer_trigger(&timer.trigger); + let name = if trigger_is_recurring(&timer.trigger) { + trigger + } else { + format!("{trigger} • one-shot") + }; + let selected_description = + format!("{}\n\nPress Enter to delete this timer.", timer.prompt); + SelectionItem { + name, + description: Some(timer.prompt), + selected_description: Some(selected_description), + is_current: false, + actions, + dismiss_on_select: true, + ..Default::default() + } + }) + .collect(); + self.bottom_pane.show_selection_view(SelectionViewParams { + title: Some("Thread timers".to_string()), + subtitle: Some("Review an timer, then press Enter to delete it.".to_string()), + footer_hint: Some(standard_popup_hint_line()), + items, + ..Default::default() + }); + self.request_redraw(); + } + pub(crate) fn add_plain_history_lines(&mut self, lines: Vec>) { self.add_boxed_history(Box::new(PlainHistoryCell::new(lines))); self.request_redraw(); diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 4156082cbb..37feec5095 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -259,6 +259,7 @@ mod review_mode; mod slash_commands; mod status_and_layout; mod status_command_tests; +mod timers; pub(crate) use helpers::make_chatwidget_manual_with_sender; pub(crate) use helpers::set_chatgpt_auth; diff --git a/codex-rs/tui/src/chatwidget/tests/helpers.rs b/codex-rs/tui/src/chatwidget/tests/helpers.rs index 46a4129a45..ce823ab893 100644 --- a/codex-rs/tui/src/chatwidget/tests/helpers.rs +++ b/codex-rs/tui/src/chatwidget/tests/helpers.rs @@ -242,6 +242,7 @@ pub(super) async fn make_chatwidget_manual( pending_status_indicator_restore: false, suppress_queue_autosend: false, thread_id: None, + thread_timers: Vec::new(), thread_name: None, forked_from: None, frame_requester: FrameRequester::test_dummy(), diff --git a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__timers__thread_timers_popup_keeps_selected_timer_prompt_visible.snap b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__timers__thread_timers_popup_keeps_selected_timer_prompt_visible.snap new file mode 100644 index 0000000000..7242eabe6f --- /dev/null +++ b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__timers__thread_timers_popup_keeps_selected_timer_prompt_visible.snap @@ -0,0 +1,11 @@ +--- +source: tui/src/chatwidget/tests/timers.rs +expression: popup +--- + Thread timers + Review an timer, then press Enter to delete it. + +› 1. delay 0s • one-shot Give me a random animal name. + Press Enter to delete this timer. + + Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__timers__thread_timers_popup_renders_schedule_triggers_readably.snap b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__timers__thread_timers_popup_renders_schedule_triggers_readably.snap new file mode 100644 index 0000000000..41818a38ef --- /dev/null +++ b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__timers__thread_timers_popup_renders_schedule_triggers_readably.snap @@ -0,0 +1,12 @@ +--- +source: tui/src/chatwidget/tests/timers.rs +expression: popup +--- + Thread timers + Review an timer, then press Enter to delete it. + +› 1. at Apr 7, 2026 10:57 AM • one-shot tell me to take a piss + Press Enter to delete this timer. + 2. weekdays at 5:00 PM wrap up for the day + + Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/tests/timers.rs b/codex-rs/tui/src/chatwidget/tests/timers.rs new file mode 100644 index 0000000000..3894f36241 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/tests/timers.rs @@ -0,0 +1,112 @@ +use super::*; +use codex_app_server_protocol::ThreadTimer; +use codex_app_server_protocol::TimerDelivery; +use codex_app_server_protocol::TimerTrigger; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::UserMessageEvent; +use insta::assert_snapshot; + +#[tokio::test] +async fn thread_timer_fired_renders_prompt_history() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + + chat.handle_codex_event_replay(Event { + id: "event-1".to_string(), + msg: EventMsg::UserMessage(UserMessageEvent { + message: " +timer-1 +delay 0s +after-turn +false + +Give me a random animal name. + + +This one-shot timer has already been removed from the schedule, so you do not need to call TimerDelete. +Do not expose scheduler internals unless they matter to the user. + + +" + .to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }), + }); + + let cells = drain_insert_history(&mut rx); + let rendered = lines_to_single_string(&cells[0]); + assert_snapshot!(rendered, @"• Give me a random animal name. Running thread timer • delay 0s • one-shot • after-turn +"); +} + +#[tokio::test] +async fn thread_timers_popup_keeps_selected_timer_prompt_visible() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + + chat.open_thread_timers_popup( + ThreadId::new(), + vec![ThreadTimer { + id: "timer-1".to_string(), + trigger: TimerTrigger::Delay { + seconds: 0, + repeat: None, + }, + prompt: "Give me a random animal name.".to_string(), + delivery: TimerDelivery::AfterTurn, + created_at: 0, + next_run_at: None, + last_run_at: None, + }], + ); + + let popup = render_bottom_popup(&chat, /*width*/ 80); + assert_snapshot!( + "thread_timers_popup_keeps_selected_timer_prompt_visible", + popup + ); +} + +#[tokio::test] +async fn thread_timers_popup_renders_schedule_triggers_readably() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + + chat.open_thread_timers_popup( + ThreadId::new(), + vec![ + ThreadTimer { + id: "timer-1".to_string(), + trigger: TimerTrigger::Schedule { + dtstart: Some("2026-04-07T10:57:00".to_string()), + rrule: None, + }, + prompt: "tell me to take a piss".to_string(), + delivery: TimerDelivery::AfterTurn, + created_at: 0, + next_run_at: None, + last_run_at: None, + }, + ThreadTimer { + id: "timer-2".to_string(), + trigger: TimerTrigger::Schedule { + dtstart: Some("2026-04-07T17:00:00".to_string()), + rrule: Some( + "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR;BYHOUR=17;BYMINUTE=0;BYSECOND=0" + .to_string(), + ), + }, + prompt: "wrap up for the day".to_string(), + delivery: TimerDelivery::AfterTurn, + created_at: 0, + next_run_at: None, + last_run_at: None, + }, + ], + ); + + let popup = render_bottom_popup(&chat, /*width*/ 80); + assert_snapshot!( + "thread_timers_popup_renders_schedule_triggers_readably", + popup + ); +} diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 7cd4c64949..f91477a475 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -103,6 +103,7 @@ mod clipboard_text; mod collaboration_modes; mod color; pub(crate) mod custom_terminal; +mod timer_scheduler; pub use custom_terminal::Terminal; mod cwd_prompt; mod debug_config; diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rs index 53f33bfb0e..a0a0456061 100644 --- a/codex-rs/tui/src/resume_picker.rs +++ b/codex-rs/tui/src/resume_picker.rs @@ -252,14 +252,7 @@ async fn run_session_picker_with_loader( ProviderFilter::MatchDefault(config.model_provider_id.to_string()) }; let codex_home = config.codex_home.as_path(); - let filter_cwd = if show_all || is_remote { - // Remote sessions live in the server's filesystem namespace, so the client - // process cwd is not a meaningful row filter. If the user provided an - // explicit remote --cd, filtering is handled server-side in thread/list. - None - } else { - std::env::current_dir().ok() - }; + let filter_cwd = picker_filter_cwd(config, show_all, is_remote); let mut state = PickerState::new( codex_home.to_path_buf(), @@ -1147,6 +1140,17 @@ fn thread_list_params( } } +fn picker_filter_cwd(config: &Config, show_all: bool, is_remote: bool) -> Option { + if show_all || is_remote { + // Remote sessions live in the server's filesystem namespace, so the client + // process cwd is not a meaningful row filter. If the user provided an + // explicit remote --cd, filtering is handled server-side in thread/list. + None + } else { + Some(config.cwd.to_path_buf()) + } +} + fn paths_match(a: &Path, b: &Path) -> bool { if let (Ok(ca), Ok(cb)) = ( path_utils::normalize_for_path_comparison(a), @@ -1645,6 +1649,7 @@ fn column_visibility( mod tests { use super::*; use chrono::Duration; + use codex_core::config::ConfigBuilder; use codex_protocol::ThreadId; use crossterm::event::KeyCode; @@ -1689,6 +1694,15 @@ mod tests { }) } + async fn build_config(temp_dir: &tempfile::TempDir, cwd: &Path) -> Config { + ConfigBuilder::default() + .codex_home(temp_dir.path().to_path_buf()) + .fallback_cwd(Some(cwd.to_path_buf())) + .build() + .await + .expect("config should build") + } + #[allow(dead_code)] fn set_rollout_mtime(path: &Path, updated_at: DateTime) { let times = FileTimes::new().set_modified(updated_at.into()); @@ -1896,6 +1910,32 @@ mod tests { assert_eq!(params.source_kinds, None); } + #[tokio::test] + async fn local_picker_filter_uses_config_cwd() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let config = build_config(&temp_dir, Path::new("/tmp/config-cwd")).await; + + assert_eq!( + picker_filter_cwd(&config, /*show_all*/ false, /*is_remote*/ false), + Some(config.cwd.to_path_buf()) + ); + } + + #[tokio::test] + async fn picker_filter_cwd_is_disabled_for_show_all_and_remote() { + let temp_dir = tempfile::tempdir().expect("tempdir"); + let config = build_config(&temp_dir, Path::new("/tmp/config-cwd")).await; + + assert_eq!( + picker_filter_cwd(&config, /*show_all*/ true, /*is_remote*/ false), + None + ); + assert_eq!( + picker_filter_cwd(&config, /*show_all*/ false, /*is_remote*/ true), + None + ); + } + #[test] fn remote_picker_does_not_filter_rows_by_local_cwd() { let loader: PageLoader = Arc::new(|_| {}); diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index ec624d3fb9..3864aca103 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -23,6 +23,7 @@ pub enum SlashCommand { Experimental, Skills, Review, + Loop, Rename, New, Resume, @@ -75,6 +76,7 @@ impl SlashCommand { SlashCommand::Init => "create an AGENTS.md file with instructions for Codex", SlashCommand::Compact => "summarize conversation to prevent hitting the context limit", SlashCommand::Review => "review my current changes and find issues", + SlashCommand::Loop => "create or list thread timers", SlashCommand::Rename => "rename the current thread", SlashCommand::Resume => "resume a saved chat", SlashCommand::Clear => "clear the terminal and start a new chat", @@ -130,6 +132,7 @@ impl SlashCommand { self, SlashCommand::Review | SlashCommand::Rename + | SlashCommand::Loop | SlashCommand::Plan | SlashCommand::Fast | SlashCommand::SandboxReadRoot @@ -162,6 +165,7 @@ impl SlashCommand { SlashCommand::Diff | SlashCommand::Copy | SlashCommand::Rename + | SlashCommand::Loop | SlashCommand::Mention | SlashCommand::Skills | SlashCommand::Status diff --git a/codex-rs/tui/src/timer_scheduler.rs b/codex-rs/tui/src/timer_scheduler.rs new file mode 100644 index 0000000000..251d2b9a07 --- /dev/null +++ b/codex-rs/tui/src/timer_scheduler.rs @@ -0,0 +1,595 @@ +use crate::AppServerTarget; +use crate::start_app_server_for_picker; +use chrono::Datelike; +use chrono::NaiveDateTime; +use chrono::Timelike; +use codex_app_server_client::AppServerEvent; +use codex_app_server_protocol::ServerNotification; +use codex_app_server_protocol::ThreadItem; +use codex_app_server_protocol::TimerDelivery; +use codex_app_server_protocol::TimerTrigger; +use codex_app_server_protocol::TurnStatus; +use codex_core::config::Config; +use codex_protocol::models::ContentItem; +use codex_protocol::models::ResponseItem; +use codex_protocol::user_input::UserInput; +use serde::Deserialize; +use serde_json::Value; +use serde_json::json; +use std::time::Duration; + +const LOCAL_DATE_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S"; +const MONTH_NAMES: [&str; 12] = [ + "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", +]; + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub(crate) struct ParsedTimerSpec { + pub(crate) trigger: TimerTrigger, + pub(crate) prompt: String, + pub(crate) delivery: TimerDelivery, +} + +pub(crate) async fn parse_timer_spec( + config: Config, + target: AppServerTarget, + spec: String, +) -> std::result::Result { + if spec.trim().is_empty() { + return Err("Could not determine a prompt from /loop input.".to_string()); + } + let user_prompt = build_user_prompt(&spec); + let mut app_server = start_app_server_for_picker(&config, &target) + .await + .map_err(|err| format!("failed to start timer spec parser: {err}"))?; + let started = app_server + .start_ephemeral_thread_with_base_instructions( + &config, + PARSE_TIMER_SYSTEM_PROMPT.to_string(), + ) + .await + .map_err(|err| format!("failed to start timer spec parser thread: {err}"))?; + let thread_id = started.session.thread_id; + let thread_id_string = thread_id.to_string(); + let response = app_server + .turn_start( + thread_id, + vec![UserInput::Text { + text: user_prompt, + text_elements: Vec::new(), + }], + started.session.cwd, + started.session.approval_policy, + started.session.approvals_reviewer, + started.session.sandbox_policy, + started.session.model, + started.session.reasoning_effort, + config.model_reasoning_summary, + Some(config.service_tier), + /*collaboration_mode*/ None, + config.personality, + Some(output_schema()), + ) + .await + .map_err(|err| format!("failed to parse timer spec with model: {err}"))?; + let turn_id = response.turn.id; + let result = wait_for_parser_response(&mut app_server, thread_id_string, turn_id).await?; + let parsed: ParsedTimerSpec = serde_json::from_str(&result) + .map_err(|err| format!("model returned invalid timer parse output: {err}"))?; + validate_parsed_timer_spec(parsed) +} + +pub(crate) fn format_timer_summary( + trigger: &TimerTrigger, + delivery: TimerDelivery, + prompt: &str, +) -> String { + let mode = if trigger_is_recurring(trigger) { + "recurring" + } else { + "one-shot" + }; + format!( + "{} ({mode}, {}) -> {prompt}", + format_timer_trigger(trigger), + delivery_str(delivery) + ) +} + +pub(crate) fn format_timer_trigger(trigger: &TimerTrigger) -> String { + match trigger { + TimerTrigger::Delay { seconds, repeat } => { + let suffix = if repeat.unwrap_or(false) { + ", repeat" + } else { + "" + }; + format!("delay {seconds}s{suffix}") + } + TimerTrigger::Schedule { dtstart, rrule } => match (dtstart, rrule) { + (Some(dtstart), Some(rrule)) => format_timer_rrule(rrule, Some(dtstart)) + .unwrap_or_else(|| { + format!("schedule from {}; {rrule}", format_timer_dtstart(dtstart)) + }), + (Some(dtstart), None) => format!("at {}", format_timer_dtstart(dtstart)), + (None, Some(rrule)) => { + format_timer_rrule(rrule, /*dtstart*/ None) + .unwrap_or_else(|| format!("schedule {rrule}")) + } + (None, None) => "invalid schedule".to_string(), + }, + } +} + +fn format_timer_dtstart(dtstart: &str) -> String { + let Ok(dtstart) = NaiveDateTime::parse_from_str(dtstart, LOCAL_DATE_TIME_FORMAT) else { + return dtstart.to_string(); + }; + let month_name = MONTH_NAMES + .get(dtstart.month0() as usize) + .copied() + .unwrap_or("???"); + format!( + "{} {}, {} {}", + month_name, + dtstart.day(), + dtstart.year(), + format_timer_time(dtstart) + ) +} + +fn format_timer_time(dtstart: NaiveDateTime) -> String { + let hour = dtstart.hour(); + let period = if hour < 12 { "AM" } else { "PM" }; + let hour = match hour % 12 { + 0 => 12, + hour => hour, + }; + if dtstart.second() == 0 { + format!("{hour}:{:02} {period}", dtstart.minute()) + } else { + format!( + "{hour}:{:02}:{:02} {period}", + dtstart.minute(), + dtstart.second() + ) + } +} + +fn format_timer_rrule(rrule: &str, dtstart: Option<&str>) -> Option { + let freq = rrule_part(rrule, "FREQ")?; + let interval = rrule_part(rrule, "INTERVAL") + .and_then(|value| value.parse::().ok()) + .unwrap_or(1); + let byday = rrule_part(rrule, "BYDAY"); + let byhour = rrule_part(rrule, "BYHOUR").and_then(|value| value.parse::().ok()); + let byminute = rrule_part(rrule, "BYMINUTE") + .and_then(|value| value.parse::().ok()) + .unwrap_or(0); + let bysecond = rrule_part(rrule, "BYSECOND") + .and_then(|value| value.parse::().ok()) + .unwrap_or(0); + let time = format_timer_rrule_time(byhour, byminute, bysecond, dtstart); + + match freq { + "HOURLY" => { + let cadence = if interval == 1 { + "hourly".to_string() + } else { + format!("every {interval} hours") + }; + if byminute == 0 && bysecond == 0 { + Some(format!("{cadence} on the hour")) + } else { + Some(format!("{cadence} at :{byminute:02}")) + } + } + "DAILY" => { + let cadence = if interval == 1 { + "daily".to_string() + } else { + format!("every {interval} days") + }; + Some(match time { + Some(time) => format!("{cadence} at {time}"), + None => cadence, + }) + } + "WEEKLY" => { + let cadence = byday.and_then(format_timer_rrule_days).unwrap_or_else(|| { + if interval == 1 { + "weekly".to_string() + } else { + format!("every {interval} weeks") + } + }); + Some(match time { + Some(time) => format!("{cadence} at {time}"), + None => cadence, + }) + } + _ => None, + } +} + +fn rrule_part<'a>(rrule: &'a str, key: &str) -> Option<&'a str> { + rrule.split(';').find_map(|part| { + part.split_once('=').and_then(|(part_key, value)| { + (part_key.eq_ignore_ascii_case(key) && !value.is_empty()).then_some(value) + }) + }) +} + +fn format_timer_rrule_days(byday: &str) -> Option { + if byday == "MO,TU,WE,TH,FR" { + return Some("weekdays".to_string()); + } + if byday == "SA,SU" { + return Some("weekends".to_string()); + } + let days = byday + .split(',') + .filter_map(format_timer_rrule_day) + .collect::>() + .join(", "); + (!days.is_empty()).then_some(days) +} + +fn format_timer_rrule_day(day: &str) -> Option<&'static str> { + match day { + "MO" => Some("Mondays"), + "TU" => Some("Tuesdays"), + "WE" => Some("Wednesdays"), + "TH" => Some("Thursdays"), + "FR" => Some("Fridays"), + "SA" => Some("Saturdays"), + "SU" => Some("Sundays"), + _ => None, + } +} + +fn format_timer_rrule_time( + byhour: Option, + byminute: u32, + bysecond: u32, + dtstart: Option<&str>, +) -> Option { + let dtstart = byhour.is_none().then_some(dtstart).flatten(); + let hour = match byhour { + Some(hour) => hour, + None => { + let dtstart = dtstart?; + let dtstart = NaiveDateTime::parse_from_str(dtstart, LOCAL_DATE_TIME_FORMAT).ok()?; + dtstart.hour() + } + }; + if hour > 23 || byminute > 59 || bysecond > 59 { + return None; + } + let dtstart = NaiveDateTime::parse_from_str( + &format!("2000-01-01T{hour:02}:{byminute:02}:{bysecond:02}"), + LOCAL_DATE_TIME_FORMAT, + ) + .ok()?; + Some(format_timer_time(dtstart)) +} + +pub(crate) fn trigger_is_recurring(trigger: &TimerTrigger) -> bool { + match trigger { + TimerTrigger::Delay { repeat, .. } => repeat.unwrap_or(false), + TimerTrigger::Schedule { rrule, .. } => { + rrule.as_ref().is_some_and(|rrule| !rrule.is_empty()) + } + } +} + +fn delivery_str(delivery: TimerDelivery) -> &'static str { + match delivery { + TimerDelivery::AfterTurn => "after-turn", + TimerDelivery::SteerCurrentTurn => "steer-current-turn", + } +} + +fn build_user_prompt(spec: &str) -> String { + let now = chrono::Local::now().format("%Y-%m-%dT%H:%M:%S"); + let timezone = chrono::Local::now().offset().to_string(); + format!("Current local datetime: {now}\nTimezone: {timezone}\nTimer spec: {spec}") +} + +async fn wait_for_parser_response( + app_server: &mut crate::app_server_session::AppServerSession, + thread_id: String, + turn_id: String, +) -> std::result::Result { + let mut last_agent_message = None; + loop { + let event = + tokio::time::timeout(Duration::from_secs(/*secs*/ 120), app_server.next_event()) + .await + .map_err(|_| "timed out while waiting for timer spec parser".to_string())? + .ok_or_else(|| { + "timer spec parser disconnected before returning output".to_string() + })?; + match event { + AppServerEvent::ServerNotification(ServerNotification::ItemCompleted(notification)) + if notification.thread_id == thread_id && notification.turn_id == turn_id => + { + if let Some(text) = thread_item_agent_text(¬ification.item) { + last_agent_message = Some(text); + } + } + AppServerEvent::ServerNotification(ServerNotification::RawResponseItemCompleted( + notification, + )) if notification.thread_id == thread_id && notification.turn_id == turn_id => { + if let Some(text) = response_item_agent_text(¬ification.item) { + last_agent_message = Some(text); + } + } + AppServerEvent::ServerNotification(ServerNotification::TurnCompleted(notification)) + if notification.thread_id == thread_id && notification.turn.id == turn_id => + { + if matches!(notification.turn.status, TurnStatus::Failed) + && let Some(error) = notification.turn.error + { + return Err(format!("timer spec parser failed: {}", error.message)); + } + return last_agent_message.ok_or_else(|| { + "timer spec parser did not return an agent message".to_string() + }); + } + AppServerEvent::ServerNotification(_) | AppServerEvent::Lagged { .. } => {} + AppServerEvent::ServerRequest(_) => { + return Err("timer spec parser unexpectedly requested user input".to_string()); + } + AppServerEvent::Disconnected { message } => { + return Err(format!("timer spec parser disconnected: {message}")); + } + } + } +} + +fn thread_item_agent_text(item: &ThreadItem) -> Option { + match item { + ThreadItem::AgentMessage { text, .. } if !text.trim().is_empty() => Some(text.clone()), + ThreadItem::AgentMessage { .. } + | ThreadItem::UserMessage { .. } + | ThreadItem::Reasoning { .. } + | ThreadItem::Plan { .. } + | ThreadItem::McpToolCall { .. } + | ThreadItem::WebSearch { .. } + | ThreadItem::DynamicToolCall { .. } + | ThreadItem::CommandExecution { .. } + | ThreadItem::FileChange { .. } + | ThreadItem::ImageView { .. } + | ThreadItem::ImageGeneration { .. } + | ThreadItem::HookPrompt { .. } + | ThreadItem::CollabAgentToolCall { .. } + | ThreadItem::EnteredReviewMode { .. } + | ThreadItem::ExitedReviewMode { .. } + | ThreadItem::ContextCompaction { .. } => None, + } +} + +fn response_item_agent_text(item: &ResponseItem) -> Option { + match item { + ResponseItem::Message { role, content, .. } if role == "assistant" => { + let text = content + .iter() + .filter_map(|content| match content { + ContentItem::OutputText { text } => Some(text.as_str()), + ContentItem::InputText { .. } | ContentItem::InputImage { .. } => None, + }) + .collect::(); + (!text.trim().is_empty()).then_some(text) + } + ResponseItem::Message { .. } + | ResponseItem::Reasoning { .. } + | ResponseItem::LocalShellCall { .. } + | ResponseItem::FunctionCall { .. } + | ResponseItem::ToolSearchCall { .. } + | ResponseItem::FunctionCallOutput { .. } + | ResponseItem::CustomToolCall { .. } + | ResponseItem::CustomToolCallOutput { .. } + | ResponseItem::WebSearchCall { .. } + | ResponseItem::ImageGenerationCall { .. } + | ResponseItem::ToolSearchOutput { .. } + | ResponseItem::GhostSnapshot { .. } + | ResponseItem::Compaction { .. } + | ResponseItem::Other => None, + } +} + +fn validate_parsed_timer_spec( + parsed: ParsedTimerSpec, +) -> std::result::Result { + if parsed.prompt.trim().is_empty() { + return Err("model did not return an timer prompt".to_string()); + } + Ok(ParsedTimerSpec { + prompt: parsed.prompt.trim().to_string(), + ..parsed + }) +} + +fn output_schema() -> Value { + json!({ + "type": "object", + "properties": { + "trigger": { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["delay", "schedule"] }, + "seconds": { "type": ["integer", "null"], "minimum": 0 }, + "repeat": { "type": ["boolean", "null"] }, + "dtstart": { "type": ["string", "null"] }, + "rrule": { "type": ["string", "null"] } + }, + "required": ["kind", "seconds", "repeat", "dtstart", "rrule"], + "additionalProperties": false + }, + "prompt": { "type": "string" }, + "delivery": { "type": "string", "enum": ["after-turn", "steer-current-turn"] } + }, + "required": ["trigger", "prompt", "delivery"], + "additionalProperties": false + }) +} + +const PARSE_TIMER_SYSTEM_PROMPT: &str = r#"Parse Codex `/loop` timer specs into a structured timer definition. + +Return only the JSON object requested by the response schema. + +Rules: +- Extract the timer prompt by removing the scheduling phrase but preserving the user's requested task. +- Use delivery "after-turn" unless the user clearly asks for same-turn/current-turn steering; then use "steer-current-turn". +- Treat `/loop` as recurring by default when there is no explicit one-time timing. A bare absolute date/time is a single run; do not infer recurrence solely from the `/loop` command name. +- For "now", "immediately", or specs with no explicit timing, use { "kind": "delay", "seconds": 0, "repeat": true } unless the user clearly asked for one-shot behavior. This means the timer fires whenever the thread is idle. +- For delay triggers, set dtstart and rrule to null. +- For schedule triggers, set seconds and repeat to null. +- For relative timing like "in 30 seconds", use a delay trigger with seconds set to the relative delay and repeat true unless the user clearly asked for one-shot behavior. +- For interval timing like "every 5 minutes", use a delay trigger with seconds set to the interval and repeat true. +- For absolute wall-clock timing like "at 9pm", "tomorrow at 8am", or "at 10:57", use a one-shot schedule trigger with dtstart set to the next matching local datetime in YYYY-MM-DDTHH:MM:SS and rrule null unless the user explicitly asks for recurrence with words like "every", "daily", "weekly", "hourly", "each", "repeat", or "recurring". +- For ambiguous wall-clock times without AM/PM, choose the soonest future local occurrence. Example: if the current local datetime is 2026-04-06T23:28:00 and the spec says "at 11:30", return 2026-04-06T23:30:00, not 2026-04-07T11:30:00. +- For recurring calendar timing, use a schedule trigger with rrule set to an RFC 5545 RRULE string and dtstart set when the user supplies a start datetime; otherwise null. +- For schedule triggers, use floating local wall-clock datetimes without timezone suffixes. +"#; + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + #[test] + fn format_timer_summary_renders_delay() { + assert_eq!( + format_timer_summary( + &TimerTrigger::Delay { + seconds: 30, + repeat: Some(false), + }, + TimerDelivery::AfterTurn, + "remind me to take a break", + ), + "delay 30s (one-shot, after-turn) -> remind me to take a break" + ); + } + + #[test] + fn format_timer_trigger_renders_one_shot_schedule_as_local_time() { + assert_eq!( + format_timer_trigger(&TimerTrigger::Schedule { + dtstart: Some("2026-04-07T21:00:00".to_string()), + rrule: None, + }), + "at Apr 7, 2026 9:00 PM" + ); + } + + #[test] + fn format_timer_trigger_preserves_invalid_schedule_dtstart() { + assert_eq!( + format_timer_trigger(&TimerTrigger::Schedule { + dtstart: Some("not-a-date".to_string()), + rrule: None, + }), + "at not-a-date" + ); + } + + #[test] + fn format_timer_trigger_renders_daily_rrule_as_local_time() { + assert_eq!( + format_timer_trigger(&TimerTrigger::Schedule { + dtstart: Some("2026-04-07T21:00:00".to_string()), + rrule: Some("FREQ=DAILY;BYHOUR=21;BYMINUTE=0;BYSECOND=0".to_string()), + }), + "daily at 9:00 PM" + ); + } + + #[test] + fn format_timer_trigger_renders_weekday_rrule_as_local_time() { + assert_eq!( + format_timer_trigger(&TimerTrigger::Schedule { + dtstart: Some("2026-04-07T17:00:00".to_string()), + rrule: Some( + "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR;BYHOUR=17;BYMINUTE=0;BYSECOND=0".to_string(), + ), + }), + "weekdays at 5:00 PM" + ); + } + + #[test] + fn format_timer_trigger_renders_hourly_rrule_as_text() { + assert_eq!( + format_timer_trigger(&TimerTrigger::Schedule { + dtstart: None, + rrule: Some("FREQ=HOURLY;BYMINUTE=0;BYSECOND=0".to_string()), + }), + "hourly on the hour" + ); + } + + #[test] + fn format_timer_trigger_preserves_unrecognized_rrule() { + assert_eq!( + format_timer_trigger(&TimerTrigger::Schedule { + dtstart: Some("2026-04-07T21:00:00".to_string()), + rrule: Some("FREQ=YEARLY;BYMONTH=4".to_string()), + }), + "schedule from Apr 7, 2026 9:00 PM; FREQ=YEARLY;BYMONTH=4" + ); + } + + #[test] + fn parser_output_schema_avoids_unsupported_union_keywords() { + let schema = output_schema(); + assert_eq!(schema.pointer("/properties/trigger/oneOf"), None); + assert_eq!(schema.pointer("/properties/trigger/anyOf"), None); + assert_eq!( + schema.pointer("/properties/trigger/properties/kind/enum"), + Some(&json!(["delay", "schedule"])) + ); + } + + #[test] + fn parser_prompt_defaults_ambiguous_loop_to_idle_recurring() { + assert!( + PARSE_TIMER_SYSTEM_PROMPT + .contains(r#"{ "kind": "delay", "seconds": 0, "repeat": true }"#) + ); + assert!(PARSE_TIMER_SYSTEM_PROMPT.contains("A bare absolute date/time is a single run")); + assert!(PARSE_TIMER_SYSTEM_PROMPT.contains("For absolute wall-clock timing like")); + assert!(PARSE_TIMER_SYSTEM_PROMPT.contains("choose the soonest future local occurrence")); + assert!(PARSE_TIMER_SYSTEM_PROMPT.contains("2026-04-06T23:30:00")); + } + + #[test] + fn parsed_timer_spec_accepts_permissive_delay_trigger_shape() { + let parsed: ParsedTimerSpec = serde_json::from_value(json!({ + "trigger": { + "kind": "delay", + "seconds": 10, + "repeat": false, + "dtstart": null, + "rrule": null + }, + "prompt": "tell me a joke", + "delivery": "after-turn" + })) + .expect("permissive parser schema output should deserialize"); + + assert_eq!( + parsed, + ParsedTimerSpec { + trigger: TimerTrigger::Delay { + seconds: 10, + repeat: Some(false), + }, + prompt: "tell me a joke".to_string(), + delivery: TimerDelivery::AfterTurn, + } + ); + } +}