Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(webhook): stream webhook events over SSE (#6029)

Wolf Mermelstein852f1ba50d92
diff --git a/Cargo.lock b/Cargo.lock
index 25a044d6b5..a7165222f3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3554,15 +3554,15 @@ dependencies = [
"agent_runtime_protocol",
"agent_session",
"agent_trigger",
- "axum",
"bot_id",
- "bots",
"channel_sender",
"channels",
"chrono",
"clap",
"crossterm 0.28.1",
"dashmap",
+ "eventsource-stream",
+ "futures",
"harness_id",
"harnesses",
"macro_event_broker",
@@ -3582,12 +3582,10 @@ dependencies = [
"tokio-util",
"toml 0.8.23",
"toml_edit 0.22.27",
- "tower 0.5.3",
"tracing",
"tracing-subscriber",
"uuid",
"webhook",
- "webhook_signature",
"workspace-hack",
]
@@ -17779,6 +17777,7 @@ dependencies = [
"serde_json",
"sqlx",
"sqs_client",
+ "strum 0.27.2",
"thiserror 2.0.18",
"tokio",
"tokio-retry",
diff --git a/Cargo.toml b/Cargo.toml
index d8412d375b..ef50db2241 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -184,6 +184,7 @@ dateparser = "0.2.1"
dotenvy = "0.15.7"
ego-tree = "0.6.2"
either = "1"
+eventsource-stream = "0.2.3"
futures = "0.3.31"
getrandom = "0.3"
glob = "0.3.3"
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index aed1112cd4..4cdeeff35f 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -1183,6 +1183,7 @@ export * from './soupThreadInfoLatestReplyAt';
export * from './soupThreadReply';
export * from './soupThreadReplyEditedAt';
export * from './starterDocumentsResponse';
+export * from './streamEventsParams';
export * from './string';
export * from './successResponse';
export * from './surfaceState';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/streamEventsParams.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/streamEventsParams.ts
new file mode 100644
index 0000000000..8e6a09918b
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/streamEventsParams.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { WebhookScope } from './webhookScope';
+
+export type StreamEventsParams = {
+ /**
+ * Personal or team workspace whose webhook lifecycle events are delivered.
+ */
+ scope: WebhookScope;
+ /**
+ * URL-encoded JSON array of webhook filters, identical to the persisted
+webhook `filters` field.
+ */
+ filters?: string;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/webhookScope.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/webhookScope.ts
index 4a3ad69f3b..82a84ccca7 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/webhookScope.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/webhookScope.ts
@@ -8,7 +8,8 @@
/**
* Scope that owns a newly-created webhook.
-Clients serialize this, so both derives are used.
+Clients serialize this, so both derives are used. `Display`/`FromStr`
+spell the same names as serde, for query strings and config values.
*/
export type WebhookScope = (typeof WebhookScope)[keyof typeof WebhookScope];
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index dac0ef851b..d24c4b0521 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -27786,6 +27786,23 @@ export const editProjectV2Response = zod.object({
error: zod.boolean().describe('Indicates if an error occurred'),
});
+/**
+ * @summary Stream matching broker events to the caller over Server-Sent Events.
+ */
+export const streamEventsQueryParams = zod.object({
+ scope: zod
+ .enum(['user', 'team'])
+ .describe(
+ 'Personal or team workspace whose webhook lifecycle events are delivered.'
+ ),
+ filters: zod
+ .string()
+ .optional()
+ .describe(
+ 'URL-encoded JSON array of webhook filters, identical to the persisted\nwebhook `filters` field.'
+ ),
+});
+
/**
* @summary List the caller's webhooks.
*/
@@ -27893,7 +27910,7 @@ export const createWebhookBody = zod
scope: zod
.enum(['user', 'team'])
.describe(
- 'Scope that owns a newly-created webhook.\n\nClients serialize this, so both derives are used.'
+ 'Scope that owns a newly-created webhook.\n\nClients serialize this, so both derives are used. `Display`\/`FromStr`\nspell the same names as serde, for query strings and config values.'
),
})
.describe(
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 41083163ad..fc69b1898b 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -11998,6 +11998,75 @@
}
}
},
+ "/webhook/events/stream": {
+ "get": {
+ "tags": ["webhook"],
+ "summary": "Stream matching broker events to the caller over Server-Sent Events.",
+ "operationId": "stream_events",
+ "parameters": [
+ {
+ "name": "scope",
+ "in": "query",
+ "description": "Personal or team workspace whose webhook lifecycle events are delivered.",
+ "required": true,
+ "schema": {
+ "$ref": "#/components/schemas/WebhookScope"
+ }
+ },
+ {
+ "name": "filters",
+ "in": "query",
+ "description": "URL-encoded JSON array of webhook filters, identical to the persisted\nwebhook `filters` field.",
+ "required": false,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Server-Sent Events stream of matching broker events",
+ "content": {
+ "text/event-stream": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Bad request",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Forbidden",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "Internal server error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/webhook/webhooks": {
"get": {
"tags": ["webhook"],
@@ -26528,7 +26597,7 @@
},
"WebhookScope": {
"type": "string",
- "description": "Scope that owns a newly-created webhook.\n\nClients serialize this, so both derives are used.",
+ "description": "Scope that owns a newly-created webhook.\n\nClients serialize this, so both derives are used. `Display`/`FromStr`\nspell the same names as serde, for query strings and config values.",
"enum": ["user", "team"]
},
"WebhookStatus": {
diff --git a/crates/coding_agent_worker/Cargo.toml b/crates/coding_agent_worker/Cargo.toml
index fc97b757d8..1017ee2a69 100644
--- a/crates/coding_agent_worker/Cargo.toml
+++ b/crates/coding_agent_worker/Cargo.toml
@@ -16,22 +16,20 @@ agent-client-protocol = { workspace = true }
agent_runtime_protocol = { path = "../agent_runtime_protocol" }
agent_session = { path = "../agent_session" }
agent_trigger = { path = "../agent_trigger" }
-axum = { workspace = true }
bot_id = { path = "../bot_id" }
-# Only the domain models: the daemon reads `GET /bots/me` and the webhook
-# API's bodies, and wants none of either crate's server-side machinery.
-bots = { path = "../bots", default-features = false }
chrono = { workspace = true }
clap = { workspace = true }
crossterm = { workspace = true }
harness_id = { path = "../harness_id" }
harnesses = { path = "../harnesses", default-features = false }
dashmap = { workspace = true }
+eventsource-stream = { workspace = true }
+futures = { workspace = true }
macro_event_broker = { path = "../macro_event_broker", default-features = false }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
ratatui = { workspace = true }
-reqwest = { workspace = true }
+reqwest = { workspace = true, features = ["stream"] }
rootcause = { workspace = true }
# The gateway dial is `wss` on every deployment but a local stack, and
# tokio-tungstenite's rustls feature selects no crypto provider.
@@ -50,7 +48,6 @@ tracing = { workspace = true }
uuid = { workspace = true }
tracing-subscriber = { workspace = true }
webhook = { path = "../webhook", default-features = false }
-webhook_signature = { path = "../webhook_signature" }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
@@ -59,4 +56,4 @@ channel_sender = { path = "../channel_sender" }
channels = { path = "../channels", default-features = false }
chrono = { workspace = true }
harness_id = { path = "../harness_id", features = ["test-utils"] }
-tower = { workspace = true, features = ["util"] }
+tokio = { workspace = true, features = ["io-util", "net"] }
diff --git a/crates/coding_agent_worker/config.example.toml b/crates/coding_agent_worker/config.example.toml
index 0df5a62abd..306ff1d9e0 100644
--- a/crates/coding_agent_worker/config.example.toml
+++ b/crates/coding_agent_worker/config.example.toml
@@ -9,8 +9,7 @@
# Base URL of the agent-harness service. Its ws(s) twin hosts the runtime
# gateway the daemon dials per session.
api_url = "http://localhost:50009/agent-harness"
-# Base URL of the storage service (harness pairing + webhook APIs); the
-# daemon registers its own trigger feed there at boot.
+# Base URL of the storage service (harness pairing + live event stream).
storage_url = "http://localhost:50009/dss"
# Optional: base URL of the Macro web app, used only to print the pairing
# link. Defaults to https://macro.com/app.
@@ -24,16 +23,6 @@ name = "erics-macbook"
# of your teammates create. The approval dialog arrives preselected to this.
scope = "private"
-[server]
-# Port `POST /macro-events` is served on.
-port = 8790
-# The URL deliveries reach this daemon at; what the feed registers.
-# Locally, the stack's relay tunnels this to the port above.
-public_url = "http://sdk-webhook-relay:8787/macro-events"
-# Optional override; normally the daemon registers its own feed at boot
-# and keeps the minted secret in a state file next to this config.
-# signing_secret = "whsec_..."
-
[harness]
command = "opencode"
args = ["acp"]
diff --git a/crates/coding_agent_worker/src/config.rs b/crates/coding_agent_worker/src/config.rs
index e6ace5e63d..c04eee47fa 100644
--- a/crates/coding_agent_worker/src/config.rs
+++ b/crates/coding_agent_worker/src/config.rs
@@ -1,6 +1,6 @@
//! The daemon's one input: a TOML file describing the Macro deployment it
-//! serves, the webhook server it listens on, and the harness it runs per
-//! session. See `config.example.toml` at the crate root.
+//! streams from and the harness it runs per session. See
+//! `config.example.toml` at the crate root.
//!
//! Deliberately credential-free: identity comes from pairing (press `p` in
//! the control panel), which persists the harness credential in a state file
@@ -22,8 +22,11 @@ pub struct Config {
/// How this daemon introduces itself when pairing.
#[serde(default)]
pub identity: Identity,
- /// The webhook server this daemon listens on.
- pub server: Server,
+ /// Unused: kept so existing configs that still declare a webhook listener
+ /// continue to parse. The daemon listens over SSE and no longer serves HTTP.
+ #[serde(default)]
+ #[expect(dead_code, reason = "accepted only so existing configs still parse")]
+ server: Option<LegacyServer>,
/// The harness process spawned per session.
pub harness: Harness,
/// The workspace every session runs against.
@@ -39,7 +42,7 @@ pub struct MacroApi {
/// prompted here, and its `ws(s)` twin hosts the runtime gateway.
pub api_url: String,
/// Base URL of the storage service, e.g. `http://localhost:50009/dss`.
- /// Hosts the harness pairing and webhook APIs.
+ /// Hosts harness pairing and `GET /webhook/events/stream`.
pub storage_url: String,
/// Base URL of the Macro web app, used only to print the pairing link.
#[serde(default = "default_web_url")]
@@ -90,22 +93,19 @@ pub enum IdentityScope {
Team,
}
-/// The webhook server this daemon listens on.
+/// Historical `[server]` table from when the daemon received signed webhooks.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
-pub struct Server {
- /// Port `POST /macro-events` is served on.
- pub port: u16,
- /// The URL webhook deliveries reach this daemon at - what the feed is
- /// registered with. Locally that is the stack's relay
- /// (`http://sdk-webhook-relay:8787/macro-events`); in production, a
- /// public HTTPS endpoint.
- pub public_url: String,
- /// Explicit signing secret, overriding boot-time feed registration.
- /// Normally absent: the daemon registers its own feed and keeps the
- /// minted secret in a state file next to the config.
+struct LegacyServer {
+ #[serde(default)]
+ #[expect(dead_code, reason = "accepted only so existing configs still parse")]
+ port: Option<u16>,
+ #[serde(default)]
+ #[expect(dead_code, reason = "accepted only so existing configs still parse")]
+ public_url: Option<String>,
#[serde(default)]
- pub signing_secret: Option<String>,
+ #[expect(dead_code, reason = "accepted only so existing configs still parse")]
+ signing_secret: Option<String>,
}
/// The harness process spawned per session. Generic on purpose: any binary
diff --git a/crates/coding_agent_worker/src/config/test.rs b/crates/coding_agent_worker/src/config/test.rs
index cfa2c21b7f..e50404ffb9 100644
--- a/crates/coding_agent_worker/src/config/test.rs
+++ b/crates/coding_agent_worker/src/config/test.rs
@@ -7,14 +7,15 @@ fn the_example_config_parses() {
let config: Config = toml::from_str(EXAMPLE).expect("example config parses");
assert_eq!(config.harness.command, "opencode");
assert_eq!(config.harness.args, vec!["acp"]);
- assert_eq!(config.server.port, 8790);
assert_eq!(config.identity.name.as_deref(), Some("erics-macbook"));
assert_eq!(config.identity.scope, IdentityScope::Private);
- assert_eq!(config.server.signing_secret, None);
- assert_eq!(
- config.server.public_url,
- "http://sdk-webhook-relay:8787/macro-events"
- );
+}
+
+#[test]
+fn leftover_server_section_is_ignored() {
+ let with_server =
+ format!("{EXAMPLE}\n[server]\nport = 8790\npublic_url = \"http://example/macro-events\"\n");
+ toml::from_str::<Config>(&with_server).expect("legacy server section still parses");
}
#[test]
diff --git a/crates/coding_agent_worker/src/daemon.rs b/crates/coding_agent_worker/src/daemon.rs
index ac3f0a1cf6..84f8db1abf 100644
--- a/crates/coding_agent_worker/src/daemon.rs
+++ b/crates/coding_agent_worker/src/daemon.rs
@@ -5,7 +5,6 @@
//! removed - which is what makes the TUI and the daemon one process.
use std::path::{Path, PathBuf};
-use std::sync::Arc;
use std::time::Duration;
use rootcause::prelude::ResultExt as _;
@@ -15,32 +14,31 @@ use crate::config::Config;
use crate::dispatch::Dispatcher;
use crate::outbound::agent_session::HarnessApi;
use crate::outbound::credentials::HarnessCredentials;
-use crate::outbound::registration::FeedReconciler;
+use crate::outbound::stream::EventStreamClient;
use crate::runtime::Runtime;
-use crate::webhook::{WebhookState, webhook_router};
+use crate::trigger::{TriggerEvent, handle_event, trigger_filters};
-/// How often the bound-agent set is re-read and the feed reconciled to it, so
-/// a newly bound agent starts triggering without a restart. Short on purpose:
-/// a mention sent before the feed covers the new agent is dropped for good,
-/// so this interval is the worst-case window where a brand-new agent is deaf.
-const FEED_RECONCILE_INTERVAL: Duration = Duration::from_secs(10);
+/// How often the bound-agent set is re-read so a newly bound agent starts
+/// triggering without a restart. Short on purpose: a mention sent before the
+/// stream covers the new agent is dropped for good, so this interval is the
+/// worst-case window where a brand-new agent is deaf.
+const BOUND_AGENT_REFRESH: Duration = Duration::from_secs(10);
-/// A running serving core: webhook receiver, feed reconciler, harness bridge.
+/// A running serving core: SSE listener, harness bridge.
pub struct Daemon {
cancel: CancellationToken,
task: tokio::task::JoinHandle<rootcause::Result<()>>,
}
impl Daemon {
- /// Bind the webhook server and start serving in background tasks.
+ /// Start listening for agent triggers in a background task.
///
- /// Returns once the listener is bound (so a failed bind is an immediate
- /// error, not a background log line); the serving itself runs until
+ /// Returns once the client is built; the serving itself runs until
/// [`Daemon::stop`] or the task fails.
pub async fn start(
config: Config,
credentials: HarnessCredentials,
- config_path: &Path,
+ _config_path: &Path,
) -> rootcause::Result<Self> {
// The ACP launch config carries command, args, and env but no working
// directory, and every session this daemon serves runs in the one
@@ -51,86 +49,43 @@ impl Daemon {
))?;
let cancel = CancellationToken::new();
-
- // The feed: make sure one exists, points here, covers the bound
- // agents, and we hold its secret. An explicit config secret skips
- // registration entirely (manual setups).
- let reconciler = Arc::new(FeedReconciler::new(
- &config.macro_api,
- &config.server,
- credentials.clone(),
- config_path,
- ));
- let signing_secret = Arc::new(std::sync::RwLock::new(String::new()));
- match &config.server.signing_secret {
- Some(secret) => {
- *signing_secret.write().expect("signing secret lock") = secret.clone();
- }
- None => {
- // `None` is a daemon with nothing bound yet: it serves anyway,
- // and the reconcile loop registers the feed the moment an
- // agent is bound in the app.
- let initial = reconciler
- .ensure_feed()
- .await
- .context("failed to register this harness's trigger feed")?;
- if let Some(feed) = &initial {
- *signing_secret.write().expect("signing secret lock") =
- feed.signing_secret.clone();
- }
- // Validation probes the endpoint, so it can only pass once we
- // serve; request it from the side once the listener is up,
- // and keep the feed covering the bound-agent set from then on.
- let reconciler = Arc::clone(&reconciler);
- let signing_secret = Arc::clone(&signing_secret);
- let cancel = cancel.clone();
- tokio::spawn(async move {
- let mut current = None;
- if let Some(feed) = initial {
- if !feed.is_valid {
- reconciler.request_validation(&feed.webhook_id).await;
- }
- current = Some(feed.webhook_id);
- }
- tokio::select! {
- () = reconcile_forever(reconciler, signing_secret, current) => {}
- () = cancel.cancelled() => {}
- }
- });
- }
- }
-
+ let client = EventStreamClient::new(&config.macro_api, &credentials);
let api = HarnessApi::new(&config.macro_api, &credentials);
let runtime = Runtime::new(&config.macro_api, &credentials, config.harness.clone());
- let app = webhook_router(WebhookState {
- executor: Dispatcher::new(api, runtime, config.workspace.clone()),
- signing_secret: Arc::clone(&signing_secret),
- });
+ let executor = Dispatcher::new(api, runtime, config.workspace.clone());
- let port = config.server.port;
- let listener = tokio::net::TcpListener::bind(("0.0.0.0", port))
- .await
- .context(format!(
- "failed to bind the webhook server to port {port} - is another macrod \
- (a separate `macrod` serve, or another tui) already running?"
- ))?;
tracing::info!(
- port,
- pid = std::process::id(),
api = %config.macro_api.api_url,
+ storage = %config.macro_api.storage_url,
harness_id = %credentials.harness_id,
harness = %config.harness.command,
workspace = %config.workspace.path.display(),
- "daemon listening for agent triggers"
+ "daemon listening for agent triggers over SSE"
);
let shutdown = cancel.clone();
let task = tokio::spawn(async move {
- axum::serve(listener, app)
- .with_graceful_shutdown(async move { shutdown.cancelled().await })
- .await
- .context("the webhook server stopped")?;
- Ok(())
+ let mut failures = 0u32;
+ loop {
+ if shutdown.is_cancelled() {
+ return Ok(());
+ }
+ match serve_once(&client, &executor, &shutdown).await {
+ ServeOutcome::Stopped => return Ok(()),
+ ServeOutcome::Idle => {
+ failures = 0;
+ }
+ ServeOutcome::Ended(error) => {
+ tracing::warn!(error = ?error, "event stream ended; reconnecting");
+ failures = failures.saturating_add(1);
+ let delay = reconnect_delay(failures);
+ tokio::select! {
+ () = shutdown.cancelled() => return Ok(()),
+ () = tokio::time::sleep(delay) => {}
+ }
+ }
+ }
+ }
});
Ok(Self { cancel, task })
@@ -141,7 +96,7 @@ impl Daemon {
!self.task.is_finished()
}
- /// Stop serving: unbind the webhook port and end the reconcile loop.
+ /// Stop serving: drop the stream and end the reconnect loop.
///
/// A live harness bridge (the WebSocket + spawned harness process) is not
/// torn down here; it dies with the process, and a restarted daemon's
@@ -159,42 +114,71 @@ pub fn absolute_config_path(config_path: &Path) -> PathBuf {
std::path::absolute(config_path).unwrap_or_else(|_| config_path.to_owned())
}
-/// Keep the feed covering the bound-agent set: registered once anything is
-/// bound, replaced (along with the secret the receiver verifies with) when
-/// the set or endpoint changes, and dropped when nothing is bound any more.
-async fn reconcile_forever(
- reconciler: Arc<FeedReconciler>,
- signing_secret: Arc<std::sync::RwLock<String>>,
- mut current_webhook_id: Option<String>,
-) {
+fn reconnect_delay(failures: u32) -> Duration {
+ let secs = 1u64.checked_shl(failures.min(5)).unwrap_or(30).min(30);
+ Duration::from_secs(secs)
+}
+
+enum ServeOutcome {
+ Stopped,
+ Idle,
+ Ended(rootcause::Report),
+}
+
+/// Open the stream (or wait for bound agents) until it ends or is cancelled.
+async fn serve_once<Executor: crate::trigger::WorkExecutor>(
+ client: &EventStreamClient,
+ executor: &Executor,
+ cancel: &CancellationToken,
+) -> ServeOutcome {
+ let bots = match client.bound_bot_ids().await {
+ Ok(bots) => bots,
+ Err(error) => return ServeOutcome::Ended(error),
+ };
+ if bots.is_empty() {
+ tracing::info!("no agents are bound; waiting before opening the event stream");
+ tokio::select! {
+ () = cancel.cancelled() => return ServeOutcome::Stopped,
+ () = tokio::time::sleep(BOUND_AGENT_REFRESH) => return ServeOutcome::Idle,
+ }
+ }
+
+ let filters = trigger_filters(bots.iter());
+ let mut stream = match client.connect::<TriggerEvent>(&filters).await {
+ Ok(stream) => stream,
+ Err(error) => return ServeOutcome::Ended(error),
+ };
+ tracing::info!(
+ bound_agents = bots.len(),
+ "connected to the agent-trigger event stream"
+ );
+
loop {
- tokio::time::sleep(FEED_RECONCILE_INTERVAL).await;
- match reconciler.ensure_feed().await {
- Ok(Some(feed)) => {
- if current_webhook_id.as_deref() != Some(feed.webhook_id.as_str()) {
- tracing::info!(webhook_id = %feed.webhook_id, "trigger feed registered");
- *signing_secret.write().expect("signing secret lock") =
- feed.signing_secret.clone();
- if !feed.is_valid {
- reconciler.request_validation(&feed.webhook_id).await;
+ tokio::select! {
+ () = cancel.cancelled() => return ServeOutcome::Stopped,
+ () = tokio::time::sleep(BOUND_AGENT_REFRESH) => {
+ match client.bound_bot_ids().await {
+ Ok(latest) if latest == bots => {}
+ Ok(_) => {
+ tracing::info!("bound-agent set changed; reconnecting the event stream");
+ return ServeOutcome::Idle;
}
- current_webhook_id = Some(feed.webhook_id);
+ Err(error) => return ServeOutcome::Ended(error),
}
}
- Ok(None) => {
- if current_webhook_id.take().is_some() {
- // Drop the secret with the feed: retaining it would keep
- // verifying deliveries signed for a webhook the server has
- // already deleted. Empty fails closed (see
- // `webhook_signature::verify`), which is correct while
- // nothing is bound to serve.
- signing_secret.write().expect("signing secret lock").clear();
- tracing::info!("trigger feed removed; no agents are bound any more");
+ next = stream.next_event() => {
+ match next {
+ Ok(Some(event)) => {
+ let _ = handle_event(event, executor).await;
+ }
+ Ok(None) => {
+ return ServeOutcome::Ended(rootcause::report!(
+ "the server closed the stream"
+ ));
+ }
+ Err(error) => return ServeOutcome::Ended(error),
}
}
- Err(error) => {
- tracing::warn!(error = ?error, "trigger feed reconciliation failed; will retry");
- }
}
}
}
diff --git a/crates/coding_agent_worker/src/dispatch.rs b/crates/coding_agent_worker/src/dispatch.rs
index 42f03555f2..0122698108 100644
--- a/crates/coding_agent_worker/src/dispatch.rs
+++ b/crates/coding_agent_worker/src/dispatch.rs
@@ -6,7 +6,7 @@ use agent_session::inbound::axum_router::{CreateAgentSessionRequest, CreateSessi
use crate::config::Workspace;
use crate::outbound::agent_session::{ApiError, HarnessApi};
use crate::runtime::Runtime;
-use crate::webhook::{TriggerWork, WorkExecutor};
+use crate::trigger::{TriggerWork, WorkExecutor};
/// A failure doing an event's work.
#[derive(Debug, thiserror::Error)]
@@ -104,9 +104,9 @@ impl WorkExecutor for Dispatcher {
// uncovered window is the sub-millisecond gap between the
// websocket's 101 and the server's `on_upgrade` attach. If
// that race ever bites, failing the delivery is the right
- // answer - webhook redelivery re-runs this arm, and a repeat
- // create answers 409 with the session id, which the branch
- // above resumes.
+ // answer. SSE has no redelivery; a later `agent_trigger.existing`
+ // or a 409 on a repeat create (session already exists) is how
+ // a follow-up lands on the same session.
self.api.prompt(session, &sender, &content).await?;
Ok(())
}
diff --git a/crates/coding_agent_worker/src/main.rs b/crates/coding_agent_worker/src/main.rs
index 70177ff829..8c77e711b3 100644
--- a/crates/coding_agent_worker/src/main.rs
+++ b/crates/coding_agent_worker/src/main.rs
@@ -1,11 +1,11 @@
//! The coding agent daemon: serve a registered harness's agent sessions from
//! this machine.
//!
-//! `macrod` is one process and one command: the serving core (webhook
-//! receiver, feed reconciler, harness bridge) running inside a terminal
-//! control panel that shows what it is serving - the registration, the agents
-//! bound to it, their sessions, and the daemon's own logs - and manages its
-//! own pairing, config, and retirement.
+//! `macrod` is one process and one command: the serving core (SSE listener,
+//! harness bridge) running inside a terminal control panel that shows what
+//! it is serving - the registration, the agents bound to it, their sessions,
+//! and the daemon's own logs - and manages its own pairing, config, and
+//! retirement.
//!
//! A first run starts unpaired: the panel offers pairing (press `p`), the
//! user approves the printed code in the web app, and the minted harness
@@ -22,8 +22,8 @@ mod dispatch;
mod harness;
mod outbound;
mod runtime;
+mod trigger;
mod tui;
-mod webhook;
use clap::Parser;
use std::path::PathBuf;
diff --git a/crates/coding_agent_worker/src/outbound/credentials.rs b/crates/coding_agent_worker/src/outbound/credentials.rs
index c46c28bbd3..19ee5c18ce 100644
--- a/crates/coding_agent_worker/src/outbound/credentials.rs
+++ b/crates/coding_agent_worker/src/outbound/credentials.rs
@@ -2,8 +2,7 @@
//! bearer token that proves it.
//!
//! Written once by pairing and read at every boot, in a state file next to
-//! the config - the same shape as the webhook feed state. Losing the file is
-//! recoverable by pairing again.
+//! the config. Losing the file is recoverable by pairing again.
use std::path::{Path, PathBuf};
@@ -16,9 +15,9 @@ mod test;
/// Whether the harness is private to its owner or shared with a team.
///
-/// Persisted because the webhook feed the daemon registers must live in the
-/// matching workspace: a team harness's feed subscribes in the team workspace
-/// so teammates' agents' triggers reach it.
+/// Persisted because the event stream must live in the matching workspace: a
+/// team harness listens in the team workspace so teammates' agents' triggers
+/// reach it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HarnessScope {
diff --git a/crates/coding_agent_worker/src/outbound/mod.rs b/crates/coding_agent_worker/src/outbound/mod.rs
index bb69857e36..434e924fcc 100644
--- a/crates/coding_agent_worker/src/outbound/mod.rs
+++ b/crates/coding_agent_worker/src/outbound/mod.rs
@@ -10,4 +10,4 @@ pub mod agent_session;
pub mod credentials;
pub mod link;
pub mod pairing;
-pub mod registration;
+pub mod stream;
diff --git a/crates/coding_agent_worker/src/outbound/registration.rs b/crates/coding_agent_worker/src/outbound/registration.rs
deleted file mode 100644
index f19180a067..0000000000
--- a/crates/coding_agent_worker/src/outbound/registration.rs
+++ /dev/null
@@ -1,346 +0,0 @@
-//! Webhook feed reconciliation: make sure this harness has a validated
-//! trigger feed pointing at this daemon and covering every agent bound to it.
-//!
-//! The flow is deliberately the plain webhook API driven as the harness: which
-//! agents am I serving (`/harnesses/me/agents`), do I have a feed (list), is
-//! it mine and current (endpoint and bound-agent match), verify it if
-//! unverified, create it if missing or stale. It leans on no server-side
-//! affordance beyond that API: the feed is an ordinary webhook, scoped to the
-//! bound bots by an `ids` filter and found again by the namespace this daemon
-//! mints for it.
-//!
-//! Run at boot and then periodically: a teammate binding a new agent to this
-//! harness changes the bound set, and the feed must grow to cover it without
-//! a daemon restart.
-//!
-//! Secrets are only ever returned at creation, so the daemon persists its
-//! feed's id and secret in a state file next to the config. Losing the file
-//! is recoverable: the stale feed is deleted and recreated.
-
-use std::collections::BTreeSet;
-use std::path::{Path, PathBuf};
-
-use agent_trigger::domain::broker_events::AgentTriggerEventName;
-use harness_id::HarnessId;
-use harnesses::domain::models::HarnessAgent;
-use rootcause::prelude::ResultExt as _;
-use serde::{Deserialize, Serialize};
-use strum::IntoEnumIterator as _;
-use webhook::domain::models::{
- CreateWebhookRequest, CreateWebhookResponse, ListWebhooksResponse, Webhook, WebhookFilter,
- WebhookScope,
-};
-
-use crate::config::{MacroApi, Server};
-use crate::outbound::credentials::{HarnessCredentials, HarnessScope};
-
-#[cfg(test)]
-mod test;
-
-const HARNESS_TOKEN_HEADER: &str = "x-macro-harness-token";
-
-/// The namespace a daemon's feed carries: derived from its harness, so the
-/// feed can be found again without the server marking it as this harness's.
-fn feed_namespace(harness: HarnessId) -> String {
- format!("harness-feed-{harness}")
-}
-
-/// Every event a trigger feed carries, straight from the topic's own
-/// vocabulary: a mention that should open a session, and a follow-up message
-/// on a thread that already has one. A name this daemon does not yet handle
-/// is still worth subscribing to - it arrives, is recognised as unsupported,
-/// and is acked - which beats silently never being sent it.
-fn trigger_events() -> Vec<String> {
- AgentTriggerEventName::iter()
- .map(|event| event.to_string())
- .collect()
-}
-
-/// The reconciled feed this daemon serves.
-#[derive(Debug, Clone)]
-pub struct FeedRegistration {
- /// The webhook row's id.
- pub webhook_id: String,
- /// The secret deliveries to this daemon are signed with.
- pub signing_secret: String,
- /// Whether the endpoint had already passed validation. When false, the
- /// caller should request validation once it is serving.
- pub is_valid: bool,
-}
-
-/// The persisted half of a registration: what only creation reveals.
-#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
-pub(crate) struct FeedState {
- webhook_id: String,
- signing_secret: String,
-}
-
-pub(crate) trait FeedStateStore {
- fn load(&self) -> rootcause::Result<Option<FeedState>>;
-
- fn save(&self, state: &FeedState) -> rootcause::Result<()>;
-}
-
-pub(crate) struct FileFeedStateStore {
- path: PathBuf,
-}
-
-impl FileFeedStateStore {
- fn failure(&self) -> String {
- format!(
- "failed to use the feed state file at {}",
- self.path.display()
- )
- }
-}
-
-impl FeedStateStore for FileFeedStateStore {
- fn load(&self) -> rootcause::Result<Option<FeedState>> {
- let found = std::fs::read_to_string(&self.path);
- if let Err(error) = &found
- && error.kind() == std::io::ErrorKind::NotFound
- {
- return Ok(None);
- }
- // State we cannot parse is state we do not have: the feed it named
- // is treated as stale, deleted, and replaced.
- let raw = found.context(self.failure())?;
- Ok(serde_json::from_str(&raw).ok())
- }
-
- fn save(&self, state: &FeedState) -> rootcause::Result<()> {
- let raw = serde_json::to_string_pretty(state).expect("a serializable state");
- std::fs::write(&self.path, raw).context(self.failure())?;
- // The secret signs deliveries to us; keep it out of other users' reach.
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt as _;
- let _ = std::fs::set_permissions(&self.path, std::fs::Permissions::from_mode(0o600));
- }
- Ok(())
- }
-}
-
-/// Where the feed state lives: next to the config it belongs to.
-pub fn state_path(config_path: &Path) -> PathBuf {
- config_path.with_extension("webhook-state.json")
-}
-
-/// The webhook-feed reconciler for one harness on one deployment.
-pub(crate) struct FeedReconciler<S = FileFeedStateStore> {
- http: reqwest::Client,
- base: String,
- credentials: HarnessCredentials,
- public_url: String,
- state_store: S,
-}
-
-impl FeedReconciler<FileFeedStateStore> {
- /// Build a reconciler from the daemon's config and paired credentials.
- pub fn new(
- macro_api: &MacroApi,
- server: &Server,
- credentials: HarnessCredentials,
- config_path: &Path,
- ) -> Self {
- Self {
- http: reqwest::Client::new(),
- base: macro_api.storage_url.trim_end_matches('/').to_owned(),
- credentials,
- public_url: server.public_url.clone(),
- state_store: FileFeedStateStore {
- path: state_path(config_path),
- },
- }
- }
-}
-
-impl<S: FeedStateStore> FeedReconciler<S> {
- fn credentialed(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
- request.header(HARNESS_TOKEN_HEADER, &self.credentials.token)
- }
-
- async fn read<T: serde::de::DeserializeOwned>(
- &self,
- what: &'static str,
- request: reqwest::RequestBuilder,
- ) -> rootcause::Result<T> {
- let response = self
- .credentialed(request)
- .send()
- .await
- .context(format!("could not reach the service to {what}"))?;
- let status = response.status();
- if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
- rootcause::bail!(
- "the service refused this harness's credentials ({status}) while trying to \
- {what}; the harness was likely removed - press p to pair again"
- );
- }
- if !status.is_success() {
- let message = response.text().await.unwrap_or_default();
- rootcause::bail!("the service answered {status} to {what}: {message}");
- }
- Ok(response
- .json()
- .await
- .context(format!("could not read the service's answer to {what}"))?)
- }
-
- /// The agents currently bound to this harness, as sorted bot-id strings -
- /// the shape the feed filter carries.
- pub async fn bound_bot_ids(&self) -> rootcause::Result<Vec<String>> {
- let agents: Vec<HarnessAgent> = self
- .read(
- "list this harness's agents",
- self.http.get(format!("{}/harnesses/me/agents", self.base)),
- )
- .await?;
- let ids: BTreeSet<String> = agents
- .into_iter()
- .map(|agent| agent.bot_id.to_string())
- .collect();
- Ok(ids.into_iter().collect())
- }
-
- /// Whether an existing feed row already covers exactly `bot_ids`.
- fn covers(row: &Webhook, public_url: &str, bot_ids: &[String]) -> bool {
- if row.endpoint_url != public_url {
- return false;
- }
- let current: BTreeSet<&str> = row
- .filters
- .iter()
- .flat_map(|filter| filter.ids.iter().flatten())
- .map(String::as_str)
- .collect();
- let wanted: BTreeSet<&str> = bot_ids.iter().map(String::as_str).collect();
- current == wanted
- }
-
- /// Reconcile: return a feed that exists, points at this daemon, and
- /// covers every agent currently bound to this harness - or `None` while
- /// nothing is bound, since a filter over no bots is nothing to subscribe
- /// to (and the webhook API rightly refuses an empty ids list).
- pub async fn ensure_feed(&self) -> rootcause::Result<Option<FeedRegistration>> {
- let harness = self.credentials.harness_id;
- let bot_ids = self.bound_bot_ids().await?;
-
- let list: ListWebhooksResponse = self
- .read(
- "list webhooks",
- self.http.get(format!("{}/webhook/webhooks", self.base)),
- )
- .await?;
- let mine: Vec<&Webhook> = list
- .webhooks
- .iter()
- .filter(|row| row.namespace == feed_namespace(harness))
- .collect();
-
- // The remembered feed, when it still exists, points here, and covers
- // the current bound set.
- if !bot_ids.is_empty()
- && let Some(state) = self.state_store.load()?
- && let Some(row) = mine.iter().find(|row| row.id == state.webhook_id)
- && Self::covers(row, &self.public_url, &bot_ids)
- {
- return Ok(Some(FeedRegistration {
- webhook_id: state.webhook_id,
- signing_secret: state.signing_secret,
- is_valid: row.is_valid,
- }));
- }
-
- // Anything else of ours is a feed whose secret is lost, whose
- // endpoint moved, or whose bound set changed: delete before
- // recreating, since one harness needs exactly one feed.
- for row in mine {
- tracing::info!(webhook_id = %row.id, "removing this harness's stale trigger feed");
- let response = self
- .credentialed(
- self.http
- .delete(format!("{}/webhook/webhooks/{}", self.base, row.id)),
- )
- .send()
- .await?;
- if !response.status().is_success() {
- tracing::warn!(webhook_id = %row.id, status = %response.status(), "stale feed delete refused");
- }
- }
-
- if bot_ids.is_empty() {
- tracing::warn!(
- "no agents are bound to this harness yet; the trigger feed will be registered \
- once one is (Settings -> Agents)"
- );
- return Ok(None);
- }
-
- // A team harness's feed subscribes in the team workspace so triggers
- // for teammates' agents - fanned out to every accessor's workspaces -
- // reach it.
- let scope = match self.credentials.scope {
- HarnessScope::User => WebhookScope::User,
- HarnessScope::Team => WebhookScope::Team,
- };
- let created: CreateWebhookResponse = self
- .read(
- "create the trigger feed",
- self.http
- .post(format!("{}/webhook/webhooks", self.base))
- .json(&CreateWebhookRequest {
- scope,
- namespace: feed_namespace(harness),
- name: "Agent trigger feed".to_owned(),
- endpoint_url: self.public_url.clone(),
- headers: None,
- // Scoped to this harness's agents: trigger events name
- // the bot they are for, so without this the feed would
- // receive every bot's triggers in channels its
- // workspace can see.
- filters: vec![WebhookFilter {
- events: trigger_events(),
- ids: Some(bot_ids),
- }],
- }),
- )
- .await?;
-
- self.state_store.save(&FeedState {
- webhook_id: created.id.clone(),
- signing_secret: created.signing_secret.clone(),
- })?;
- tracing::info!(webhook_id = %created.id, %harness, "trigger feed registered");
-
- Ok(Some(FeedRegistration {
- webhook_id: created.id,
- signing_secret: created.signing_secret,
- is_valid: created.is_valid,
- }))
- }
-
- /// Ask the service to validate the feed's endpoint; call once serving.
- /// Best-effort: a rate-limited or failed validation is retried by a
- /// later boot, and deliveries to an unvalidated feed simply wait.
- pub async fn request_validation(&self, webhook_id: &str) {
- let result = self
- .credentialed(self.http.post(format!(
- "{}/webhook/webhooks/{}/validate",
- self.base, webhook_id
- )))
- .send()
- .await;
- match result {
- Ok(response) if response.status().is_success() => {
- tracing::info!(%webhook_id, "trigger feed validated");
- }
- Ok(response) => {
- tracing::warn!(%webhook_id, status = %response.status(), "feed validation refused");
- }
- Err(error) => {
- tracing::warn!(error = ?error, %webhook_id, "feed validation failed");
- }
- }
- }
-}
diff --git a/crates/coding_agent_worker/src/outbound/registration/test.rs b/crates/coding_agent_worker/src/outbound/registration/test.rs
deleted file mode 100644
index 45cb970968..0000000000
--- a/crates/coding_agent_worker/src/outbound/registration/test.rs
+++ /dev/null
@@ -1,86 +0,0 @@
-use std::{
- path::{Path, PathBuf},
- time::{SystemTime, UNIX_EPOCH},
-};
-
-use super::*;
-
-struct TestFile(PathBuf);
-
-impl TestFile {
- fn new() -> Self {
- let nonce = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .expect("time after epoch")
- .as_nanos();
- Self(std::env::temp_dir().join(format!(
- "coding-agent-worker-feed-state-{}-{nonce}.json",
- std::process::id()
- )))
- }
-
- fn path(&self) -> &Path {
- &self.0
- }
-
- fn store(&self) -> FileFeedStateStore {
- FileFeedStateStore {
- path: self.0.clone(),
- }
- }
-}
-
-impl Drop for TestFile {
- fn drop(&mut self) {
- let _ = std::fs::remove_file(&self.0);
- }
-}
-
-#[test]
-fn missing_feed_state_is_absent() {
- let file = TestFile::new();
-
- assert_eq!(file.store().load().expect("load state"), None);
-}
-
-#[test]
-fn malformed_feed_state_is_absent() {
- let file = TestFile::new();
- std::fs::write(file.path(), "not json").expect("write malformed state");
-
- assert_eq!(file.store().load().expect("load state"), None);
-}
-
-#[test]
-fn feed_state_round_trips() {
- let file = TestFile::new();
- let state = FeedState {
- webhook_id: "webhook-id".to_owned(),
- signing_secret: "signing-secret".to_owned(),
- };
-
- let store = file.store();
- store.save(&state).expect("save state");
-
- assert_eq!(store.load().expect("load state"), Some(state));
-}
-
-#[cfg(unix)]
-#[test]
-fn saved_feed_state_is_private() {
- use std::os::unix::fs::PermissionsExt as _;
-
- let file = TestFile::new();
- let state = FeedState {
- webhook_id: "webhook-id".to_owned(),
- signing_secret: "signing-secret".to_owned(),
- };
-
- file.store().save(&state).expect("save state");
-
- let mode = std::fs::metadata(file.path())
- .expect("state metadata")
- .permissions()
- .mode();
- assert_eq!(mode & 0o777, 0o600);
-}
diff --git a/crates/coding_agent_worker/src/outbound/stream.rs b/crates/coding_agent_worker/src/outbound/stream.rs
new file mode 100644
index 0000000000..1151b78f3e
--- /dev/null
+++ b/crates/coding_agent_worker/src/outbound/stream.rs
@@ -0,0 +1,165 @@
+//! Live trigger stream: hold `GET /webhook/events/stream` open as this
+//! harness, covering every agent currently bound to it.
+//!
+//! The body is Server-Sent Events, decoded by `eventsource-stream`. Each
+//! event's `data` is the same broker envelope persisted webhooks deliver,
+//! decoded straight into the caller's envelope type. Delivery is
+//! best-effort: a dropped connection misses events published while it was
+//! down.
+
+use std::collections::BTreeSet;
+use std::marker::PhantomData;
+use std::pin::Pin;
+
+use eventsource_stream::{Event, EventStreamError, Eventsource as _};
+use futures::{Stream, StreamExt as _};
+use harnesses::domain::models::HarnessAgent;
+use rootcause::prelude::ResultExt as _;
+use serde::de::DeserializeOwned;
+use webhook::domain::models::{WebhookFilter, WebhookScope};
+
+use crate::config::MacroApi;
+use crate::outbound::credentials::{HarnessCredentials, HarnessScope};
+
+#[cfg(test)]
+mod test;
+
+const HARNESS_TOKEN_HEADER: &str = "x-macro-harness-token";
+
+/// Map the harness's ownership onto the stream query's workspace scope.
+pub fn stream_scope(scope: HarnessScope) -> WebhookScope {
+ match scope {
+ HarnessScope::User => WebhookScope::User,
+ HarnessScope::Team => WebhookScope::Team,
+ }
+}
+
+/// Client for the storage service's live event stream, acting as one harness.
+pub struct EventStreamClient {
+ http: reqwest::Client,
+ base: String,
+ token: String,
+ scope: WebhookScope,
+}
+
+impl EventStreamClient {
+ /// Build a client from the daemon's config and paired credentials.
+ pub fn new(config: &MacroApi, credentials: &HarnessCredentials) -> Self {
+ Self {
+ http: reqwest::Client::new(),
+ base: config.storage_url.trim_end_matches('/').to_owned(),
+ token: credentials.token.clone(),
+ scope: stream_scope(credentials.scope),
+ }
+ }
+
+ fn credentialed(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
+ request.header(HARNESS_TOKEN_HEADER, &self.token)
+ }
+
+ async fn read<T: DeserializeOwned>(
+ &self,
+ what: &'static str,
+ request: reqwest::RequestBuilder,
+ ) -> rootcause::Result<T> {
+ let response = self
+ .credentialed(request)
+ .send()
+ .await
+ .context(format!("could not reach the service to {what}"))?;
+ let status = response.status();
+ if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
+ rootcause::bail!(
+ "the service refused this harness's credentials ({status}) while trying to \
+ {what}; the harness was likely removed - press p to pair again"
+ );
+ }
+ if !status.is_success() {
+ let message = response.text().await.unwrap_or_default();
+ rootcause::bail!("the service answered {status} to {what}: {message}");
+ }
+ Ok(response
+ .json()
+ .await
+ .context(format!("could not read the service's answer to {what}"))?)
+ }
+
+ /// The agents currently bound to this harness, as sorted bot-id strings —
+ /// the shape the stream filter carries.
+ pub async fn bound_bot_ids(&self) -> rootcause::Result<Vec<String>> {
+ let agents: Vec<HarnessAgent> = self
+ .read(
+ "list this harness's agents",
+ self.http.get(format!("{}/harnesses/me/agents", self.base)),
+ )
+ .await?;
+ let ids: BTreeSet<String> = agents
+ .into_iter()
+ .map(|agent| agent.bot_id.to_string())
+ .collect();
+ Ok(ids.into_iter().collect())
+ }
+
+ /// Open `GET /webhook/events/stream` and start reading envelopes of
+ /// type `E`.
+ #[tracing::instrument(skip(self, filters), err)]
+ pub async fn connect<E: DeserializeOwned>(
+ &self,
+ filters: &[WebhookFilter],
+ ) -> rootcause::Result<EventStream<E>> {
+ let filters =
+ serde_json::to_string(filters).context("could not encode the stream filters")?;
+ let response = self
+ .credentialed(
+ self.http
+ .get(format!("{}/webhook/events/stream", self.base))
+ .header(reqwest::header::ACCEPT, "text/event-stream")
+ .query(&[
+ ("scope", self.scope.to_string().as_str()),
+ ("filters", filters.as_str()),
+ ]),
+ )
+ .send()
+ .await
+ .context("could not reach the service to open the event stream")?;
+ let status = response.status();
+ if !status.is_success() {
+ let message = response.text().await.unwrap_or_default();
+ rootcause::bail!("the service answered {status} to open the event stream: {message}");
+ }
+ Ok(EventStream {
+ events: Box::pin(response.bytes_stream().eventsource()),
+ _envelope: PhantomData,
+ })
+ }
+}
+
+type SseEvents =
+ Pin<Box<dyn Stream<Item = Result<Event, EventStreamError<reqwest::Error>>> + Send>>;
+
+/// An open SSE response, yielding one decoded envelope at a time.
+pub struct EventStream<E> {
+ events: SseEvents,
+ _envelope: PhantomData<E>,
+}
+
+impl<E: DeserializeOwned> EventStream<E> {
+ /// The next envelope, or `None` when the server closes.
+ ///
+ /// Keep-alive comments never surface as events; a `data` payload that
+ /// does not decode as `E` is skipped rather than ending the stream.
+ pub async fn next_event(&mut self) -> rootcause::Result<Option<E>> {
+ loop {
+ let Some(event) = self.events.next().await else {
+ return Ok(None);
+ };
+ let event = event.context("could not read the event stream")?;
+ match serde_json::from_str(&event.data) {
+ Ok(value) => return Ok(Some(value)),
+ Err(error) => {
+ tracing::debug!(error = ?error, id = %event.id, "undecodable SSE data; skipped");
+ }
+ }
+ }
+ }
+}
diff --git a/crates/coding_agent_worker/src/outbound/stream/test.rs b/crates/coding_agent_worker/src/outbound/stream/test.rs
new file mode 100644
index 0000000000..0bf2560910
--- /dev/null
+++ b/crates/coding_agent_worker/src/outbound/stream/test.rs
@@ -0,0 +1,113 @@
+use super::*;
+use crate::config::MacroApi;
+use crate::outbound::credentials::{HarnessCredentials, HarnessScope};
+use harness_id::HarnessId;
+use webhook::domain::models::WebhookFilter;
+
+fn test_client(storage_url: &str) -> EventStreamClient {
+ EventStreamClient::new(
+ &MacroApi {
+ api_url: "http://unused".to_owned(),
+ storage_url: storage_url.to_owned(),
+ web_url: "https://macro.com/app".to_owned(),
+ },
+ &HarnessCredentials {
+ harness_id: HarnessId::TEST_A,
+ token: "mhns_test".to_owned(),
+ scope: HarnessScope::User,
+ },
+ )
+}
+
+#[test]
+fn stream_scope_maps_harness_ownership() {
+ assert_eq!(stream_scope(HarnessScope::User), WebhookScope::User);
+ assert_eq!(stream_scope(HarnessScope::Team), WebhookScope::Team);
+}
+
+#[derive(Debug, PartialEq, Eq, serde::Deserialize)]
+struct Envelope {
+ n: u8,
+}
+
+#[tokio::test]
+async fn connect_yields_typed_envelopes_and_skips_keep_alives_and_junk() {
+ let url = serve_once(
+ "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n\
+ : keep-alive\n\n\
+ id: evt-1\n\
+ event: agent_trigger.new\n\
+ data: {\"n\":1}\n\n\
+ data: not json\n\n\
+ data: {\"other\":true}\n\n\
+ data: {\"n\":\r\ndata: 2}\r\n\r\n",
+ )
+ .await;
+ let client = test_client(&url);
+ let mut stream = client
+ .connect::<Envelope>(&[WebhookFilter {
+ events: vec!["agent_trigger.new".to_owned()],
+ ids: None,
+ }])
+ .await
+ .expect("open the stream");
+
+ let first = stream.next_event().await.expect("read").expect("first");
+ assert_eq!(first, Envelope { n: 1 });
+ let second = stream.next_event().await.expect("read").expect("second");
+ assert_eq!(second, Envelope { n: 2 });
+ assert!(stream.next_event().await.expect("closed").is_none());
+}
+
+#[tokio::test]
+async fn connect_refuses_a_non_2xx_answer() {
+ let url = serve_once(
+ "HTTP/1.1 403 Forbidden\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{\"message\":\"nope\"}",
+ )
+ .await;
+ let client = test_client(&url);
+
+ let error = client
+ .connect::<Envelope>(&[])
+ .await
+ .err()
+ .expect("a 403 is refused");
+ assert!(format!("{error:?}").contains("403"));
+}
+
+#[tokio::test]
+async fn bound_bot_ids_are_sorted_and_unique() {
+ let url = serve_once(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n\
+ [{\"bot_id\":\"00000000-0000-0000-0000-000000000002\",\"name\":\"b\",\"handle\":\"b\"},\
+ {\"bot_id\":\"00000000-0000-0000-0000-000000000001\",\"name\":\"a\",\"handle\":\"a\"},\
+ {\"bot_id\":\"00000000-0000-0000-0000-000000000002\",\"name\":\"b2\",\"handle\":\"b2\"}]",
+ )
+ .await;
+ let client = test_client(&url);
+ let ids = client.bound_bot_ids().await.expect("list agents");
+ assert_eq!(
+ ids,
+ vec![
+ "00000000-0000-0000-0000-000000000001".to_owned(),
+ "00000000-0000-0000-0000-000000000002".to_owned()
+ ]
+ );
+}
+
+async fn serve_once(response: &'static str) -> String {
+ use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind test listener");
+ let addr = listener.local_addr().expect("listener address");
+ tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.expect("accept");
+ let mut buf = vec![0u8; 4096];
+ let _ = socket.read(&mut buf).await;
+ let _ = socket.write_all(response.as_bytes()).await;
+ let _ = socket.shutdown().await;
+ });
+ format!("http://{addr}")
+}
diff --git a/crates/coding_agent_worker/src/webhook.rs b/crates/coding_agent_worker/src/trigger.rs
similarity index 52%
rename from crates/coding_agent_worker/src/webhook.rs
rename to crates/coding_agent_worker/src/trigger.rs
index abfdbc8bb2..5055c39cdc 100644
--- a/crates/coding_agent_worker/src/webhook.rs
+++ b/crates/coding_agent_worker/src/trigger.rs
@@ -1,27 +1,18 @@
-//! Signed webhook ingest: agent-trigger events delivered over HTTP, driving
-//! sessions the same way a human driving the API by hand would - create,
-//! dial, prompt.
+//! Translate agent-trigger broker events into the work this daemon serves.
//!
-//! Non-2xx responses make the deliverer redeliver, so failures are only
-//! signalled for work worth retrying: an undecodable payload or an event
-//! this daemon has nothing to do for is acked and dropped.
-
-use std::sync::Arc;
+//! Pure event vocabulary, split out so it can be tested without a live stream
+//! or harness - the same shape as the harness service's own Kafka inbound.
use agent_session::domain::model::AgentSessionId;
use agent_trigger::domain::broker_events::{
- AgentTriggerTopicEvent, ExistingAgentSessionEvent, NewAgentSessionEvent,
+ AgentTriggerEventName, AgentTriggerTopicEvent, ExistingAgentSessionEvent, NewAgentSessionEvent,
};
-use axum::Router;
-use axum::body::Bytes;
-use axum::extract::State;
-use axum::http::{HeaderMap, StatusCode};
-use axum::routing::post;
use bot_id::BotId;
use macro_event_broker::Event;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
-use webhook_signature::{SIGNATURE_HEADER, TIMESTAMP_HEADER};
+use strum::IntoEnumIterator as _;
+use webhook::domain::models::WebhookFilter;
#[cfg(test)]
mod test;
@@ -65,7 +56,7 @@ pub enum TriggerWork {
}
/// Why an event yielded no work. Only for logging - none of these are
-/// errors, and the deliverer is acked either way.
+/// errors, and the stream is left open either way.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Skipped {
/// The sender is not a user, so there is nobody to act for.
@@ -113,81 +104,47 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Ski
}
}
-/// Executes translated work. The one capability the route needs, so tests
-/// can drive it without a live service or harness.
+/// Every event this daemon's stream asks for, scoped to the bound bots.
+///
+/// A name this daemon does not yet handle is still worth subscribing to -
+/// it arrives, is recognised as unsupported, and is skipped - which beats
+/// silently never being sent it.
+pub fn trigger_filters(bots: impl IntoIterator<Item = impl ToString>) -> Vec<WebhookFilter> {
+ let ids: Vec<String> = bots.into_iter().map(|bot| bot.to_string()).collect();
+ vec![WebhookFilter {
+ events: AgentTriggerEventName::iter()
+ .map(|event| event.to_string())
+ .collect(),
+ ids: Some(ids),
+ }]
+}
+
+/// Executes translated work. The one capability the stream listener needs,
+/// so tests can drive it without a live service or harness.
pub trait WorkExecutor: Send + Sync + 'static {
- /// Do one event's work; an error is worth a redelivery.
+ /// Do one event's work. SSE has no redelivery, so the listener logs a
+ /// failure and keeps the stream open.
fn execute(
&self,
work: TriggerWork,
) -> impl Future<Output = Result<(), crate::dispatch::DispatchError>> + Send;
}
-/// State for the events route.
-pub struct WebhookState<Executor> {
- /// Where translated work goes.
- pub executor: Executor,
- /// The webhook's signing secret, shared with the deliverer. Behind a lock
- /// because feed reconciliation replaces the feed - and its secret - when
- /// the bound-agent set changes.
- pub signing_secret: std::sync::Arc<std::sync::RwLock<String>>,
-}
-
-/// Build the router serving `POST /macro-events`.
-pub fn webhook_router<Executor: WorkExecutor>(state: WebhookState<Executor>) -> Router {
- Router::new()
- .route("/macro-events", post(ingest::<Executor>))
- .with_state(Arc::new(state))
-}
-
-/// Verify, decode, translate, execute.
-async fn ingest<Executor: WorkExecutor>(
- State(state): State<Arc<WebhookState<Executor>>>,
- headers: HeaderMap,
- body: Bytes,
-) -> StatusCode {
- let header = |name: &str| headers.get(name).and_then(|value| value.to_str().ok());
- let (Some(timestamp), Some(signature)) = (header(TIMESTAMP_HEADER), header(SIGNATURE_HEADER))
- else {
- return StatusCode::UNAUTHORIZED;
- };
- let signing_secret = state
- .signing_secret
- .read()
- .expect("signing secret lock")
- .clone();
- if !webhook_signature::verify(&signing_secret, timestamp, &body, signature) {
- return StatusCode::UNAUTHORIZED;
- }
-
- let Ok(event) = serde_json::from_slice::<Event<AgentTriggerTopicEvent>>(&body) else {
- // The webhook service's validation probe is the everyday case here:
- // signed, not a trigger event, and answered 200 - which is exactly
- // what marks the feed valid. Anything else undecodable will not
- // improve on redelivery either: ack and drop.
- if serde_json::from_slice::<serde_json::Value>(&body)
- .ok()
- .and_then(|value| value.get("event").cloned())
- .is_some_and(|name| name == "webhook.validation.test")
- {
- tracing::info!("acknowledged the feed validation probe");
- } else {
- tracing::warn!("undecodable agent-trigger webhook payload; acked");
- }
- return StatusCode::OK;
- };
+/// The envelope the stream delivers: the broker's, carrying a trigger event.
+pub type TriggerEvent = Event<AgentTriggerTopicEvent>;
+/// Translate one delivered event and execute it. Skippable events are
+/// ignored; an execute failure is returned so the caller can log it.
+#[tracing::instrument(skip(executor, event), fields(event_id = %event.event_id), err)]
+pub async fn handle_event<Executor: WorkExecutor>(
+ event: TriggerEvent,
+ executor: &Executor,
+) -> Result<(), crate::dispatch::DispatchError> {
match trigger_to_work(event.event) {
- Ok(work) => match state.executor.execute(work).await {
- Ok(()) => StatusCode::OK,
- Err(error) => {
- tracing::error!(error = ?error, "agent-trigger webhook work failed");
- StatusCode::INTERNAL_SERVER_ERROR
- }
- },
+ Ok(work) => executor.execute(work).await,
Err(skipped) => {
- tracing::debug!(?skipped, "agent-trigger webhook event skipped");
- StatusCode::OK
+ tracing::debug!(?skipped, "agent-trigger stream event skipped");
+ Ok(())
}
}
}
diff --git a/crates/coding_agent_worker/src/webhook/test.rs b/crates/coding_agent_worker/src/trigger/test.rs
similarity index 61%
rename from crates/coding_agent_worker/src/webhook/test.rs
rename to crates/coding_agent_worker/src/trigger/test.rs
index 441f774e41..bc3b126aa5 100644
--- a/crates/coding_agent_worker/src/webhook/test.rs
+++ b/crates/coding_agent_worker/src/trigger/test.rs
@@ -6,8 +6,6 @@ use channels::domain::models::ChannelType;
use chrono::Utc;
use std::sync::Mutex;
-const SECRET: &str = "signing-secret";
-
fn test_session() -> AgentSessionId {
AgentSessionId::new_from_uuid(Uuid::from_u128(0xA))
}
@@ -91,6 +89,24 @@ fn a_bots_own_message_is_skipped() {
assert_eq!(trigger_to_work(event), Err(Skipped::NotFromUser));
}
+#[test]
+fn trigger_filters_name_this_bot_and_every_trigger_event() {
+ let filters = trigger_filters([bot_id::BotId::TEST_A]);
+ assert_eq!(filters.len(), 1);
+ let filter = &filters[0];
+ assert_eq!(
+ filter.events,
+ vec![
+ "agent_trigger.new".to_owned(),
+ "agent_trigger.existing".to_owned()
+ ]
+ );
+ assert_eq!(
+ filter.ids.as_deref(),
+ Some([bot_id::BotId::TEST_A.to_string()].as_slice())
+ );
+}
+
/// Records executed work instead of doing anything.
#[derive(Default)]
struct RecordingExecutor {
@@ -113,83 +129,44 @@ impl WorkExecutor for std::sync::Arc<RecordingExecutor> {
}
}
-fn delivery(event: &AgentTriggerTopicEvent, secret: &str) -> (HeaderMap, Bytes) {
- let body = serde_json::to_vec(&Event::new(event.clone())).unwrap();
- let timestamp = "1755188000";
- let signature = webhook_signature::sign(secret, timestamp, &body).unwrap();
- let mut headers = HeaderMap::new();
- headers.insert(TIMESTAMP_HEADER, timestamp.parse().unwrap());
- headers.insert(SIGNATURE_HEADER, signature.parse().unwrap());
- (headers, Bytes::from(body))
-}
-
-fn state(
- executor: std::sync::Arc<RecordingExecutor>,
-) -> Arc<WebhookState<std::sync::Arc<RecordingExecutor>>> {
- Arc::new(WebhookState {
- executor,
- signing_secret: std::sync::Arc::new(std::sync::RwLock::new(SECRET.to_owned())),
- })
-}
-
#[tokio::test]
-async fn a_signed_mention_executes() {
+async fn a_mention_event_executes() {
let executor = std::sync::Arc::new(RecordingExecutor::default());
- let (headers, body) = delivery(&mention("fix it"), SECRET);
- let status = ingest(State(state(executor.clone())), headers, body).await;
+ handle_event(Event::new(mention("fix it")), &executor)
+ .await
+ .expect("a mention is work");
- assert_eq!(status, StatusCode::OK);
assert_eq!(executor.executed.lock().unwrap().len(), 1);
}
#[tokio::test]
-async fn a_bad_signature_is_rejected_before_anything_runs() {
- let executor = std::sync::Arc::new(RecordingExecutor::default());
- let (headers, body) = delivery(&mention("fix it"), "wrong-secret");
-
- let status = ingest(State(state(executor.clone())), headers, body).await;
-
- assert_eq!(status, StatusCode::UNAUTHORIZED);
- assert!(executor.executed.lock().unwrap().is_empty());
-}
-
-#[tokio::test]
-async fn missing_signature_headers_are_rejected() {
- let executor = std::sync::Arc::new(RecordingExecutor::default());
- let (_, body) = delivery(&mention("fix it"), SECRET);
-
- let status = ingest(State(state(executor.clone())), HeaderMap::new(), body).await;
-
- assert_eq!(status, StatusCode::UNAUTHORIZED);
- assert!(executor.executed.lock().unwrap().is_empty());
-}
-
-#[tokio::test]
-async fn an_undecodable_payload_is_acked_and_dropped() {
+async fn a_skipped_event_is_not_an_error() {
let executor = std::sync::Arc::new(RecordingExecutor::default());
- let body = Bytes::from_static(b"not json");
- let timestamp = "1755188000";
- let signature = webhook_signature::sign(SECRET, timestamp, &body).unwrap();
- let mut headers = HeaderMap::new();
- headers.insert(TIMESTAMP_HEADER, timestamp.parse().unwrap());
- headers.insert(SIGNATURE_HEADER, signature.parse().unwrap());
+ let mut event = mention("self talk");
+ if let AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(mentioned)) =
+ &mut event
+ {
+ mentioned.message.sender = ChannelSender::new_from_bot(bot_id::BotId::TEST_B);
+ }
- let status = ingest(State(state(executor.clone())), headers, body).await;
+ handle_event(Event::new(event), &executor)
+ .await
+ .expect("skipped events are not errors");
- assert_eq!(status, StatusCode::OK);
assert!(executor.executed.lock().unwrap().is_empty());
}
#[tokio::test]
-async fn failed_work_asks_for_redelivery() {
+async fn failed_work_is_returned() {
let executor = std::sync::Arc::new(RecordingExecutor {
fail: true,
..Default::default()
});
- let (headers, body) = delivery(&mention("fix it"), SECRET);
- let status = ingest(State(state(executor.clone())), headers, body).await;
-
- assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
+ assert!(
+ handle_event(Event::new(mention("fix it")), &executor)
+ .await
+ .is_err()
+ );
}
diff --git a/crates/coding_agent_worker/src/tui.rs b/crates/coding_agent_worker/src/tui.rs
index d1d4e35974..72e6dbd5e5 100644
--- a/crates/coding_agent_worker/src/tui.rs
+++ b/crates/coding_agent_worker/src/tui.rs
@@ -1,11 +1,10 @@
//! The macrod control panel: one process that serves and shows itself.
//!
-//! `macrod` runs the serving core (webhook receiver, feed reconciler,
-//! harness bridge) inside a terminal UI that shows what the server knows
-//! about this harness - its registration, the agents bound to it, their
-//! sessions, and the daemon's own logs - and drives its lifecycle: edit
-//! `macro.toml`, pair (or re-pair, restarting the core on the new
-//! credential), and retire the harness.
+//! `macrod` runs the serving core (SSE listener, harness bridge) inside a
+//! terminal UI that shows what the server knows about this harness - its
+//! registration, the agents bound to it, their sessions, and the daemon's
+//! own logs - and drives its lifecycle: edit `macro.toml`, pair (or re-pair,
+//! restarting the core on the new credential), and retire the harness.
mod api;
mod config_form;
@@ -23,7 +22,6 @@ use crate::config::Config;
use crate::daemon::Daemon;
use crate::outbound::credentials::{CredentialStore as _, FileCredentialStore, HarnessCredentials};
use crate::outbound::pairing::{ClaimStatus, PairingClient};
-use crate::outbound::registration;
use api::{HarnessSelfApi, Snapshot};
use config_form::{ConfigForm, FIELDS, FieldKind};
@@ -353,7 +351,7 @@ impl App {
let _ = std::fs::remove_file(crate::outbound::credentials::credentials_path(
&self.config_path,
));
- let _ = std::fs::remove_file(registration::state_path(&self.config_path));
+ let _ = std::fs::remove_file(self.config_path.with_extension("webhook-state.json"));
self.credentials = None;
self.snapshot = Snapshot::default();
self.ok("harness removed - press p to pair again");
diff --git a/crates/coding_agent_worker/src/tui/config_form.rs b/crates/coding_agent_worker/src/tui/config_form.rs
index 92d5d9c212..3719f0b2fd 100644
--- a/crates/coding_agent_worker/src/tui/config_form.rs
+++ b/crates/coding_agent_worker/src/tui/config_form.rs
@@ -30,8 +30,6 @@ pub enum FieldKind {
Text,
/// A string that may be absent; an empty edit removes the key.
OptionalText,
- /// An integer port.
- Port,
/// A string array, edited comma-separated.
List,
/// `private` / `team`, toggled rather than typed.
@@ -94,18 +92,6 @@ pub const FIELDS: &[Field] = &[
key: "web_url",
kind: FieldKind::OptionalText,
},
- Field {
- label: "Webhook port",
- section: "server",
- key: "port",
- kind: FieldKind::Port,
- },
- Field {
- label: "Webhook public URL",
- section: "server",
- key: "public_url",
- kind: FieldKind::Text,
- },
];
/// The config document being viewed and edited.
@@ -145,10 +131,6 @@ impl ConfigForm {
.join(", ")
})
.unwrap_or_default(),
- (FieldKind::Port, Some(Item::Value(value))) => value
- .as_integer()
- .map(|port| port.to_string())
- .unwrap_or_default(),
(FieldKind::Scope, item) => item.and_then(Item::as_str).unwrap_or("private").to_owned(),
(_, Some(Item::Value(value))) => value.as_str().unwrap_or_default().to_owned(),
_ => String::new(),
@@ -175,12 +157,6 @@ impl ConfigForm {
section[field.key] = value(input);
}
}
- FieldKind::Port => {
- let port: u16 = input
- .parse()
- .map_err(|_| format!("{} must be a port number", field.label))?;
- section[field.key] = value(i64::from(port));
- }
FieldKind::List => {
let mut array = toml_edit::Array::new();
for entry in input.split(',').map(str::trim).filter(|s| !s.is_empty()) {
diff --git a/crates/coding_agent_worker/src/tui/ui.rs b/crates/coding_agent_worker/src/tui/ui.rs
index 321d56ab3c..b43cc68f1f 100644
--- a/crates/coding_agent_worker/src/tui/ui.rs
+++ b/crates/coding_agent_worker/src/tui/ui.rs
@@ -65,10 +65,7 @@ fn render_header(frame: &mut Frame, app: &App, area: Rect) {
.unwrap_or_else(|| "macrod".to_owned());
let serving: Vec<Span> = if app.serving() {
- vec![
- Span::styled(" ⏵ serving ", Style::new().fg(OK)),
- Span::styled(format!(":{}", app.config.server.port), Style::new().fg(DIM)),
- ]
+ vec![Span::styled(" ⏵ serving SSE", Style::new().fg(OK))]
} else if app.paired() {
vec![Span::styled(" ⏸ daemon stopped", Style::new().fg(ERR))]
} else {
diff --git a/crates/kafka_util/src/lib.rs b/crates/kafka_util/src/lib.rs
index e7acd2d9d7..e7e07ed202 100644
--- a/crates/kafka_util/src/lib.rs
+++ b/crates/kafka_util/src/lib.rs
@@ -176,15 +176,6 @@ pub enum InitialOffset {
Latest,
}
-impl InitialOffset {
- fn as_kafka_offset(self) -> Offset {
- match self {
- Self::Earliest => Offset::Beginning,
- Self::Latest => Offset::End,
- }
- }
-}
-
/// Shared Kafka consumer with environment-aware transport and type-safe group behavior.
///
/// Consumers parameterized by a [`GroupName`] may subscribe and commit offsets.
@@ -277,10 +268,20 @@ fn create_producer_from_env(
})
}
+/// Polls the consumer once with a no-op waker so OAUTHBEARER installs its
+/// initial token before a synchronous broker request (metadata, list offsets)
+/// needs a connection.
+fn prime_oauth_token<C: ConsumerContext + 'static>(consumer: &StreamConsumer<C>) {
+ let mut recv = std::pin::pin!(consumer.recv());
+ let waker = std::task::Waker::noop();
+ let mut context = std::task::Context::from_waker(waker);
+ let _ = std::future::Future::poll(recv.as_mut(), &mut context);
+}
+
fn build_assignment<C, T>(
consumer: &T,
topics: &[&str],
- initial_offset: InitialOffset,
+ offset: Offset,
metadata_timeout: Duration,
) -> KafkaResult<TopicPartitionList>
where
@@ -319,11 +320,7 @@ where
if let Some(error) = partition.error() {
return Err(KafkaError::MetadataFetch(error.into()));
}
- assignment.add_partition_offset(
- topic,
- partition.id(),
- initial_offset.as_kafka_offset(),
- )?;
+ assignment.add_partition_offset(topic, partition.id(), offset)?;
}
}
@@ -417,8 +414,8 @@ impl KafkaEventConsumer<Ungrouped> {
/// Manually assigns every current partition of `topics` at `initial_offset`.
///
/// Manual assignment does not join a consumer group, persist offsets, or
- /// automatically discover partitions added after this call. Callers that
- /// support partition-count changes must refresh the assignment themselves.
+ /// automatically discover partitions added after this call. Reconnect to
+ /// discover partition-count changes.
pub fn assign_topics(
&self,
topics: &[&str],
@@ -426,19 +423,12 @@ impl KafkaEventConsumer<Ungrouped> {
metadata_timeout: Duration,
) -> KafkaResult<()> {
either::for_both!(&self.consumer.0, consumer => {
- // OAUTHBEARER requires polling once to install the initial token
- // before a synchronous metadata request can connect to a broker.
- let mut recv = std::pin::pin!(consumer.recv());
- let waker = std::task::Waker::noop();
- let mut context = std::task::Context::from_waker(waker);
- let _ = std::future::Future::poll(recv.as_mut(), &mut context);
-
- let assignment = build_assignment(
- consumer,
- topics,
- initial_offset,
- metadata_timeout,
- )?;
+ prime_oauth_token(consumer);
+ let offset = match initial_offset {
+ InitialOffset::Earliest => Offset::Beginning,
+ InitialOffset::Latest => Offset::End,
+ };
+ let assignment = build_assignment(consumer, topics, offset, metadata_timeout)?;
consumer.assign(&assignment)
})
}
diff --git a/crates/kafka_util/src/test.rs b/crates/kafka_util/src/test.rs
index fe85196334..1dc2d8eaa0 100644
--- a/crates/kafka_util/src/test.rs
+++ b/crates/kafka_util/src/test.rs
@@ -45,9 +45,3 @@ fn ungrouped_config_uses_unique_internal_groups_without_offset_storage() {
assert_eq!(first.get("enable.auto.offset.store"), Some("false"));
assert_eq!(first.get("auto.offset.reset"), None);
}
-
-#[test]
-fn ungrouped_initial_offsets_are_explicit() {
- assert_eq!(InitialOffset::Earliest.as_kafka_offset(), Offset::Beginning);
- assert_eq!(InitialOffset::Latest.as_kafka_offset(), Offset::End);
-}
diff --git a/crates/webhook/Cargo.toml b/crates/webhook/Cargo.toml
index 6f57624dd5..ea197d345d 100644
--- a/crates/webhook/Cargo.toml
+++ b/crates/webhook/Cargo.toml
@@ -13,7 +13,7 @@ consumer = [
"ingestion",
"macro_event_broker/outbound",
]
-default = ["consumer", "inbound", "outbound", "ports"]
+default = ["consumer", "inbound", "outbound", "ports", "stream"]
inbound = [
"dep:axum",
"dep:axum-extra",
@@ -50,6 +50,15 @@ outbound = [
"ports",
]
ports = ["dep:serde_json", "dep:url"]
+stream = [
+ "dep:futures",
+ "dep:kafka_util",
+ "dep:tokio",
+ "dep:uuid",
+ "ingestion",
+ "inbound",
+ "macro_event_broker/outbound",
+]
worker = ["dep:tokio", "ports"]
[dependencies]
@@ -83,8 +92,9 @@ serde_json = { workspace = true, optional = true }
webhook_signature = { path = "../webhook_signature", optional = true }
sqlx = { workspace = true, optional = true }
sqs_client = { path = "../sqs_client", default-features = false, optional = true }
+strum = { workspace = true }
thiserror = { workspace = true }
-tokio = { workspace = true, features = ["macros", "time"], optional = true }
+tokio = { workspace = true, features = ["macros", "sync", "time"], optional = true }
tokio-retry = { workspace = true, optional = true }
tracing = { workspace = true }
url = { workspace = true, optional = true }
diff --git a/crates/webhook/src/domain/ingestion.rs b/crates/webhook/src/domain/ingestion.rs
index 5c8147ad6f..b0cce0b670 100644
--- a/crates/webhook/src/domain/ingestion.rs
+++ b/crates/webhook/src/domain/ingestion.rs
@@ -5,6 +5,8 @@
//! separate from `WebhookService`, which is the CRUD surface for webhook
//! creation and edits.
+#[cfg(feature = "stream")]
+pub(crate) mod stream;
#[cfg(test)]
mod test;
@@ -235,7 +237,7 @@ where
}
}
-fn normalized_document_event(
+pub(crate) fn normalized_document_event(
event: &Event<DocumentTopicEvent>,
) -> Result<Option<NormalizedWebhookEvent>, WebhookEventIngestionError> {
let (event_name, entity_id) = match &event.event {
@@ -269,7 +271,7 @@ fn normalized_document_event(
)))
}
-fn normalized_channel_event(
+pub(crate) fn normalized_channel_event(
event: &Event<ChannelTopicEvent>,
) -> Result<NormalizedWebhookEvent, WebhookEventIngestionError> {
let (event_name, channel_id) = match &event.event {
@@ -312,7 +314,7 @@ fn normalized_channel_event(
))
}
-fn normalized_webhook_event(
+pub(crate) fn normalized_webhook_event(
event: &Event<WebhookTopicEvent>,
) -> Result<(NormalizedWebhookEvent, String), WebhookEventIngestionError> {
let (event_name, webhook_id, workspace_id) = match &event.event {
@@ -381,9 +383,9 @@ fn normalized_event(
///
/// Not the bot the event names: that is what a subscriber filters on, and a
/// bot is not an entity anyone holds access to.
-struct TriggerAudience {
- entity_id: String,
- entity_type: EntityType,
+pub(crate) struct TriggerAudience {
+ pub(crate) entity_id: String,
+ pub(crate) entity_type: EntityType,
}
/// Normalize one agent-trigger event.
@@ -397,7 +399,7 @@ struct TriggerAudience {
/// own grants - its owner, and the channel it came from - so the session is
/// the authoritative audience, and whatever channel a later message happened
/// to land in is incidental to it.
-fn normalized_agent_trigger_event(
+pub(crate) fn normalized_agent_trigger_event(
event: &Event<AgentTriggerTopicEvent>,
) -> Result<(NormalizedWebhookEvent, TriggerAudience), WebhookEventIngestionError> {
use agent_trigger::domain::broker_events::{
diff --git a/crates/webhook/src/domain/ingestion/stream.rs b/crates/webhook/src/domain/ingestion/stream.rs
new file mode 100644
index 0000000000..aaa3e1d1fc
--- /dev/null
+++ b/crates/webhook/src/domain/ingestion/stream.rs
@@ -0,0 +1,65 @@
+//! Stream-candidate adapters over shared webhook event normalization.
+
+use super::{
+ WebhookEventIngestionError, normalized_agent_trigger_event, normalized_channel_event,
+ normalized_document_event, normalized_webhook_event,
+};
+use crate::domain::{
+ events::WebhookTopicEvent,
+ stream::{StreamAudience, StreamCandidateEvent},
+};
+use agent_trigger::domain::broker_events::AgentTriggerTopicEvent;
+use channels::domain::broker_events::ChannelTopicEvent;
+use documents::domain::events::DocumentTopicEvent;
+use entity_access::domain::models::EntityType;
+use macro_event_broker::Event;
+
+pub(crate) fn document_stream_candidate(
+ event: &Event<DocumentTopicEvent>,
+) -> Result<Option<StreamCandidateEvent>, WebhookEventIngestionError> {
+ Ok(
+ normalized_document_event(event)?.map(|normalized| StreamCandidateEvent {
+ audience: StreamAudience::Entity {
+ entity_id: normalized.entity_id.clone(),
+ entity_type: EntityType::Document,
+ },
+ event: normalized,
+ }),
+ )
+}
+
+pub(crate) fn channel_stream_candidate(
+ event: &Event<ChannelTopicEvent>,
+) -> Result<StreamCandidateEvent, WebhookEventIngestionError> {
+ let normalized = normalized_channel_event(event)?;
+ Ok(StreamCandidateEvent {
+ audience: StreamAudience::Entity {
+ entity_id: normalized.entity_id.clone(),
+ entity_type: EntityType::Channel,
+ },
+ event: normalized,
+ })
+}
+
+pub(crate) fn webhook_stream_candidate(
+ event: &Event<WebhookTopicEvent>,
+) -> Result<StreamCandidateEvent, WebhookEventIngestionError> {
+ let (normalized, workspace_id) = normalized_webhook_event(event)?;
+ Ok(StreamCandidateEvent {
+ audience: StreamAudience::Workspace { workspace_id },
+ event: normalized,
+ })
+}
+
+pub(crate) fn agent_trigger_stream_candidate(
+ event: &Event<AgentTriggerTopicEvent>,
+) -> Result<StreamCandidateEvent, WebhookEventIngestionError> {
+ let (normalized, audience) = normalized_agent_trigger_event(event)?;
+ Ok(StreamCandidateEvent {
+ audience: StreamAudience::Entity {
+ entity_id: audience.entity_id,
+ entity_type: audience.entity_type,
+ },
+ event: normalized,
+ })
+}
diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rs
index 56203bcfcd..fcf6513fb1 100644
--- a/crates/webhook/src/domain/ingestion/test.rs
+++ b/crates/webhook/src/domain/ingestion/test.rs
@@ -236,6 +236,13 @@ impl WebhookWorkspaceResolver for MockRepository {
}
Ok(state.resolved_workspace_ids.clone())
}
+
+ async fn get_user_team_workspace_id(
+ &self,
+ _user_id: MacroUserIdStr<'static>,
+ ) -> Result<Option<String>, Self::Err> {
+ Ok(None)
+ }
}
impl WebhookRepo for MockRepository {
diff --git a/crates/webhook/src/domain/mod.rs b/crates/webhook/src/domain/mod.rs
index 9fe3b95b26..de741aa3be 100644
--- a/crates/webhook/src/domain/mod.rs
+++ b/crates/webhook/src/domain/mod.rs
@@ -18,3 +18,6 @@ pub mod ports;
#[cfg(feature = "ports")]
/// Webhook service implementation.
pub mod service;
+#[cfg(feature = "stream")]
+/// Live webhook event streaming service.
+pub mod stream;
diff --git a/crates/webhook/src/domain/models.rs b/crates/webhook/src/domain/models.rs
index e6fcb310c7..12fb4d733e 100644
--- a/crates/webhook/src/domain/models.rs
+++ b/crates/webhook/src/domain/models.rs
@@ -277,6 +277,17 @@ pub struct WebhookFilter {
pub ids: Option<Vec<String>>,
}
+impl WebhookFilter {
+ /// Return whether this filter accepts an event name and entity id.
+ pub fn accepts(&self, event_name: &str, entity_id: &str) -> bool {
+ self.events.iter().any(|event| event == event_name)
+ && self
+ .ids
+ .as_ref()
+ .is_none_or(|ids| ids.iter().any(|id| id == entity_id))
+ }
+}
+
/// Collection of webhook filters used to decide delivery eligibility.
pub type WebhookFilters = Vec<WebhookFilter>;
@@ -319,10 +330,14 @@ impl std::str::FromStr for WebhookStatus {
/// Scope that owns a newly-created webhook.
///
-/// Clients serialize this, so both derives are used.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+/// Clients serialize this, so both derives are used. `Display`/`FromStr`
+/// spell the same names as serde, for query strings and config values.
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
+)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
pub enum WebhookScope {
/// The authenticated user's personal workspace.
User,
diff --git a/crates/webhook/src/domain/models_test.rs b/crates/webhook/src/domain/models_test.rs
index 126f475b38..baf9f841af 100644
--- a/crates/webhook/src/domain/models_test.rs
+++ b/crates/webhook/src/domain/models_test.rs
@@ -2,11 +2,21 @@
use super::models::{
NormalizedWebhookEvent, WEBHOOK_EVENT_QUEUE_MESSAGE_VERSION, WebhookEventQueueMessage,
};
-use super::models::{WebhookFilter, WebhookFilters};
+use super::models::{WebhookFilter, WebhookFilters, WebhookScope};
#[cfg(feature = "ports")]
use chrono::{DateTime, Utc};
use serde_json::json;
+#[test]
+fn webhook_scope_strum_names_match_serde() {
+ for scope in [WebhookScope::User, WebhookScope::Team] {
+ let serde_name = serde_json::to_value(scope).unwrap();
+ assert_eq!(serde_name, json!(scope.to_string()));
+ assert_eq!(scope.to_string().parse::<WebhookScope>().unwrap(), scope);
+ }
+ assert!("workspace".parse::<WebhookScope>().is_err());
+}
+
#[test]
fn deserializes_filter_with_events_and_ids() {
let filters: WebhookFilters =
diff --git a/crates/webhook/src/domain/ports.rs b/crates/webhook/src/domain/ports.rs
index 1f24c856bf..724b45a755 100644
--- a/crates/webhook/src/domain/ports.rs
+++ b/crates/webhook/src/domain/ports.rs
@@ -96,6 +96,13 @@ pub trait WebhookWorkspaceResolver: Clone + Send + Sync + 'static {
&self,
people: Vec<MacroUserIdStr<'static>>,
) -> impl Future<Output = Result<Vec<String>, Self::Err>> + Send;
+
+ /// The caller's team workspace, matching persisted-webhook create/list:
+ /// highest `team_role`, one team.
+ fn get_user_team_workspace_id(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;
}
/// Port for enqueueing one normalized event for one matched webhook.
diff --git a/crates/webhook/src/domain/service.rs b/crates/webhook/src/domain/service.rs
index dc25617ad4..8523c120d9 100644
--- a/crates/webhook/src/domain/service.rs
+++ b/crates/webhook/src/domain/service.rs
@@ -190,7 +190,9 @@ fn validate_filter_ids(ids: &[String]) -> Result<(), WebhookError> {
Ok(())
}
-fn validate_filters(filters: &WebhookFilters) -> Result<(), WebhookError> {
+/// Validate a filter set for persistence or streaming: non-empty, within the
+/// per-list and per-value size caps, no blank entries.
+pub(crate) fn validate_filters(filters: &WebhookFilters) -> Result<(), WebhookError> {
if filters.is_empty() {
return Err(WebhookError::BadRequest(
"filters must be a non-empty array".to_string(),
diff --git a/crates/webhook/src/domain/stream.rs b/crates/webhook/src/domain/stream.rs
new file mode 100644
index 0000000000..d17c20d62f
--- /dev/null
+++ b/crates/webhook/src/domain/stream.rs
@@ -0,0 +1,294 @@
+//! Live webhook event streaming: broker events in, per-subscriber SSE out.
+//!
+//! `WebhookEventStreamService` is the inbound port driven by the SSE handler
+//! in `crate::inbound::stream_router`. Unlike ingestion — which matches
+//! persisted webhook subscriptions and enqueues durable deliveries — a stream
+//! is ephemeral: the caller supplies [`WebhookFilters`] on the request, each
+//! candidate event is checked against the same accessor set persisted
+//! webhooks fan out to (`get_users_by_entity`), and nothing is persisted.
+//! Team-scoped workspace events use `get_user_team_workspace_id` and
+//! re-check membership per event.
+//!
+//! Delivery is best-effort through a process-local broadcast channel. Slow or
+//! disconnected subscribers may miss events and must resync out of band when
+//! continuity matters.
+
+#[cfg(test)]
+mod test;
+
+use crate::domain::models::{NormalizedWebhookEvent, WebhookFilters, WebhookScope};
+use crate::domain::ports::WebhookWorkspaceResolver;
+use entity_access::domain::models::{AccessError, EntityType};
+use entity_access::domain::ports::EntityAccessService;
+use futures::StreamExt as _;
+use futures::stream::BoxStream;
+use macro_user_id::user_id::MacroUserIdStr;
+use std::future::Future;
+use std::sync::Arc;
+use tokio::sync::broadcast;
+
+/// Number of events retained for each active subscriber before it starts
+/// missing events.
+pub const WEBHOOK_STREAM_CHANNEL_CAPACITY: usize = 1_024;
+
+/// Whose access decides who may see one candidate event.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum StreamAudience {
+ /// Anyone with access to this entity.
+ Entity {
+ /// Entity whose access list gates the event.
+ entity_id: String,
+ /// Access entity type of `entity_id`.
+ entity_type: EntityType,
+ },
+ /// Anyone whose personal or team webhook workspace is this workspace.
+ Workspace {
+ /// Owning workspace id.
+ workspace_id: String,
+ },
+}
+
+/// One normalized broker event plus whose access gates it.
+#[derive(Debug, Clone)]
+pub struct StreamCandidateEvent {
+ /// Normalized event, matched against filters and delivered verbatim.
+ pub event: NormalizedWebhookEvent,
+ /// Whose access decides visibility.
+ pub audience: StreamAudience,
+}
+
+/// Webhook event stream error.
+#[derive(Debug, thiserror::Error)]
+pub enum WebhookStreamError {
+ /// The request's filters or scope are invalid.
+ #[error("{0}")]
+ BadRequest(String),
+ /// Adapter or infrastructure failure.
+ #[error("internal stream failure")]
+ Internal(rootcause::Report),
+}
+
+impl From<rootcause::Report> for WebhookStreamError {
+ fn from(report: rootcause::Report) -> Self {
+ Self::Internal(report)
+ }
+}
+
+/// Inbound port for opening filtered, access-checked event streams.
+pub trait WebhookEventStreamService: Clone + Send + Sync + 'static {
+ /// Open an event stream for `subscriber`.
+ ///
+ /// `scope` selects the subscriber's personal or current team workspace for
+ /// webhook lifecycle events. Entity events remain gated by entity access.
+ ///
+ fn open_stream(
+ &self,
+ subscriber: MacroUserIdStr<'static>,
+ scope: WebhookScope,
+ filters: WebhookFilters,
+ ) -> impl Future<Output = Result<BoxStream<'static, NormalizedWebhookEvent>, WebhookStreamError>>
+ + Send;
+}
+
+/// Webhook event stream service implementation.
+pub struct WebhookEventStreamServiceImpl<A, R> {
+ sender: broadcast::Sender<StreamCandidateEvent>,
+ entity_access_service: Arc<A>,
+ workspace_resolver: R,
+}
+
+impl<A, R: Clone> Clone for WebhookEventStreamServiceImpl<A, R> {
+ fn clone(&self) -> Self {
+ Self {
+ sender: self.sender.clone(),
+ entity_access_service: self.entity_access_service.clone(),
+ workspace_resolver: self.workspace_resolver.clone(),
+ }
+ }
+}
+
+impl<A, R> WebhookEventStreamServiceImpl<A, R> {
+ /// Create a webhook event stream service.
+ pub fn new(
+ sender: broadcast::Sender<StreamCandidateEvent>,
+ entity_access_service: Arc<A>,
+ workspace_resolver: R,
+ ) -> Self {
+ Self {
+ sender,
+ entity_access_service,
+ workspace_resolver,
+ }
+ }
+}
+
+/// Owned per-stream state advanced by the unfold loop.
+struct StreamState<A, R> {
+ receiver: broadcast::Receiver<StreamCandidateEvent>,
+ entity_access_service: Arc<A>,
+ workspace_resolver: R,
+ subscriber: MacroUserIdStr<'static>,
+ scope: WebhookScope,
+ filters: WebhookFilters,
+}
+
+impl<A, R> StreamState<A, R>
+where
+ A: EntityAccessService,
+ R: WebhookWorkspaceResolver,
+{
+ /// The workspace this stream currently represents for webhook.* events.
+ ///
+ /// Re-resolved per event so a revoked team membership cannot keep
+ /// receiving workspace lifecycle payloads on a held connection.
+ async fn scoped_workspace_id(&self) -> Result<Option<String>, rootcause::Report> {
+ match self.scope {
+ WebhookScope::User => Ok(Some(self.subscriber.as_ref().to_string())),
+ WebhookScope::Team => self
+ .workspace_resolver
+ .get_user_team_workspace_id(self.subscriber.clone())
+ .await
+ .map_err(|error| {
+ let error: anyhow::Error = error.into();
+ rootcause::report!("failed to resolve subscriber team workspace: {error:?}")
+ }),
+ }
+ }
+
+ /// Whether the subscriber may see an event with this audience.
+ async fn subscriber_in_audience(
+ &mut self,
+ audience: &StreamAudience,
+ ) -> Result<bool, rootcause::Report> {
+ match audience {
+ StreamAudience::Workspace { workspace_id } => {
+ let current = self.scoped_workspace_id().await?;
+ if self.scope == WebhookScope::Team && current.is_none() {
+ return Err(rootcause::report!(
+ "team-scoped stream lost team membership"
+ ));
+ }
+ Ok(current.as_deref() == Some(workspace_id.as_str()))
+ }
+ StreamAudience::Entity {
+ entity_id,
+ entity_type,
+ } => {
+ // Same accessor set persisted webhooks fan out to. PUBLIC/TEAM
+ // link-share is View via `get_access_level` but is not an
+ // accessor, so it must not open the live firehose.
+ match self
+ .entity_access_service
+ .get_users_by_entity(entity_id, *entity_type)
+ .await
+ {
+ Ok(accessors) => Ok(accessors
+ .iter()
+ .any(|user| user.as_ref() == self.subscriber.as_ref())),
+ // Agent sessions (and other non-fanout types) have no
+ // accessor expansion. Fall back to the subscriber's own
+ // access level so existing-session triggers still reach
+ // an authorized listener.
+ Err(AccessError::BadRequest(_)) => Ok(self
+ .entity_access_service
+ .get_access_level(Some(&self.subscriber), entity_id, *entity_type)
+ .await
+ .map_err(|error| rootcause::report!(error).into_dynamic())?
+ .is_some()),
+ Err(error) => Err(rootcause::report!(error).into_dynamic()),
+ }
+ }
+ }
+ }
+
+ /// Await the next event that matches the filters and passes access.
+ ///
+ /// Returns `None` when the channel closes or an access check fails.
+ async fn next_delivered(&mut self) -> Option<NormalizedWebhookEvent> {
+ loop {
+ let candidate = match self.receiver.recv().await {
+ Ok(candidate) => candidate,
+ Err(broadcast::error::RecvError::Lagged(skipped)) => {
+ tracing::warn!(skipped, "webhook event stream subscriber missed events");
+ continue;
+ }
+ Err(broadcast::error::RecvError::Closed) => {
+ return None;
+ }
+ };
+ if !self.filters.iter().any(|filter| {
+ filter.accepts(&candidate.event.event_name, &candidate.event.entity_id)
+ }) {
+ continue;
+ }
+ match self.subscriber_in_audience(&candidate.audience).await {
+ Ok(true) => return Some(candidate.event),
+ Ok(false) => continue,
+ Err(error) => {
+ tracing::error!(error = ?error, "webhook event stream access check failed; ending stream");
+ return None;
+ }
+ }
+ }
+ }
+}
+
+/// Reject filter sets a persisted webhook could not be created with.
+///
+/// Streams share the persisted-webhook validation rules exactly, so a filter
+/// set is either valid for both delivery mechanisms or neither.
+fn validate_filters(filters: &WebhookFilters) -> Result<(), WebhookStreamError> {
+ crate::domain::service::validate_filters(filters).map_err(|error| match error {
+ crate::domain::ports::WebhookError::BadRequest(message) => {
+ WebhookStreamError::BadRequest(message)
+ }
+ other => WebhookStreamError::BadRequest(other.to_string()),
+ })
+}
+
+impl<A, R> WebhookEventStreamService for WebhookEventStreamServiceImpl<A, R>
+where
+ A: EntityAccessService,
+ R: WebhookWorkspaceResolver,
+{
+ #[tracing::instrument(skip(self, filters), fields(filter_count = filters.len()))]
+ async fn open_stream(
+ &self,
+ subscriber: MacroUserIdStr<'static>,
+ scope: WebhookScope,
+ filters: WebhookFilters,
+ ) -> Result<BoxStream<'static, NormalizedWebhookEvent>, WebhookStreamError> {
+ validate_filters(&filters)?;
+
+ if scope == WebhookScope::Team {
+ let team_workspace_id = self
+ .workspace_resolver
+ .get_user_team_workspace_id(subscriber.clone())
+ .await
+ .map_err(|error| {
+ let error: anyhow::Error = error.into();
+ WebhookStreamError::Internal(rootcause::report!(
+ "failed to resolve subscriber team workspace: {error:?}"
+ ))
+ })?;
+ if team_workspace_id.is_none() {
+ return Err(WebhookStreamError::BadRequest(
+ "team scope requires the user to belong to a team".to_string(),
+ ));
+ }
+ }
+
+ let state = StreamState {
+ receiver: self.sender.subscribe(),
+ entity_access_service: self.entity_access_service.clone(),
+ workspace_resolver: self.workspace_resolver.clone(),
+ subscriber,
+ scope,
+ filters,
+ };
+ Ok(futures::stream::unfold(state, |mut state| async move {
+ state.next_delivered().await.map(|event| (event, state))
+ })
+ .boxed())
+ }
+}
diff --git a/crates/webhook/src/domain/stream/test.rs b/crates/webhook/src/domain/stream/test.rs
new file mode 100644
index 0000000000..f0371af109
--- /dev/null
+++ b/crates/webhook/src/domain/stream/test.rs
@@ -0,0 +1,536 @@
+use super::*;
+use crate::domain::models::WebhookFilter;
+use chrono::Utc;
+use entity_access::domain::models::{
+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EntityAccessReceipt,
+ EntityPermission, RequiredPermission, TeamRole, UserTeamInfo,
+};
+use futures::StreamExt as _;
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use std::sync::{Arc, Mutex};
+use tokio::sync::broadcast;
+use uuid::Uuid;
+
+const SUBSCRIBER_ID: &str = "macro|[email protected]";
+const DOCUMENT_ID: &str = "11111111-1111-1111-1111-111111111111";
+const OTHER_DOCUMENT_ID: &str = "22222222-2222-2222-2222-222222222222";
+const TEAM_WORKSPACE_ID: &str = "33333333-3333-3333-3333-333333333333";
+const FOREIGN_WORKSPACE_ID: &str = "44444444-4444-4444-4444-444444444444";
+
+fn subscriber() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(SUBSCRIBER_ID.to_string()).expect("valid user id")
+}
+
+fn normalized(event_name: &str, entity_id: &str) -> NormalizedWebhookEvent {
+ NormalizedWebhookEvent {
+ event_id: Uuid::now_v7().to_string(),
+ schema_version: 1,
+ event_name: event_name.to_string(),
+ entity_type: "document".to_string(),
+ entity_id: entity_id.to_string(),
+ ordering_key: entity_id.to_string(),
+ occurred_at: Utc::now(),
+ broker_envelope: serde_json::json!({ "event_type": event_name }),
+ }
+}
+
+fn document_candidate(event_name: &str, document_id: &str) -> StreamCandidateEvent {
+ StreamCandidateEvent {
+ event: normalized(event_name, document_id),
+ audience: StreamAudience::Entity {
+ entity_id: document_id.to_string(),
+ entity_type: EntityType::Document,
+ },
+ }
+}
+
+fn workspace_candidate(event_name: &str, workspace_id: &str) -> StreamCandidateEvent {
+ let mut candidate = document_candidate(event_name, "wh_test");
+ candidate.audience = StreamAudience::Workspace {
+ workspace_id: workspace_id.to_string(),
+ };
+ candidate
+}
+
+fn filter(events: &[&str]) -> WebhookFilters {
+ vec![WebhookFilter {
+ events: events.iter().map(|event| event.to_string()).collect(),
+ ids: None,
+ }]
+}
+
+/// Access service granting explicit accessor membership to a fixed entity id set.
+#[derive(Clone)]
+struct FakeAccessService {
+ accessor_entity_ids: Vec<String>,
+ /// Entity ids `get_access_level` would treat as View (e.g. PUBLIC link-share).
+ link_share_entity_ids: Vec<String>,
+ users_by_entity_calls: Arc<Mutex<usize>>,
+ access_level_calls: Arc<Mutex<usize>>,
+}
+
+impl FakeAccessService {
+ fn allowing(entity_ids: &[&str]) -> Self {
+ Self {
+ accessor_entity_ids: entity_ids.iter().map(|id| id.to_string()).collect(),
+ link_share_entity_ids: Vec::new(),
+ users_by_entity_calls: Arc::default(),
+ access_level_calls: Arc::default(),
+ }
+ }
+
+ fn link_share_only(entity_ids: &[&str]) -> Self {
+ Self {
+ accessor_entity_ids: Vec::new(),
+ link_share_entity_ids: entity_ids.iter().map(|id| id.to_string()).collect(),
+ users_by_entity_calls: Arc::default(),
+ access_level_calls: Arc::default(),
+ }
+ }
+}
+
+impl EntityAccessService for FakeAccessService {
+ async fn generate_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_org_id: Option<i64>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ unimplemented!("not used by webhook event streaming")
+ }
+
+ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ _bot_id: BotId,
+ _scope: BotAccessScope,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ unimplemented!("not used by webhook event streaming")
+ }
+
+ async fn get_access_level(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ *self.access_level_calls.lock().unwrap() += 1;
+ Ok(self
+ .accessor_entity_ids
+ .iter()
+ .chain(self.link_share_entity_ids.iter())
+ .any(|allowed| allowed == entity_id)
+ .then_some(AccessLevel::View))
+ }
+
+ async fn check_access(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ unimplemented!("not used by webhook event streaming")
+ }
+
+ async fn check_public_access(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ unimplemented!("not used by webhook event streaming")
+ }
+
+ async fn get_entity_permission(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _user_org_id: Option<i64>,
+ ) -> Result<EntityPermission, AccessError> {
+ unimplemented!("not used by webhook event streaming")
+ }
+
+ async fn get_crm_entity_permission_with_team(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<(EntityPermission, Uuid, TeamRole), AccessError> {
+ unimplemented!("not used by webhook event streaming")
+ }
+
+ async fn get_users_by_entity(
+ &self,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {
+ *self.users_by_entity_calls.lock().unwrap() += 1;
+ if entity_type == EntityType::AgentSession {
+ return Err(AccessError::BadRequest(
+ "get_users_by_entity does not support this entity type",
+ ));
+ }
+ if self
+ .accessor_entity_ids
+ .iter()
+ .any(|allowed| allowed == entity_id)
+ {
+ Ok(vec![subscriber()])
+ } else {
+ Ok(vec![])
+ }
+ }
+
+ async fn get_call_channel(
+ &self,
+ _call_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ unimplemented!("not used by webhook event streaming")
+ }
+
+ async fn get_call_channel_by_channel_id(
+ &self,
+ _channel_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ unimplemented!("not used by webhook event streaming")
+ }
+
+ async fn get_user_team(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<UserTeamInfo>, AccessError> {
+ unimplemented!("not used by webhook event streaming")
+ }
+}
+
+#[derive(Clone)]
+struct FakeWorkspaceResolver {
+ /// Highest-role team, matching `get_user_team_workspace_id`.
+ team_workspace_id: Arc<Mutex<Option<String>>>,
+}
+
+impl FakeWorkspaceResolver {
+ fn with_team(team_workspace_id: Option<String>) -> Self {
+ Self {
+ team_workspace_id: Arc::new(Mutex::new(team_workspace_id)),
+ }
+ }
+}
+
+impl WebhookWorkspaceResolver for FakeWorkspaceResolver {
+ type Err = anyhow::Error;
+
+ async fn resolve_workspace_ids(
+ &self,
+ people: Vec<MacroUserIdStr<'static>>,
+ ) -> Result<Vec<String>, Self::Err> {
+ let mut ids: Vec<String> = people
+ .iter()
+ .map(|person| person.as_ref().to_string())
+ .collect();
+ if let Some(team) = self.team_workspace_id.lock().unwrap().clone() {
+ ids.push(team);
+ }
+ Ok(ids)
+ }
+
+ async fn get_user_team_workspace_id(
+ &self,
+ _user_id: MacroUserIdStr<'static>,
+ ) -> Result<Option<String>, Self::Err> {
+ Ok(self.team_workspace_id.lock().unwrap().clone())
+ }
+}
+
+type TestService = WebhookEventStreamServiceImpl<FakeAccessService, FakeWorkspaceResolver>;
+
+fn service(access: FakeAccessService) -> (TestService, broadcast::Sender<StreamCandidateEvent>) {
+ service_with_team(access, Some(TEAM_WORKSPACE_ID.to_string()))
+}
+
+fn service_with_team(
+ access: FakeAccessService,
+ team_workspace_id: Option<String>,
+) -> (TestService, broadcast::Sender<StreamCandidateEvent>) {
+ let (sender, _) = broadcast::channel(16);
+ let service = WebhookEventStreamServiceImpl::new(
+ sender.clone(),
+ Arc::new(access),
+ FakeWorkspaceResolver::with_team(team_workspace_id),
+ );
+ (service, sender)
+}
+
+#[test]
+fn filter_accepts_its_events_and_optional_entity_ids() {
+ let document_filter = WebhookFilter {
+ events: vec!["document.updated".to_string()],
+ ids: Some(vec![DOCUMENT_ID.to_string()]),
+ };
+ let channel_filter = WebhookFilter {
+ events: vec!["channel.message_posted".to_string()],
+ ids: None,
+ };
+
+ assert!(document_filter.accepts("document.updated", DOCUMENT_ID));
+ assert!(!document_filter.accepts("document.updated", OTHER_DOCUMENT_ID));
+ assert!(!document_filter.accepts("document.created", DOCUMENT_ID));
+ assert!(channel_filter.accepts("channel.message_posted", "any-channel-id"));
+}
+
+#[tokio::test]
+async fn open_stream_delivers_only_matching_accessible_events() {
+ let candidates = vec![
+ document_candidate("document.updated", DOCUMENT_ID),
+ // Filter matches but the subscriber has no access: skipped.
+ document_candidate("document.updated", OTHER_DOCUMENT_ID),
+ // Access would pass but the filter does not match: skipped.
+ document_candidate("document.created", DOCUMENT_ID),
+ workspace_candidate("document.updated", SUBSCRIBER_ID),
+ workspace_candidate("document.updated", TEAM_WORKSPACE_ID),
+ workspace_candidate("document.updated", FOREIGN_WORKSPACE_ID),
+ ];
+ let (service, sender) = service(FakeAccessService::allowing(&[DOCUMENT_ID]));
+
+ let stream = service
+ .open_stream(
+ subscriber(),
+ WebhookScope::Team,
+ filter(&["document.updated"]),
+ )
+ .await
+ .expect("stream opens");
+ for candidate in candidates {
+ sender.send(candidate).unwrap();
+ }
+ let delivered: Vec<NormalizedWebhookEvent> = stream.take(2).collect().await;
+
+ let delivered_entities: Vec<&str> = delivered
+ .iter()
+ .map(|event| event.entity_id.as_str())
+ .collect();
+ assert_eq!(delivered_entities, vec![DOCUMENT_ID, "wh_test"]);
+}
+
+#[tokio::test]
+async fn team_scope_requires_team_membership() {
+ let (service, _) = service_with_team(FakeAccessService::allowing(&[]), None);
+
+ let Err(error) = service
+ .open_stream(
+ subscriber(),
+ WebhookScope::Team,
+ filter(&["webhook.updated"]),
+ )
+ .await
+ else {
+ panic!("team scope without team membership must be rejected");
+ };
+
+ assert!(matches!(error, WebhookStreamError::BadRequest(_)));
+}
+
+#[tokio::test]
+async fn open_stream_checks_access_for_each_matching_event() {
+ let candidates = vec![
+ document_candidate("document.updated", DOCUMENT_ID),
+ document_candidate("document.updated", DOCUMENT_ID),
+ document_candidate("document.updated", DOCUMENT_ID),
+ ];
+ let access = FakeAccessService::allowing(&[DOCUMENT_ID]);
+ let call_count = access.users_by_entity_calls.clone();
+ let (service, sender) = service(access);
+
+ let stream = service
+ .open_stream(
+ subscriber(),
+ WebhookScope::Team,
+ filter(&["document.updated"]),
+ )
+ .await
+ .expect("stream opens");
+ for candidate in candidates {
+ sender.send(candidate).unwrap();
+ }
+ let delivered: Vec<NormalizedWebhookEvent> = stream.take(3).collect().await;
+
+ assert_eq!(delivered.len(), 3);
+ assert_eq!(*call_count.lock().unwrap(), 3);
+}
+
+#[tokio::test]
+async fn open_stream_rejects_empty_or_degenerate_filters() {
+ let (service, _) = service(FakeAccessService::allowing(&[]));
+
+ for filters in [
+ vec![],
+ vec![WebhookFilter {
+ events: vec![],
+ ids: None,
+ }],
+ vec![WebhookFilter {
+ events: vec![String::new()],
+ ids: None,
+ }],
+ vec![WebhookFilter {
+ events: vec!["document.updated".to_string()],
+ ids: Some(vec![]),
+ }],
+ ] {
+ let Err(error) = service
+ .open_stream(subscriber(), WebhookScope::Team, filters)
+ .await
+ else {
+ panic!("degenerate filters must be rejected");
+ };
+ assert!(matches!(error, WebhookStreamError::BadRequest(_)));
+ }
+}
+
+#[tokio::test]
+async fn lagged_stream_skips_missed_events_and_continues() {
+ let (sender, _) = broadcast::channel(2);
+ let service = WebhookEventStreamServiceImpl::new(
+ sender.clone(),
+ Arc::new(FakeAccessService::allowing(&[DOCUMENT_ID])),
+ FakeWorkspaceResolver::with_team(Some(TEAM_WORKSPACE_ID.to_string())),
+ );
+ let mut stream = service
+ .open_stream(
+ subscriber(),
+ WebhookScope::Team,
+ filter(&["document.updated"]),
+ )
+ .await
+ .expect("stream opens");
+
+ sender
+ .send(document_candidate("document.updated", DOCUMENT_ID))
+ .unwrap();
+ sender
+ .send(document_candidate("document.updated", DOCUMENT_ID))
+ .unwrap();
+ let latest = document_candidate("document.updated", DOCUMENT_ID);
+ let latest_id = latest.event.event_id.clone();
+ sender.send(latest).unwrap();
+
+ let delivered = stream.next().await.expect("stream continues after lag");
+ assert_ne!(delivered.event_id, latest_id);
+ assert_eq!(stream.next().await.unwrap().event_id, latest_id);
+}
+
+#[tokio::test]
+async fn open_stream_does_not_deliver_link_share_only_entities() {
+ let (service, sender) = service(FakeAccessService::link_share_only(&[DOCUMENT_ID]));
+
+ let stream = service
+ .open_stream(
+ subscriber(),
+ WebhookScope::User,
+ filter(&["document.updated"]),
+ )
+ .await
+ .expect("stream opens");
+ sender
+ .send(document_candidate("document.updated", DOCUMENT_ID))
+ .unwrap();
+ sender
+ .send(workspace_candidate("document.updated", SUBSCRIBER_ID))
+ .unwrap();
+
+ let delivered: Vec<NormalizedWebhookEvent> = stream.take(1).collect().await;
+ assert_eq!(
+ delivered
+ .iter()
+ .map(|event| event.entity_id.as_str())
+ .collect::<Vec<_>>(),
+ vec!["wh_test"]
+ );
+}
+
+#[tokio::test]
+async fn team_scope_uses_highest_role_team_not_first_resolved_workspace() {
+ // Highest-role team is FOREIGN; TEAM would sort first by team_id text.
+ let (service, sender) = service_with_team(
+ FakeAccessService::allowing(&[]),
+ Some(FOREIGN_WORKSPACE_ID.to_string()),
+ );
+
+ let stream = service
+ .open_stream(
+ subscriber(),
+ WebhookScope::Team,
+ filter(&["webhook.created"]),
+ )
+ .await
+ .expect("stream opens");
+ sender
+ .send(workspace_candidate("webhook.created", TEAM_WORKSPACE_ID))
+ .unwrap();
+ sender
+ .send(workspace_candidate("webhook.created", FOREIGN_WORKSPACE_ID))
+ .unwrap();
+
+ let delivered: Vec<NormalizedWebhookEvent> = stream.take(1).collect().await;
+ assert_eq!(delivered.len(), 1);
+}
+
+#[tokio::test]
+async fn team_membership_revocation_ends_the_stream() {
+ let resolver = FakeWorkspaceResolver::with_team(Some(TEAM_WORKSPACE_ID.to_string()));
+ let (sender, _) = broadcast::channel(16);
+ let service = WebhookEventStreamServiceImpl::new(
+ sender.clone(),
+ Arc::new(FakeAccessService::allowing(&[])),
+ resolver.clone(),
+ );
+ let mut stream = service
+ .open_stream(
+ subscriber(),
+ WebhookScope::Team,
+ filter(&["webhook.created"]),
+ )
+ .await
+ .expect("stream opens");
+
+ *resolver.team_workspace_id.lock().unwrap() = None;
+ sender
+ .send(workspace_candidate("webhook.created", TEAM_WORKSPACE_ID))
+ .unwrap();
+
+ assert!(stream.next().await.is_none());
+}
+
+#[tokio::test]
+async fn agent_session_events_fall_back_to_access_level() {
+ const SESSION_ID: &str = "55555555-5555-5555-5555-555555555555";
+ let access = FakeAccessService::allowing(&[SESSION_ID]);
+ let access_level_calls = access.access_level_calls.clone();
+ let (service, sender) = service(access);
+
+ let stream = service
+ .open_stream(
+ subscriber(),
+ WebhookScope::User,
+ filter(&["agent_trigger.existing"]),
+ )
+ .await
+ .expect("stream opens");
+ sender
+ .send(StreamCandidateEvent {
+ event: normalized("agent_trigger.existing", SESSION_ID),
+ audience: StreamAudience::Entity {
+ entity_id: SESSION_ID.to_string(),
+ entity_type: EntityType::AgentSession,
+ },
+ })
+ .unwrap();
+
+ let delivered: Vec<NormalizedWebhookEvent> = stream.take(1).collect().await;
+ assert_eq!(delivered[0].entity_id, SESSION_ID);
+ assert_eq!(*access_level_calls.lock().unwrap(), 1);
+}
diff --git a/crates/webhook/src/inbound/kafka_consumer.rs b/crates/webhook/src/inbound/kafka_consumer.rs
index d9793789da..a7f4cdeca1 100644
--- a/crates/webhook/src/inbound/kafka_consumer.rs
+++ b/crates/webhook/src/inbound/kafka_consumer.rs
@@ -21,14 +21,9 @@
#[cfg(test)]
mod test;
-use crate::domain::{
- events::WebhookMacroEvent,
- ingestion::{WebhookEventIngestionError, WebhookEventIngestionService},
-};
-use agent_trigger::domain::broker_events::AgentSessionMacroEvent;
+use crate::domain::ingestion::{WebhookEventIngestionError, WebhookEventIngestionService};
+use crate::topics::DeclaredMacroEvent;
use anyhow::Context as _;
-use channels::domain::broker_events::ChannelMacroEvent;
-use documents::domain::events::DocumentMacroEvent;
use kafka_util::{GroupName, KafkaEventConsumer};
use macro_event_broker::{
KafkaConsumerAdapter, MacroEvent as _, MacroEventCollection as _, MacroEventConsumerService,
@@ -51,13 +46,6 @@ type WebhookKafkaAdapter =
KafkaConsumerAdapter<WebhookEventIngestionConsumerGroup, DeclaredMacroEvent>;
type WebhookKafkaConsumer = MacroEventConsumerService<DeclaredMacroEvent, WebhookKafkaAdapter>;
-macro_event_broker::declare_topics!(
- DeclaredMacroEvent: DocumentMacroEvent,
- ChannelMacroEvent,
- WebhookMacroEvent,
- AgentSessionMacroEvent,
-);
-
/// Maximum in-process ingestion attempts per event before the consumer bails
/// out and lets a restart redeliver from the last committed offset.
const MAX_INGEST_ATTEMPTS: u32 = 5;
diff --git a/crates/webhook/src/inbound/kafka_consumer/test.rs b/crates/webhook/src/inbound/kafka_consumer/test.rs
index 6ae93d2a98..1762e37590 100644
--- a/crates/webhook/src/inbound/kafka_consumer/test.rs
+++ b/crates/webhook/src/inbound/kafka_consumer/test.rs
@@ -1,6 +1,6 @@
use super::*;
use crate::domain::{
- events::{WebhookDeletedMetadata, WebhookTopicEvent},
+ events::{WebhookDeletedMetadata, WebhookMacroEvent, WebhookTopicEvent},
ingestion::WebhookEventIngestionError,
};
use channel_sender::ChannelSender;
diff --git a/crates/webhook/src/inbound/kafka_stream_consumer.rs b/crates/webhook/src/inbound/kafka_stream_consumer.rs
new file mode 100644
index 0000000000..28d777eecb
--- /dev/null
+++ b/crates/webhook/src/inbound/kafka_stream_consumer.rs
@@ -0,0 +1,77 @@
+//! Process-level Kafka consumer feeding the local webhook stream channel.
+
+use crate::domain::ingestion::{
+ WebhookEventIngestionError,
+ stream::{
+ agent_trigger_stream_candidate, channel_stream_candidate, document_stream_candidate,
+ webhook_stream_candidate,
+ },
+};
+use crate::domain::stream::StreamCandidateEvent;
+use crate::topics::DeclaredMacroEvent;
+use kafka_util::{InitialOffset, KafkaEventConsumer, Ungrouped};
+use macro_event_broker::{KafkaConsumerAdapter, MacroEvent as _, MacroEventConsumerService};
+use std::time::Duration;
+use tokio::sync::broadcast;
+
+/// Time allowed for topic metadata lookup.
+const METADATA_TIMEOUT: Duration = Duration::from_secs(10);
+
+type WebhookStreamKafkaAdapter = KafkaConsumerAdapter<Ungrouped, DeclaredMacroEvent>;
+type WebhookStreamKafkaConsumer =
+ MacroEventConsumerService<DeclaredMacroEvent, WebhookStreamKafkaAdapter>;
+
+/// Consume broker events from now onward and publish normalized stream candidates.
+pub async fn run_webhook_stream_consumer(
+ brokers: &str,
+ sender: &broadcast::Sender<StreamCandidateEvent>,
+) -> Result<(), rootcause::Report> {
+ let consumer = KafkaEventConsumer::<Ungrouped>::from_env(brokers)
+ .map_err(|error| rootcause::report!(error))?;
+ let consumer =
+ WebhookStreamKafkaAdapter::new(consumer, InitialOffset::Latest, METADATA_TIMEOUT)?;
+ let consumer = WebhookStreamKafkaConsumer::new(consumer);
+
+ loop {
+ let message = consumer.recv().await?;
+ let decoded = match message.decode_payload() {
+ Ok(decoded) => decoded,
+ // Poison records must not wedge the process-level stream consumer.
+ Err(error) => {
+ tracing::warn!(error = ?error, "skipping undecodable broker event");
+ continue;
+ }
+ };
+ match candidate_from(&decoded) {
+ Ok(Some(candidate)) => {
+ // Having no active subscribers is expected; SSE delivery is best-effort.
+ let _ = sender.send(candidate);
+ }
+ Ok(None) => {}
+ Err(error) => {
+ tracing::warn!(error = ?error, "skipping non-streamable broker event");
+ }
+ }
+ }
+}
+
+/// Normalize one decoded broker event into a stream candidate.
+///
+/// `None` means the event shape is deliberately not exposed to subscribers,
+/// mirroring webhook ingestion's normalization.
+fn candidate_from(
+ decoded: &DeclaredMacroEvent,
+) -> Result<Option<StreamCandidateEvent>, WebhookEventIngestionError> {
+ match decoded {
+ DeclaredMacroEvent::DocumentMacroEvent(event) => document_stream_candidate(event.event()),
+ DeclaredMacroEvent::ChannelMacroEvent(event) => {
+ channel_stream_candidate(event.event()).map(Some)
+ }
+ DeclaredMacroEvent::WebhookMacroEvent(event) => {
+ webhook_stream_candidate(event.event()).map(Some)
+ }
+ DeclaredMacroEvent::AgentSessionMacroEvent(event) => {
+ agent_trigger_stream_candidate(event.event()).map(Some)
+ }
+ }
+}
diff --git a/crates/webhook/src/inbound/mod.rs b/crates/webhook/src/inbound/mod.rs
index 0fd89fda58..174e9df66e 100644
--- a/crates/webhook/src/inbound/mod.rs
+++ b/crates/webhook/src/inbound/mod.rs
@@ -6,5 +6,11 @@ pub mod axum_router;
#[cfg(feature = "consumer")]
pub mod kafka_consumer;
+#[cfg(feature = "stream")]
+pub mod kafka_stream_consumer;
+
+#[cfg(feature = "stream")]
+pub mod stream_router;
+
#[cfg(feature = "worker")]
pub mod worker;
diff --git a/crates/webhook/src/inbound/stream_router.rs b/crates/webhook/src/inbound/stream_router.rs
new file mode 100644
index 0000000000..e821c3837d
--- /dev/null
+++ b/crates/webhook/src/inbound/stream_router.rs
@@ -0,0 +1,184 @@
+//! Axum SSE router for live webhook event streaming.
+//!
+//! `GET /webhook/events/stream` holds a Server-Sent Events response open and
+//! delivers every broker event that matches the caller's filters and passes
+//! the caller's entity access. Each SSE event's `id` is the UUIDv7 broker
+//! event id and its `event` is the event name; the `data` is the same broker
+//! envelope persisted webhooks deliver. Delivery is best-effort: disconnected
+//! or slow clients can miss events and must resync out of band when needed.
+
+use crate::domain::models::{WebhookFilters, WebhookScope};
+use crate::domain::stream::{WebhookEventStreamService, WebhookStreamError};
+use axum::{
+ Json, Router,
+ extract::{FromRef, Query, State},
+ http::StatusCode,
+ response::{
+ IntoResponse, Response,
+ sse::{Event, KeepAlive, Sse},
+ },
+ routing::get,
+};
+use futures::{Stream, StreamExt as _};
+use macro_authorization::{
+ ActingUser, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+};
+use model_error_response::ErrorResponse;
+use std::convert::Infallible;
+use std::time::Duration;
+
+/// Interval between SSE comment keep-alives.
+///
+/// Must stay well under every load balancer idle timeout on the path.
+const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(20);
+
+/// State for the webhook event stream router.
+pub struct WebhookStreamRouterState<St, Auth> {
+ stream_service: St,
+ authorization_state: MacroAuthorizationState<Auth>,
+}
+
+impl<St: Clone, Auth> Clone for WebhookStreamRouterState<St, Auth> {
+ fn clone(&self) -> Self {
+ Self {
+ stream_service: self.stream_service.clone(),
+ authorization_state: self.authorization_state.clone(),
+ }
+ }
+}
+
+impl<St, Auth> WebhookStreamRouterState<St, Auth> {
+ /// Create webhook event stream router state.
+ pub fn new(stream_service: St, authorization_state: MacroAuthorizationState<Auth>) -> Self {
+ Self {
+ stream_service,
+ authorization_state,
+ }
+ }
+}
+
+impl<St, Auth> FromRef<WebhookStreamRouterState<St, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &WebhookStreamRouterState<St, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
+/// Create the webhook event stream router.
+pub fn webhook_stream_router<St, Auth, T>(state: WebhookStreamRouterState<St, Auth>) -> Router<T>
+where
+ St: WebhookEventStreamService,
+ Auth: MacroAuthorizationService,
+ T: Send + Sync + 'static,
+{
+ Router::new()
+ .route("/events/stream", get(stream_events::<St, Auth>))
+ .with_state(state)
+}
+
+/// Query parameters selecting the events a stream delivers.
+#[derive(Debug, serde::Deserialize, utoipa::IntoParams)]
+#[into_params(parameter_in = Query)]
+pub struct StreamEventsQuery {
+ /// Personal or team workspace whose webhook lifecycle events are delivered.
+ pub scope: WebhookScope,
+ /// URL-encoded JSON array of webhook filters, identical to the persisted
+ /// webhook `filters` field.
+ pub filters: Option<String>,
+}
+
+/// Parse the query's filters into the typed filter model.
+fn parse_filters(filters: Option<String>) -> Result<WebhookFilters, WebhookStreamHandlerError> {
+ let bad_request =
+ |message: String| WebhookStreamHandlerError(WebhookStreamError::BadRequest(message));
+
+ let Some(filters) = filters else {
+ return Err(bad_request("`filters` is required".to_string()));
+ };
+ serde_json::from_str(&filters)
+ .map_err(|error| bad_request(format!("invalid `filters` JSON: {error}")))
+}
+
+/// Stream matching broker events to the caller over Server-Sent Events.
+#[utoipa::path(
+ get,
+ path = "/webhook/events/stream",
+ params(StreamEventsQuery),
+ responses(
+ (status = 200, description = "Server-Sent Events stream of matching broker events", content_type = "text/event-stream", body = String),
+ (status = 400, description = "Bad request", body = ErrorResponse),
+ (status = 403, description = "Forbidden", body = ErrorResponse),
+ (status = 500, description = "Internal server error", body = ErrorResponse),
+ ),
+ tag = "webhook"
+)]
+pub async fn stream_events<St: WebhookEventStreamService, Auth: MacroAuthorizationService>(
+ State(state): State<WebhookStreamRouterState<St, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth, ActingUser>,
+ Query(query): Query<StreamEventsQuery>,
+) -> Result<
+ Sse<impl Stream<Item = Result<Event, Infallible>> + Send + 'static>,
+ WebhookStreamHandlerError,
+> {
+ let filters = parse_filters(query.filters)?;
+
+ let events = state
+ .stream_service
+ .open_stream(
+ authorization.authorization.user.macro_user_id,
+ query.scope,
+ filters,
+ )
+ .await?;
+
+ let events = events.filter_map(|event| async move {
+ match Event::default()
+ .id(&event.event_id)
+ .event(&event.event_name)
+ .json_data(&event.broker_envelope)
+ {
+ Ok(sse_event) => Some(Ok(sse_event)),
+ // A broker envelope is already-parsed JSON; failure here is a bug.
+ Err(error) => {
+ tracing::error!(error = ?error, event_id = %event.event_id, "failed to encode SSE event");
+ None
+ }
+ }
+ });
+
+ Ok(Sse::new(events).keep_alive(
+ KeepAlive::new()
+ .interval(KEEP_ALIVE_INTERVAL)
+ .text("keep-alive"),
+ ))
+}
+
+/// Webhook stream handler error.
+pub struct WebhookStreamHandlerError(WebhookStreamError);
+
+impl From<WebhookStreamError> for WebhookStreamHandlerError {
+ fn from(error: WebhookStreamError) -> Self {
+ Self(error)
+ }
+}
+
+impl IntoResponse for WebhookStreamHandlerError {
+ fn into_response(self) -> Response {
+ let status = match self.0 {
+ WebhookStreamError::BadRequest(_) => StatusCode::BAD_REQUEST,
+ WebhookStreamError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+ let message = if status == StatusCode::INTERNAL_SERVER_ERROR {
+ tracing::error!(error = ?self.0, "webhook stream handler error");
+ "internal server error".to_string()
+ } else {
+ self.0.to_string()
+ };
+ (
+ status,
+ Json(ErrorResponse {
+ message: message.into(),
+ }),
+ )
+ .into_response()
+ }
+}
diff --git a/crates/webhook/src/lib.rs b/crates/webhook/src/lib.rs
index b409b36db6..e04c7c9f15 100644
--- a/crates/webhook/src/lib.rs
+++ b/crates/webhook/src/lib.rs
@@ -6,6 +6,9 @@ pub mod domain;
#[cfg(any(feature = "inbound", feature = "consumer", feature = "worker"))]
/// HTTP, Kafka consumer, and queue worker adapters.
pub mod inbound;
-#[cfg(feature = "outbound")]
-/// Postgres and HTTP adapters.
+#[cfg(any(feature = "outbound", feature = "stream"))]
+/// Postgres, HTTP, and Kafka stream adapters.
pub mod outbound;
+#[cfg(any(feature = "consumer", feature = "stream"))]
+/// Broker topics shared by every webhook consumption path.
+pub mod topics;
diff --git a/crates/webhook/src/outbound.rs b/crates/webhook/src/outbound.rs
index 59044264f5..4a74d2a659 100644
--- a/crates/webhook/src/outbound.rs
+++ b/crates/webhook/src/outbound.rs
@@ -1,13 +1,23 @@
//! Outbound adapters.
+#[cfg(feature = "outbound")]
pub mod http_delivery;
+#[cfg(feature = "outbound")]
pub mod http_validator;
+#[cfg(feature = "outbound")]
pub mod pg_delivery_repository;
+#[cfg(feature = "outbound")]
pub mod pg_repository;
+#[cfg(feature = "outbound")]
pub mod sqs_queue;
+#[cfg(feature = "outbound")]
pub use http_delivery::ReqwestWebhookDeliveryClient;
+#[cfg(feature = "outbound")]
pub use http_validator::ReqwestWebhookValidationClient;
+#[cfg(feature = "outbound")]
pub use pg_delivery_repository::PgWebhookDeliveryRepository;
+#[cfg(feature = "outbound")]
pub use pg_repository::PgRepository;
+#[cfg(feature = "outbound")]
pub use sqs_queue::SqsWebhookQueue;
diff --git a/crates/webhook/src/outbound/pg_repository.rs b/crates/webhook/src/outbound/pg_repository.rs
index b6b2b2664b..c113e6526f 100644
--- a/crates/webhook/src/outbound/pg_repository.rs
+++ b/crates/webhook/src/outbound/pg_repository.rs
@@ -118,6 +118,26 @@ async fn fetch_webhook(pool: &PgPool, webhook_id: &str) -> Result<Option<Webhook
row.map(row_to_webhook).transpose()
}
+async fn fetch_user_team_workspace_id(
+ pool: &PgPool,
+ user_id: MacroUserIdStr<'static>,
+) -> Result<Option<String>, sqlx::Error> {
+ let team_id = sqlx::query_scalar!(
+ r#"
+ SELECT team_id
+ FROM team_user
+ WHERE user_id = $1
+ ORDER BY team_role DESC
+ LIMIT 1
+ "#,
+ user_id.as_ref()
+ )
+ .fetch_optional(pool)
+ .await?;
+
+ Ok(team_id.map(|id| id.to_string()))
+}
+
impl WebhookWorkspaceResolver for PgRepository {
type Err = sqlx::Error;
@@ -154,6 +174,14 @@ impl WebhookWorkspaceResolver for PgRepository {
workspace_ids.dedup();
Ok(workspace_ids)
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_user_team_workspace_id(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ) -> Result<Option<String>, Self::Err> {
+ fetch_user_team_workspace_id(&self.pool, user_id).await
+ }
}
impl WebhookRepo for PgRepository {
@@ -387,20 +415,6 @@ impl WebhookRepo for PgRepository {
&self,
user_id: MacroUserIdStr<'static>,
) -> Result<Option<String>, Self::Err> {
- let user_id = user_id.as_ref();
- let team_id = sqlx::query_scalar!(
- r#"
- SELECT team_id
- FROM team_user
- WHERE user_id = $1
- ORDER BY team_role DESC
- LIMIT 1
- "#,
- user_id
- )
- .fetch_optional(&self.pool)
- .await?;
-
- Ok(team_id.map(|id| id.to_string()))
+ fetch_user_team_workspace_id(&self.pool, user_id).await
}
}
diff --git a/crates/webhook/src/outbound/pg_repository_test.rs b/crates/webhook/src/outbound/pg_repository_test.rs
index 1d7b052877..fb93bc17d0 100644
--- a/crates/webhook/src/outbound/pg_repository_test.rs
+++ b/crates/webhook/src/outbound/pg_repository_test.rs
@@ -706,7 +706,11 @@ async fn get_user_team_workspace_id_returns_team_membership(pool: PgPool) -> any
let repo = PgRepository::new(pool);
assert_eq!(
- repo.get_user_team_workspace_id(user_id()).await?,
+ WebhookRepo::get_user_team_workspace_id(&repo, user_id()).await?,
+ Some(TEAM_ID.to_string())
+ );
+ assert_eq!(
+ WebhookWorkspaceResolver::get_user_team_workspace_id(&repo, user_id()).await?,
Some(TEAM_ID.to_string())
);
Ok(())
diff --git a/crates/webhook/src/topics.rs b/crates/webhook/src/topics.rs
new file mode 100644
index 0000000000..fe53a4c3e3
--- /dev/null
+++ b/crates/webhook/src/topics.rs
@@ -0,0 +1,18 @@
+//! The broker topics the webhook system subscribes to.
+//!
+//! One declaration shared by both consumption paths — the durable ingestion
+//! consumer (`inbound::kafka_consumer`) and the process-level SSE consumer
+//! (`inbound::kafka_stream_consumer`) — so the two can never drift onto
+//! different topic sets.
+
+use crate::domain::events::WebhookMacroEvent;
+use agent_trigger::domain::broker_events::AgentSessionMacroEvent;
+use channels::domain::broker_events::ChannelMacroEvent;
+use documents::domain::events::DocumentMacroEvent;
+
+macro_event_broker::declare_topics!(
+ DeclaredMacroEvent: DocumentMacroEvent,
+ ChannelMacroEvent,
+ WebhookMacroEvent,
+ AgentSessionMacroEvent,
+);
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index 905b23dc18..f5e0f3c780 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -130,16 +130,14 @@ await macro.channels
.send(msg`Deploy ${sha} finished. ${here}`);
```
-# Webhook Events
+# Events
-Pass a `webhookSecret` (or set `MACRO_WEBHOOK_SECRET`) to receive events. You
-should use a framework like Hono or Express to handle the webhook request and
-pass it to the SDK which will handle verification and dispatching.
+`macro.events` is always available. The default transport is a live SSE
+stream — no public URL, persisted webhook, or signing secret required.
```ts
const macro = new Macro({
token: process.env.MACRO_API_KEY,
- webhookSecret: process.env.MACRO_WEBHOOK_SECRET,
});
const me = await macro.users.me();
@@ -149,6 +147,37 @@ macro.events.on('channel.message_posted', async ({ metadata, message }) => {
await message.reply('hi!');
});
+const stop = await macro.events.listen();
+// later: stop();
+```
+
+`listen()` opens `GET /webhook/events/stream` with the same `WebhookFilters`
+model as persisted webhooks. If you omit `filters`, it derives one filter from
+the event names already registered with `.on()`. Pass `scope: 'team'` for a
+team workspace (defaults to `'user'`). Delivery is best-effort: there is no
+replay if you disconnect.
+
+Handlers receive the same hydrated payloads as webhook deliveries — ORM
+handles for every entity the event names.
+
+### Persisted webhooks
+
+To receive the same events as HTTPS POSTs instead of (or in addition to) SSE,
+register a webhook and pass a `webhookSecret` (or set `MACRO_WEBHOOK_SECRET`).
+Use a framework like Hono or Express to handle the request; the SDK verifies
+the signature and dispatches.
+
+```ts
+const macro = new Macro({
+ token: process.env.MACRO_API_KEY,
+ webhookSecret: process.env.MACRO_WEBHOOK_SECRET,
+});
+
+macro.events.on('channel.message_posted', async ({ metadata, message }) => {
+ if (metadata.sender === me.id) return;
+ await message.reply('hi!');
+});
+
// Hono
app.post('/webhook', (c) => macro.events.webhook()(c.req.raw));
```
@@ -170,8 +199,9 @@ support by adding a wrapper to the appropriate model. There is CI to ensure that
we don't forget to add coverage or explicitly skip coverage for new generated
functions (endpoints).
-## Webhook events
+## Events
Event names and payloads are **generated from the backend**: the Rust webhook
crate exposes a `WebhookEvent` union in the storage OpenAPI spec, and
-`src/events/types.ts` derives `EventName` / `EventPayload` from it.
+`src/events/types.ts` derives `EventName` / `EventPayload` from it. SSE
+(`listen()`) and persisted webhooks (`webhook()`) dispatch the same union.
diff --git a/packages/sdk/examples/sse-events.ts b/packages/sdk/examples/sse-events.ts
new file mode 100644
index 0000000000..2d7eb22a99
--- /dev/null
+++ b/packages/sdk/examples/sse-events.ts
@@ -0,0 +1,59 @@
+import type { Env } from '../src/config';
+import type { EventName } from '../src/events/types';
+import { Macro } from '../src/macro';
+
+const actAs = process.argv[2];
+const botToken = process.env.MACRO_BOT_TOKEN;
+if (!actAs || !botToken) {
+ console.error(
+ 'usage: MACRO_BOT_TOKEN=mbot_... bun examples/sse-events.ts <acting-user-id>',
+ );
+ process.exit(1);
+}
+
+const env = (process.env.MACRO_ENV ?? 'dev') as Env;
+const bot = new Macro({ env, auth: { type: 'bot', token: botToken } });
+const macro = bot.requestedAs(bot.users.byId(actAs));
+
+const ALL_EVENTS = [
+ 'channel.created',
+ 'channel.deleted',
+ 'channel.message_attachment_created',
+ 'channel.message_attachment_removed',
+ 'channel.message_deleted',
+ 'channel.message_patched',
+ 'channel.message_posted',
+ 'channel.participant_added',
+ 'channel.participant_removed',
+ 'channel.updated',
+ 'document.copied',
+ 'document.created',
+ 'document.deleted',
+ 'document.updated',
+] as const satisfies readonly EventName[];
+
+for (const name of ALL_EVENTS) {
+ macro.events.on(name, (event) => console.log(name, event.metadata));
+}
+
+macro.events.on('document.created', async (e) => {
+ const owner = await e.owner.name();
+ console.log(
+ ` -> ${await e.document.name()} created by ${owner ?? 'someone'}`,
+ );
+});
+
+macro.events.on('channel.message_posted', async (e) => {
+ const from = e.sender ? ((await e.sender.name()) ?? e.sender.id) : 'a bot';
+ console.log(` -> ${from} posted in ${await e.channel.name()}`);
+});
+
+const stop = await macro.events.listen();
+console.log('listening for events over SSE; Ctrl+C to stop');
+
+const shutdown = () => {
+ stop();
+ process.exit(0);
+};
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.ts
index 79e3cdc8d1..da07cfc261 100644
--- a/packages/sdk/generated/storage/index.ts
+++ b/packages/sdk/generated/storage/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentChannelScope, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollabSurfaceResponse, CollabSurfaceTokenResponse, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreatePairingRequest, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, NewChannelAttachment, NotificationFilters, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, RequestedHarnessScope, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
+export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentChannelScope, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollabSurfaceResponse, CollabSurfaceTokenResponse, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreatePairingRequest, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, NewChannelAttachment, NotificationFilters, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, RequestedHarnessScope, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.ts
index 70e61c57b0..579837ba6a 100644
--- a/packages/sdk/generated/storage/sdk.gen.ts
+++ b/packages/sdk/generated/storage/sdk.gen.ts
@@ -1,8 +1,8 @@
// This file is auto-generated by @hey-api/openapi-ts
-import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
+import type { Client, ClientMeta, Options as Options2, RequestResult, ServerSentEventsResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateReminderData, CreateReminderErrors, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderErrors, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderErrors, GetReminderResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListRemindersData, ListRemindersErrors, ListRemindersResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateReminderData, UpdateReminderErrors, UpdateReminderResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';
+import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateReminderData, CreateReminderErrors, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderErrors, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderErrors, GetReminderResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListRemindersData, ListRemindersErrors, ListRemindersResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateReminderData, UpdateReminderErrors, UpdateReminderResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -2018,6 +2018,13 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * Stream matching broker events to the caller over Server-Sent Events.
+ */
+ public streamEvents<ThrowOnError extends boolean = false>(options: Options<StreamEventsData, ThrowOnError, StreamEventsResponse>): Promise<ServerSentEventsResult<StreamEventsResponses>> {
+ return (options.client ?? this.client).sse.get<StreamEventsResponses, StreamEventsErrors, ThrowOnError>({ url: '/webhook/events/stream', ...options });
+ }
+
/**
* List the caller's webhooks.
*/
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 09b3ef6ec8..12ede791e6 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -8955,7 +8955,8 @@ export type WebhookFilter = {
/**
* Scope that owns a newly-created webhook.
*
- * Clients serialize this, so both derives are used.
+ * Clients serialize this, so both derives are used. `Display`/`FromStr`
+ * spell the same names as serde, for query strings and config values.
*/
export type WebhookScope = 'user' | 'team';
@@ -14010,6 +14011,49 @@ export type EditProjectV2Responses = {
export type EditProjectV2Response = EditProjectV2Responses[keyof EditProjectV2Responses];
+export type StreamEventsData = {
+ body?: never;
+ path?: never;
+ query: {
+ /**
+ * Personal or team workspace whose webhook lifecycle events are delivered.
+ */
+ scope: WebhookScope;
+ /**
+ * URL-encoded JSON array of webhook filters, identical to the persisted
+ * webhook `filters` field.
+ */
+ filters?: string;
+ };
+ url: '/webhook/events/stream';
+};
+
+export type StreamEventsErrors = {
+ /**
+ * Bad request
+ */
+ 400: ErrorResponse;
+ /**
+ * Forbidden
+ */
+ 403: ErrorResponse;
+ /**
+ * Internal server error
+ */
+ 500: ErrorResponse;
+};
+
+export type StreamEventsError = StreamEventsErrors[keyof StreamEventsErrors];
+
+export type StreamEventsResponses = {
+ /**
+ * Server-Sent Events stream of matching broker events
+ */
+ 200: string;
+};
+
+export type StreamEventsResponse = StreamEventsResponses[keyof StreamEventsResponses];
+
export type ListWebhooksData = {
body?: never;
path?: never;
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 41083163ad..fc69b1898b 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -11998,6 +11998,75 @@
}
}
},
+ "/webhook/events/stream": {
+ "get": {
+ "tags": ["webhook"],
+ "summary": "Stream matching broker events to the caller over Server-Sent Events.",
+ "operationId": "stream_events",
+ "parameters": [
+ {
+ "name": "scope",
+ "in": "query",
+ "description": "Personal or team workspace whose webhook lifecycle events are delivered.",
+ "required": true,
+ "schema": {
+ "$ref": "#/components/schemas/WebhookScope"
+ }
+ },
+ {
+ "name": "filters",
+ "in": "query",
+ "description": "URL-encoded JSON array of webhook filters, identical to the persisted\nwebhook `filters` field.",
+ "required": false,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Server-Sent Events stream of matching broker events",
+ "content": {
+ "text/event-stream": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Bad request",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Forbidden",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "Internal server error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/webhook/webhooks": {
"get": {
"tags": ["webhook"],
@@ -26528,7 +26597,7 @@
},
"WebhookScope": {
"type": "string",
- "description": "Scope that owns a newly-created webhook.\n\nClients serialize this, so both derives are used.",
+ "description": "Scope that owns a newly-created webhook.\n\nClients serialize this, so both derives are used. `Display`/`FromStr`\nspell the same names as serde, for query strings and config values.",
"enum": ["user", "team"]
},
"WebhookStatus": {
diff --git a/packages/sdk/src/config.ts b/packages/sdk/src/config.ts
index d1cf182ba2..edfe2927f2 100644
--- a/packages/sdk/src/config.ts
+++ b/packages/sdk/src/config.ts
@@ -106,7 +106,12 @@ export interface MacroOpts {
hosts?: Partial<Record<ServiceName, string>>;
/** Override the web app base URL (e.g. for local frontend dev). Also reads MACRO_WEB_URL. */
webAppUrl?: string;
- /** Signing secret for verifying incoming webhooks. Falls back to MACRO_WEBHOOK_SECRET. */
+ /**
+ * Signing secret for verifying incoming persisted-webhook deliveries.
+ * Required only for `macro.events.webhook()` / `macro.events.handle()`.
+ * SSE via `macro.events.listen()` uses the API token and does not need
+ * this. Falls back to MACRO_WEBHOOK_SECRET.
+ */
webhookSecret?: string;
wsVerify?: string;
/** User id the bot acts for, sent as `x-macro-bot-for-macro-user-id` on
diff --git a/packages/sdk/src/entities/webhooks/webhook.ts b/packages/sdk/src/entities/webhooks/webhook.ts
index 315d30eec2..55e70c4c41 100644
--- a/packages/sdk/src/entities/webhooks/webhook.ts
+++ b/packages/sdk/src/entities/webhooks/webhook.ts
@@ -22,7 +22,9 @@ import { User } from '../users/user';
* The signing secret is only ever returned once, from {@link create}; it's
* exposed there as {@link Webhook.signingSecret}. Save it — patches, gets,
* and `byId` handles never carry it again — and pass it to
- * `MacroOpts.webhookSecret` so `MacroEvents` can verify deliveries.
+ * `MacroOpts.webhookSecret` so `macro.events.webhook()` can verify
+ * deliveries. Live SSE via `macro.events.listen()` does not use a
+ * persisted webhook or signing secret.
*/
export class Webhook extends MacroEntity<WebhookRecord> {
/**
diff --git a/packages/sdk/src/events/receiver.ts b/packages/sdk/src/events/receiver.ts
index 61703aedc5..98fabd48c3 100644
--- a/packages/sdk/src/events/receiver.ts
+++ b/packages/sdk/src/events/receiver.ts
@@ -1,4 +1,8 @@
import { match, P } from 'ts-pattern';
+import type {
+ WebhookFilter,
+ WebhookScope,
+} from '../../generated/storage/types.gen';
import { MacroError } from '../utils';
import type { MacroClient } from '../utils/client';
import { hydrateChannelEvent } from './hydrate/channel';
@@ -17,8 +21,28 @@ type AnyHandler = (event: unknown) => void | Promise<void>;
/** Sent by Macro when validating a newly registered endpoint; acked, never dispatched. */
const VALIDATION_EVENT = 'webhook.validation.test';
+/** Options for {@link MacroEvents.listen}. */
+export interface ListenOptions {
+ /**
+ * Event/entity-id filters, identical to persisted webhook `filters`.
+ * Defaults to one filter covering every event currently registered with
+ * {@link MacroEvents.on}.
+ */
+ filters?: WebhookFilter[];
+ /**
+ * Personal or team workspace whose webhook lifecycle events are delivered.
+ * Defaults to `'user'`.
+ */
+ scope?: WebhookScope;
+ /** Abort the stream. */
+ signal?: AbortSignal;
+}
+
/** Attach the entity handles defined for each webhook event. */
-function hydrate(client: MacroClient, event: MacroEvent): EventMap[EventName] {
+function hydrate(
+ client: MacroClient,
+ event: MacroEvent,
+): EventMap[EventName] | undefined {
return match(event)
.with({ event_type: P.string.startsWith('document.') }, (documentEvent) =>
hydrateDocumentEvent(client, documentEvent),
@@ -26,13 +50,13 @@ function hydrate(client: MacroClient, event: MacroEvent): EventMap[EventName] {
.with({ event_type: P.string.startsWith('channel.') }, (channelEvent) =>
hydrateChannelEvent(client, channelEvent),
)
- .exhaustive();
+ .otherwise(() => undefined);
}
/**
- * Per-instance webhook receiver. Register ONE webhook with Macro (one URL, one
- * signing secret) and mount this receiver at it; all `.on` handlers fan out
- * from here.
+ * Per-instance event receiver. Subscribe with {@link MacroEvents.on}, then
+ * either {@link MacroEvents.listen} (SSE, the default) or mount
+ * {@link MacroEvents.webhook} at a persisted webhook URL.
*
* Obtain via `macro.events` — do not construct directly.
*/
@@ -41,7 +65,7 @@ export class MacroEvents {
constructor(
private readonly client: MacroClient,
- private readonly secret: string,
+ private readonly secret?: string,
) {}
/**
@@ -62,12 +86,15 @@ export class MacroEvents {
* (user auth).
*
* `channel.mentioned` deliveries cover every mention in channels the
- * webhook's workspace can access (its `ids` filter, like all channel
- * events, holds channel ids); picking out "me" happens here, client-side.
- * The caller's identity is resolved lazily (once) on the first delivery.
- * The webhook itself is registered separately and once, e.g.
- * `macro.webhooks.create({ filters: [{ events: ['channel.mentioned'] }],
- * … })`.
+ * stream's (or webhook's) workspace can access (its `ids` filter, like all
+ * channel events, holds channel ids); picking out "me" happens here,
+ * client-side. The caller's identity is resolved lazily (once) on the first
+ * delivery.
+ *
+ * For SSE, register this handler before {@link listen} so the derived
+ * filters include `channel.mentioned`. For persisted webhooks, register the
+ * webhook separately, e.g. `macro.webhooks.create({ filters: [{ events:
+ * ['channel.mentioned'] }], … })`.
*
* @returns An unsubscribe function.
*/
@@ -83,12 +110,82 @@ export class MacroEvents {
}
/**
- * Feed a raw delivery in: verifies the signature, parses, and dispatches to
- * matching handlers.
+ * Open a live Server-Sent Events stream of matching broker events. This is
+ * the default way to receive events — no public URL or signing secret
+ * required. Delivery is best-effort: events published before the
+ * connection, while disconnected, or dropped for a slow subscriber are
+ * missed; there is no replay.
+ *
+ * Filters default to the event names currently registered with {@link on}.
+ * The stream uses those filters for its lifetime; later `.on` / unsubscribe
+ * calls do not change what the server sends.
+ *
+ * @returns A function that closes the stream.
+ */
+ async listen(opts: ListenOptions = {}): Promise<() => void> {
+ const filters = opts.filters ?? this.filtersFromHandlers();
+ if (
+ filters.length === 0 ||
+ filters.every((filter) => filter.events.length === 0)
+ ) {
+ throw new MacroError(
+ 'listen() needs filters — pass filters or register handlers with .on() first',
+ );
+ }
+
+ const controller = new AbortController();
+ if (opts.signal) {
+ if (opts.signal.aborted) {
+ controller.abort();
+ } else {
+ opts.signal.addEventListener('abort', () => controller.abort(), {
+ once: true,
+ });
+ }
+ }
+
+ const { stream } = await this.client.storage.streamEvents({
+ query: {
+ scope: opts.scope ?? 'user',
+ filters: JSON.stringify(filters),
+ },
+ signal: controller.signal,
+ });
+
+ const consume = (async () => {
+ try {
+ for await (const data of stream) {
+ await this.dispatchEvent(data);
+ }
+ } catch {
+ if (controller.signal.aborted) return;
+ throw new MacroError('event stream failed');
+ }
+ })();
+ consume.catch(() => {
+ // Connection errors are retried by the generated SSE client. A terminal
+ // failure after listen() has returned must not become an unhandled
+ // rejection; the caller already has `stop`.
+ });
+
+ return () => {
+ controller.abort();
+ };
+ }
+
+ /**
+ * Feed a raw webhook delivery in: verifies the signature, parses, and
+ * dispatches to matching handlers.
*
- * @throws {MacroError} if the signature is missing or invalid.
+ * @throws {MacroError} if no signing secret was configured, or if the
+ * signature is missing or invalid.
*/
async handle(rawBody: string, headers: DeliveryHeaders): Promise<void> {
+ if (!this.secret) {
+ throw new MacroError(
+ 'webhookSecret is required to verify incoming webhook deliveries',
+ );
+ }
const ok = await verifySignature({
secret: this.secret,
timestamp: headers.timestamp ?? '',
@@ -99,22 +196,23 @@ export class MacroEvents {
if (headers.event === VALIDATION_EVENT) return;
- const event = JSON.parse(rawBody) as MacroEvent;
- if (!('event_type' in event)) return;
- const handlers = this.handlers.get(event.event_type);
- if (!handlers || handlers.size === 0) return;
-
- const payload = hydrate(this.client, event);
- await Promise.all([...handlers].map((handler) => handler(payload)));
+ await this.dispatchEvent(JSON.parse(rawBody));
}
/**
- * A Fetch-style handler to mount at your webhook route.
+ * A Fetch-style handler to mount at your persisted webhook route.
+ *
+ * Requires `webhookSecret` (or `MACRO_WEBHOOK_SECRET`).
*
* @example
* app.post('/webhook', macro.events.webhook()); // Hono
*/
webhook(): (req: Request) => Promise<Response> {
+ if (!this.secret) {
+ throw new MacroError(
+ 'webhookSecret is required to verify incoming webhook deliveries',
+ );
+ }
return async (req: Request) => {
await this.handle(await req.text(), {
event: req.headers.get('x-macro-event') ?? undefined,
@@ -125,4 +223,30 @@ export class MacroEvents {
return new Response('ok');
};
}
+
+ private filtersFromHandlers(): WebhookFilter[] {
+ const events = [...this.handlers.entries()]
+ .filter(([, set]) => set.size > 0)
+ .map(([name]) => name);
+ return events.length > 0 ? [{ events }] : [];
+ }
+
+ private async dispatchEvent(data: unknown): Promise<void> {
+ const event =
+ typeof data === 'string' ? (JSON.parse(data) as unknown) : data;
+ if (
+ event === null ||
+ typeof event !== 'object' ||
+ !('event_type' in event)
+ ) {
+ return;
+ }
+ const typed = event as MacroEvent;
+ const handlers = this.handlers.get(typed.event_type);
+ if (!handlers || handlers.size === 0) return;
+
+ const payload = hydrate(this.client, typed);
+ if (!payload) return;
+ await Promise.all([...handlers].map((handler) => handler(payload)));
+ }
}
diff --git a/packages/sdk/src/macro.ts b/packages/sdk/src/macro.ts
index fbd1dd9092..6da9c25a54 100644
--- a/packages/sdk/src/macro.ts
+++ b/packages/sdk/src/macro.ts
@@ -22,6 +22,7 @@ import type { MacroEvents } from './events/receiver';
import { MacroClient } from './utils/client';
export type { MacroOpts } from './config';
+export type { ListenOptions, MacroEvents } from './events/receiver';
export {
here,
type Interpolation,
@@ -53,9 +54,7 @@ export class Macro<T extends MacroOpts = MacroOpts> {
readonly teams: TeamNamespace;
readonly users: UserNamespace;
readonly webhooks: WebhooksNamespace;
- declare readonly events: T extends { webhookSecret: string }
- ? MacroEvents
- : undefined;
+ readonly events: MacroEvents;
/** Base URL of the Macro web app, used to build entity URLs. */
readonly webAppUrl: string;
/** Direct access to the underlying hey-api service clients. */
@@ -84,7 +83,7 @@ export class Macro<T extends MacroOpts = MacroOpts> {
this.teams = new TeamNamespace(client);
this.users = new UserNamespace(client);
this.webhooks = new WebhooksNamespace(client);
- (this as { events?: MacroEvents }).events = client.events;
+ this.events = client.events;
this.webAppUrl = client.webAppUrl;
}
diff --git a/packages/sdk/src/utils/client.ts b/packages/sdk/src/utils/client.ts
index 9275a5d991..9b9aefb5c4 100644
--- a/packages/sdk/src/utils/client.ts
+++ b/packages/sdk/src/utils/client.ts
@@ -34,7 +34,7 @@ export class MacroClient {
readonly storage: StorageSdk;
readonly webAppUrl: string;
readonly wsVerify?: string;
- readonly events?: MacroEvents;
+ readonly events: MacroEvents;
/** Resolved authentication config (distinct from `auth`, the auth-service SDK). */
readonly authConfig: MacroAuth;
/** Resolved service base urls: env defaults, then the local-stack portmap,
@@ -93,9 +93,7 @@ export class MacroClient {
? process.env.MACRO_WEBHOOK_SECRET
: undefined;
const webhookSecret = opts.webhookSecret ?? envWebhookSecret;
- if (webhookSecret) {
- this.events = new MacroEvents(this, webhookSecret);
- }
+ this.events = new MacroEvents(this, webhookSecret);
}
/** Whether requests have a user identity accepted by acting-user endpoints. */
diff --git a/packages/sdk/tests/events.test.ts b/packages/sdk/tests/events.test.ts
new file mode 100644
index 0000000000..9929df2afc
--- /dev/null
+++ b/packages/sdk/tests/events.test.ts
@@ -0,0 +1,183 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { Macro } from '../src/macro';
+import { MacroError } from '../src/utils';
+
+const originalFetch = globalThis.fetch;
+
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
+
+const created = {
+ event_type: 'document.created' as const,
+ metadata: {
+ document_id: 'doc_1',
+ document_name: 'Notes',
+ owner: 'macro|[email protected]',
+ },
+};
+
+function sseBody(event: unknown): string {
+ return `event: ${typeof event === 'object' && event && 'event_type' in event ? event.event_type : 'message'}\ndata: ${JSON.stringify(event)}\n\n`;
+}
+
+async function sign(
+ secret: string,
+ timestamp: string,
+ rawBody: string,
+): Promise<string> {
+ const enc = new TextEncoder();
+ const key = await crypto.subtle.importKey(
+ 'raw',
+ enc.encode(secret),
+ { name: 'HMAC', hash: 'SHA-256' },
+ false,
+ ['sign'],
+ );
+ const digest = await crypto.subtle.sign(
+ 'HMAC',
+ key,
+ enc.encode(`${timestamp}.${rawBody}`),
+ );
+ return `v1=${new Uint8Array(digest).toHex()}`;
+}
+
+describe('MacroEvents', () => {
+ test('is always available and defaults listen() filters from .on()', async () => {
+ let request: Request | undefined;
+ const delivered = Promise.withResolvers<typeof created>();
+ globalThis.fetch = (async (input) => {
+ request = input instanceof Request ? input : new Request(input);
+ return new Response(sseBody(created), {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
+ });
+ }) as typeof fetch;
+
+ const macro = new Macro({
+ token: 'user-token',
+ hosts: { storage: 'https://storage.example.test' },
+ });
+ expect(macro.events).toBeDefined();
+
+ macro.events.on('document.created', (event) => {
+ delivered.resolve({
+ event_type: event.event_type,
+ metadata: event.metadata,
+ });
+ });
+ const stop = await macro.events.listen();
+ const event = await delivered.promise;
+ stop();
+
+ expect(event).toEqual(created);
+ expect(request?.method).toBe('GET');
+ expect(request?.headers.get('authorization')).toBe('Bearer user-token');
+ const url = new URL(request?.url ?? '');
+ expect(url.origin + url.pathname).toBe(
+ 'https://storage.example.test/webhook/events/stream',
+ );
+ expect(url.searchParams.get('scope')).toBe('user');
+ expect(JSON.parse(url.searchParams.get('filters') ?? '[]')).toEqual([
+ { events: ['document.created'] },
+ ]);
+ });
+
+ test('listen() sends explicit filters and scope', async () => {
+ const seen = Promise.withResolvers<Request>();
+ globalThis.fetch = (async (input) => {
+ const request = input instanceof Request ? input : new Request(input);
+ seen.resolve(request);
+ return new Response('', {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
+ });
+ }) as typeof fetch;
+
+ const macro = new Macro({
+ token: 'user-token',
+ hosts: { storage: 'https://storage.example.test' },
+ });
+ const stop = await macro.events.listen({
+ filters: [{ events: ['channel.message_posted'], ids: ['chan_1'] }],
+ scope: 'team',
+ });
+ const request = await seen.promise;
+ stop();
+
+ const url = new URL(request.url);
+ expect(url.searchParams.get('scope')).toBe('team');
+ expect(JSON.parse(url.searchParams.get('filters') ?? '[]')).toEqual([
+ { events: ['channel.message_posted'], ids: ['chan_1'] },
+ ]);
+ });
+
+ test('listen() throws when there are no filters or handlers', async () => {
+ const macro = new Macro({
+ token: 'user-token',
+ hosts: { storage: 'https://storage.example.test' },
+ });
+ await expect(macro.events.listen()).rejects.toThrow(MacroError);
+ });
+
+ test('webhook() requires a signing secret', () => {
+ const macro = new Macro({
+ token: 'user-token',
+ hosts: { storage: 'https://storage.example.test' },
+ });
+ expect(() => macro.events.webhook()).toThrow(MacroError);
+ });
+
+ test('webhook() verifies the signature and dispatches', async () => {
+ const rawBody = JSON.stringify(created);
+ const timestamp = '1710000000';
+ const secret = 'whsec_test';
+ const signature = await sign(secret, timestamp, rawBody);
+ const received = Promise.withResolvers<string>();
+
+ const macro = new Macro({
+ token: 'user-token',
+ webhookSecret: secret,
+ hosts: { storage: 'https://storage.example.test' },
+ });
+ macro.events.on('document.created', (event) => {
+ received.resolve(event.document.id);
+ });
+
+ const response = await macro.events.webhook()(
+ new Request('https://example.test/webhook', {
+ method: 'POST',
+ body: rawBody,
+ headers: {
+ 'x-macro-event': 'document.created',
+ 'x-macro-timestamp': timestamp,
+ 'x-macro-signature': signature,
+ },
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ await expect(received.promise).resolves.toBe('doc_1');
+ });
+
+ test('webhook() rejects a bad signature', async () => {
+ const macro = new Macro({
+ token: 'user-token',
+ webhookSecret: 'whsec_test',
+ hosts: { storage: 'https://storage.example.test' },
+ });
+
+ await expect(
+ macro.events.webhook()(
+ new Request('https://example.test/webhook', {
+ method: 'POST',
+ body: JSON.stringify(created),
+ headers: {
+ 'x-macro-timestamp': '1710000000',
+ 'x-macro-signature': 'v1=deadbeef',
+ },
+ }),
+ ),
+ ).rejects.toThrow('invalid webhook signature');
+ });
+});
diff --git a/services/document_storage_service/src/api.rs b/services/document_storage_service/src/api.rs
index 523a1ff0a4..7f9689b9a9 100644
--- a/services/document_storage_service/src/api.rs
+++ b/services/document_storage_service/src/api.rs
@@ -256,7 +256,11 @@ fn api_router(state: ApiContext) -> Router {
)
.nest(
"/webhook",
- webhook::inbound::axum_router::webhook_router(state.webhook_state.clone()),
+ webhook::inbound::axum_router::webhook_router(state.webhook_state.clone()).merge(
+ webhook::inbound::stream_router::webhook_stream_router(
+ state.sse_stream_state.clone(),
+ ),
+ ),
)
.nest(
"/crm",
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 6365cbeba2..d2f2967d83 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -124,7 +124,9 @@ use system_properties::{
use tokio_util::task::TaskTracker;
use webhook::{
domain::service::WebhookServiceImpl,
+ domain::stream::WebhookEventStreamServiceImpl,
inbound::axum_router::WebhookRouterState as MacroWebhookRouterState,
+ inbound::stream_router::WebhookStreamRouterState,
outbound::{
http_validator::ReqwestWebhookValidationClient,
pg_repository::PgRepository as PgWebhookRepo,
@@ -506,6 +508,14 @@ pub(crate) type DssWebhookRateLimiter =
pub(crate) type DssWebhookState =
MacroWebhookRouterState<DssWebhookService, DssWebhookRateLimiter, AuthorizationService>;
+/// Type alias for the service backing the webhook-event SSE endpoint.
+pub(crate) type DssSseStreamService =
+ WebhookEventStreamServiceImpl<EntityAccessService, PgWebhookRepo>;
+
+/// Type alias for the webhook-event SSE router state.
+pub(crate) type DssSseStreamState =
+ WebhookStreamRouterState<DssSseStreamService, AuthorizationService>;
+
#[derive(Clone, FromRef)]
pub(crate) struct ApiContext {
pub db: PgPool,
@@ -557,6 +567,7 @@ pub(crate) struct ApiContext {
pub call_state: DssCallState,
pub call_webhook_state: DssCallWebhookState,
pub webhook_state: DssWebhookState,
+ pub sse_stream_state: DssSseStreamState,
pub call_internal_state: DssCallInternalState,
pub cal_webhook_state: DssCalWebhookState,
pub entity_access_management_service: EntityAccessManagementService,
diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rs
index 9fbc527ed4..1f8208e31a 100644
--- a/services/document_storage_service/src/api/swagger.rs
+++ b/services/document_storage_service/src/api/swagger.rs
@@ -294,6 +294,7 @@ use utoipa::OpenApi;
webhook::inbound::axum_router::list_webhooks,
webhook::inbound::axum_router::patch_webhook,
webhook::inbound::axum_router::validate_webhook,
+ webhook::inbound::stream_router::stream_events,
call::inbound::axum_router::ring_status_handler,
call::inbound::axum_router::transcript_handler,
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 60a788e4ad..a008541b4e 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -753,6 +753,50 @@ async fn run() -> anyhow::Result<()> {
authorization_state.clone(),
);
+ let (webhook_stream_sender, _) =
+ tokio::sync::broadcast::channel(webhook::domain::stream::WEBHOOK_STREAM_CHANNEL_CAPACITY);
+ let sse_stream_service = webhook::domain::stream::WebhookEventStreamServiceImpl::new(
+ webhook_stream_sender.clone(),
+ entity_access_service.clone(),
+ webhook_repository.clone(),
+ );
+ let sse_stream_state = webhook::inbound::stream_router::WebhookStreamRouterState::new(
+ sse_stream_service,
+ authorization_state.clone(),
+ );
+ consumer_tracker.spawn({
+ let brokers = config.kafka_brokers.as_ref().to_string();
+ let sender = webhook_stream_sender;
+ let cancellation_token = consumer_cancellation_token.clone();
+ async move {
+ loop {
+ let result = tokio::select! {
+ biased;
+ _ = cancellation_token.cancelled() => break,
+ result = webhook::inbound::kafka_stream_consumer::run_webhook_stream_consumer(
+ &brokers,
+ &sender,
+ ) => result,
+ };
+
+ if cancellation_token.is_cancelled() {
+ break;
+ }
+ if let Err(error) = result {
+ tracing::error!(
+ error = ?error,
+ "webhook SSE Kafka consumer stopped"
+ );
+ tokio::select! {
+ biased;
+ _ = cancellation_token.cancelled() => break,
+ _ = tokio::time::sleep(Duration::from_secs(1)) => {}
+ }
+ }
+ }
+ }
+ });
+
let webhook_ingestion_service =
webhook::domain::ingestion::WebhookEventIngestionServiceImpl::new(
entity_access_service.clone(),
@@ -1372,6 +1416,7 @@ async fn run() -> anyhow::Result<()> {
call_state,
call_webhook_state,
webhook_state,
+ sse_stream_state,
call_internal_state,
cal_webhook_state,
entity_access_management_service,