diff --git a/CHANGELOG.md b/CHANGELOG.md index a41c351dd..d80f0b379 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## Unreleased: `HookEngine::agent_thought` (tinyagents#91) + +Added `HookEngine::agent_thought(identity, text, duration_ms)` to +`tinyagents_hooks::command`. It fires the observational `afterAgentThought` +event with a `TextPayload`, returns without building an envelope when no hook +is configured, and schedules matching hooks in the background so the turn never +waits on them. Matchers select on the thought text. This completes the +lifecycle entry points hosts previously re-implemented. + ## 3.1.4 - Releases are cut from `main`: the version bump merges through a pull request diff --git a/crates/tinyagents-hooks/src/command/README.md b/crates/tinyagents-hooks/src/command/README.md index 917c38fb7..f97661d65 100644 --- a/crates/tinyagents-hooks/src/command/README.md +++ b/crates/tinyagents-hooks/src/command/README.md @@ -20,6 +20,17 @@ so that teardown can finish, then drops the future. A spawner that refuses returns `Err`, which is a hook failure like any other (fail-open, or a denial when the definition sets `fail_closed`). +## Lifecycle entry points + +Events with no tool-call seam are fired through `HookEngine` methods in +`ops.rs`: `session_started`, `session_ended`, `prompt_submitted` (returning a +`PromptVerdict`), `pre_compact`, `subagent_starting`, `subagent_stopped`, and +`agent_thought`. Each returns immediately when no hook is configured for its +event. `agent_thought` fires the observational `afterAgentThought` event with a +`TextPayload` (the reasoning text and its optional `duration_ms`); its hooks +run in the background, matchers select on the thought text, and their output +is ignored. + ## Configuration and trust Configuration is read from system, user, workspace, and project layers. Lists diff --git a/crates/tinyagents-hooks/src/command/command_tests.rs b/crates/tinyagents-hooks/src/command/command_tests.rs index 3639e957a..b5b89bfea 100644 --- a/crates/tinyagents-hooks/src/command/command_tests.rs +++ b/crates/tinyagents-hooks/src/command/command_tests.rs @@ -407,6 +407,72 @@ async fn lifecycle_entrypoints_dispatch_configured_hooks_and_apply_decisions() { engine.session_ended(identity, "completed", Some(100)).await; } +#[cfg(unix)] +#[tokio::test] +async fn agent_thought_fires_matching_hooks_in_the_background() { + use super::context::TurnIdentity; + + let engine = HookEngine::default(); + // A matcher with regex syntax searches the thought text; a bare word would + // have to equal the whole text. + let dir = scratch( + r#"{"version":1,"hooks":{ + "afterAgentThought":[{"command":"./thought.sh","matcher":"secret.*"}] + }}"#, + Some(( + "thought.sh", + // Sleep first so a caller that waited on the hook would be caught, + // and print a denial to show an observer's verdict is ignored. + "#!/bin/sh\nsleep 1\ncat >> thoughts.log\necho >> thoughts.log\n\ + echo '{\"permission\":\"deny\"}'\n", + )), + ); + engine + .install(config::load(&host(), None, Some(dir.path()))) + .await; + assert!(engine.has_hooks(HookEvent::AfterAgentThought).await); + let identity = TurnIdentity { + session_id: Some("session-thought".into()), + conversation_id: Some("thread-1".into()), + ..Default::default() + }; + + let started = std::time::Instant::now(); + engine + .agent_thought(identity.clone(), "nothing to see", Some(5)) + .await; + engine + .agent_thought(identity, "a secret plan", Some(42)) + .await; + assert!( + started.elapsed() < Duration::from_millis(900), + "an observational event must not wait for its hooks" + ); + + let log = dir.path().join("thoughts.log"); + let deadline = std::time::Instant::now() + Duration::from_secs(15); + let body = loop { + if let Ok(body) = std::fs::read_to_string(&log) + && body.ends_with('\n') + { + break body; + } + assert!( + std::time::Instant::now() < deadline, + "the matching hook never ran" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + }; + let lines: Vec<&str> = body.lines().filter(|line| !line.is_empty()).collect(); + assert_eq!(lines.len(), 1, "only the matching thought fires: {body}"); + let event: serde_json::Value = serde_json::from_str(lines[0]).expect("event json"); + assert_eq!(event["hook_event_name"], "afterAgentThought"); + assert_eq!(event["session_id"], "session-thought"); + assert_eq!(event["conversation_id"], "thread-1"); + assert_eq!(event["text"], "a secret plan"); + assert_eq!(event["duration_ms"], 42); +} + #[cfg(unix)] #[tokio::test] async fn a_denial_short_circuits_the_remaining_hooks() { diff --git a/crates/tinyagents-hooks/src/command/ops.rs b/crates/tinyagents-hooks/src/command/ops.rs index f1a96bbbb..1b33daa35 100644 --- a/crates/tinyagents-hooks/src/command/ops.rs +++ b/crates/tinyagents-hooks/src/command/ops.rs @@ -189,6 +189,31 @@ impl HookEngine { .output .followup_message } + + /// Fire the observational `afterAgentThought` event for a reasoning block. + /// + /// The hooks run on a background task, so this returns as soon as they are + /// scheduled and nothing they print can change the turn. Matchers select on + /// the thought text. + pub async fn agent_thought( + &self, + identity: TurnIdentity, + text: &str, + duration_ms: Option, + ) { + if !self.has_hooks(HookEvent::AfterAgentThought).await { + return; + } + let input = build_input( + HookEvent::AfterAgentThought, + identity, + HookPayload::Text(TextPayload { + text: text.to_owned(), + duration_ms, + }), + ); + self.dispatch(HookEvent::AfterAgentThought, input).await; + } } #[cfg(test)] diff --git a/crates/tinyagents-hooks/src/command/ops_tests.rs b/crates/tinyagents-hooks/src/command/ops_tests.rs index 8154bdf7d..960aae94c 100644 --- a/crates/tinyagents-hooks/src/command/ops_tests.rs +++ b/crates/tinyagents-hooks/src/command/ops_tests.rs @@ -31,5 +31,8 @@ async fn lifecycle_entrypoints_are_noops_without_registered_hooks() { .await, None ); + engine + .agent_thought(identity.clone(), "thinking", Some(1)) + .await; engine.session_ended(identity, "completed", Some(1)).await; }