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(agent_session): lifecycle events on Kafka, webhook fan-out, SDK hydration (#6318)

Wolf Mermelsteincaacc480543b
diff --git a/.github/kafka-cluster-topics.json b/.github/kafka-cluster-topics.json
index 9a9c86f5d1..d03fd7eef4 100644
--- a/.github/kafka-cluster-topics.json
+++ b/.github/kafka-cluster-topics.json
@@ -1,4 +1,5 @@
[
+ "macro.agent_session_lifecycle",
"macro.agent_sessions",
"macro.bots",
"macro.calendar",
diff --git a/Cargo.lock b/Cargo.lock
index 2adba787b9..ae5608450b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -440,7 +440,8 @@ dependencies = [
"harness_id",
"macro_authorization",
"macro_db_migrator",
- "macro_service_urls",
+ "macro_event_broker",
+ "macro_event_topics",
"macro_user_id",
"macro_uuid",
"mockall",
@@ -18055,6 +18056,8 @@ dependencies = [
name = "webhook"
version = "0.1.0"
dependencies = [
+ "agent_fold",
+ "agent_runtime_protocol",
"agent_session",
"agent_trigger",
"anyhow",
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentActionId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentActionId.ts
new file mode 100644
index 0000000000..1144d789b0
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentActionId.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Identifies one accepted [`AgentAction`] end to end: returned by the
+control endpoint, written as the JSON-RPC request id on the action's wire
+frame, and read back off that frame as `request_id` on the folded message
+it derives.
+
+Minted only by the server at accept time, as a v7 uuid so ids sort by mint
+time. On the wire and in JSON it is the bare uuid, and a uuid-shaped
+request id is the whole ownership test: the server is the only writer of
+runtime-bound frames. The machine's own handshake request ids
+(`agent_session:{session}:{n}`) are not uuids and stay `None`.
+ */
+export type AgentActionId = string;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEvent.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEvent.ts
new file mode 100644
index 0000000000..126abc38e5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEvent.ts
@@ -0,0 +1,34 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionLifecycleEventOneOf } from './agentSessionLifecycleEventOneOf';
+import type { AgentSessionLifecycleEventOneOfFive } from './agentSessionLifecycleEventOneOfFive';
+import type { AgentSessionLifecycleEventOneOfNine } from './agentSessionLifecycleEventOneOfNine';
+import type { AgentSessionLifecycleEventOneOfOnefive } from './agentSessionLifecycleEventOneOfOnefive';
+import type { AgentSessionLifecycleEventOneOfOneone } from './agentSessionLifecycleEventOneOfOneone';
+import type { AgentSessionLifecycleEventOneOfOneseven } from './agentSessionLifecycleEventOneOfOneseven';
+import type { AgentSessionLifecycleEventOneOfOnethree } from './agentSessionLifecycleEventOneOfOnethree';
+import type { AgentSessionLifecycleEventOneOfSeven } from './agentSessionLifecycleEventOneOfSeven';
+import type { AgentSessionLifecycleEventOneOfThree } from './agentSessionLifecycleEventOneOfThree';
+
+/**
+ * Events publishable to [`MacroAgentSessionLifecycleTopic`].
+
+The serde tag and [`AgentSessionLifecycleEventName`] spell the same wire
+names: subscribers filter on them, so they are API. The
+`event_names_match_the_wire` test holds the two in step. Exhaustive on
+purpose: a consumer's match should break when a variant is added.
+ */
+export type AgentSessionLifecycleEvent =
+ | AgentSessionLifecycleEventOneOf
+ | AgentSessionLifecycleEventOneOfThree
+ | AgentSessionLifecycleEventOneOfFive
+ | AgentSessionLifecycleEventOneOfSeven
+ | AgentSessionLifecycleEventOneOfNine
+ | AgentSessionLifecycleEventOneOfOneone
+ | AgentSessionLifecycleEventOneOfOnethree
+ | AgentSessionLifecycleEventOneOfOnefive
+ | AgentSessionLifecycleEventOneOfOneseven;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOf.ts
new file mode 100644
index 0000000000..4cf35f09b9
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOf.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionLifecycleEventOneOfEventType } from './agentSessionLifecycleEventOneOfEventType';
+import type { SessionOpenedMetadata } from './sessionOpenedMetadata';
+
+/**
+ * A session was created.
+ */
+export type AgentSessionLifecycleEventOneOf = {
+ event_type: AgentSessionLifecycleEventOneOfEventType;
+ /** A session was created. */
+ metadata: SessionOpenedMetadata;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfEventType.ts
new file mode 100644
index 0000000000..d4520e67dc
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfEventType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type AgentSessionLifecycleEventOneOfEventType =
+ (typeof AgentSessionLifecycleEventOneOfEventType)[keyof typeof AgentSessionLifecycleEventOneOfEventType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentSessionLifecycleEventOneOfEventType = {
+ agent_sessionopened: 'agent_session.opened',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfFive.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfFive.ts
new file mode 100644
index 0000000000..fbd9c05f05
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfFive.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionLifecycleEventOneOfFiveEventType } from './agentSessionLifecycleEventOneOfFiveEventType';
+import type { TurnEndedMetadata } from './turnEndedMetadata';
+
+/**
+ * The runtime answered a turn.
+ */
+export type AgentSessionLifecycleEventOneOfFive = {
+ event_type: AgentSessionLifecycleEventOneOfFiveEventType;
+ /** The runtime answered a turn. */
+ metadata: TurnEndedMetadata;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfFiveEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfFiveEventType.ts
new file mode 100644
index 0000000000..4bf4053313
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfFiveEventType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type AgentSessionLifecycleEventOneOfFiveEventType =
+ (typeof AgentSessionLifecycleEventOneOfFiveEventType)[keyof typeof AgentSessionLifecycleEventOneOfFiveEventType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentSessionLifecycleEventOneOfFiveEventType = {
+ agent_sessionturn_ended: 'agent_session.turn_ended',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfNine.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfNine.ts
new file mode 100644
index 0000000000..d24797cb3d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfNine.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionLifecycleEventOneOfNineEventType } from './agentSessionLifecycleEventOneOfNineEventType';
+import type { WaitingForInputMetadata } from './waitingForInputMetadata';
+
+/**
+ * The agent is blocked on a question to its owner.
+ */
+export type AgentSessionLifecycleEventOneOfNine = {
+ event_type: AgentSessionLifecycleEventOneOfNineEventType;
+ /** The agent is blocked on a question to its owner. */
+ metadata: WaitingForInputMetadata;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfNineEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfNineEventType.ts
new file mode 100644
index 0000000000..16e5d4f4be
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfNineEventType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type AgentSessionLifecycleEventOneOfNineEventType =
+ (typeof AgentSessionLifecycleEventOneOfNineEventType)[keyof typeof AgentSessionLifecycleEventOneOfNineEventType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentSessionLifecycleEventOneOfNineEventType = {
+ agent_sessionwaiting_for_input: 'agent_session.waiting_for_input',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnefive.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnefive.ts
new file mode 100644
index 0000000000..a16a0146eb
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnefive.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionLifecycleEventOneOfOnefiveEventType } from './agentSessionLifecycleEventOneOfOnefiveEventType';
+import type { SessionRenamedMetadata } from './sessionRenamedMetadata';
+
+/**
+ * The session was renamed.
+ */
+export type AgentSessionLifecycleEventOneOfOnefive = {
+ event_type: AgentSessionLifecycleEventOneOfOnefiveEventType;
+ /** The session was renamed. */
+ metadata: SessionRenamedMetadata;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnefiveEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnefiveEventType.ts
new file mode 100644
index 0000000000..12e376fb4e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnefiveEventType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type AgentSessionLifecycleEventOneOfOnefiveEventType =
+ (typeof AgentSessionLifecycleEventOneOfOnefiveEventType)[keyof typeof AgentSessionLifecycleEventOneOfOnefiveEventType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentSessionLifecycleEventOneOfOnefiveEventType = {
+ agent_sessionrenamed: 'agent_session.renamed',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneone.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneone.ts
new file mode 100644
index 0000000000..979bddbffe
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneone.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionLifecycleEventOneOfOneoneEventType } from './agentSessionLifecycleEventOneOfOneoneEventType';
+import type { InputReceivedMetadata } from './inputReceivedMetadata';
+
+/**
+ * The question was answered or withdrawn.
+ */
+export type AgentSessionLifecycleEventOneOfOneone = {
+ event_type: AgentSessionLifecycleEventOneOfOneoneEventType;
+ /** The question was answered or withdrawn. */
+ metadata: InputReceivedMetadata;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneoneEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneoneEventType.ts
new file mode 100644
index 0000000000..bc1053855e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneoneEventType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type AgentSessionLifecycleEventOneOfOneoneEventType =
+ (typeof AgentSessionLifecycleEventOneOfOneoneEventType)[keyof typeof AgentSessionLifecycleEventOneOfOneoneEventType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentSessionLifecycleEventOneOfOneoneEventType = {
+ agent_sessioninput_received: 'agent_session.input_received',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneseven.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneseven.ts
new file mode 100644
index 0000000000..c9fc4c438b
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOneseven.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionLifecycleEventOneOfOnesevenEventType } from './agentSessionLifecycleEventOneOfOnesevenEventType';
+import type { SessionDeletedMetadata } from './sessionDeletedMetadata';
+
+/**
+ * The session was deleted.
+ */
+export type AgentSessionLifecycleEventOneOfOneseven = {
+ event_type: AgentSessionLifecycleEventOneOfOnesevenEventType;
+ /** The session was deleted. */
+ metadata: SessionDeletedMetadata;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnesevenEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnesevenEventType.ts
new file mode 100644
index 0000000000..0afbef60ea
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnesevenEventType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type AgentSessionLifecycleEventOneOfOnesevenEventType =
+ (typeof AgentSessionLifecycleEventOneOfOnesevenEventType)[keyof typeof AgentSessionLifecycleEventOneOfOnesevenEventType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentSessionLifecycleEventOneOfOnesevenEventType = {
+ agent_sessiondeleted: 'agent_session.deleted',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnethree.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnethree.ts
new file mode 100644
index 0000000000..0d5598abff
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnethree.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionLifecycleEventOneOfOnethreeEventType } from './agentSessionLifecycleEventOneOfOnethreeEventType';
+import type { SessionStoppedMetadata } from './sessionStoppedMetadata';
+
+/**
+ * The session's live actor is gone.
+ */
+export type AgentSessionLifecycleEventOneOfOnethree = {
+ event_type: AgentSessionLifecycleEventOneOfOnethreeEventType;
+ /** The session's live actor is gone. */
+ metadata: SessionStoppedMetadata;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnethreeEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnethreeEventType.ts
new file mode 100644
index 0000000000..c7847afe5c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfOnethreeEventType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type AgentSessionLifecycleEventOneOfOnethreeEventType =
+ (typeof AgentSessionLifecycleEventOneOfOnethreeEventType)[keyof typeof AgentSessionLifecycleEventOneOfOnethreeEventType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentSessionLifecycleEventOneOfOnethreeEventType = {
+ agent_sessionstopped: 'agent_session.stopped',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfSeven.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfSeven.ts
new file mode 100644
index 0000000000..a93318a565
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfSeven.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionLifecycleEventOneOfSevenEventType } from './agentSessionLifecycleEventOneOfSevenEventType';
+import type { SessionSettledMetadata } from './sessionSettledMetadata';
+
+/**
+ * A turn ended with nothing queued behind it.
+ */
+export type AgentSessionLifecycleEventOneOfSeven = {
+ event_type: AgentSessionLifecycleEventOneOfSevenEventType;
+ /** A turn ended with nothing queued behind it. */
+ metadata: SessionSettledMetadata;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfSevenEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfSevenEventType.ts
new file mode 100644
index 0000000000..310100f8d8
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfSevenEventType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type AgentSessionLifecycleEventOneOfSevenEventType =
+ (typeof AgentSessionLifecycleEventOneOfSevenEventType)[keyof typeof AgentSessionLifecycleEventOneOfSevenEventType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentSessionLifecycleEventOneOfSevenEventType = {
+ agent_sessionsettled: 'agent_session.settled',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfThree.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfThree.ts
new file mode 100644
index 0000000000..2c40b0f03d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfThree.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionLifecycleEventOneOfThreeEventType } from './agentSessionLifecycleEventOneOfThreeEventType';
+import type { TurnStartedMetadata } from './turnStartedMetadata';
+
+/**
+ * A prompt was delivered to the runtime.
+ */
+export type AgentSessionLifecycleEventOneOfThree = {
+ event_type: AgentSessionLifecycleEventOneOfThreeEventType;
+ /** A prompt was delivered to the runtime. */
+ metadata: TurnStartedMetadata;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfThreeEventType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfThreeEventType.ts
new file mode 100644
index 0000000000..f2b99ad91f
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentSessionLifecycleEventOneOfThreeEventType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type AgentSessionLifecycleEventOneOfThreeEventType =
+ (typeof AgentSessionLifecycleEventOneOfThreeEventType)[keyof typeof AgentSessionLifecycleEventOneOfThreeEventType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentSessionLifecycleEventOneOfThreeEventType = {
+ agent_sessionturn_started: 'agent_session.turn_started',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/inFlightTurnSummary.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/inFlightTurnSummary.ts
new file mode 100644
index 0000000000..d86c8b02ed
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/inFlightTurnSummary.ts
@@ -0,0 +1,25 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentActionId } from './agentActionId';
+import type { InFlightTurnSummaryActor } from './inFlightTurnSummaryActor';
+import type { InFlightTurnSummaryAnnouncementMessageId } from './inFlightTurnSummaryAnnouncementMessageId';
+
+/**
+ * A turn the runtime never answered: the session stopped underneath it.
+ */
+export interface InFlightTurnSummary {
+ /** The action that opened the turn. */
+ action_id: AgentActionId;
+ actor?: InFlightTurnSummaryActor;
+ /** The magic-chip message posted for this turn, when one was. */
+ announcement_message_id?: InFlightTurnSummaryAnnouncementMessageId;
+ /**
+ * Position in the session's log.
+ * @minimum 0
+ */
+ turn: number;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/inFlightTurnSummaryActor.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/inFlightTurnSummaryActor.ts
new file mode 100644
index 0000000000..1a538c0a69
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/inFlightTurnSummaryActor.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { MacroUserIdStr } from './macroUserIdStr';
+
+export type InFlightTurnSummaryActor = null | MacroUserIdStr;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/inFlightTurnSummaryAnnouncementMessageId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/inFlightTurnSummaryAnnouncementMessageId.ts
new file mode 100644
index 0000000000..b7eaed6783
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/inFlightTurnSummaryAnnouncementMessageId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The magic-chip message posted for this turn, when one was.
+ */
+export type InFlightTurnSummaryAnnouncementMessageId = string | null;
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 7921de6cb4..f16aca98f2 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
@@ -14,6 +14,7 @@ export * from './addFavoriteRequestEntityType';
export * from './addParticipantsRequest';
export * from './addPinRequest';
export * from './agent';
+export * from './agentActionId';
export * from './agentChannelScope';
export * from './agentHarnessId';
export * from './agentMcpServer';
@@ -22,6 +23,25 @@ export * from './agentMcpServersOneOf';
export * from './agentMcpServersOneOfScope';
export * from './agentMcpServersOneOfThree';
export * from './agentMcpServersOneOfThreeScope';
+export * from './agentSessionLifecycleEvent';
+export * from './agentSessionLifecycleEventOneOf';
+export * from './agentSessionLifecycleEventOneOfEventType';
+export * from './agentSessionLifecycleEventOneOfFive';
+export * from './agentSessionLifecycleEventOneOfFiveEventType';
+export * from './agentSessionLifecycleEventOneOfNine';
+export * from './agentSessionLifecycleEventOneOfNineEventType';
+export * from './agentSessionLifecycleEventOneOfOnefive';
+export * from './agentSessionLifecycleEventOneOfOnefiveEventType';
+export * from './agentSessionLifecycleEventOneOfOneone';
+export * from './agentSessionLifecycleEventOneOfOneoneEventType';
+export * from './agentSessionLifecycleEventOneOfOneseven';
+export * from './agentSessionLifecycleEventOneOfOnesevenEventType';
+export * from './agentSessionLifecycleEventOneOfOnethree';
+export * from './agentSessionLifecycleEventOneOfOnethreeEventType';
+export * from './agentSessionLifecycleEventOneOfSeven';
+export * from './agentSessionLifecycleEventOneOfSevenEventType';
+export * from './agentSessionLifecycleEventOneOfThree';
+export * from './agentSessionLifecycleEventOneOfThreeEventType';
export * from './anchor';
export * from './anchorId';
export * from './anchorIdOneOf';
@@ -796,6 +816,10 @@ export * from './hashMapOneOfFour';
export * from './hashMapOneOfFourAllOf';
export * from './hashMapOneOfFourAllOfType';
export * from './highlightType';
+export * from './inFlightTurnSummary';
+export * from './inFlightTurnSummaryActor';
+export * from './inFlightTurnSummaryAnnouncementMessageId';
+export * from './inputReceivedMetadata';
export * from './interactionReason';
export * from './item';
export * from './itemWithUserAccessLevel';
@@ -1013,6 +1037,15 @@ export * from './saveDocumentRequestSha';
export * from './saveDocumentResponse';
export * from './saveDocumentResponseData';
export * from './saveDocumentResponseDataPresignedUrl';
+export * from './sessionDeletedMetadata';
+export * from './sessionIdentity';
+export * from './sessionIdentityOrigin';
+export * from './sessionOpenedMetadata';
+export * from './sessionRenamedMetadata';
+export * from './sessionSettledMetadata';
+export * from './sessionSettledMetadataLastTurn';
+export * from './sessionStoppedMetadata';
+export * from './sessionStoppedMetadataTurnInFlight';
export * from './setCompanyHiddenRequest';
export * from './setCompanyNameRequest';
export * from './setContactHiddenRequest';
@@ -1222,6 +1255,7 @@ export * from './teamRole';
export * from './thread';
export * from './threadCreatedAt';
export * from './threadDeletedAt';
+export * from './threadOrigin';
export * from './threadResponse';
export * from './threadUpdatedAt';
export * from './transcriptSegmentRequest';
@@ -1229,6 +1263,16 @@ export * from './transcriptSegmentRequestDiarizedSpeakerId';
export * from './transcriptSegmentRequestEmbedding';
export * from './transcriptSegmentRequestEndedAt';
export * from './transcriptSegmentRequestStreamStartedAt';
+export * from './turnEndedMetadata';
+export * from './turnEndedMetadataActor';
+export * from './turnEndedMetadataAnnouncementMessageId';
+export * from './turnStartedMetadata';
+export * from './turnStartedMetadataActor';
+export * from './turnStartedMetadataAnnouncementMessageId';
+export * from './turnSummary';
+export * from './turnSummaryActor';
+export * from './turnSummaryAnnouncementMessageId';
+export * from './turnSummaryExcerpt';
export * from './typedSuccessResponse';
export * from './typedSuccessResponseDataOneOf';
export * from './typedSuccessResponseGetDocumentResponseData';
@@ -1288,6 +1332,8 @@ export * from './view';
export * from './viewPatch';
export * from './viewPatchName';
export * from './viewsResponse';
+export * from './waitingForInputMetadata';
+export * from './waitingForInputMetadataAnnouncementMessageId';
export * from './webhook';
export * from './webhookDeletedAt';
export * from './webhookFilter';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/inputReceivedMetadata.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/inputReceivedMetadata.ts
new file mode 100644
index 0000000000..358ce002f4
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/inputReceivedMetadata.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentActionId } from './agentActionId';
+import type { SessionIdentity } from './sessionIdentity';
+
+/**
+ * The pending question was answered or withdrawn.
+ */
+export interface InputReceivedMetadata {
+ /** The action that opened the turn. */
+ action_id: AgentActionId;
+ /** The session. */
+ identity: SessionIdentity;
+ /**
+ * The turn that was asking.
+ * @minimum 0
+ */
+ turn: number;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionDeletedMetadata.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionDeletedMetadata.ts
new file mode 100644
index 0000000000..5d823a5560
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionDeletedMetadata.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SessionIdentity } from './sessionIdentity';
+
+/**
+ * The session was deleted.
+ */
+export interface SessionDeletedMetadata {
+ /** The session as it was. */
+ identity: SessionIdentity;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionIdentity.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionIdentity.ts
new file mode 100644
index 0000000000..2ef6e49b26
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionIdentity.ts
@@ -0,0 +1,27 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { BotId } from './botId';
+import type { MacroUserIdStr } from './macroUserIdStr';
+import type { SessionIdentityOrigin } from './sessionIdentityOrigin';
+
+/**
+ * Who and what a session is; carried by every lifecycle event so a
+consumer never has to look the session up.
+ */
+export interface SessionIdentity {
+ /** Bot the session runs for. */
+ bot_id: BotId;
+ /** The bot's display name at the time of the event. */
+ bot_name: string;
+ origin?: SessionIdentityOrigin;
+ /** User who owns the session. */
+ owner_id: MacroUserIdStr;
+ /** The session. */
+ session_id: string;
+ /** User-facing session name at the time of the event. */
+ session_name: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionIdentityOrigin.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionIdentityOrigin.ts
new file mode 100644
index 0000000000..3626546e6c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionIdentityOrigin.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ThreadOrigin } from './threadOrigin';
+
+export type SessionIdentityOrigin = null | ThreadOrigin;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionOpenedMetadata.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionOpenedMetadata.ts
new file mode 100644
index 0000000000..e77b550c3e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionOpenedMetadata.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 { SessionIdentity } from './sessionIdentity';
+
+/**
+ * A session was created.
+ */
+export interface SessionOpenedMetadata {
+ /** Harness slug the session runs on. */
+ harness: string;
+ /** The session. */
+ identity: SessionIdentity;
+ /** Model slug the session runs with. */
+ model: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionRenamedMetadata.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionRenamedMetadata.ts
new file mode 100644
index 0000000000..bf9ad070bf
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionRenamedMetadata.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SessionIdentity } from './sessionIdentity';
+
+/**
+ * The session was renamed; `identity` carries the new name.
+ */
+export interface SessionRenamedMetadata {
+ /** The session, with its new name. */
+ identity: SessionIdentity;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionSettledMetadata.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionSettledMetadata.ts
new file mode 100644
index 0000000000..4a036c94b6
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionSettledMetadata.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SessionIdentity } from './sessionIdentity';
+import type { SessionSettledMetadataLastTurn } from './sessionSettledMetadataLastTurn';
+
+/**
+ * A turn ended and nothing is queued: the agent has stopped working.
+ */
+export interface SessionSettledMetadata {
+ /** The session. */
+ identity: SessionIdentity;
+ last_turn?: SessionSettledMetadataLastTurn;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionSettledMetadataLastTurn.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionSettledMetadataLastTurn.ts
new file mode 100644
index 0000000000..89afa9888b
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionSettledMetadataLastTurn.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { TurnSummary } from './turnSummary';
+
+export type SessionSettledMetadataLastTurn = null | TurnSummary;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionStoppedMetadata.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionStoppedMetadata.ts
new file mode 100644
index 0000000000..0465485164
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionStoppedMetadata.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 { SessionIdentity } from './sessionIdentity';
+import type { SessionStoppedMetadataTurnInFlight } from './sessionStoppedMetadataTurnInFlight';
+
+/**
+ * The session's live actor is gone: idle teardown, transport loss, or crash.
+ */
+export interface SessionStoppedMetadata {
+ /** The session. */
+ identity: SessionIdentity;
+ /** Why it stopped, as the session machine reported it. */
+ reason: string;
+ turn_in_flight?: SessionStoppedMetadataTurnInFlight;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionStoppedMetadataTurnInFlight.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionStoppedMetadataTurnInFlight.ts
new file mode 100644
index 0000000000..0c44986fc7
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sessionStoppedMetadataTurnInFlight.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { InFlightTurnSummary } from './inFlightTurnSummary';
+
+export type SessionStoppedMetadataTurnInFlight = null | InFlightTurnSummary;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadOrigin.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadOrigin.ts
new file mode 100644
index 0000000000..f50c717834
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadOrigin.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The channel thread a session was opened from, when it was.
+ */
+export interface ThreadOrigin {
+ /** Channel the thread lives in. */
+ channel_id: string;
+ /** The message whose mention opened the session. */
+ originating_message_id: string;
+ /** Root message of the thread. */
+ thread_id: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnEndedMetadata.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnEndedMetadata.ts
new file mode 100644
index 0000000000..1c41131cf1
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnEndedMetadata.ts
@@ -0,0 +1,36 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentActionId } from './agentActionId';
+import type { SessionIdentity } from './sessionIdentity';
+import type { TurnEndedMetadataActor } from './turnEndedMetadataActor';
+import type { TurnEndedMetadataAnnouncementMessageId } from './turnEndedMetadataAnnouncementMessageId';
+
+/**
+ * The runtime answered a turn. Another prompt may follow at once; see
+[`SessionSettledMetadata`] for "nothing left to do".
+ */
+export interface TurnEndedMetadata {
+ /** The action that opened the turn. */
+ action_id: AgentActionId;
+ actor?: TurnEndedMetadataActor;
+ /** The magic-chip message posted for this turn, when one was. */
+ announcement_message_id?: TurnEndedMetadataAnnouncementMessageId;
+ /** The session. */
+ identity: SessionIdentity;
+ /**
+ * Prompts still waiting behind this turn.
+ * @minimum 0
+ */
+ queued_remaining: number;
+ /** The ACP stop reason, or `"error"` when the runtime refused the prompt. */
+ stop_reason: string;
+ /**
+ * Position in the session's log.
+ * @minimum 0
+ */
+ turn: number;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnEndedMetadataActor.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnEndedMetadataActor.ts
new file mode 100644
index 0000000000..f5afc30f63
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnEndedMetadataActor.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { MacroUserIdStr } from './macroUserIdStr';
+
+export type TurnEndedMetadataActor = null | MacroUserIdStr;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnEndedMetadataAnnouncementMessageId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnEndedMetadataAnnouncementMessageId.ts
new file mode 100644
index 0000000000..7b28523ac8
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnEndedMetadataAnnouncementMessageId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The magic-chip message posted for this turn, when one was.
+ */
+export type TurnEndedMetadataAnnouncementMessageId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnStartedMetadata.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnStartedMetadata.ts
new file mode 100644
index 0000000000..29f4682ecf
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnStartedMetadata.ts
@@ -0,0 +1,28 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentActionId } from './agentActionId';
+import type { SessionIdentity } from './sessionIdentity';
+import type { TurnStartedMetadataActor } from './turnStartedMetadataActor';
+import type { TurnStartedMetadataAnnouncementMessageId } from './turnStartedMetadataAnnouncementMessageId';
+
+/**
+ * A prompt was delivered to the runtime.
+ */
+export interface TurnStartedMetadata {
+ /** The action that opened the turn. */
+ action_id: AgentActionId;
+ actor?: TurnStartedMetadataActor;
+ /** The magic-chip message posted for this turn, when one was. */
+ announcement_message_id?: TurnStartedMetadataAnnouncementMessageId;
+ /** The session. */
+ identity: SessionIdentity;
+ /**
+ * Position in the session's log.
+ * @minimum 0
+ */
+ turn: number;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnStartedMetadataActor.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnStartedMetadataActor.ts
new file mode 100644
index 0000000000..f12c6324f5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnStartedMetadataActor.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { MacroUserIdStr } from './macroUserIdStr';
+
+export type TurnStartedMetadataActor = null | MacroUserIdStr;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnStartedMetadataAnnouncementMessageId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnStartedMetadataAnnouncementMessageId.ts
new file mode 100644
index 0000000000..34febd249c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnStartedMetadataAnnouncementMessageId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The magic-chip message posted for this turn, when one was.
+ */
+export type TurnStartedMetadataAnnouncementMessageId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnSummary.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnSummary.ts
new file mode 100644
index 0000000000..79706221cc
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnSummary.ts
@@ -0,0 +1,31 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentActionId } from './agentActionId';
+import type { TurnSummaryActor } from './turnSummaryActor';
+import type { TurnSummaryAnnouncementMessageId } from './turnSummaryAnnouncementMessageId';
+import type { TurnSummaryExcerpt } from './turnSummaryExcerpt';
+
+/**
+ * A turn the runtime answered.
+ */
+export interface TurnSummary {
+ /** The action that opened the turn. */
+ action_id: AgentActionId;
+ actor?: TurnSummaryActor;
+ /** The magic-chip message posted for this turn, when one was. */
+ announcement_message_id?: TurnSummaryAnnouncementMessageId;
+ /** The agent's last text in the turn, whole; what the magic chip shows
+once the turn ends. `None` when the turn produced no prose. */
+ excerpt?: TurnSummaryExcerpt;
+ /** The ACP stop reason, or `"error"` when the runtime refused the prompt. */
+ stop_reason: string;
+ /**
+ * Position in the session's log.
+ * @minimum 0
+ */
+ turn: number;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnSummaryActor.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnSummaryActor.ts
new file mode 100644
index 0000000000..e84d3e4f62
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnSummaryActor.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { MacroUserIdStr } from './macroUserIdStr';
+
+export type TurnSummaryActor = null | MacroUserIdStr;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnSummaryAnnouncementMessageId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnSummaryAnnouncementMessageId.ts
new file mode 100644
index 0000000000..2a4b75e6bd
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnSummaryAnnouncementMessageId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The magic-chip message posted for this turn, when one was.
+ */
+export type TurnSummaryAnnouncementMessageId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnSummaryExcerpt.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnSummaryExcerpt.ts
new file mode 100644
index 0000000000..06eb977933
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/turnSummaryExcerpt.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The agent's last text in the turn, whole; what the magic chip shows
+once the turn ends. `None` when the turn produced no prose.
+ */
+export type TurnSummaryExcerpt = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/waitingForInputMetadata.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/waitingForInputMetadata.ts
new file mode 100644
index 0000000000..1f5aa4d46b
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/waitingForInputMetadata.ts
@@ -0,0 +1,28 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentActionId } from './agentActionId';
+import type { SessionIdentity } from './sessionIdentity';
+import type { WaitingForInputMetadataAnnouncementMessageId } from './waitingForInputMetadataAnnouncementMessageId';
+
+/**
+ * The agent asked its owner a question and is blocked on the answer.
+ */
+export interface WaitingForInputMetadata {
+ /** The action that opened the turn. */
+ action_id: AgentActionId;
+ /** The magic-chip message posted for this turn, when one was. */
+ announcement_message_id?: WaitingForInputMetadataAnnouncementMessageId;
+ /** The session. */
+ identity: SessionIdentity;
+ /** The question, as the agent phrased it. */
+ question: string;
+ /**
+ * The turn asking.
+ * @minimum 0
+ */
+ turn: number;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/waitingForInputMetadataAnnouncementMessageId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/waitingForInputMetadataAnnouncementMessageId.ts
new file mode 100644
index 0000000000..68dcc241c8
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/waitingForInputMetadataAnnouncementMessageId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The magic-chip message posted for this turn, when one was.
+ */
+export type WaitingForInputMetadataAnnouncementMessageId = string | null;
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 40ef448102..357adc5241 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -12923,6 +12923,11 @@
}
}
},
+ "AgentActionId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Identifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives.\n\nMinted only by the server at accept time, as a v7 uuid so ids sort by mint\ntime. On the wire and in JSON it is the bare uuid, and a uuid-shaped\nrequest id is the whole ownership test: the server is the only writer of\nruntime-bound frames. The machine's own handshake request ids\n(`agent_session:{session}:{n}`) are not uuids and stay `None`."
+ },
"AgentChannelScope": {
"type": "string",
"description": "Whether an agent is available everywhere or only in selected channels.",
@@ -12977,6 +12982,146 @@
],
"description": "Which Pipedream MCP servers an agent's sessions are handed.\n\nOne value for the whole choice, so a selection can never travel without\nits scope or a scope without its selection. Serialized with a `scope` tag,\nwhich the generated TypeScript sees as a discriminated union."
},
+ "AgentSessionLifecycleEvent": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "A session was created.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.opened"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/SessionOpenedMetadata",
+ "description": "A session was created."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "A prompt was delivered to the runtime.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.turn_started"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/TurnStartedMetadata",
+ "description": "A prompt was delivered to the runtime."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The runtime answered a turn.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.turn_ended"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/TurnEndedMetadata",
+ "description": "The runtime answered a turn."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "A turn ended with nothing queued behind it.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.settled"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/SessionSettledMetadata",
+ "description": "A turn ended with nothing queued behind it."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The agent is blocked on a question to its owner.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.waiting_for_input"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/WaitingForInputMetadata",
+ "description": "The agent is blocked on a question to its owner."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The question was answered or withdrawn.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.input_received"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/InputReceivedMetadata",
+ "description": "The question was answered or withdrawn."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The session's live actor is gone.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.stopped"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/SessionStoppedMetadata",
+ "description": "The session's live actor is gone."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The session was renamed.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.renamed"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/SessionRenamedMetadata",
+ "description": "The session was renamed."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The session was deleted.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.deleted"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/SessionDeletedMetadata",
+ "description": "The session was deleted."
+ }
+ }
+ }
+ ],
+ "description": "Events publishable to [`MacroAgentSessionLifecycleTopic`].\n\nThe serde tag and [`AgentSessionLifecycleEventName`] spell the same wire\nnames: subscribers filter on them, so they are API. The\n`event_names_match_the_wire` test holds the two in step. Exhaustive on\npurpose: a consumer's match should break when a variant is added."
+ },
"Anchor": {
"oneOf": [
{
@@ -22199,6 +22344,60 @@
"type": "integer",
"enum": [1, 2, 3]
},
+ "InFlightTurnSummary": {
+ "type": "object",
+ "description": "A turn the runtime never answered: the session stopped underneath it.",
+ "required": ["turn", "action_id"],
+ "properties": {
+ "action_id": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "The action that opened the turn."
+ },
+ "actor": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "User who prompted it, absent when a bot acted on nobody's behalf."
+ }
+ ]
+ },
+ "announcement_message_id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The magic-chip message posted for this turn, when one was."
+ },
+ "turn": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Position in the session's log.",
+ "minimum": 0
+ }
+ }
+ },
+ "InputReceivedMetadata": {
+ "type": "object",
+ "description": "The pending question was answered or withdrawn.",
+ "required": ["identity", "turn", "action_id"],
+ "properties": {
+ "action_id": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "The action that opened the turn."
+ },
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session."
+ },
+ "turn": {
+ "type": "integer",
+ "format": "int32",
+ "description": "The turn that was asking.",
+ "minimum": 0
+ }
+ }
+ },
"InteractionReason": {
"type": "string",
"description": "Why a document interaction was reported.",
@@ -24291,6 +24490,140 @@
}
}
},
+ "SessionDeletedMetadata": {
+ "type": "object",
+ "description": "The session was deleted.",
+ "required": ["identity"],
+ "properties": {
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session as it was."
+ }
+ }
+ },
+ "SessionIdentity": {
+ "type": "object",
+ "description": "Who and what a session is; carried by every lifecycle event so a\nconsumer never has to look the session up.",
+ "required": [
+ "session_id",
+ "session_name",
+ "bot_id",
+ "bot_name",
+ "owner_id"
+ ],
+ "properties": {
+ "bot_id": {
+ "$ref": "#/components/schemas/BotId",
+ "description": "Bot the session runs for."
+ },
+ "bot_name": {
+ "type": "string",
+ "description": "The bot's display name at the time of the event."
+ },
+ "origin": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ThreadOrigin",
+ "description": "Thread the session was opened from, when it was."
+ }
+ ]
+ },
+ "owner_id": {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "User who owns the session."
+ },
+ "session_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The session."
+ },
+ "session_name": {
+ "type": "string",
+ "description": "User-facing session name at the time of the event."
+ }
+ }
+ },
+ "SessionOpenedMetadata": {
+ "type": "object",
+ "description": "A session was created.",
+ "required": ["identity", "model", "harness"],
+ "properties": {
+ "harness": {
+ "type": "string",
+ "description": "Harness slug the session runs on."
+ },
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session."
+ },
+ "model": {
+ "type": "string",
+ "description": "Model slug the session runs with."
+ }
+ }
+ },
+ "SessionRenamedMetadata": {
+ "type": "object",
+ "description": "The session was renamed; `identity` carries the new name.",
+ "required": ["identity"],
+ "properties": {
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session, with its new name."
+ }
+ }
+ },
+ "SessionSettledMetadata": {
+ "type": "object",
+ "description": "A turn ended and nothing is queued: the agent has stopped working.",
+ "required": ["identity"],
+ "properties": {
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session."
+ },
+ "last_turn": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/TurnSummary",
+ "description": "The turn that just ended, when the emitter still had its record."
+ }
+ ]
+ }
+ }
+ },
+ "SessionStoppedMetadata": {
+ "type": "object",
+ "description": "The session's live actor is gone: idle teardown, transport loss, or crash.",
+ "required": ["identity", "reason"],
+ "properties": {
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session."
+ },
+ "reason": {
+ "type": "string",
+ "description": "Why it stopped, as the session machine reported it."
+ },
+ "turn_in_flight": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/InFlightTurnSummary",
+ "description": "The turn that was running when it stopped, if any."
+ }
+ ]
+ }
+ }
+ },
"SetCompanyHiddenRequest": {
"type": "object",
"description": "Request body for `PUT /companies/{company_id}/hidden`.",
@@ -26470,6 +26803,28 @@
}
}
},
+ "ThreadOrigin": {
+ "type": "object",
+ "description": "The channel thread a session was opened from, when it was.",
+ "required": ["channel_id", "thread_id", "originating_message_id"],
+ "properties": {
+ "channel_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Channel the thread lives in."
+ },
+ "originating_message_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The message whose mention opened the session."
+ },
+ "thread_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Root message of the thread."
+ }
+ }
+ },
"ThreadResponse": {
"type": "object",
"required": ["data"],
@@ -26538,6 +26893,136 @@
}
}
},
+ "TurnEndedMetadata": {
+ "type": "object",
+ "description": "The runtime answered a turn. Another prompt may follow at once; see\n[`SessionSettledMetadata`] for \"nothing left to do\".",
+ "required": [
+ "identity",
+ "turn",
+ "action_id",
+ "stop_reason",
+ "queued_remaining"
+ ],
+ "properties": {
+ "action_id": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "The action that opened the turn."
+ },
+ "actor": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "User who prompted it, absent when a bot acted on nobody's behalf."
+ }
+ ]
+ },
+ "announcement_message_id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The magic-chip message posted for this turn, when one was."
+ },
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session."
+ },
+ "queued_remaining": {
+ "type": "integer",
+ "description": "Prompts still waiting behind this turn.",
+ "minimum": 0
+ },
+ "stop_reason": {
+ "type": "string",
+ "description": "The ACP stop reason, or `\"error\"` when the runtime refused the prompt."
+ },
+ "turn": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Position in the session's log.",
+ "minimum": 0
+ }
+ }
+ },
+ "TurnStartedMetadata": {
+ "type": "object",
+ "description": "A prompt was delivered to the runtime.",
+ "required": ["identity", "turn", "action_id"],
+ "properties": {
+ "action_id": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "The action that opened the turn."
+ },
+ "actor": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "User who prompted it, absent when a bot acted on nobody's behalf."
+ }
+ ]
+ },
+ "announcement_message_id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The magic-chip message posted for this turn, when one was."
+ },
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session."
+ },
+ "turn": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Position in the session's log.",
+ "minimum": 0
+ }
+ }
+ },
+ "TurnSummary": {
+ "type": "object",
+ "description": "A turn the runtime answered.",
+ "required": ["turn", "action_id", "stop_reason"],
+ "properties": {
+ "action_id": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "The action that opened the turn."
+ },
+ "actor": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "User who prompted it, absent when a bot acted on nobody's behalf."
+ }
+ ]
+ },
+ "announcement_message_id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The magic-chip message posted for this turn, when one was."
+ },
+ "excerpt": {
+ "type": ["string", "null"],
+ "description": "The agent's last text in the turn, whole; what the magic chip shows\nonce the turn ends. `None` when the turn produced no prose."
+ },
+ "stop_reason": {
+ "type": "string",
+ "description": "The ACP stop reason, or `\"error\"` when the runtime refused the prompt."
+ },
+ "turn": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Position in the session's log.",
+ "minimum": 0
+ }
+ }
+ },
"TypedSuccessResponse": {
"type": "object",
"required": ["error", "data"],
@@ -27117,6 +27602,36 @@
}
}
},
+ "WaitingForInputMetadata": {
+ "type": "object",
+ "description": "The agent asked its owner a question and is blocked on the answer.",
+ "required": ["identity", "turn", "action_id", "question"],
+ "properties": {
+ "action_id": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "The action that opened the turn."
+ },
+ "announcement_message_id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The magic-chip message posted for this turn, when one was."
+ },
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session."
+ },
+ "question": {
+ "type": "string",
+ "description": "The question, as the agent phrased it."
+ },
+ "turn": {
+ "type": "integer",
+ "format": "int32",
+ "description": "The turn asking.",
+ "minimum": 0
+ }
+ }
+ },
"Webhook": {
"type": "object",
"description": "Webhook row returned by application APIs.\n\nClients deserialize this, so both derives are used.",
@@ -27201,6 +27716,10 @@
{
"$ref": "#/components/schemas/ChannelTopicEvent",
"description": "Channel and message events from the `macro.channels` topic."
+ },
+ {
+ "$ref": "#/components/schemas/AgentSessionLifecycleEvent",
+ "description": "Agent session lifecycle events from the `macro.agent_session_lifecycle`\ntopic."
}
],
"description": "Any entity event deliverable to a webhook endpoint.\n\nSerialized bodies carry an `event_type` tag naming the event (for example\n`document.created` or `channel.message_posted`) and a `metadata` object\nwith the event payload. Endpoint validation additionally sends a\n`WebhookValidationTestEvent`, which is not part of this union."
diff --git a/crates/agent_fold/src/domain/lifecycle.rs b/crates/agent_fold/src/domain/lifecycle.rs
new file mode 100644
index 0000000000..e7d59c320f
--- /dev/null
+++ b/crates/agent_fold/src/domain/lifecycle.rs
@@ -0,0 +1,155 @@
+//! [`LifecycleFold`]: the fold, plus what each frame meant for the turn.
+//!
+//! The fold already knows when an agent message closes and why, what it
+//! said, and which question it is holding for the user. Everything else that
+//! wanted those facts used to derive them again from the raw frames - the
+//! session machine parsing `stopReason` a second time, the harness refolding
+//! the log to find the last passage. This wraps the fold once and hands the
+//! facts back with every push as [`TurnSignal`]s, so there is one definition
+//! of "the turn ended", and it is the one the chip renders from.
+//!
+//! Deliberately not a [`FoldMachine`](crate::domain::ports::FoldMachine): a
+//! signal is inseparable from the frame that implied it, so [`push`] returns
+//! the fold's events and the turn's signals together, and nothing is held
+//! back for later. Folding stored history is the caller's plain decision to
+//! push it and ignore what it signals - history is not news, and only the
+//! caller knows which frames are history.
+//!
+//! [`push`]: LifecycleFold::push
+
+use std::collections::HashSet;
+
+use crate::domain::fold::FoldMachineImpl;
+use crate::domain::log::AgentSessionLog;
+use crate::domain::model::{
+ Author, ElicitationRequestId, FoldEvent, FoldedMessage, MessagePart, OwnedFoldEvent,
+ SessionMetadata, TurnId, TurnSignal,
+};
+use crate::domain::ports::FoldMachine as _;
+
+/// What one frame did: how the fold's messages changed, and what that meant
+/// for the turn.
+#[derive(Debug, Default, PartialEq)]
+#[must_use = "a dropped push loses the frame's turn signals"]
+pub struct Pushed {
+ /// The fold's own report, exactly as a bare [`FoldMachineImpl`] gives it.
+ pub events: Vec<OwnedFoldEvent>,
+ /// The turn facts the frame established, in order. Usually empty.
+ pub signals: Vec<TurnSignal>,
+}
+
+/// A fold that also says what each frame meant for the turn's lifecycle.
+#[derive(Debug, Default)]
+pub struct LifecycleFold {
+ inner: FoldMachineImpl,
+ /// Turns already reported closed. A later update to a closed agent
+ /// message must not close its turn twice.
+ closed: HashSet<TurnId>,
+ /// The pending elicitation after the last push, to diff against.
+ pending: Option<(ElicitationRequestId, TurnId)>,
+}
+
+impl LifecycleFold {
+ /// A fold that has folded nothing.
+ #[must_use]
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Advance the fold by one frame, reporting its events and turn signals.
+ pub fn push(&mut self, log: AgentSessionLog) -> Pushed {
+ let events: Vec<OwnedFoldEvent> = self
+ .inner
+ .push(log)
+ .into_iter()
+ .map(FoldEvent::into_owned)
+ .collect();
+ let mut signals = Vec::new();
+ for event in &events {
+ match event {
+ FoldEvent::NewMessage(message) | FoldEvent::MessageUpdate(message) => {
+ self.observe_message(message, &mut signals);
+ }
+ FoldEvent::MessagesReplaced(messages) => self.observe_replacement(messages),
+ FoldEvent::MetadataUpdated(metadata) => {
+ self.observe_metadata(metadata, &mut signals);
+ }
+ }
+ }
+ Pushed { events, signals }
+ }
+
+ /// The fold itself, for its messages and metadata.
+ #[must_use]
+ pub fn inner(&self) -> &FoldMachineImpl {
+ &self.inner
+ }
+
+ fn observe_message(&mut self, message: &FoldedMessage, signals: &mut Vec<TurnSignal>) {
+ let (Author::Agent, Some(stop)) = (&message.author, &message.stop) else {
+ return;
+ };
+ if !self.closed.insert(message.id) {
+ return;
+ }
+ // The prompt that opened the turn carries the action id; the agent's
+ // reply never does.
+ let action_id = self
+ .inner
+ .messages()
+ .iter()
+ .find(|candidate| {
+ candidate.id == message.id && matches!(candidate.author, Author::User { .. })
+ })
+ .and_then(|prompt| prompt.request_id);
+ signals.push(TurnSignal::TurnEnded {
+ turn: message.id,
+ action_id,
+ stop: stop.clone(),
+ last_text: last_text(message),
+ });
+ }
+
+ fn observe_metadata(&mut self, metadata: &SessionMetadata, signals: &mut Vec<TurnSignal>) {
+ let now = metadata
+ .pending_elicitation
+ .as_ref()
+ .map(|pending| (pending.request_id.clone(), TurnId(pending.turn)));
+ if now == self.pending {
+ return;
+ }
+ let before = std::mem::replace(&mut self.pending, now.clone());
+ if let Some((request_id, turn)) = before {
+ signals.push(TurnSignal::ElicitationCleared { turn, request_id });
+ }
+ if let (Some((request_id, turn)), Some(pending)) = (now, &metadata.pending_elicitation) {
+ signals.push(TurnSignal::ElicitationRaised {
+ turn,
+ request_id,
+ question: pending.message.clone(),
+ });
+ }
+ }
+
+ fn observe_replacement(&mut self, messages: &[FoldedMessage]) {
+ self.closed = messages
+ .iter()
+ .filter(|message| matches!(message.author, Author::Agent) && message.stop.is_some())
+ .map(|message| message.id)
+ .collect();
+ }
+}
+
+/// The last prose part of a message, trimmed; `None` when there is none.
+fn last_text(message: &FoldedMessage) -> Option<String> {
+ message
+ .parts
+ .iter()
+ .rev()
+ .find_map(|part| match part {
+ MessagePart::Text { text } => Some(text.trim()),
+ _ => None,
+ })
+ .filter(|text| !text.is_empty())
+ .map(str::to_owned)
+}
diff --git a/crates/agent_fold/src/domain/mod.rs b/crates/agent_fold/src/domain/mod.rs
index c42ed55dab..cb7b9de1da 100644
--- a/crates/agent_fold/src/domain/mod.rs
+++ b/crates/agent_fold/src/domain/mod.rs
@@ -9,6 +9,8 @@ pub mod fold;
pub mod harness;
/// Durable snapshot and live-row ingestion around the append-only protocol fold.
pub mod ingestion;
+/// A fold that also reports what each frame meant for the turn.
+pub mod lifecycle;
/// The raw log vocabulary the fold consumes.
pub mod log;
/// The renderable message vocabulary.
diff --git a/crates/agent_fold/src/domain/model.rs b/crates/agent_fold/src/domain/model.rs
index e28a014bee..1d407e61f3 100644
--- a/crates/agent_fold/src/domain/model.rs
+++ b/crates/agent_fold/src/domain/model.rs
@@ -30,6 +30,8 @@ mod part;
mod permission;
/// The agent's plan.
mod plan;
+/// Turn-level facts derived from the fold.
+mod signal;
/// Delegated agents.
mod subagent;
/// Tool calls.
@@ -47,6 +49,7 @@ pub use metadata::{AvailableCommand, Harness, ModelOption, SessionMetadata};
pub use part::{Control, ControlOutcome, MessagePart, StopReason};
pub use permission::{PermissionOption, PermissionOptionKind, PermissionOutcome};
pub use plan::{PlanEntry, PlanEntryPriority, PlanEntryStatus};
+pub use signal::TurnSignal;
pub use subagent::{SubagentResult, ToolStats};
pub use tool::{AnsiText, FileDiff, ToolDetail, ToolName, ToolStatus};
pub use user_tool::UserToolOutcome;
diff --git a/crates/agent_fold/src/domain/model/part.rs b/crates/agent_fold/src/domain/model/part.rs
index 802e7dda2c..71f946337b 100644
--- a/crates/agent_fold/src/domain/model/part.rs
+++ b/crates/agent_fold/src/domain/model/part.rs
@@ -2,7 +2,7 @@
use std::str::FromStr;
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
use specta::Type;
use super::ToolUseId;
@@ -166,7 +166,7 @@ pub enum ControlOutcome {
/// anything unmodelled falls through to [`Self::Other`], so parsing never
/// fails. [`Self::Failed`] is the exception - no wire string produces it,
/// because it is what a turn that got no `stopReason` at all stopped for.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum StopReason {
/// The agent finished its turn.
diff --git a/crates/agent_fold/src/domain/model/signal.rs b/crates/agent_fold/src/domain/model/signal.rs
new file mode 100644
index 0000000000..fc2e0011cd
--- /dev/null
+++ b/crates/agent_fold/src/domain/model/signal.rs
@@ -0,0 +1,47 @@
+//! Turn-level facts derived from the fold, for whoever drives a session.
+
+use agent_runtime_protocol::domain::action::AgentActionId;
+use serde::{Deserialize, Serialize};
+
+use super::{ElicitationRequestId, StopReason};
+use crate::domain::model::TurnId;
+
+/// A turn-level fact the fold vouches for, derived from one pushed frame.
+///
+/// These are what the log means for the session's lifecycle, as opposed to
+/// how it renders: the harness gates its prompt queue on them and publishes
+/// them downstream. Only facts the log can establish appear here. That a
+/// prompt was dispatched, or that nothing is queued behind a turn, is the
+/// dispatcher's knowledge and stays with it.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub enum TurnSignal {
+ /// The agent's message for `turn` closed.
+ TurnEnded {
+ /// The turn that closed.
+ turn: TurnId,
+ /// The prompt's action id, when the turn was opened by one this
+ /// server minted. `None` for a turn resumed from elsewhere.
+ action_id: Option<AgentActionId>,
+ /// How the turn stopped.
+ stop: StopReason,
+ /// The last text part of the agent's message, whole. `None` when the
+ /// turn ended without prose.
+ last_text: Option<String>,
+ },
+ /// The agent is holding a question for the owner.
+ ElicitationRaised {
+ /// The turn asking.
+ turn: TurnId,
+ /// The agent's request id; what an answer must name.
+ request_id: ElicitationRequestId,
+ /// What the agent is asking, in prose.
+ question: String,
+ },
+ /// The held question was answered or withdrawn.
+ ElicitationCleared {
+ /// The turn that was asking.
+ turn: TurnId,
+ /// The request that was held.
+ request_id: ElicitationRequestId,
+ },
+}
diff --git a/crates/agent_fold/src/domain/test.rs b/crates/agent_fold/src/domain/test.rs
index 230269eb93..980cd7bd45 100644
--- a/crates/agent_fold/src/domain/test.rs
+++ b/crates/agent_fold/src/domain/test.rs
@@ -5,6 +5,7 @@ mod elicitation;
mod fold;
mod harness;
mod harness_readers;
+mod lifecycle;
mod machine;
mod macro_tools;
mod metadata;
diff --git a/crates/agent_fold/src/domain/test/lifecycle.rs b/crates/agent_fold/src/domain/test/lifecycle.rs
new file mode 100644
index 0000000000..fdc8950830
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/lifecycle.rs
@@ -0,0 +1,265 @@
+//! What the lifecycle fold signals, and what it stays silent about.
+use super::util::{TURN, parse_log};
+use crate::domain::fold::{FoldMachineImpl, fold};
+use crate::domain::lifecycle::LifecycleFold;
+use crate::domain::log::AgentSessionLog;
+use crate::domain::model::{FoldEvent, FoldedMessage, StopReason, TurnSignal};
+use crate::domain::ports::FoldMachine as _;
+use crate::testing::fixtures::{ELICITATION_CLAUDE_SINGLE_SELECT, RESUMED_NO_PROMPT};
+use serde_json::{Value, json};
+
+fn frame(direction: &str, body: Value) -> AgentSessionLog {
+ let mut content = body;
+ content["type"] = json!("acp");
+ content["jsonrpc"] = json!("2.0");
+ parse_log(&json!({"direction":direction,"content":content}).to_string())
+ .pop()
+ .unwrap()
+}
+fn request(method: &str, id: Value) -> AgentSessionLog {
+ frame(
+ "to_runtime",
+ json!({"id":id,"method":method,"params":{"sessionId":"s","cwd":"/","mcpServers":[]}}),
+ )
+}
+fn prompt(id: Value, text: &str) -> AgentSessionLog {
+ frame(
+ "to_runtime",
+ json!({"id":id,"method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":text}]}}),
+ )
+}
+fn result(id: Value) -> AgentSessionLog {
+ frame("to_server", json!({"id":id,"result":{}}))
+}
+fn update(kind: &str, text: &str) -> AgentSessionLog {
+ frame(
+ "to_server",
+ json!({"method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":kind,"content":{"type":"text","text":text}}}}),
+ )
+}
+
+/// Push a whole log live and collect every signal, in order.
+fn signals_of(log: &[AgentSessionLog]) -> (LifecycleFold, Vec<TurnSignal>) {
+ let mut machine = LifecycleFold::new();
+ let mut signals = Vec::new();
+ for entry in log {
+ signals.extend(machine.push(entry.clone()).signals);
+ }
+ (machine, signals)
+}
+
+fn apply(visible: &mut Vec<FoldedMessage>, event: FoldEvent<'_>) {
+ match event {
+ FoldEvent::MessagesReplaced(messages) => *visible = messages.into_owned(),
+ FoldEvent::NewMessage(message) => visible.push(message.into_owned()),
+ FoldEvent::MessageUpdate(message) => {
+ let at = visible
+ .iter()
+ .position(|old| old.id() == message.id())
+ .unwrap();
+ visible[at] = message.into_owned();
+ }
+ FoldEvent::MetadataUpdated(_) => {}
+ }
+}
+
+#[test]
+fn passes_fold_events_through_unchanged() {
+ let log = parse_log(TURN);
+ let mut lifecycle = LifecycleFold::new();
+ let mut bare = FoldMachineImpl::new();
+ let mut visible = vec![];
+ for entry in &log {
+ let wrapped = lifecycle.push(entry.clone()).events;
+ let plain: Vec<_> = bare
+ .push(entry.clone())
+ .into_iter()
+ .map(FoldEvent::into_owned)
+ .collect();
+ assert_eq!(wrapped, plain);
+ for event in wrapped {
+ apply(&mut visible, event);
+ }
+ assert_eq!(visible, lifecycle.inner().messages());
+ }
+ assert_eq!(visible, fold(log.iter().cloned()));
+}
+
+#[test]
+fn a_complete_turn_signals_one_end_with_its_stop_and_last_text() {
+ let log = parse_log(TURN);
+ let (machine, signals) = signals_of(&log);
+
+ let reply = machine
+ .inner()
+ .messages()
+ .iter()
+ .rev()
+ .find(|message| message.stop.is_some())
+ .expect("the agent's reply closed the turn");
+ assert!(
+ matches!(
+ signals.as_slice(),
+ [TurnSignal::TurnEnded { turn, action_id, stop: StopReason::EndTurn, last_text: Some(text) }]
+ if *turn == reply.id
+ // The hand-shaped fixture's prompt id is not a uuid this
+ // server minted, so no action id is attributed.
+ && action_id.is_none()
+ && !text.is_empty()
+ ),
+ "exactly one turn end, quoting the reply: {signals:#?}"
+ );
+}
+
+#[test]
+fn a_turn_our_prompt_opened_ends_naming_that_action() {
+ let action = "01a08989-2892-7311-9c01-3dd1efda7880";
+ let log = vec![
+ request("initialize", json!(0)),
+ result(json!(0)),
+ request("session/new", json!(1)),
+ frame("to_server", json!({"id":1,"result":{"sessionId":"s"}})),
+ prompt(json!(action), "do it"),
+ update("agent_message_chunk", "done"),
+ frame(
+ "to_server",
+ json!({"id":action,"result":{"stopReason":"end_turn"}}),
+ ),
+ ];
+ let (_, signals) = signals_of(&log);
+
+ assert!(
+ matches!(
+ signals.as_slice(),
+ [TurnSignal::TurnEnded { action_id: Some(id), stop: StopReason::EndTurn, last_text: Some(text), .. }]
+ if id.as_uuid().to_string() == action && text == "done"
+ ),
+ "{signals:#?}"
+ );
+}
+
+#[test]
+fn a_question_is_raised_then_cleared_before_the_turn_ends() {
+ let log = parse_log(ELICITATION_CLAUDE_SINGLE_SELECT);
+ let (_, signals) = signals_of(&log);
+
+ let kinds: Vec<&str> = signals
+ .iter()
+ .map(|signal| match signal {
+ TurnSignal::ElicitationRaised { .. } => "raised",
+ TurnSignal::ElicitationCleared { .. } => "cleared",
+ TurnSignal::TurnEnded { .. } => "ended",
+ })
+ .collect();
+ assert_eq!(kinds, ["raised", "cleared", "ended"], "{signals:#?}");
+ assert!(matches!(
+ &signals[0],
+ TurnSignal::ElicitationRaised { question, .. } if !question.is_empty()
+ ));
+ let (raised_id, cleared_id) = match (&signals[0], &signals[1]) {
+ (
+ TurnSignal::ElicitationRaised {
+ request_id: raised, ..
+ },
+ TurnSignal::ElicitationCleared {
+ request_id: cleared,
+ ..
+ },
+ ) => (raised, cleared),
+ other => panic!("{other:?}"),
+ };
+ assert_eq!(raised_id, cleared_id);
+}
+
+/// Folding stored history is the caller's plain decision to push it and
+/// ignore what it signals; the fold needs no notion of "history" for a live
+/// turn afterwards to be signalled correctly.
+#[test]
+fn history_pushed_and_ignored_leaves_a_live_turn_signalling_normally() {
+ let history = parse_log(TURN);
+ let mut live = LifecycleFold::new();
+ for entry in &history {
+ // What the log writer does on catch-up: fold, discard the signals.
+ let _ = live.push(entry.clone());
+ }
+ assert_eq!(live.inner().messages(), fold(history.iter().cloned()));
+
+ let _ = live.push(prompt(json!(7), "once more"));
+ let _ = live.push(update("agent_message_chunk", "again"));
+ let pushed = live.push(frame(
+ "to_server",
+ json!({"id":7,"result":{"stopReason":"end_turn"}}),
+ ));
+ assert!(
+ matches!(
+ pushed.signals.as_slice(),
+ [TurnSignal::TurnEnded { stop: StopReason::EndTurn, last_text: Some(text), .. }]
+ if text == "again"
+ ),
+ "{:#?}",
+ pushed.signals
+ );
+}
+
+#[test]
+fn a_load_replacement_signals_nothing_for_the_replaced_history() {
+ let load = json!(1);
+ let log = vec![
+ request("initialize", json!(0)),
+ result(json!(0)),
+ request("session/load", load.clone()),
+ update("user_message_chunk", "question"),
+ update("agent_message_chunk", "answer"),
+ result(load),
+ ];
+ let (machine, signals) = signals_of(&log);
+
+ assert!(signals.is_empty(), "{signals:#?}");
+ assert_eq!(machine.inner().messages().len(), 2);
+}
+
+/// A resumed session's log is history: its turns were replaced in, not
+/// lived through, so nothing about them is signalled.
+#[test]
+fn a_resumed_sessions_history_signals_nothing() {
+ let log = parse_log(RESUMED_NO_PROMPT);
+ let (machine, signals) = signals_of(&log);
+
+ assert!(signals.is_empty(), "{signals:#?}");
+ assert!(
+ machine
+ .inner()
+ .messages()
+ .iter()
+ .any(|message| message.stop.is_some())
+ );
+}
+
+/// A turn nobody here prompted - streamed after a resume - ends on the
+/// runtime's `_session/turn_complete`, which the session machine ignores but
+/// the fold does not.
+#[test]
+fn an_unprompted_turn_ends_on_turn_complete_with_no_action_id() {
+ let log = vec![
+ request("initialize", json!(0)),
+ result(json!(0)),
+ request("session/new", json!(1)),
+ frame("to_server", json!({"id":1,"result":{"sessionId":"s"}})),
+ update("user_message_chunk", "carried over"),
+ update("agent_message_chunk", "picking up where we left off"),
+ frame(
+ "to_server",
+ json!({"method":"_session/turn_complete","params":{"sessionId":"s","outcome":{"kind":"finished"}}}),
+ ),
+ ];
+ let (_, signals) = signals_of(&log);
+
+ assert!(
+ matches!(
+ signals.as_slice(),
+ [TurnSignal::TurnEnded { action_id: None, stop: StopReason::EndTurn, last_text: Some(text), .. }]
+ if text == "picking up where we left off"
+ ),
+ "{signals:#?}"
+ );
+}
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index 30502c609b..c1cd387663 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -2,6 +2,7 @@
use agent_client_protocol::schema::v1::{HttpHeader, McpServer as AcpMcpServer, McpServerHttp};
use agent_egress::domain::model::McpServerSlug;
+use agent_fold::domain::model::TurnSignal;
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
use agent_session::domain::model::{AgentMcpServers, AgentSessionId, MessageId, SandboxSize};
use agent_session::domain::ports::ControlEvent;
@@ -211,14 +212,18 @@ pub enum HarnessCommand {
/// The user responsible, as on [`Self::EditQueued`].
actor: Option<MacroUserIdStr<'static>>,
},
- /// The session's runtime answered its in-flight turn: clear the busy
- /// mark and dispatch the next queued action. Internal - enqueued by the
- /// turn observer on the managing replica, never forwarded.
- TurnEnded,
+ /// The session's fold reported a turn fact: an ended turn clears the
+ /// busy mark and dispatches the next queued action; a raised or cleared
+ /// question is published as is. Internal - enqueued by the turn observer
+ /// on the managing replica, never forwarded.
+ Turn(TurnSignal),
/// The session's live actor stopped: clear the busy mark and nothing
/// more - resuming a dead runtime stays the next user action's job.
- /// Internal, like [`Self::TurnEnded`].
- SessionStopped,
+ /// Internal, like [`Self::Turn`].
+ SessionStopped {
+ /// Why the actor stopped.
+ reason: String,
+ },
/// Change the session's sandbox size and the owner's default.
SetSandboxSize(SandboxSize),
/// Release a session's live resources and delete it.
@@ -306,6 +311,13 @@ pub struct SessionAnnouncement {
pub triggered_by: MacroUserIdStr<'static>,
}
+/// The channel message an announcement became.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct AnnouncedMessage {
+ /// The posted message: the magic chip its turn renders into.
+ pub message_id: Uuid,
+}
+
/// Values required to provision a new session container.
#[derive(Debug, Clone)]
pub struct SpawnContainer {
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index a6103a8da4..4bc5cc50d5 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -14,8 +14,8 @@ use macro_user_id::user_id::MacroUserIdStr;
use super::error::{HarnessError, Result};
use super::model::{
- AgentRuntimeConfig, CommandOutcome, HarnessCommand, PriorChannelMessage, ProvisionedEgress,
- SandboxEgress, SessionAnnouncement, SpawnContainer,
+ AgentRuntimeConfig, AnnouncedMessage, CommandOutcome, HarnessCommand, PriorChannelMessage,
+ ProvisionedEgress, SandboxEgress, SessionAnnouncement, SpawnContainer,
};
use super::sandbox::SandboxResizeEffect;
@@ -130,11 +130,11 @@ pub trait AgentPromptComposer: Send + Sync + 'static {
/// Posts a pointer to a new agent session into its originating thread.
pub trait SessionAnnouncer: Send + Sync + 'static {
- /// Publish one session announcement.
+ /// Publish one session announcement, returning the message it became.
fn announce(
&self,
announcement: SessionAnnouncement,
- ) -> impl Future<Output = Result<()>> + Send;
+ ) -> impl Future<Output = Result<AnnouncedMessage>> + Send;
}
/// Where a session finds its bot's live runtime connection.
diff --git a/crates/agent_harness/src/domain/ports/test.rs b/crates/agent_harness/src/domain/ports/test.rs
index 7a022dfa43..da73247a24 100644
--- a/crates/agent_harness/src/domain/ports/test.rs
+++ b/crates/agent_harness/src/domain/ports/test.rs
@@ -19,6 +19,10 @@ use super::ContainerManager;
use crate::domain::model::{AgentKind, SpawnContainer};
use crate::testing::helpers::containers::{ContainerMock, MockContainerManager};
use crate::testing::helpers::egress::test_egress;
+use agent_session::domain::model::ReplicaId;
+use agent_session::domain::ports::{
+ NoOpAgentSessionNameGenerator, NoOpTurnObserver, NoopLifecyclePublisher,
+};
fn owner() -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from_email("[email protected]").unwrap()
@@ -62,6 +66,10 @@ async fn container_session_runs_and_logs_end_to_end() {
store.clone(),
FoldedMessageService::new(store.clone()),
NoOpRealtime,
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
));
let containers = MockContainerManager::new();
let attachment = containers
@@ -146,6 +154,10 @@ async fn attaching_a_second_transport_to_an_active_session_fails() {
store.clone(),
FoldedMessageService::new(store),
NoOpRealtime,
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
);
let first = ContainerMock::default();
let second = ContainerMock::default();
diff --git a/crates/agent_harness/src/domain/queue.rs b/crates/agent_harness/src/domain/queue.rs
index c396354737..3b406963b7 100644
--- a/crates/agent_harness/src/domain/queue.rs
+++ b/crates/agent_harness/src/domain/queue.rs
@@ -17,12 +17,15 @@
use std::collections::VecDeque;
+use agent_fold::domain::model::TurnId;
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
+use agent_session::domain::events::{InFlightTurnSummary, TurnSummary};
use agent_session::domain::model::AgentSessionId;
use agent_session::domain::ports::QueuedControl;
use chrono::{DateTime, Utc};
use dashmap::DashMap;
use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
use super::model::AnnounceOrigin;
@@ -47,14 +50,59 @@ pub struct QueuedEntry {
/// Where to announce the prompt at dispatch, when it came from somewhere
/// the session should answer back into.
pub announce: Option<AnnounceOrigin>,
- /// Whether the chip has been posted. Set by the dispatch that posts it,
- /// and carried through a requeue, so a dispatch that fails *after*
+ /// The chip message, once posted. Set by the dispatch that posts it and
+ /// carried through a requeue, so a dispatch that fails *after*
/// announcing retries without posting a second chip.
- pub announced: bool,
+ pub announced: Option<Uuid>,
/// When it was accepted.
pub created_at: DateTime<Utc>,
}
+/// The turn a session is running: what the busy mark remembers once the
+/// queued entry has been consumed by dispatch.
+///
+/// In-memory like the queue: a restart mid-turn forgets it, and that turn's
+/// end is then observed without a record. `turn` is the fold's next turn id
+/// at dispatch, which for a compaction (no user message) is the turn the
+/// fold would assign to the next prompt.
+#[derive(Debug, Clone)]
+pub struct InFlightTurn {
+ /// The action that opened the turn.
+ pub action_id: AgentActionId,
+ /// Position in the session's log.
+ pub turn: TurnId,
+ /// The user who prompted it, absent when a bot acted on nobody's behalf.
+ pub actor: Option<MacroUserIdStr<'static>>,
+ /// The chip message posted for this turn, when one was.
+ pub announcement_message_id: Option<Uuid>,
+}
+
+impl InFlightTurn {
+ /// This turn as a session that died underneath it reports it.
+ #[must_use]
+ pub fn summary(&self) -> InFlightTurnSummary {
+ InFlightTurnSummary {
+ turn: self.turn,
+ action_id: self.action_id,
+ actor: self.actor.clone(),
+ announcement_message_id: self.announcement_message_id,
+ }
+ }
+
+ /// This turn as a settled session reports it.
+ #[must_use]
+ pub fn ended(self, stop_reason: String, excerpt: Option<String>) -> TurnSummary {
+ TurnSummary {
+ turn: self.turn,
+ action_id: self.action_id,
+ actor: self.actor,
+ announcement_message_id: self.announcement_message_id,
+ stop_reason,
+ excerpt,
+ }
+ }
+}
+
impl From<&QueuedEntry> for QueuedControl {
fn from(entry: &QueuedEntry) -> Self {
Self {
diff --git a/crates/agent_harness/src/domain/queue/test.rs b/crates/agent_harness/src/domain/queue/test.rs
index 48d21ea488..5a8b040ff1 100644
--- a/crates/agent_harness/src/domain/queue/test.rs
+++ b/crates/agent_harness/src/domain/queue/test.rs
@@ -9,7 +9,7 @@ fn prompt_entry(text: &str) -> QueuedEntry {
action: AgentAction::prompt(text),
actor: None,
announce: None,
- announced: false,
+ announced: None,
created_at: Utc::now(),
}
}
@@ -130,7 +130,7 @@ fn only_prompts_are_editable() {
action: AgentAction::Compact,
actor: None,
announce: None,
- announced: false,
+ announced: None,
created_at: Utc::now(),
};
queues.enqueue(session, compact.clone()).unwrap();
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index ad29c0f771..fe1d52f8e2 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -18,6 +18,7 @@ mod test;
mod deliver;
mod lifecycle;
+mod lifecycle_events;
mod open;
mod queue;
@@ -31,8 +32,8 @@ use agent_session::domain::model::{
SandboxSize,
};
use agent_session::domain::ports::{
- AcceptedControl, AgentSessionNotificationRecipient, AgentSessionQueueChanged,
- ControlDisposition, ControlEvent, QueuedControl,
+ AcceptedControl, AgentSessionLifecyclePublisher, AgentSessionNotificationRecipient,
+ AgentSessionQueueChanged, ControlDisposition, ControlEvent, QueuedControl,
};
use agent_session::domain::service::AgentSessionService;
use bot_id::BotId;
@@ -52,7 +53,7 @@ use crate::domain::ports::{
AgentPromptComposer, ChannelPromptContext, CommandForwarder, ContainerManager,
RuntimeConnections, SandboxEgressProvisioner, SessionAnnouncer,
};
-use crate::domain::queue::{QueueError, QueuedEntry, SessionQueues};
+use crate::domain::queue::{InFlightTurn, QueueError, QueuedEntry, SessionQueues};
use crate::domain::sandbox::SandboxResizeEffect;
use self::queue::{ErasedForwarder, SessionWorkers};
@@ -78,11 +79,13 @@ struct AgentHarnessInner<
/// Turn-occupying actions waiting for their session's running turn to
/// end. In-memory beside the live actors this replica manages.
queues: SessionQueues,
- /// The sessions with a turn in flight. Marked when a turn-occupying
- /// action reaches the runtime, cleared by `TurnEnded`/`SessionStopped`.
- /// Only ever touched from the session's own command worker, which is
- /// what serializes it against dispatch.
- busy: DashMap<AgentSessionId, ()>,
+ /// The sessions with a turn in flight, and which turn. Marked when a
+ /// turn-occupying action reaches the runtime, cleared by
+ /// `TurnEnded`/`SessionStopped`. Only ever touched from the session's
+ /// own command worker, which is what serializes it against dispatch.
+ busy: DashMap<AgentSessionId, InFlightTurn>,
+ /// Where lifecycle facts go. Erased so it is not an eighth type parameter.
+ lifecycle_publisher: Arc<dyn AgentSessionLifecyclePublisher>,
}
/// Turns trigger commands into running, announced agent sessions.
@@ -166,6 +169,7 @@ where
egress: Egress,
forwarder: impl CommandForwarder,
defaults: impl Into<HarnessDefaults>,
+ lifecycle_publisher: impl AgentSessionLifecyclePublisher,
) -> Self {
Self {
inner: Arc::new(AgentHarnessInner {
@@ -180,6 +184,7 @@ where
defaults: defaults.into(),
queues: SessionQueues::new(),
busy: DashMap::new(),
+ lifecycle_publisher: Arc::new(lifecycle_publisher),
}),
workers: Arc::new(DashMap::new()),
}
@@ -258,6 +263,9 @@ where
triggered_by: prompt.sender,
})
.await
+ // The external runtime drives this turn itself; there is no
+ // in-flight record here to remember the chip in.
+ .map(drop)
}
}
diff --git a/crates/agent_harness/src/domain/service/deliver.rs b/crates/agent_harness/src/domain/service/deliver.rs
index f556da63f9..41b5c9cda4 100644
--- a/crates/agent_harness/src/domain/service/deliver.rs
+++ b/crates/agent_harness/src/domain/service/deliver.rs
@@ -158,6 +158,7 @@ where
action: &AgentAction,
actor: Option<&MacroUserIdStr<'static>>,
announce: Option<AnnounceOrigin>,
+ prompted_message_id: MessageId,
) -> Result<Option<SessionAnnouncement>> {
let (Some(origin), Some(triggered_by), AgentAction::Prompt(prompt)) =
(announce, actor, action)
@@ -175,7 +176,7 @@ where
origin_channel_id: origin.channel_id,
origin_thread_id: origin.thread_id,
origin_message_id: origin.message_id,
- prompted_message_id: self.sessions.next_prompt_message_id(session_id).await?,
+ prompted_message_id,
prompted_content: prompt.prompt.clone(),
triggered_by: triggered_by.clone(),
}))
diff --git a/crates/agent_harness/src/domain/service/lifecycle.rs b/crates/agent_harness/src/domain/service/lifecycle.rs
index 951914ddd9..ea01851e74 100644
--- a/crates/agent_harness/src/domain/service/lifecycle.rs
+++ b/crates/agent_harness/src/domain/service/lifecycle.rs
@@ -1,6 +1,9 @@
//! A session after it is open: control events from the app, sandbox sizing,
//! turn boundaries, and teardown.
+use agent_fold::domain::model::TurnSignal;
+use agent_session::domain::session::StopReason;
+
use super::*;
/// The harness is what holds a session's live resources, so it is what the
@@ -152,12 +155,17 @@ where
PromptComposer: AgentPromptComposer,
Egress: SandboxEgressProvisioner,
{
- fn turn_ended(&self, id: AgentSessionId) {
- drop(self.execute_here(id, HarnessCommand::TurnEnded));
+ fn signal(&self, id: AgentSessionId, signal: TurnSignal) {
+ drop(self.execute_here(id, HarnessCommand::Turn(signal)));
}
- fn session_stopped(&self, id: AgentSessionId) {
- drop(self.execute_here(id, HarnessCommand::SessionStopped));
+ fn session_stopped(&self, id: AgentSessionId, reason: StopReason) {
+ drop(self.execute_here(
+ id,
+ HarnessCommand::SessionStopped {
+ reason: reason.to_string(),
+ },
+ ));
}
}
diff --git a/crates/agent_harness/src/domain/service/lifecycle_events.rs b/crates/agent_harness/src/domain/service/lifecycle_events.rs
new file mode 100644
index 0000000000..8a32559e10
--- /dev/null
+++ b/crates/agent_harness/src/domain/service/lifecycle_events.rs
@@ -0,0 +1,79 @@
+//! Publishing a session's lifecycle facts: who the session is.
+
+use agent_session::domain::events::{
+ AgentSessionLifecycleEvent, SessionIdentity, SessionOpenedMetadata,
+};
+use agent_session::domain::lifecycle::session_identity;
+
+use super::*;
+
+impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress>
+ AgentHarnessInner<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ >
+where
+ Sessions: AgentSessionService,
+ Containers: ContainerManager,
+ Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
+ PromptContext: ChannelPromptContext,
+ PromptComposer: AgentPromptComposer,
+ Egress: SandboxEgressProvisioner,
+{
+ /// The identity block for one session, from its row and its bot.
+ pub(super) async fn identity(&self, session_id: AgentSessionId) -> Result<SessionIdentity> {
+ let session = self.sessions.get_session(session_id).await?;
+ self.identity_of(&session).await
+ }
+
+ /// The identity block for a session whose row is already in hand.
+ pub(super) async fn identity_of(&self, session: &AgentSession) -> Result<SessionIdentity> {
+ let bot = self.sessions.session_bot(session.bot_id).await?;
+ Ok(session_identity(session, &bot))
+ }
+
+ /// Publish one fact about `session_id`, built once its identity is known.
+ ///
+ /// Never fails the command it rides on: a session whose identity cannot be
+ /// loaded is logged and skipped, because the fact itself already happened.
+ pub(super) async fn publish_lifecycle(
+ &self,
+ session_id: AgentSessionId,
+ build: impl FnOnce(SessionIdentity) -> AgentSessionLifecycleEvent,
+ ) {
+ match self.identity(session_id).await {
+ Ok(identity) => self.lifecycle_publisher.publish(build(identity)).await,
+ Err(error) => tracing::warn!(
+ error = ?error,
+ %session_id,
+ "skipping agent session lifecycle event: identity unavailable"
+ ),
+ }
+ }
+
+ /// Publish `agent_session.opened` for a row just created.
+ pub(super) async fn publish_opened(&self, session: &AgentSession) {
+ match self.identity_of(session).await {
+ Ok(identity) => {
+ self.lifecycle_publisher
+ .publish(AgentSessionLifecycleEvent::Opened(SessionOpenedMetadata {
+ identity,
+ model: session.model.clone(),
+ harness: session.harness.clone(),
+ }))
+ .await;
+ }
+ Err(error) => tracing::warn!(
+ error = ?error,
+ session_id = %session.id,
+ "skipping agent_session.opened: identity unavailable"
+ ),
+ }
+ }
+}
diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rs
index dc662e12fc..aa9d5e8157 100644
--- a/crates/agent_harness/src/domain/service/open.rs
+++ b/crates/agent_harness/src/domain/service/open.rs
@@ -62,6 +62,7 @@ where
// mention; it must not grant the channel anything.
})
.await?;
+ self.inner.publish_opened(&session).await;
if let Some(thread) = request.thread {
let announcement = SessionAnnouncement {
@@ -169,6 +170,7 @@ where
egress_token_hash: Some(egress.session_token_hash),
})
.await?;
+ self.inner.publish_opened(&session).await;
let mcp_servers = egress.sandbox.acp_servers();
let container = match self
@@ -299,7 +301,8 @@ where
.provision(session_id, &origin.sender, &repo_url, &runtime.mcp_servers)
.await?;
- self.sessions
+ let session = self
+ .sessions
.create_session(CreateAgentSessionParams {
id: session_id,
owner_id: origin.sender.clone(),
@@ -323,6 +326,7 @@ where
// This open came from the trigger pipeline seeing the mention.
})
.await?;
+ self.publish_opened(&session).await;
let mcp_servers = egress.sandbox.acp_servers();
let container = match self
diff --git a/crates/agent_harness/src/domain/service/queue.rs b/crates/agent_harness/src/domain/service/queue.rs
index 8dfcac4600..8dc9e3e8eb 100644
--- a/crates/agent_harness/src/domain/service/queue.rs
+++ b/crates/agent_harness/src/domain/service/queue.rs
@@ -1,8 +1,24 @@
//! The per-session command queue: admission, the worker that drains it one
//! command at a time, and routing to the replica that holds the session.
+use agent_fold::domain::model::{StopReason, TurnSignal};
+use agent_session::domain::events::{
+ AgentSessionLifecycleEvent, InputReceivedMetadata, SessionDeletedMetadata,
+ SessionSettledMetadata, SessionStoppedMetadata, TurnEndedMetadata, TurnStartedMetadata,
+ WaitingForInputMetadata,
+};
+
use super::*;
+/// What [`AgentHarnessInner::dispatch_next`] found waiting.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(super) enum Dispatch {
+ /// The oldest queued action reached the runtime.
+ Dispatched,
+ /// Nothing was queued: the session is idle.
+ QueueEmpty,
+}
+
pub(super) type SessionWorkers = DashMap<AgentSessionId, mpsc::UnboundedSender<QueuedCommand>>;
pub(super) struct QueuedCommand {
@@ -251,8 +267,8 @@ where
}
}
HarnessCommand::Open(_)
- | HarnessCommand::TurnEnded
- | HarnessCommand::SessionStopped
+ | HarnessCommand::Turn(_)
+ | HarnessCommand::SessionStopped { .. }
| HarnessCommand::SetSandboxSize(_)
| HarnessCommand::Delete => {}
}
@@ -291,18 +307,112 @@ where
self.publish_queue(session_id).await;
Ok(CommandOutcome::Completed)
}
- HarnessCommand::TurnEnded => {
- self.busy.remove(&session_id);
+ HarnessCommand::Turn(TurnSignal::TurnEnded {
+ stop,
+ last_text,
+ action_id: fold_action_id,
+ ..
+ }) => {
+ let ended = self.busy.remove(&session_id).map(|(_, turn)| turn);
+ // A turn end with no record: this replica restarted mid-turn
+ // and the in-memory mark went with it, or the fold closed a
+ // turn nobody here prompted. The queue still drains; only the
+ // facts about *that* turn are unknowable.
+ if ended.is_none() {
+ tracing::info!(%session_id, "turn ended with no in-flight record");
+ }
+ if let (Some(turn), Some(fold_action_id)) = (&ended, fold_action_id)
+ && turn.action_id != fold_action_id
+ {
+ tracing::warn!(
+ %session_id,
+ dispatched = %turn.action_id,
+ folded = %fold_action_id,
+ "the fold closed a different turn than the one dispatched"
+ );
+ }
+ let stop_reason = wire_stop_reason(&stop);
+ if let Some(turn) = &ended {
+ let turn = turn.clone();
+ let queued_remaining = self.queues.list(session_id).len();
+ let stop_reason = stop_reason.clone();
+ self.publish_lifecycle(session_id, |identity| {
+ AgentSessionLifecycleEvent::TurnEnded(TurnEndedMetadata {
+ identity,
+ turn: turn.turn,
+ action_id: turn.action_id,
+ actor: turn.actor,
+ announcement_message_id: turn.announcement_message_id,
+ stop_reason,
+ queued_remaining,
+ })
+ })
+ .await;
+ }
let dispatched = self.dispatch_next(session_id).await;
// Published whatever dispatching did: a claim, a requeued
// failure, and an emptied queue are all changes a viewer is
// watching for.
self.publish_queue(session_id).await;
- dispatched?;
+ let dispatched = dispatched?;
+ // Settled: the turn ended and nothing followed it. Emitted
+ // only with the turn's record, because "settled" without
+ // knowing what settled is a fact nobody can act on. The
+ // excerpt is the fold's last text for the turn: the same
+ // passage the chip shows once it is done.
+ if let (Dispatch::QueueEmpty, Some(turn)) = (dispatched, ended) {
+ self.publish_lifecycle(session_id, |identity| {
+ AgentSessionLifecycleEvent::Settled(SessionSettledMetadata {
+ identity,
+ last_turn: Some(turn.ended(stop_reason, last_text)),
+ })
+ })
+ .await;
+ }
Ok(CommandOutcome::Completed)
}
- HarnessCommand::SessionStopped => {
- self.busy.remove(&session_id);
+ HarnessCommand::SessionStopped { reason } => {
+ let in_flight = self.busy.remove(&session_id).map(|(_, turn)| turn);
+ self.publish_lifecycle(session_id, |identity| {
+ AgentSessionLifecycleEvent::Stopped(SessionStoppedMetadata {
+ identity,
+ reason,
+ turn_in_flight: in_flight.as_ref().map(InFlightTurn::summary),
+ })
+ })
+ .await;
+ Ok(CommandOutcome::Completed)
+ }
+ HarnessCommand::Turn(TurnSignal::ElicitationRaised { question, .. }) => {
+ let Some(turn) = self.busy.get(&session_id).map(|turn| turn.clone()) else {
+ tracing::warn!(%session_id, "elicitation raised with no in-flight record");
+ return Ok(CommandOutcome::Completed);
+ };
+ self.publish_lifecycle(session_id, |identity| {
+ AgentSessionLifecycleEvent::WaitingForInput(WaitingForInputMetadata {
+ identity,
+ turn: turn.turn,
+ action_id: turn.action_id,
+ announcement_message_id: turn.announcement_message_id,
+ question,
+ })
+ })
+ .await;
+ Ok(CommandOutcome::Completed)
+ }
+ HarnessCommand::Turn(TurnSignal::ElicitationCleared { .. }) => {
+ let Some(turn) = self.busy.get(&session_id).map(|turn| turn.clone()) else {
+ tracing::warn!(%session_id, "elicitation cleared with no in-flight record");
+ return Ok(CommandOutcome::Completed);
+ };
+ self.publish_lifecycle(session_id, |identity| {
+ AgentSessionLifecycleEvent::InputReceived(InputReceivedMetadata {
+ identity,
+ turn: turn.turn,
+ action_id: turn.action_id,
+ })
+ })
+ .await;
Ok(CommandOutcome::Completed)
}
HarnessCommand::SetSandboxSize(size) => {
@@ -310,6 +420,8 @@ where
Ok(CommandOutcome::Completed)
}
HarnessCommand::Delete => {
+ // Identity first: the row is gone once the delete succeeds.
+ let identity = self.identity(session_id).await;
self.delete(session_id).await?;
// The queue and busy mark die with the session: a deleted
// session's entries will never dispatch, and leaving them
@@ -318,6 +430,20 @@ where
self.busy.remove(&session_id);
self.queues.drop_session(session_id);
self.publish_queue(session_id).await;
+ match identity {
+ Ok(identity) => {
+ self.lifecycle_publisher
+ .publish(AgentSessionLifecycleEvent::Deleted(
+ SessionDeletedMetadata { identity },
+ ))
+ .await;
+ }
+ Err(error) => tracing::warn!(
+ error = ?error,
+ %session_id,
+ "skipping agent_session.deleted: identity unavailable"
+ ),
+ }
Ok(CommandOutcome::Completed)
}
}
@@ -344,7 +470,7 @@ where
action: command.action,
actor: command.actor,
announce: command.announce,
- announced: false,
+ announced: None,
created_at: chrono::Utc::now(),
},
),
@@ -354,7 +480,7 @@ where
let dispatched = if self.busy.contains_key(&session_id) {
Ok(())
} else {
- self.dispatch_next(session_id).await
+ self.dispatch_next(session_id).await.map(drop)
};
self.publish_queue(session_id).await;
dispatched?;
@@ -403,9 +529,9 @@ where
/// the queue meanwhile. The error still propagates, so a caller whose
/// own action triggered this dispatch hears about it.
#[tracing::instrument(err, skip(self), fields(%session_id))]
- pub(super) async fn dispatch_next(&self, session_id: AgentSessionId) -> Result<()> {
+ pub(super) async fn dispatch_next(&self, session_id: AgentSessionId) -> Result<Dispatch> {
let Some(mut entry) = self.queues.claim_next(session_id) else {
- return Ok(());
+ return Ok(Dispatch::QueueEmpty);
};
// Compose a copy: the queued entry stays raw so a retry still edits
@@ -420,13 +546,25 @@ where
return Err(error);
}
- if !entry.announced {
+ // The turn this action opens, read before delivery appends the
+ // prompt to the log. Unchanged across a failed attempt, so a retry
+ // reports the same turn.
+ let prompted_message_id = match self.sessions.next_prompt_message_id(session_id).await {
+ Ok(message_id) => message_id,
+ Err(error) => {
+ self.queues.requeue_front(session_id, entry);
+ return Err(error.into());
+ }
+ };
+
+ if entry.announced.is_none() {
let announcement = match self
.announcement(
session_id,
&entry.action,
entry.actor.as_ref(),
entry.announce.clone(),
+ prompted_message_id,
)
.await
{
@@ -437,11 +575,13 @@ where
}
};
if let Some(announcement) = announcement {
- if let Err(error) = self.announcer.announce(announcement).await {
- self.queues.requeue_front(session_id, entry);
- return Err(error);
+ match self.announcer.announce(announcement).await {
+ Ok(announced) => entry.announced = Some(announced.message_id),
+ Err(error) => {
+ self.queues.requeue_front(session_id, entry);
+ return Err(error);
+ }
}
- entry.announced = true;
}
}
@@ -453,8 +593,24 @@ where
};
match self.deliver(session_id, command).await {
Ok(()) => {
- self.busy.insert(session_id, ());
- Ok(())
+ let turn = InFlightTurn {
+ action_id: entry.action_id,
+ turn: prompted_message_id.turn,
+ actor: entry.actor,
+ announcement_message_id: entry.announced,
+ };
+ self.busy.insert(session_id, turn.clone());
+ self.publish_lifecycle(session_id, |identity| {
+ AgentSessionLifecycleEvent::TurnStarted(TurnStartedMetadata {
+ identity,
+ turn: turn.turn,
+ action_id: turn.action_id,
+ actor: turn.actor,
+ announcement_message_id: turn.announcement_message_id,
+ })
+ })
+ .await;
+ Ok(Dispatch::Dispatched)
}
Err(error) => {
self.queues.requeue_front(session_id, entry);
@@ -464,6 +620,20 @@ where
}
}
+/// The stop reason as downstream reads it: the ACP wire word for the reasons
+/// ACP names, `error` for a prompt the runtime refused.
+fn wire_stop_reason(stop: &StopReason) -> String {
+ match stop {
+ StopReason::EndTurn => "end_turn".to_owned(),
+ StopReason::MaxTokens => "max_tokens".to_owned(),
+ StopReason::MaxTurnRequests => "max_turn_requests".to_owned(),
+ StopReason::Refusal => "refusal".to_owned(),
+ StopReason::Cancelled => "cancelled".to_owned(),
+ StopReason::Other { reason } => reason.clone(),
+ StopReason::Failed { .. } => "error".to_owned(),
+ }
+}
+
/// Map a queue refusal into the session vocabulary, which is where the
/// control surface's callers read their errors from.
pub(super) fn queue_result<T>(
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index b72dbdf506..f761eb0eb1 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -9,6 +9,7 @@ use agent_client_protocol::schema::v1::{
AgentCapabilities, ClientRequest, ContentBlock, InitializeResponse, NewSessionResponse,
ResumeSessionResponse, SessionCapabilities, SessionId, SessionResumeCapabilities,
};
+use agent_fold::domain::model::TurnSignal;
use agent_fold::domain::model::{AuthorKind, MessageId};
use agent_fold::domain::service::FoldedMessageService;
use agent_runtime_protocol::domain::{
@@ -16,15 +17,17 @@ use agent_runtime_protocol::domain::{
schema::v0::{AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage},
};
use agent_session::PROTOCOL_VERSION;
+use agent_session::domain::events::AgentSessionLifecycleEvent;
use agent_session::domain::model::{
AgentMcpServers, AgentSessionId, CreateAgentSessionParams, Message, SandboxSize,
};
use agent_session::domain::ports::{
AgentSessionLogRepo as _, AgentSessionNotificationRecipient as _, AgentSessionRepo as _,
- ControlEvent, NoOpRealtime,
+ ControlEvent, NoOpRealtime, NoopLifecyclePublisher,
};
use agent_session::domain::service::AgentSessionServiceImpl;
-use agent_session::testing::InMemoryAgentSessionRepo;
+use agent_session::domain::session::StopReason;
+use agent_session::testing::{InMemoryAgentSessionRepo, RecordingLifecyclePublisher};
use bot_id::BotId;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
@@ -47,6 +50,8 @@ use crate::testing::helpers::announcer::AnnouncerMock;
use crate::testing::helpers::containers::{ContainerMock, ContainerSender, MockContainerManager};
use crate::testing::helpers::egress::{EgressProvisionerMock, test_egress};
use agent_session::domain::error::AgentSessionError;
+use agent_session::domain::model::ReplicaId;
+use agent_session::domain::ports::{NoOpAgentSessionNameGenerator, NoOpTurnObserver};
use agent_session::domain::ports::{
OpenExternalAgentSession, OpenManagedSession, SessionOpener as _,
};
@@ -239,19 +244,40 @@ struct SignallingTurnObserver {
}
impl agent_session::domain::ports::SessionTurnObserver for SignallingTurnObserver {
- fn turn_ended(&self, id: AgentSessionId) {
- agent_session::domain::ports::SessionTurnObserver::turn_ended(&self.harness, id);
- let _ = self.ended.send(id);
+ fn signal(&self, id: AgentSessionId, signal: TurnSignal) {
+ let ended = matches!(signal, TurnSignal::TurnEnded { .. });
+ agent_session::domain::ports::SessionTurnObserver::signal(&self.harness, id, signal);
+ if ended {
+ let _ = self.ended.send(id);
+ }
}
- fn session_stopped(&self, id: AgentSessionId) {
- agent_session::domain::ports::SessionTurnObserver::session_stopped(&self.harness, id);
+ fn session_stopped(&self, id: AgentSessionId, reason: StopReason) {
+ agent_session::domain::ports::SessionTurnObserver::session_stopped(
+ &self.harness,
+ id,
+ reason,
+ );
}
}
-/// The test's half of [`SignallingTurnObserver`].
+/// The test's half of [`SignallingTurnObserver`], plus the lifecycle facts
+/// the harness and its session service published.
struct TurnSignals {
ended: mpsc::UnboundedReceiver<AgentSessionId>,
+ lifecycle: RecordingLifecyclePublisher,
+}
+
+impl TurnSignals {
+ /// Every lifecycle event published so far, in order.
+ fn lifecycle(&self) -> Vec<AgentSessionLifecycleEvent> {
+ self.lifecycle.published()
+ }
+
+ /// Wait until at least `count` lifecycle events have been published.
+ async fn lifecycle_published(&self, count: usize) {
+ self.lifecycle.wait_for_published(count).await;
+ }
}
impl TurnSignals {
@@ -292,13 +318,19 @@ fn harness_with_signals(
// Same knot as production wiring: the harness is built from the session
// service and is also its turn observer, so the observer binds late.
let turn_observer = Arc::new(agent_session::domain::ports::LateBoundTurnObserver::new());
+ // One recorder for both publishers, as in production: renames come from
+ // the session service, everything else from the harness.
+ let lifecycle = RecordingLifecyclePublisher::new();
let service = AgentHarnessService::new(
AgentSessionServiceImpl::new(
repo.clone(),
FoldedMessageService::new(repo.clone()),
NoOpRealtime,
- )
- .with_turn_observer(turn_observer.clone()),
+ NoOpAgentSessionNameGenerator,
+ turn_observer.clone(),
+ Arc::new(lifecycle.clone()),
+ ReplicaId::mint(),
+ ),
containers.clone(),
announcer.clone(),
TestConnections::new(MirrorBindings, Arc::clone(&runtimes)),
@@ -312,6 +344,7 @@ fn harness_with_signals(
harness: "opencode".to_owned(),
repo_url: "https://github.com/macro-inc/macro".to_owned(),
},
+ lifecycle.clone(),
);
let (ended, ended_rx) = mpsc::unbounded_channel();
turn_observer.bind(SignallingTurnObserver {
@@ -320,7 +353,10 @@ fn harness_with_signals(
});
(
(service, repo, containers, announcer, runtimes),
- TurnSignals { ended: ended_rx },
+ TurnSignals {
+ ended: ended_rx,
+ lifecycle,
+ },
)
}
@@ -1798,6 +1834,10 @@ async fn a_managed_session_opens_as_the_managed_default_bot() {
repo.clone(),
FoldedMessageService::new(repo.clone()),
NoOpRealtime,
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
),
containers.clone(),
AnnouncerMock::new(),
@@ -1822,6 +1862,7 @@ async fn a_managed_session_opens_as_the_managed_default_bot() {
},
)
.with_managed_bot(inmem_bot),
+ NoopLifecyclePublisher,
);
let session = service
@@ -2248,6 +2289,10 @@ async fn commands_for_a_peer_managed_session_forward_through_redis() {
repo.clone(),
FoldedMessageService::new(repo.clone()),
NoOpRealtime,
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
),
MockContainerManager::new(),
AnnouncerMock::new(),
@@ -2262,6 +2307,7 @@ async fn commands_for_a_peer_managed_session_forward_through_redis() {
harness: "opencode".to_owned(),
repo_url: "https://github.com/macro-inc/macro".to_owned(),
},
+ NoopLifecyclePublisher,
);
service
@@ -2291,6 +2337,10 @@ async fn unmanaged_external_session_forwards_to_its_remote_harness() {
repo.clone(),
FoldedMessageService::new(repo.clone()),
NoOpRealtime,
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
),
MockContainerManager::new(),
AnnouncerMock::new(),
@@ -2305,6 +2355,7 @@ async fn unmanaged_external_session_forwards_to_its_remote_harness() {
harness: "opencode".to_owned(),
repo_url: "https://github.com/macro-inc/macro".to_owned(),
},
+ NoopLifecyclePublisher,
);
let session = service
.open_external_session(open_external_request("/srv/agent"))
@@ -2328,3 +2379,294 @@ async fn unmanaged_external_session_forwards_to_its_remote_harness() {
"the command did not execute on this replica"
);
}
+
+/// The lifecycle facts the harness publishes, end to end through a live
+/// session: the mock agent answers, asks, and dies; the recorder says what
+/// downstream would have heard.
+mod lifecycle_events {
+ use super::*;
+
+ use agent_client_protocol::JsonRpcMessage as _;
+ use agent_client_protocol::schema::v1::{
+ CreateElicitationRequest, ElicitationFormMode, ElicitationSchema, ElicitationSessionScope,
+ RequestId,
+ };
+ use agent_fold::domain::model::TurnId;
+ use agent_runtime_protocol::domain::action::{
+ AgentActionId, ElicitationAnswer, ElicitationRequestId,
+ };
+ use agent_session::domain::events::AgentSessionLifecycleEvent as Lifecycle;
+
+ /// Open a session from a mention and let its first turn settle: `Opened`,
+ /// `TurnStarted`, `TurnEnded`, `Settled`.
+ async fn settled_session() -> (TestBench, TurnSignals, AgentSessionId, ContainerMock) {
+ let (bench, mut turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let container = live_session(&bench.0, &bench.2, id).await;
+ turns.settled(id).await;
+ turns.lifecycle_published(4).await;
+ (bench, turns, id, container)
+ }
+
+ fn ask(agent: &FakeAgent, request_id: i64, question: &str) {
+ let request = CreateElicitationRequest::new(
+ ElicitationFormMode::new(
+ ElicitationSessionScope::new(SessionId::new("acp-test")),
+ ElicitationSchema::new(),
+ ),
+ question,
+ );
+ let (method, params) = request
+ .to_untyped_message()
+ .expect("an elicitation serializes")
+ .into_parts();
+ agent.sends_raw(
+ RawJsonRpcMessage::request(method, params, RequestId::Number(request_id))
+ .expect("elicitation params are an object"),
+ );
+ }
+
+ #[tokio::test]
+ async fn the_first_turn_publishes_opened_started_ended_and_settled() {
+ let ((_, _, _, announcer, _), turns, id, _container) = settled_session().await;
+
+ let chip = announcer.announced_messages()[0].message_id;
+ let events = turns.lifecycle();
+ assert!(
+ matches!(
+ events.as_slice(),
+ [
+ Lifecycle::Opened(opened),
+ Lifecycle::TurnStarted(started),
+ Lifecycle::TurnEnded(ended),
+ Lifecycle::Settled(settled),
+ ] if opened.identity.session_id == id
+ // No origin asserted: the in-memory repo cannot derive the
+ // thread's channel, which only the message row knows.
+ && started.turn == TurnId(0)
+ && started.announcement_message_id == Some(chip)
+ && ended.turn == TurnId(0)
+ && ended.stop_reason == "end_turn"
+ && ended.queued_remaining == 0
+ && ended.announcement_message_id == Some(chip)
+ && settled.last_turn.as_ref().is_some_and(|turn| {
+ turn.turn == TurnId(0)
+ && turn.stop_reason == "end_turn"
+ && turn.announcement_message_id == Some(chip)
+ })
+ ),
+ "one full turn, in order: {events:#?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_queued_prompt_defers_settled_until_it_too_is_answered() {
+ let ((service, _, _, _, _), turns, id, container) = settled_session().await;
+ let agent = container.agent();
+
+ // The first forward dispatches at once; the second waits behind it.
+ service
+ .execute(id, HarnessCommand::Deliver(forward_message("first")))
+ .await
+ .expect("first forward dispatches");
+ let queued = service
+ .execute(id, HarnessCommand::Deliver(forward_message("second")))
+ .await
+ .expect("second forward is accepted");
+ assert_eq!(queued, CommandOutcome::Queued);
+ turns.lifecycle_published(5).await;
+
+ agent.completes_prompt().await;
+ turns.lifecycle_published(7).await;
+ let events = turns.lifecycle();
+ assert!(
+ matches!(
+ &events[4..7],
+ [
+ Lifecycle::TurnStarted(first),
+ Lifecycle::TurnEnded(first_ended),
+ Lifecycle::TurnStarted(second),
+ ] if first.turn == TurnId(1)
+ && first_ended.turn == TurnId(1)
+ && first_ended.queued_remaining == 1
+ && second.turn == TurnId(2)
+ ),
+ "the first turn ends with one queued and the second starts, no settle between: {events:#?}"
+ );
+
+ agent.completes_prompt().await;
+ turns.lifecycle_published(9).await;
+ let events = turns.lifecycle();
+ assert!(
+ matches!(
+ &events[7..9],
+ [Lifecycle::TurnEnded(ended), Lifecycle::Settled(settled)]
+ if ended.turn == TurnId(2)
+ && ended.queued_remaining == 0
+ && settled.last_turn.as_ref().is_some_and(|turn| turn.turn == TurnId(2))
+ ),
+ "the second turn ends and the session settles: {events:#?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_question_publishes_waiting_for_input_then_input_received() {
+ let ((service, _, _, announcer, _), turns, id, container) = settled_session().await;
+ let agent = container.agent();
+ service
+ .execute(id, HarnessCommand::Deliver(forward_message("pick one")))
+ .await
+ .expect("the prompt dispatches");
+ turns.lifecycle_published(5).await;
+ let chip = announcer
+ .announced_messages()
+ .last()
+ .expect("the forward posted a chip")
+ .message_id;
+
+ ask(&agent, 7, "Which approach?");
+ turns.lifecycle_published(6).await;
+ assert!(
+ matches!(
+ turns.lifecycle().last(),
+ Some(Lifecycle::WaitingForInput(waiting))
+ if waiting.turn == TurnId(1)
+ && waiting.question == "Which approach?"
+ && waiting.announcement_message_id == Some(chip)
+ ),
+ "the question is published against its chip: {:#?}",
+ turns.lifecycle()
+ );
+
+ service
+ .execute(
+ id,
+ HarnessCommand::Deliver(DeliverAction::control(
+ AgentActionId::mint(),
+ ControlEvent {
+ action: AgentAction::respond_elicitation(
+ ElicitationRequestId::Number(7),
+ ElicitationAnswer::Decline,
+ ),
+ actor: Some(staff_sender()),
+ },
+ )),
+ )
+ .await
+ .expect("the answer is delivered");
+ turns.lifecycle_published(7).await;
+ assert!(
+ matches!(
+ turns.lifecycle().last(),
+ Some(Lifecycle::InputReceived(received)) if received.turn == TurnId(1)
+ ),
+ "answering clears the wait: {:#?}",
+ turns.lifecycle()
+ );
+ }
+
+ /// The excerpt is the fold's last text for the turn - no refold, no
+ /// second read of the log - which is what the chip shows once done.
+ #[tokio::test]
+ async fn settled_carries_the_agents_last_text() {
+ let ((service, _, _, _, _), turns, id, container) = settled_session().await;
+ let agent = container.agent();
+ service
+ .execute(
+ id,
+ HarnessCommand::Deliver(forward_message("say something")),
+ )
+ .await
+ .expect("the prompt dispatches");
+ turns.lifecycle_published(5).await;
+
+ agent.sends_raw(
+ RawJsonRpcMessage::notification(
+ "session/update".to_owned(),
+ serde_json::json!({
+ "sessionId": "acp-test",
+ "update": {
+ "sessionUpdate": "agent_message_chunk",
+ "content": {"type": "text", "text": "Hello there."}
+ }
+ }),
+ )
+ .expect("notification params are an object"),
+ );
+ agent.completes_prompt().await;
+ turns.lifecycle_published(7).await;
+
+ let events = turns.lifecycle();
+ assert!(
+ matches!(
+ &events[5..7],
+ [Lifecycle::TurnEnded(ended), Lifecycle::Settled(settled)]
+ if ended.stop_reason == "end_turn"
+ && settled.last_turn.as_ref().is_some_and(|turn| {
+ turn.excerpt.as_deref() == Some("Hello there.")
+ && turn.stop_reason == "end_turn"
+ })
+ ),
+ "settled quotes the agent's last words: {events:#?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_death_mid_turn_publishes_stopped_with_the_turn_and_no_settled() {
+ let ((service, _, _, _, _), turns, id, container) = settled_session().await;
+ service
+ .execute(id, HarnessCommand::Deliver(forward_message("keep going")))
+ .await
+ .expect("the prompt dispatches");
+ turns.lifecycle_published(5).await;
+
+ container.disconnects();
+ turns.lifecycle_published(6).await;
+
+ let events = turns.lifecycle();
+ assert!(
+ matches!(
+ events.last(),
+ Some(Lifecycle::Stopped(stopped))
+ if stopped.turn_in_flight.as_ref().is_some_and(|turn| turn.turn == TurnId(1))
+ && !stopped.reason.is_empty()
+ ),
+ "the stop names the turn it interrupted: {events:#?}"
+ );
+ assert_eq!(
+ events
+ .iter()
+ .filter(|event| matches!(event, Lifecycle::Settled(_)))
+ .count(),
+ 1,
+ "only the first turn settled; a death is not a settle: {events:#?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_delete_publishes_deleted_and_nothing_after() {
+ let ((service, _, _, _, _), turns, id, _container) = settled_session().await;
+
+ service
+ .execute(id, HarnessCommand::Delete)
+ .await
+ .expect("delete succeeds");
+ turns.lifecycle_published(5).await;
+
+ // Deleting also stops the actor, but by the time that stop is
+ // observed the row is gone and nothing can describe the session, so
+ // `Deleted` is the last word. Give a late `Stopped` every chance to
+ // show up wrongly before asserting it did not.
+ tokio::task::yield_now().await;
+ let events = turns.lifecycle();
+ assert!(
+ matches!(
+ events.last(),
+ Some(Lifecycle::Deleted(deleted)) if deleted.identity.session_id == id
+ ),
+ "deleted is the last fact about the session: {events:#?}"
+ );
+ assert_eq!(events.len(), 5, "nothing follows deleted: {events:#?}");
+ }
+}
diff --git a/crates/agent_harness/src/outbound/channel_announcer.rs b/crates/agent_harness/src/outbound/channel_announcer.rs
index c54160d117..75473f2092 100644
--- a/crates/agent_harness/src/outbound/channel_announcer.rs
+++ b/crates/agent_harness/src/outbound/channel_announcer.rs
@@ -23,8 +23,9 @@ use lexical_client::LexicalClient;
use lexical_client::parse_markdown::{AgentAnnouncementChip, AgentAnnouncementReplyTarget};
use crate::domain::error::{HarnessError, Result};
-use crate::domain::model::SessionAnnouncement;
+use crate::domain::model::{AnnouncedMessage, SessionAnnouncement};
use crate::domain::ports::SessionAnnouncer;
+use macro_uuid::Uuid;
fn announcement_chip(announcement: &SessionAnnouncement) -> AgentAnnouncementChip {
AgentAnnouncementChip {
@@ -64,7 +65,7 @@ impl<Channels> SessionAnnouncer for ChannelAnnouncer<Channels>
where
Channels: ChannelService + Send + Sync + 'static,
{
- async fn announce(&self, announcement: SessionAnnouncement) -> Result<()> {
+ async fn announce(&self, announcement: SessionAnnouncement) -> Result<AnnouncedMessage> {
let reply_target = announcement_reply_target(&announcement);
let chip = announcement_chip(&announcement);
let content = self
@@ -73,7 +74,8 @@ where
.await
.map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
- self.channels
+ let posted = self
+ .channels
.post_message(
ChannelSender::new_from_bot(announcement.bot_id),
announcement.origin_channel_id,
@@ -92,6 +94,18 @@ where
.await
.map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
- Ok(())
+ // Message ids are uuids everywhere in the channels domain; anything
+ // else here is a bug in the poster, not a shape to tolerate.
+ let message_id = Uuid::parse_str(&posted.id).map_err(|error| {
+ HarnessError::Announce(
+ rootcause::report!(error)
+ .context(format!(
+ "announcement posted a non-uuid message id {}",
+ posted.id
+ ))
+ .into(),
+ )
+ })?;
+ Ok(AnnouncedMessage { message_id })
}
}
diff --git a/crates/agent_harness/src/testing/helpers/announcer.rs b/crates/agent_harness/src/testing/helpers/announcer.rs
index 352f4efc0b..ecc8b95cec 100644
--- a/crates/agent_harness/src/testing/helpers/announcer.rs
+++ b/crates/agent_harness/src/testing/helpers/announcer.rs
@@ -3,14 +3,14 @@
use std::sync::{Arc, Mutex};
use crate::domain::error::{HarnessError, Result};
-use crate::domain::model::SessionAnnouncement;
+use crate::domain::model::{AnnouncedMessage, SessionAnnouncement};
use crate::domain::ports::SessionAnnouncer;
/// A [`SessionAnnouncer`] that records instead of posting. Cloning shares one
/// record.
#[derive(Clone, Default)]
pub struct AnnouncerMock {
- announced: Arc<Mutex<Vec<SessionAnnouncement>>>,
+ announced: Arc<Mutex<Vec<(SessionAnnouncement, AnnouncedMessage)>>>,
/// When set, every announce fails with this message.
failure: Arc<Mutex<Option<String>>>,
}
@@ -37,12 +37,25 @@ impl AnnouncerMock {
self.announced
.lock()
.expect("announcer mock lock should not be poisoned")
- .clone()
+ .iter()
+ .map(|(announcement, _)| announcement.clone())
+ .collect()
+ }
+
+ /// The message each recorded announcement became, in order.
+ #[must_use]
+ pub fn announced_messages(&self) -> Vec<AnnouncedMessage> {
+ self.announced
+ .lock()
+ .expect("announcer mock lock should not be poisoned")
+ .iter()
+ .map(|(_, message)| *message)
+ .collect()
}
}
impl SessionAnnouncer for AnnouncerMock {
- async fn announce(&self, announcement: SessionAnnouncement) -> Result<()> {
+ async fn announce(&self, announcement: SessionAnnouncement) -> Result<AnnouncedMessage> {
if let Some(message) = self
.failure
.lock()
@@ -52,10 +65,13 @@ impl SessionAnnouncer for AnnouncerMock {
return Err(HarnessError::Announce(rootcause::report!("{message}")));
}
+ let message = AnnouncedMessage {
+ message_id: macro_uuid::generate_uuid_v7(),
+ };
self.announced
.lock()
.expect("announcer mock lock should not be poisoned")
- .push(announcement);
- Ok(())
+ .push((announcement, message));
+ Ok(message)
}
}
diff --git a/crates/agent_inmem/src/outbound/manager/test.rs b/crates/agent_inmem/src/outbound/manager/test.rs
index a412759b1e..11f308c6b5 100644
--- a/crates/agent_inmem/src/outbound/manager/test.rs
+++ b/crates/agent_inmem/src/outbound/manager/test.rs
@@ -21,6 +21,10 @@ use macro_user_id::user_id::MacroUserIdStr;
use super::*;
use crate::outbound::log_frames::LogFrameSource;
use crate::testing::ScriptedEngine;
+use agent_session::domain::model::ReplicaId;
+use agent_session::domain::ports::{
+ NoOpAgentSessionNameGenerator, NoOpTurnObserver, NoopLifecyclePublisher,
+};
/// Instructions long enough to be unmistakable in an assertion, and shaped
/// like something a real session would carry.
@@ -142,6 +146,10 @@ async fn a_prompt_runs_end_to_end_through_the_real_session_machine() {
repo.clone(),
FoldedMessageService::new(repo.clone()),
NoOpRealtime,
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
);
let id = AgentSessionId::new();
@@ -277,6 +285,10 @@ async fn a_restarted_manager_rebuilds_the_conversation_from_the_log() {
repo.clone(),
FoldedMessageService::new(repo.clone()),
NoOpRealtime,
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
);
let id = AgentSessionId::new();
@@ -419,6 +431,10 @@ async fn instructions_reach_every_turn_including_after_a_reattach() {
repo.clone(),
FoldedMessageService::new(repo.clone()),
NoOpRealtime,
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
);
let id = AgentSessionId::new();
@@ -489,6 +505,10 @@ async fn a_session_without_instructions_hands_the_engine_none() {
repo.clone(),
FoldedMessageService::new(repo.clone()),
NoOpRealtime,
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
);
let id = AgentSessionId::new();
diff --git a/crates/agent_session/Cargo.toml b/crates/agent_session/Cargo.toml
index 20943de5f6..7dd702d72c 100644
--- a/crates/agent_session/Cargo.toml
+++ b/crates/agent_session/Cargo.toml
@@ -5,6 +5,32 @@ edition = "2024"
publish = false
[features]
+default = ["inbound", "outbound"]
+# The `seed_jsonl` replay binary: an argument parser, and the Postgres
+# adapter it writes through.
+cli = ["dep:clap", "outbound"]
+# The axum router serving sessions over HTTP.
+inbound = [
+ "dep:axum",
+ "dep:macro_authorization",
+ "entity_access/inbound",
+ "macro_authorization/axum",
+ "schema",
+]
+# Postgres, the connection gateway, and the model-backed name generator.
+outbound = [
+ "bots/outbound",
+ "dep:agent",
+ "dep:ai_usage",
+ "dep:connection_gateway_client",
+ "dep:entity_access_db_utils",
+ "dep:model-entity",
+ "dep:sqlx",
+ "macro_user_id/sqlx",
+]
+# OpenAPI schemas for the vocabulary that reaches an HTTP boundary: the
+# router's DTOs, and the lifecycle events the webhook union carries.
+schema = ["dep:utoipa", "agent_runtime_protocol/utoipa", "macro_user_id/schema"]
# Mock and in-memory port implementations, for crates that test against this one.
test-utils = ["dep:mockall", "agent_fold/test-utils"]
@@ -12,31 +38,31 @@ test-utils = ["dep:mockall", "agent_fold/test-utils"]
agent-client-protocol = { workspace = true }
harness_id = { path = "../harness_id" }
-agent = { path = "../agent" }
-ai_usage = { path = "../ai_usage" }
+agent = { path = "../agent", optional = true }
+ai_usage = { path = "../ai_usage", optional = true }
dashmap = { workspace = true }
macro_uuid = { path = "../macro_uuid" }
mockall = { workspace = true, optional = true }
agent_fold = { path = "../agent_fold" }
-agent_runtime_protocol = { path = "../agent_runtime_protocol", features = ["utoipa"] }
-axum = { workspace = true }
-bots = { path = "../bots"}
-connection_gateway_client = { path = "../connection_gateway_client" }
+# Only the domain vocabulary; `outbound` would pull rdkafka into every
+# consumer of this crate.
+macro_event_broker = { path = "../macro_event_broker", default-features = false }
+macro_event_topics = { path = "../macro_event_topics" }
+agent_runtime_protocol = { path = "../agent_runtime_protocol" }
+axum = { workspace = true, optional = true }
+bots = { path = "../bots", default-features = false }
+connection_gateway_client = { path = "../connection_gateway_client", optional = true }
entity_access = { path = "../entity_access", default-features = false, features = [
- "inbound",
"ports",
] }
-entity_access_db_utils = { path = "../entity_access_db_utils" }
-model-entity = { path = "../model-entity" }
-clap = { workspace = true }
-macro_authorization = { path = "../macro_authorization", default-features = false, features = [
- "axum",
-] }
-macro_service_urls = { path = "../macro_service_urls" }
-macro_user_id = { path = "../macro_user_id", features = ["sqlx"] }
-utoipa = { workspace = true }
+entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }
+model-entity = { path = "../model-entity", optional = true }
+clap = { workspace = true, optional = true }
+macro_authorization = { path = "../macro_authorization", default-features = false, optional = true }
+macro_user_id = { path = "../macro_user_id" }
+utoipa = { workspace = true, optional = true }
rootcause = { workspace = true }
-sqlx = { workspace = true, features = ["json"] }
+sqlx = { workspace = true, features = ["json"], optional = true }
chrono = { workspace = true }
thiserror = { workspace = true }
anyhow = { workspace = true }
@@ -48,6 +74,11 @@ tokio-util = { workspace = true, features = ["rt"] }
tracing = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
+[[bin]]
+name = "seed_jsonl"
+path = "src/bin/seed_jsonl.rs"
+required-features = ["cli"]
+
[dev-dependencies]
agent-client-protocol = { workspace = true }
bot_id = { path = "../bot_id", features = ["test-utils"] }
diff --git a/crates/agent_session/src/domain/events.rs b/crates/agent_session/src/domain/events.rs
new file mode 100644
index 0000000000..f8e416c176
--- /dev/null
+++ b/crates/agent_session/src/domain/events.rs
@@ -0,0 +1,336 @@
+//! Agent session lifecycle facts, published to
+//! [`MacroAgentSessionLifecycleTopic`] and keyed by session id.
+//!
+//! These are facts about a session after the fact - opened, a turn started or
+//! ended, nothing left to do, asking its owner something, gone - for anyone
+//! downstream to react to: webhooks, notifications, observability. Commands
+//! that *drive* a session travel on `macro.agent_sessions` instead.
+//!
+//! Consumers that only decode these events depend on this crate with
+//! `default-features = false`: the domain compiles without the inbound and
+//! outbound adapters' axum, sqlx, and client dependencies.
+
+#[cfg(test)]
+mod test;
+
+use agent_runtime_protocol::domain::action::AgentActionId;
+use bots::domain::models::BotId;
+use macro_event_broker::{Event, MacroEvent, TopicEvent};
+use macro_event_topics::MacroAgentSessionLifecycleTopic;
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use serde::{Deserialize, Serialize};
+
+use super::model::{AgentSessionId, TurnId};
+
+/// The channel thread a session was opened from, when it was.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct ThreadOrigin {
+ /// Channel the thread lives in.
+ pub channel_id: Uuid,
+ /// Root message of the thread.
+ pub thread_id: Uuid,
+ /// The message whose mention opened the session.
+ pub originating_message_id: Uuid,
+}
+
+/// Who and what a session is; carried by every lifecycle event so a
+/// consumer never has to look the session up.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct SessionIdentity {
+ /// The session.
+ #[cfg_attr(feature = "schema", schema(value_type = String, format = Uuid))]
+ pub session_id: AgentSessionId,
+ /// User-facing session name at the time of the event.
+ pub session_name: String,
+ /// Bot the session runs for.
+ pub bot_id: BotId,
+ /// The bot's display name at the time of the event.
+ pub bot_name: String,
+ /// User who owns the session.
+ pub owner_id: MacroUserIdStr<'static>,
+ /// Thread the session was opened from, when it was.
+ pub origin: Option<ThreadOrigin>,
+}
+
+/// A turn the runtime answered.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct TurnSummary {
+ /// Position in the session's log.
+ #[cfg_attr(feature = "schema", schema(value_type = u32))]
+ pub turn: TurnId,
+ /// The action that opened the turn.
+ pub action_id: AgentActionId,
+ /// User who prompted it, absent when a bot acted on nobody's behalf.
+ pub actor: Option<MacroUserIdStr<'static>>,
+ /// The magic-chip message posted for this turn, when one was.
+ pub announcement_message_id: Option<Uuid>,
+ /// The ACP stop reason, or `"error"` when the runtime refused the prompt.
+ pub stop_reason: String,
+ /// The agent's last text in the turn, whole; what the magic chip shows
+ /// once the turn ends. `None` when the turn produced no prose.
+ pub excerpt: Option<String>,
+}
+
+/// A turn the runtime never answered: the session stopped underneath it.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct InFlightTurnSummary {
+ /// Position in the session's log.
+ #[cfg_attr(feature = "schema", schema(value_type = u32))]
+ pub turn: TurnId,
+ /// The action that opened the turn.
+ pub action_id: AgentActionId,
+ /// User who prompted it, absent when a bot acted on nobody's behalf.
+ pub actor: Option<MacroUserIdStr<'static>>,
+ /// The magic-chip message posted for this turn, when one was.
+ pub announcement_message_id: Option<Uuid>,
+}
+
+/// A session was created.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct SessionOpenedMetadata {
+ /// The session.
+ pub identity: SessionIdentity,
+ /// Model slug the session runs with.
+ pub model: String,
+ /// Harness slug the session runs on.
+ pub harness: String,
+}
+
+/// A prompt was delivered to the runtime.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct TurnStartedMetadata {
+ /// The session.
+ pub identity: SessionIdentity,
+ /// Position in the session's log.
+ #[cfg_attr(feature = "schema", schema(value_type = u32))]
+ pub turn: TurnId,
+ /// The action that opened the turn.
+ pub action_id: AgentActionId,
+ /// User who prompted it, absent when a bot acted on nobody's behalf.
+ pub actor: Option<MacroUserIdStr<'static>>,
+ /// The magic-chip message posted for this turn, when one was.
+ pub announcement_message_id: Option<Uuid>,
+}
+
+/// The runtime answered a turn. Another prompt may follow at once; see
+/// [`SessionSettledMetadata`] for "nothing left to do".
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct TurnEndedMetadata {
+ /// The session.
+ pub identity: SessionIdentity,
+ /// Position in the session's log.
+ #[cfg_attr(feature = "schema", schema(value_type = u32))]
+ pub turn: TurnId,
+ /// The action that opened the turn.
+ pub action_id: AgentActionId,
+ /// User who prompted it, absent when a bot acted on nobody's behalf.
+ pub actor: Option<MacroUserIdStr<'static>>,
+ /// The magic-chip message posted for this turn, when one was.
+ pub announcement_message_id: Option<Uuid>,
+ /// The ACP stop reason, or `"error"` when the runtime refused the prompt.
+ pub stop_reason: String,
+ /// Prompts still waiting behind this turn.
+ pub queued_remaining: usize,
+}
+
+/// A turn ended and nothing is queued: the agent has stopped working.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct SessionSettledMetadata {
+ /// The session.
+ pub identity: SessionIdentity,
+ /// The turn that just ended, when the emitter still had its record.
+ pub last_turn: Option<TurnSummary>,
+}
+
+/// The agent asked its owner a question and is blocked on the answer.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct WaitingForInputMetadata {
+ /// The session.
+ pub identity: SessionIdentity,
+ /// The turn asking.
+ #[cfg_attr(feature = "schema", schema(value_type = u32))]
+ pub turn: TurnId,
+ /// The action that opened the turn.
+ pub action_id: AgentActionId,
+ /// The magic-chip message posted for this turn, when one was.
+ pub announcement_message_id: Option<Uuid>,
+ /// The question, as the agent phrased it.
+ pub question: String,
+}
+
+/// The pending question was answered or withdrawn.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct InputReceivedMetadata {
+ /// The session.
+ pub identity: SessionIdentity,
+ /// The turn that was asking.
+ #[cfg_attr(feature = "schema", schema(value_type = u32))]
+ pub turn: TurnId,
+ /// The action that opened the turn.
+ pub action_id: AgentActionId,
+}
+
+/// The session's live actor is gone: idle teardown, transport loss, or crash.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct SessionStoppedMetadata {
+ /// The session.
+ pub identity: SessionIdentity,
+ /// Why it stopped, as the session machine reported it.
+ pub reason: String,
+ /// The turn that was running when it stopped, if any.
+ pub turn_in_flight: Option<InFlightTurnSummary>,
+}
+
+/// The session was renamed; `identity` carries the new name.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct SessionRenamedMetadata {
+ /// The session, with its new name.
+ pub identity: SessionIdentity,
+}
+
+/// The session was deleted.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct SessionDeletedMetadata {
+ /// The session as it was.
+ pub identity: SessionIdentity,
+}
+
+/// Events publishable to [`MacroAgentSessionLifecycleTopic`].
+///
+/// The serde tag and [`AgentSessionLifecycleEventName`] spell the same wire
+/// names: subscribers filter on them, so they are API. The
+/// `event_names_match_the_wire` test holds the two in step. Exhaustive on
+/// purpose: a consumer's match should break when a variant is added.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::EnumDiscriminants)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(tag = "event_type", content = "metadata")]
+#[strum_discriminants(
+ name(AgentSessionLifecycleEventName),
+ derive(strum::Display, strum::EnumIter, strum::IntoStaticStr),
+ doc = "The wire name of an [`AgentSessionLifecycleEvent`], as subscribers filter on it."
+)]
+pub enum AgentSessionLifecycleEvent {
+ /// A session was created.
+ #[serde(rename = "agent_session.opened")]
+ #[strum_discriminants(strum(serialize = "agent_session.opened"))]
+ Opened(SessionOpenedMetadata),
+ /// A prompt was delivered to the runtime.
+ #[serde(rename = "agent_session.turn_started")]
+ #[strum_discriminants(strum(serialize = "agent_session.turn_started"))]
+ TurnStarted(TurnStartedMetadata),
+ /// The runtime answered a turn.
+ #[serde(rename = "agent_session.turn_ended")]
+ #[strum_discriminants(strum(serialize = "agent_session.turn_ended"))]
+ TurnEnded(TurnEndedMetadata),
+ /// A turn ended with nothing queued behind it.
+ #[serde(rename = "agent_session.settled")]
+ #[strum_discriminants(strum(serialize = "agent_session.settled"))]
+ Settled(SessionSettledMetadata),
+ /// The agent is blocked on a question to its owner.
+ #[serde(rename = "agent_session.waiting_for_input")]
+ #[strum_discriminants(strum(serialize = "agent_session.waiting_for_input"))]
+ WaitingForInput(WaitingForInputMetadata),
+ /// The question was answered or withdrawn.
+ #[serde(rename = "agent_session.input_received")]
+ #[strum_discriminants(strum(serialize = "agent_session.input_received"))]
+ InputReceived(InputReceivedMetadata),
+ /// The session's live actor is gone.
+ #[serde(rename = "agent_session.stopped")]
+ #[strum_discriminants(strum(serialize = "agent_session.stopped"))]
+ Stopped(SessionStoppedMetadata),
+ /// The session was renamed.
+ #[serde(rename = "agent_session.renamed")]
+ #[strum_discriminants(strum(serialize = "agent_session.renamed"))]
+ Renamed(SessionRenamedMetadata),
+ /// The session was deleted.
+ #[serde(rename = "agent_session.deleted")]
+ #[strum_discriminants(strum(serialize = "agent_session.deleted"))]
+ Deleted(SessionDeletedMetadata),
+}
+
+impl AgentSessionLifecycleEvent {
+ /// The session this event is about.
+ #[must_use]
+ pub fn identity(&self) -> &SessionIdentity {
+ match self {
+ Self::Opened(metadata) => &metadata.identity,
+ Self::TurnStarted(metadata) => &metadata.identity,
+ Self::TurnEnded(metadata) => &metadata.identity,
+ Self::Settled(metadata) => &metadata.identity,
+ Self::WaitingForInput(metadata) => &metadata.identity,
+ Self::InputReceived(metadata) => &metadata.identity,
+ Self::Stopped(metadata) => &metadata.identity,
+ Self::Renamed(metadata) => &metadata.identity,
+ Self::Deleted(metadata) => &metadata.identity,
+ }
+ }
+
+ /// The session's id.
+ #[must_use]
+ pub fn session_id(&self) -> AgentSessionId {
+ self.identity().session_id
+ }
+
+ /// The wire name subscribers filter on.
+ #[must_use]
+ pub fn name(&self) -> &'static str {
+ AgentSessionLifecycleEventName::from(self).into()
+ }
+}
+
+impl TopicEvent for AgentSessionLifecycleEvent {
+ type Topic = MacroAgentSessionLifecycleTopic;
+
+ const SCHEMA_VERSION: u8 = 1;
+}
+
+/// Publishable event for [`MacroAgentSessionLifecycleTopic`].
+///
+/// Keyed by session id: one session's facts land on one partition, in order,
+/// so a consumer sees `turn_started` before `turn_ended` before `settled`.
+#[derive(Debug, Clone)]
+pub struct AgentSessionLifecycleMacroEvent {
+ key: String,
+ event: Event<AgentSessionLifecycleEvent>,
+}
+
+impl AgentSessionLifecycleMacroEvent {
+ /// Wrap a lifecycle fact for publication.
+ #[must_use]
+ pub fn new(event: AgentSessionLifecycleEvent) -> Self {
+ Self {
+ key: event.session_id().to_string(),
+ event: Event::new(event),
+ }
+ }
+}
+
+impl MacroEvent for AgentSessionLifecycleMacroEvent {
+ type EventPayload = AgentSessionLifecycleEvent;
+
+ fn key(&self) -> &str {
+ &self.key
+ }
+
+ fn event(&self) -> &Event<Self::EventPayload> {
+ &self.event
+ }
+
+ fn from_event(key: String, event: Event<Self::EventPayload>) -> Self {
+ Self { key, event }
+ }
+}
diff --git a/crates/agent_session/src/domain/events/test.rs b/crates/agent_session/src/domain/events/test.rs
new file mode 100644
index 0000000000..76bb5117f5
--- /dev/null
+++ b/crates/agent_session/src/domain/events/test.rs
@@ -0,0 +1,144 @@
+use super::*;
+use bots::domain::models::BotId;
+
+use macro_user_id::cowlike::CowLike;
+use serde_json::json;
+
+fn owner() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .expect("valid user id")
+ .into_owned()
+}
+
+fn identity() -> SessionIdentity {
+ SessionIdentity {
+ session_id: AgentSessionId::TEST_A,
+ session_name: "Fix the flaky test".to_owned(),
+ bot_id: BotId::TEST_A,
+ bot_name: "Macro Coder".to_owned(),
+ owner_id: owner(),
+ origin: Some(ThreadOrigin {
+ channel_id: Uuid::from_u128(1),
+ thread_id: Uuid::from_u128(2),
+ originating_message_id: Uuid::from_u128(3),
+ }),
+ }
+}
+
+fn action_id() -> AgentActionId {
+ AgentActionId::mint()
+}
+
+fn one_of_each() -> Vec<AgentSessionLifecycleEvent> {
+ vec![
+ AgentSessionLifecycleEvent::Opened(SessionOpenedMetadata {
+ identity: identity(),
+ model: "claude".to_owned(),
+ harness: "claude_code".to_owned(),
+ }),
+ AgentSessionLifecycleEvent::TurnStarted(TurnStartedMetadata {
+ identity: identity(),
+ turn: TurnId(0),
+ action_id: action_id(),
+ actor: Some(owner()),
+ announcement_message_id: Some(Uuid::from_u128(4)),
+ }),
+ AgentSessionLifecycleEvent::TurnEnded(TurnEndedMetadata {
+ identity: identity(),
+ turn: TurnId(0),
+ action_id: action_id(),
+ actor: Some(owner()),
+ announcement_message_id: Some(Uuid::from_u128(4)),
+ stop_reason: "end_turn".to_owned(),
+ queued_remaining: 0,
+ }),
+ AgentSessionLifecycleEvent::Settled(SessionSettledMetadata {
+ identity: identity(),
+ last_turn: Some(TurnSummary {
+ turn: TurnId(0),
+ action_id: action_id(),
+ actor: Some(owner()),
+ announcement_message_id: Some(Uuid::from_u128(4)),
+ stop_reason: "end_turn".to_owned(),
+ excerpt: Some("Done.".to_owned()),
+ }),
+ }),
+ AgentSessionLifecycleEvent::WaitingForInput(WaitingForInputMetadata {
+ identity: identity(),
+ turn: TurnId(1),
+ action_id: action_id(),
+ announcement_message_id: None,
+ question: "Which approach?".to_owned(),
+ }),
+ AgentSessionLifecycleEvent::InputReceived(InputReceivedMetadata {
+ identity: identity(),
+ turn: TurnId(1),
+ action_id: action_id(),
+ }),
+ AgentSessionLifecycleEvent::Stopped(SessionStoppedMetadata {
+ identity: identity(),
+ reason: "transport closed".to_owned(),
+ turn_in_flight: None,
+ }),
+ AgentSessionLifecycleEvent::Renamed(SessionRenamedMetadata {
+ identity: identity(),
+ }),
+ AgentSessionLifecycleEvent::Deleted(SessionDeletedMetadata {
+ identity: identity(),
+ }),
+ ]
+}
+
+#[test]
+fn event_names_match_the_wire() {
+ use strum::IntoEnumIterator as _;
+
+ // Subscribers filter on these names, so the serde tag is the contract and
+ // `AgentSessionLifecycleEventName` must agree with it variant for variant.
+ let wire_names: Vec<String> = one_of_each()
+ .into_iter()
+ .map(|event| {
+ serde_json::to_value(event).expect("serialize event")["event_type"].to_string()
+ })
+ .collect();
+ let names: Vec<String> = AgentSessionLifecycleEventName::iter()
+ .map(|name| serde_json::Value::String(name.to_string()).to_string())
+ .collect();
+
+ assert_eq!(names, wire_names);
+}
+
+#[test]
+fn name_is_the_wire_name() {
+ for event in one_of_each() {
+ let value = serde_json::to_value(&event).expect("serialize event");
+ assert_eq!(value["event_type"], json!(event.name()));
+ }
+}
+
+#[test]
+fn every_variant_round_trips() {
+ for event in one_of_each() {
+ let value = serde_json::to_value(&event).expect("serialize event");
+ assert_eq!(
+ value["metadata"]["identity"]["session_id"],
+ json!(AgentSessionId::TEST_A)
+ );
+ let parsed: AgentSessionLifecycleEvent =
+ serde_json::from_value(value).expect("deserialize event");
+ assert_eq!(parsed, event);
+ }
+}
+
+#[test]
+fn macro_event_is_keyed_by_session_id() {
+ let event = AgentSessionLifecycleMacroEvent::new(AgentSessionLifecycleEvent::Renamed(
+ SessionRenamedMetadata {
+ identity: identity(),
+ },
+ ));
+
+ assert_eq!(event.key(), AgentSessionId::TEST_A.to_string());
+ assert_eq!(event.event().schema_version, 1);
+ assert_eq!(event.event().event.session_id(), AgentSessionId::TEST_A);
+}
diff --git a/crates/agent_session/src/domain/lifecycle.rs b/crates/agent_session/src/domain/lifecycle.rs
new file mode 100644
index 0000000000..6e35cb03eb
--- /dev/null
+++ b/crates/agent_session/src/domain/lifecycle.rs
@@ -0,0 +1,46 @@
+//! Building lifecycle-event identity from the session's own rows.
+
+use crate::domain::events::{SessionIdentity, ThreadOrigin};
+
+use super::model::{AgentSession, SessionBot};
+
+/// The identity block every lifecycle event carries, from the session row
+/// and its bot.
+///
+/// A thread origin needs all three of its ids. A session created from a
+/// thread has them all; one created without a message has none. Anything in
+/// between is a row this code does not know how to describe, so it is
+/// reported as no origin rather than a half one.
+#[must_use]
+pub fn session_identity(session: &AgentSession, bot: &SessionBot) -> SessionIdentity {
+ let origin = match (
+ session.thread_channel_id,
+ session.thread_id,
+ session.originating_message_id,
+ ) {
+ (Some(channel_id), Some(thread_id), Some(originating_message_id)) => Some(ThreadOrigin {
+ channel_id,
+ thread_id,
+ originating_message_id,
+ }),
+ (None, None, None) => None,
+ (channel_id, thread_id, originating_message_id) => {
+ tracing::warn!(
+ session_id = %session.id,
+ ?channel_id,
+ ?thread_id,
+ ?originating_message_id,
+ "agent session has a partial thread origin; reporting none"
+ );
+ None
+ }
+ };
+ SessionIdentity {
+ session_id: session.id,
+ session_name: session.name.clone(),
+ bot_id: session.bot_id,
+ bot_name: bot.name.clone(),
+ owner_id: session.owner_id.clone(),
+ origin,
+ }
+}
diff --git a/crates/agent_session/src/domain/mod.rs b/crates/agent_session/src/domain/mod.rs
index d1592e0b9d..9a00c48cd5 100644
--- a/crates/agent_session/src/domain/mod.rs
+++ b/crates/agent_session/src/domain/mod.rs
@@ -1,5 +1,7 @@
pub mod connection;
pub mod error;
+pub mod events;
+pub mod lifecycle;
pub mod model;
pub mod ports;
mod sandbox_size;
diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rs
index c805eb0b14..1a1c3d3e6d 100644
--- a/crates/agent_session/src/domain/model.rs
+++ b/crates/agent_session/src/domain/model.rs
@@ -279,7 +279,8 @@ pub struct ExternalSession {
}
/// The agent behind a session, as much of it as rendering a message needs.
-#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)]
+#[derive(Debug, Clone, serde::Serialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct SessionBot {
/// The bot's id. A message it sent has `"bot|{id}"` as its sender.
@@ -296,7 +297,8 @@ pub struct SessionBot {
/// Clients deserialize this, so both derives are used.
// Domain-owned because the queue GET endpoint and the realtime snapshot
// serialize this type byte-identically; that identity is the client contract.
-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct QueuedActionDto {
/// The id the action was accepted under.
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index 239748010b..7b8246d46c 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -1,6 +1,11 @@
+use std::pin::Pin;
+
use super::error::{AgentSessionError, Result};
use super::model::*;
+use super::session::StopReason;
+use crate::domain::events::AgentSessionLifecycleEvent;
use agent_client_protocol::schema::v1::SessionId;
+use agent_fold::domain::model::TurnSignal;
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
use agent_runtime_protocol::domain::ports::Transport;
use agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};
@@ -480,20 +485,31 @@ pub trait AgentSessionLogRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<Vec<StoredAgentSessionLog>>> + Send;
}
+/// One frame appended: its durable identity, and what the fold made of it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Appended {
+ /// The log row the frame became.
+ pub log_id: Uuid,
+ /// What the frame meant for the turn, per the connection's live fold.
+ /// Empty for most frames; never filled while catching up on history.
+ pub signals: Vec<TurnSignal>,
+}
+
/// Sequential live log writer owned by one session actor.
pub trait AgentSessionLogWriter: Send + 'static {
/// Persist and fold one frame into this connection's live projection.
- fn append(&mut self, log: AgentSessionLog) -> impl Future<Output = Result<Uuid>> + Send {
+ fn append(&mut self, log: AgentSessionLog) -> impl Future<Output = Result<Appended>> + Send {
self.append_with_boundary(log, None)
}
/// Persist a frame and optional successful-load boundary in one transaction.
- /// Returns its durable row identity before the actor continues.
+ /// Returns its durable row identity, and the turn signals the frame
+ /// implied, before the actor continues.
fn append_with_boundary(
&mut self,
log: AgentSessionLog,
boundary: Option<HistoryBoundary>,
- ) -> impl Future<Output = Result<Uuid>> + Send;
+ ) -> impl Future<Output = Result<Appended>> + Send;
}
/// A session's queue changed; this is the whole queue as it stands now.
@@ -542,33 +558,79 @@ pub trait AgentSessionRealtime {
}
}
-/// Told when a session's turn ends and when its live actor stops.
+/// Publishing a session's lifecycle facts for anyone downstream: webhooks,
+/// notifications, observability.
+///
+/// Best effort by contract: an implementation logs a failed publish and never
+/// returns it, because nothing about the session itself went wrong. Object-
+/// safe so the harness and this service can hold it erased rather than as one
+/// more type parameter; the broker's `send_event` is generic and cannot be.
+pub trait AgentSessionLifecyclePublisher: Send + Sync + 'static {
+ /// Publish one fact. Resolves once the publish has been attempted.
+ fn publish(
+ &self,
+ event: AgentSessionLifecycleEvent,
+ ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
+}
+
+impl<Publisher: AgentSessionLifecyclePublisher + ?Sized> AgentSessionLifecyclePublisher
+ for std::sync::Arc<Publisher>
+{
+ fn publish(
+ &self,
+ event: AgentSessionLifecycleEvent,
+ ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
+ (**self).publish(event)
+ }
+}
+
+/// An [`AgentSessionLifecyclePublisher`] that publishes nothing: tests,
+/// offline tooling, and replay.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct NoopLifecyclePublisher;
+
+impl AgentSessionLifecyclePublisher for NoopLifecyclePublisher {
+ fn publish(
+ &self,
+ _event: AgentSessionLifecycleEvent,
+ ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
+ Box::pin(async {})
+ }
+}
+
+/// Told what the session's log meant for its turn, and when its live actor
+/// stops.
///
/// What the harness gates its prompt queue on: a turn ending means the agent
/// can take the next queued prompt, an actor stopping means no turn is in
-/// flight anymore however the last one looked. Both fire from the actor's own
-/// task, so implementations must only hand the fact off - enqueue, notify -
-/// never do the resulting work inline.
+/// flight anymore however the last one looked. Every method fires from the
+/// actor's own task, so implementations must only hand the fact off -
+/// enqueue, notify - never do the resulting work inline.
+///
+/// Turn signals come from the connection's live fold - the same fold the
+/// chip renders from - so "the turn ended" has one definition. That includes
+/// turns nobody here prompted: a resumed session's runtime reports those
+/// with `_session/turn_complete`, and the fold closes them too.
///
/// Object-safe and synchronous on purpose: the service stores it erased so
/// wiring it is not another type parameter, and the one production
/// implementation admits work to a queue synchronously.
pub trait SessionTurnObserver: Send + Sync + 'static {
- /// The runtime answered the session's in-flight turn.
- fn turn_ended(&self, id: AgentSessionId);
+ /// A fold-derived fact about the session's turn.
+ fn signal(&self, id: AgentSessionId, signal: TurnSignal);
/// The session's live actor is gone - disconnect, teardown, or crash. Any
- /// in-flight turn went with it, without [`Self::turn_ended`] firing.
- fn session_stopped(&self, id: AgentSessionId);
+ /// in-flight turn went with it, without a [`TurnSignal::TurnEnded`].
+ fn session_stopped(&self, id: AgentSessionId, reason: StopReason);
}
impl<T: SessionTurnObserver + ?Sized> SessionTurnObserver for std::sync::Arc<T> {
- fn turn_ended(&self, id: AgentSessionId) {
- (**self).turn_ended(id);
+ fn signal(&self, id: AgentSessionId, signal: TurnSignal) {
+ (**self).signal(id, signal);
}
- fn session_stopped(&self, id: AgentSessionId) {
- (**self).session_stopped(id);
+ fn session_stopped(&self, id: AgentSessionId, reason: StopReason) {
+ (**self).session_stopped(id, reason);
}
}
@@ -578,9 +640,9 @@ impl<T: SessionTurnObserver + ?Sized> SessionTurnObserver for std::sync::Arc<T>
pub struct NoOpTurnObserver;
impl SessionTurnObserver for NoOpTurnObserver {
- fn turn_ended(&self, _id: AgentSessionId) {}
+ fn signal(&self, _id: AgentSessionId, _signal: TurnSignal) {}
- fn session_stopped(&self, _id: AgentSessionId) {}
+ fn session_stopped(&self, _id: AgentSessionId, _reason: StopReason) {}
}
/// A [`SessionTurnObserver`] bound after construction, for the composition
@@ -609,15 +671,15 @@ impl LateBoundTurnObserver {
}
impl SessionTurnObserver for LateBoundTurnObserver {
- fn turn_ended(&self, id: AgentSessionId) {
+ fn signal(&self, id: AgentSessionId, signal: TurnSignal) {
if let Some(observer) = self.observer.get() {
- observer.turn_ended(id);
+ observer.signal(id, signal);
}
}
- fn session_stopped(&self, id: AgentSessionId) {
+ fn session_stopped(&self, id: AgentSessionId, reason: StopReason) {
if let Some(observer) = self.observer.get() {
- observer.session_stopped(id);
+ observer.session_stopped(id, reason);
}
}
}
diff --git a/crates/agent_session/src/domain/sandbox_size.rs b/crates/agent_session/src/domain/sandbox_size.rs
index 1b895e88ee..3601212d4b 100644
--- a/crates/agent_session/src/domain/sandbox_size.rs
+++ b/crates/agent_session/src/domain/sandbox_size.rs
@@ -1,7 +1,6 @@
//! Named compute tier for a managed coding-agent sandbox.
use serde::{Deserialize, Serialize};
-use utoipa::ToSchema;
#[cfg(test)]
mod test;
@@ -10,7 +9,8 @@ mod test;
///
/// The API and database store the name. CPU, RAM, and disk live in
/// `crates/agent_harness/sandbox_sizes.json`.
-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub enum SandboxSize {
/// Smallest named tier.
diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rs
index 3b0f90f45f..8f682449ee 100644
--- a/crates/agent_session/src/domain/service.rs
+++ b/crates/agent_session/src/domain/service.rs
@@ -28,8 +28,9 @@ mod test;
use std::sync::Arc;
use agent_client_protocol::schema::v1::SessionId;
-use agent_fold::domain::fold::FoldMachineImpl;
-use agent_fold::domain::ports::{FoldMachine, FoldedMessageRepo};
+use agent_fold::domain::lifecycle::LifecycleFold;
+use agent_fold::domain::model::TurnSignal;
+use agent_fold::domain::ports::FoldedMessageRepo;
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
use agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToServerMessage};
use dashmap::DashMap;
@@ -46,6 +47,8 @@ use bots::domain::models::BotId;
use super::connection::RuntimeAttachment;
use super::error::{AgentSessionError, Result};
+use super::lifecycle::session_identity;
+use super::model::SessionBot;
use super::model::{
AgentSession, AgentSessionId, AgentSessionLog, AgentSessionRenamed, AuthorKind, ChannelSession,
ClaimOutcome, CreateAgentSessionParams, LogAppended, MAX_AGENT_SESSION_NAME_CHARS, Message,
@@ -53,12 +56,13 @@ use super::model::{
StoredAgentSessionLog,
};
use super::ports::{
- AgentConnector, AgentSessionLogRepo, AgentSessionLogWriter, AgentSessionNameGenerator,
- AgentSessionQueueChanged, AgentSessionRealtime, AgentSessionRepo,
- NoOpAgentSessionNameGenerator, NoOpTurnObserver, SessionOwnership, SessionTurnObserver,
+ AgentConnector, AgentSessionLifecyclePublisher, AgentSessionLogRepo, AgentSessionLogWriter,
+ AgentSessionNameGenerator, AgentSessionQueueChanged, AgentSessionRealtime, AgentSessionRepo,
+ Appended, NoOpAgentSessionNameGenerator, SessionOwnership, SessionTurnObserver,
};
use super::session::actors::{SessionActor, SessionCommand, Stepped};
use super::session::{CloseReason, Input};
+use crate::domain::events::{AgentSessionLifecycleEvent, SessionRenamedMetadata};
/// Buffered not-yet-accepted commands per session actor.
const COMMAND_BUFFER: usize = 1028;
@@ -189,6 +193,9 @@ pub trait AgentSessionService: Send + Sync + 'static {
bot_id: Option<BotId>,
) -> impl Future<Output = Result<ChannelSession>> + Send;
+ /// The bot a session runs for, as viewers see it.
+ fn session_bot(&self, id: BotId) -> impl Future<Output = Result<SessionBot>> + Send;
+
/// The user-message id the next prompt appended to this session will fold to.
fn next_prompt_message_id(
&self,
@@ -254,6 +261,9 @@ pub struct AgentSessionServiceImpl<R, Folds, Rt, Namer = NoOpAgentSessionNameGen
/// Told when a session's turn ends or its actor stops - the harness's
/// prompt-queue gate. Erased so wiring it is not another type parameter.
turn_observer: Arc<dyn SessionTurnObserver>,
+ /// Where lifecycle facts go - renames, from here; everything else from
+ /// the harness. Erased for the same reason as the observer.
+ lifecycle_publisher: Arc<dyn AgentSessionLifecyclePublisher>,
active: Arc<ActiveSessions>,
/// This service's identity in the session-management lease. Minted at
/// construction: a restarted process is a new replica, and its claims
@@ -264,57 +274,44 @@ pub struct AgentSessionServiceImpl<R, Folds, Rt, Namer = NoOpAgentSessionNameGen
lifecycle: Arc<Mutex<()>>,
}
-impl<R, Folds, Rt> AgentSessionServiceImpl<R, Folds, Rt> {
- /// Build a service from its persistence port, fold, and realtime
- /// publisher.
+impl<R, Folds, Rt, Namer> AgentSessionServiceImpl<R, Folds, Rt, Namer> {
+ /// Build a service from every port it drives.
+ ///
+ /// Nothing is defaulted: a caller with no viewers passes
+ /// [`NoOpRealtime`](super::ports::NoOpRealtime), one with no queue above
+ /// it passes [`NoOpTurnObserver`], one with nothing downstream passes
+ /// [`NoopLifecyclePublisher`], and one that is the only service instance
+ /// in its process mints its own [`ReplicaId`] - each choice visible at the
+ /// call site rather than hidden in a builder's default.
///
- /// Only a live session streams, so a caller with no viewers to serve -
- /// tests, and offline tooling - passes
- /// [`NoOpRealtime`](super::ports::NoOpRealtime).
- pub fn new(repo: R, folds: Folds, realtime: Rt) -> Self {
+ /// `replica` is this service's identity in the session-management lease.
+ /// A restarted process is a new replica whose claims are recovered by
+ /// heartbeat staleness, never inherited. A process with more than one
+ /// attach-capable instance hands every instance the same id: commands
+ /// forward to an address, and every instance in a process shares one.
+ pub fn new(
+ repo: R,
+ folds: Folds,
+ realtime: Rt,
+ name_generator: Namer,
+ turn_observer: Arc<dyn SessionTurnObserver>,
+ lifecycle_publisher: Arc<dyn AgentSessionLifecyclePublisher>,
+ replica: ReplicaId,
+ ) -> Self {
Self {
repo,
folds,
realtime,
- name_generator: NoOpAgentSessionNameGenerator,
- turn_observer: Arc::new(NoOpTurnObserver),
+ name_generator,
+ turn_observer,
+ lifecycle_publisher,
active: Arc::new(DashMap::new()),
- replica: ReplicaId::mint(),
+ replica,
tasks: TaskTracker::new(),
cancellation: CancellationToken::new(),
lifecycle: Arc::new(Mutex::new(())),
}
}
-}
-
-impl<R, Folds, Rt, Namer> AgentSessionServiceImpl<R, Folds, Rt, Namer> {
- /// Replace the no-op name generator with a production adapter.
- #[must_use]
- pub fn with_name_generator<NextNamer>(
- self,
- name_generator: NextNamer,
- ) -> AgentSessionServiceImpl<R, Folds, Rt, NextNamer> {
- AgentSessionServiceImpl {
- repo: self.repo,
- folds: self.folds,
- realtime: self.realtime,
- name_generator,
- turn_observer: self.turn_observer,
- active: self.active,
- replica: self.replica,
- tasks: self.tasks,
- cancellation: self.cancellation,
- lifecycle: self.lifecycle,
- }
- }
-
- /// Replace the no-op turn observer with whoever gates prompts on turns -
- /// in production, the harness's queue.
- #[must_use]
- pub fn with_turn_observer(mut self, turn_observer: Arc<dyn SessionTurnObserver>) -> Self {
- self.turn_observer = turn_observer;
- self
- }
/// This service's identity in the session-management lease, for the
/// composition root to heartbeat while the process lives.
@@ -323,19 +320,6 @@ impl<R, Folds, Rt, Namer> AgentSessionServiceImpl<R, Folds, Rt, Namer> {
self.replica
}
- /// Adopt a caller-minted replica identity, replacing the constructor's.
- ///
- /// For processes with more than one attach-capable service instance: the
- /// lease's replica is the *process* (commands forward to an address, and
- /// every instance in a process shares one), so the composition root mints
- /// a single id and stamps it on each instance. The instances' session
- /// sets are disjoint by construction, so they never contend for a lease.
- #[must_use]
- pub fn with_replica(mut self, replica: ReplicaId) -> Self {
- self.replica = replica;
- self
- }
-
/// Stop active actors and wait for their tasks to release their transports.
pub async fn shutdown(&self) {
let lifecycle = self.lifecycle.lock().await;
@@ -582,6 +566,7 @@ where
tracing::warn!(error = ?error, %id, "failed to publish agent session rename");
})
.ok();
+ publish_renamed_lifecycle(&self.repo, &self.lifecycle_publisher, id).await;
Ok(())
}
@@ -714,6 +699,7 @@ where
spawn_initial_agent_session_rename(
self.repo.clone(),
self.realtime.clone(),
+ self.lifecycle_publisher.clone(),
self.name_generator.clone(),
id,
initial_prompt,
@@ -722,6 +708,10 @@ where
Ok(())
}
+ async fn session_bot(&self, id: BotId) -> Result<SessionBot> {
+ self.repo.session_bot(id).await
+ }
+
async fn next_prompt_message_id(&self, id: AgentSessionId) -> Result<MessageId> {
Ok(MessageId {
turn: self.folds.next_turn_id(id).await?,
@@ -789,6 +779,7 @@ where
fn spawn_initial_agent_session_rename<R, Rt, Namer>(
repo: R,
realtime: Rt,
+ lifecycle_publisher: Arc<dyn AgentSessionLifecyclePublisher>,
name_generator: Namer,
id: AgentSessionId,
initial_prompt: String,
@@ -835,6 +826,7 @@ fn spawn_initial_agent_session_rename<R, Rt, Namer>(
name,
})
.await?;
+ publish_renamed_lifecycle(&repo, &lifecycle_publisher, id).await;
Ok("renamed")
}
.await;
@@ -853,6 +845,38 @@ fn spawn_initial_agent_session_rename<R, Rt, Namer>(
);
}
+/// Publish `agent_session.renamed` for a session whose name just changed.
+///
+/// The rename itself is already durable, so a failure to describe it here is
+/// logged and swallowed: the event is a courtesy to downstream, not part of
+/// the rename.
+async fn publish_renamed_lifecycle<R>(
+ repo: &R,
+ lifecycle_publisher: &Arc<dyn AgentSessionLifecyclePublisher>,
+ id: AgentSessionId,
+) where
+ R: AgentSessionRepo,
+{
+ let identity = async {
+ let session = repo.get(id).await?;
+ let bot = repo.session_bot(session.bot_id).await?;
+ Ok::<_, AgentSessionError>(session_identity(&session, &bot))
+ }
+ .await;
+ match identity {
+ Ok(identity) => {
+ lifecycle_publisher
+ .publish(AgentSessionLifecycleEvent::Renamed(
+ SessionRenamedMetadata { identity },
+ ))
+ .await;
+ }
+ Err(error) => {
+ tracing::warn!(error = ?error, %id, "skipping agent_session.renamed: identity unavailable");
+ }
+ }
+}
+
/// The telemetry shape of a log frame: its kind, and the status event it
/// carries when it is one.
///
@@ -902,7 +926,7 @@ fn validate_agent_session_name(raw: &str) -> Result<&str> {
pub struct LiveSessionLogWriter<R, Rt> {
repo: R,
realtime: Rt,
- fold: Option<FoldMachineImpl>,
+ fold: Option<LifecycleFold>,
/// The management claim this writer appends under, when it has one. A
/// session actor always writes fenced; the unfenced constructor exists
/// for writers outside any live-management contest - `seed_jsonl`
@@ -948,7 +972,7 @@ where
&mut self,
log: AgentSessionLog,
boundary: Option<crate::domain::model::HistoryBoundary>,
- ) -> Result<macro_uuid::Uuid> {
+ ) -> Result<Appended> {
let session = log.agent_session_id;
// The wire tap: every frame of every session, both directions,
@@ -978,20 +1002,24 @@ where
None => AgentSessionLogRepo::create(&self.repo, log.clone()).await?,
};
- if let Some(fold) = &mut self.fold {
- let _ = fold.push(log.clone());
+ let signals = if let Some(fold) = &mut self.fold {
+ fold.push(log.clone()).signals
} else {
match self.catch_up(session).await {
- Ok(fold) => self.fold = Some(fold),
+ Ok((fold, signals)) => {
+ self.fold = Some(fold);
+ signals
+ }
Err(error) => {
tracing::error!(
error = ?error,
%session,
"failed to fold agent session frame"
);
+ Vec::new()
}
}
- }
+ };
// Projected on every frame - idempotent, rebuildable from the log,
// and best-effort like the stream below, so a failed write must not
@@ -999,7 +1027,7 @@ where
if let Some(model) = self
.fold
.as_ref()
- .and_then(|fold| fold.metadata().model.clone())
+ .and_then(|fold| fold.inner().metadata().model.clone())
&& let Err(error) = self.repo.set_model(session, &model).await
{
tracing::error!(
@@ -1012,7 +1040,7 @@ where
// Best-effort once the durable append has succeeded: the port drops
// frames by contract, and the log this was derived from is already
// durable, so the worst a failure costs is a viewer who has to reload.
- let id = stored.id;
+ let log_id = stored.id;
if let Err(error) = self.stream(session, stored).await {
tracing::error!(
error = ?error,
@@ -1020,7 +1048,7 @@ where
"failed to stream agent session frame"
);
}
- Ok(id)
+ Ok(Appended { log_id, signals })
}
}
@@ -1151,8 +1179,10 @@ where
/// starts from where the session actually is rather than from nothing.
///
/// Runs once per connection, on its first frame - by which point that
- /// frame is already in the log, so replaying the log folds it too and the
- /// caller must not push it again.
+ /// frame is already in the log. Everything before it is history: folded,
+ /// and whatever it signalled discarded, because a reconnect must not
+ /// announce past turns again. The frame itself is live, so its signals
+ /// are returned like any later frame's.
///
/// This is what makes re-attaching correct.
/// [`TurnId`](agent_fold::domain::model::TurnId)s are a counter over the
@@ -1163,16 +1193,20 @@ where
async fn catch_up(
&self,
session: AgentSessionId,
- ) -> std::result::Result<FoldMachineImpl, rootcause::Report> {
- let log = AgentSessionLogRepo::list_by_session(&self.repo, session)
+ ) -> std::result::Result<(LifecycleFold, Vec<TurnSignal>), rootcause::Report> {
+ let mut log = AgentSessionLogRepo::list_by_session(&self.repo, session)
.await
.map_err(|error| rootcause::report!(error))?;
- let mut fold = FoldMachineImpl::new();
+ let mut fold = LifecycleFold::new();
+ let just_appended = log.pop();
for stored in log {
let _ = fold.push(stored.entry);
}
- Ok(fold)
+ let signals = just_appended
+ .map(|stored| fold.push(stored.entry).signals)
+ .unwrap_or_default();
+ Ok((fold, signals))
}
}
@@ -1195,17 +1229,17 @@ async fn run_session<Connector, Logs, Ownership>(
Logs: AgentSessionLogWriter + AgentSessionRepo,
Ownership: SessionOwnership,
{
- loop {
+ let stop_reason = loop {
let input = tokio::select! {
biased;
() = cancellation.cancelled() => Input::Closed(CloseReason::Abandoned),
input = actor.next_input() => input,
};
let stepped = actor.dispatch(input).await;
- if stepped == Stepped::Stopped {
- break;
+ if let Stepped::Stopped(reason) = stepped {
+ break reason;
}
- }
+ };
// Refuse late commands before releasing the registry entry, so a caller
// cannot enqueue into an actor that will never step again.
@@ -1230,5 +1264,5 @@ async fn run_session<Connector, Logs, Ownership>(
// Last, after the registry entry is gone: whatever the observer does with
// the fact - clear a busy flag, dispatch nothing - it sees a session that
// really has no actor anymore.
- turn_observer.session_stopped(id);
+ turn_observer.session_stopped(id, stop_reason);
}
diff --git a/crates/agent_session/src/domain/service/test.rs b/crates/agent_session/src/domain/service/test.rs
index 66a86477b0..97e664d04b 100644
--- a/crates/agent_session/src/domain/service/test.rs
+++ b/crates/agent_session/src/domain/service/test.rs
@@ -4,8 +4,11 @@ use crate::domain::model::{
DEFAULT_AGENT_SESSION_NAME, Message, ReplicaAddress, SessionBot, SessionManager,
};
use crate::domain::ports::NoOpRealtime;
+use crate::domain::ports::{NoOpTurnObserver, NoopLifecyclePublisher};
use crate::domain::session::HandshakeStatus;
-use crate::testing::{InMemoryAgentSessionRepo, RecordingRealtime, test_agent_session};
+use crate::testing::{
+ InMemoryAgentSessionRepo, RecordingLifecyclePublisher, RecordingRealtime, test_agent_session,
+};
use agent_fold::domain::fold::fold;
use agent_fold::domain::service::FoldedMessageService;
use agent_fold::testing::{TURN, parse_log_as, test_session};
@@ -42,6 +45,10 @@ fn fixture() -> Fixture {
repo.clone(),
FoldedMessageService::new(repo.clone()),
NoOpRealtime,
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
),
repo,
session,
@@ -160,7 +167,7 @@ impl AgentSessionLogWriter for BlockingPromptLogs {
&mut self,
log: AgentSessionLog,
_boundary: Option<crate::domain::model::HistoryBoundary>,
- ) -> Result<macro_uuid::Uuid> {
+ ) -> Result<Appended> {
let is_prompt = matches!(
&log.content,
Message::ToRuntime(ToRuntimeMessage::Acp(AcpMessage(
@@ -171,7 +178,10 @@ impl AgentSessionLogWriter for BlockingPromptLogs {
self.entered.notify_one();
self.release.notified().await;
}
- Ok(AgentSessionLogRepo::create(&self.repo, log).await?.id)
+ Ok(Appended {
+ log_id: AgentSessionLogRepo::create(&self.repo, log).await?.id,
+ signals: Vec::new(),
+ })
}
}
@@ -207,6 +217,10 @@ async fn manual_rename_trims_persists_and_publishes() {
repo.clone(),
FoldedMessageService::new(repo.clone()),
realtime.clone(),
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
);
service
@@ -238,6 +252,10 @@ async fn manual_rename_rejects_blank_and_overlong_names() {
repo.clone(),
FoldedMessageService::new(repo),
RenameRealtime::default(),
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
);
assert!(matches!(
@@ -267,6 +285,10 @@ async fn manual_rename_rejects_access_for_another_entity_type() {
repo.clone(),
FoldedMessageService::new(repo),
RenameRealtime::default(),
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
);
let wrong_access = EntityAccessReceipt::<OwnerAccessLevel>::dangerously_assert_internal_user(
&session.as_uuid().to_string(),
@@ -287,28 +309,32 @@ async fn background_naming_persists_then_publishes_the_generated_name() {
let session = test_session();
repo.insert_session(test_agent_session(session));
let realtime = RenameRealtime::default();
+ let lifecycle = RecordingLifecyclePublisher::new();
spawn_initial_agent_session_rename(
repo.clone(),
realtime.clone(),
+ Arc::new(lifecycle.clone()),
FixedNameGenerator,
session,
"fix the flaky tests".to_owned(),
);
- for _ in 0..20 {
- if !realtime
- .0
- .lock()
- .expect("rename store is not poisoned")
- .is_empty()
- {
- break;
- }
- tokio::task::yield_now().await;
- }
+ // The lifecycle event is published last, so its arrival means the
+ // rename and its realtime push are done too.
+ lifecycle.wait_for_published(1).await;
let stored = repo.get(session).await.expect("get session");
assert_eq!(stored.name, "Fix Flaky Tests");
+ assert!(
+ matches!(
+ lifecycle.published().as_slice(),
+ [AgentSessionLifecycleEvent::Renamed(renamed)]
+ if renamed.identity.session_id == session
+ && renamed.identity.session_name == "Fix Flaky Tests"
+ ),
+ "renamed is published with the new name: {:?}",
+ lifecycle.published()
+ );
assert_eq!(
realtime
.0
@@ -334,6 +360,7 @@ async fn background_naming_does_not_overwrite_a_manual_name() {
spawn_initial_agent_session_rename(
repo.clone(),
realtime.clone(),
+ Arc::new(NoopLifecyclePublisher),
FixedNameGenerator,
session,
"fix the flaky tests".to_owned(),
@@ -696,6 +723,10 @@ async fn a_second_replica_cannot_attach_a_session_with_a_live_manager() {
fx.repo.clone(),
FoldedMessageService::new(fx.repo.clone()),
NoOpRealtime,
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
);
let result = second_replica
.attach_session(fx.session, RuntimeAttachment::solo(PendingTransport))
@@ -989,6 +1020,10 @@ async fn marking_disconnected_persists_and_publishes_the_event() {
repo.clone(),
FoldedMessageService::new(repo.clone()),
realtime.clone(),
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
);
service
@@ -1026,8 +1061,15 @@ async fn marking_disconnected_is_bounded_when_persistence_hangs() {
hang_disconnect: true,
fail_restore_log: None,
};
- let service =
- AgentSessionServiceImpl::new(hanging, FoldedMessageService::new(repo), NoOpRealtime);
+ let service = AgentSessionServiceImpl::new(
+ hanging,
+ FoldedMessageService::new(repo),
+ NoOpRealtime,
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
+ );
let disconnect = tokio::spawn(async move { service.mark_disconnected(session).await });
tokio::task::yield_now().await;
tokio::time::advance(SESSION_PERSIST_TIMEOUT).await;
@@ -1199,6 +1241,10 @@ async fn session_log_returns_the_sessions_frames_in_order() {
store.clone(),
FoldedMessageService::new(store.clone()),
NoOpRealtime,
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
);
let log = service
@@ -1508,18 +1554,17 @@ async fn assert_restore_persistence_failure_does_not_send_prompt(failure: Restor
};
assert_eq!(load.method.as_ref(), "session/load");
failed_response_id = Some(load.id.clone());
- assert_eq!(
+ assert!(matches!(
actor
.dispatch(Input::Inbound(ToServerMessage::Acp(AcpMessage(
RawJsonRpcMessage::response(load.id, Ok(serde_json::json!({}))),
))))
.await,
- Stepped::Stopped
- );
+ Stepped::Stopped(_)
+ ));
} else {
- assert_eq!(
- step,
- Stepped::Stopped,
+ assert!(
+ matches!(step, Stepped::Stopped(_)),
"initialization failure stops before load"
);
}
@@ -1559,3 +1604,62 @@ async fn assert_restore_persistence_failure_does_not_send_prompt(failure: Restor
}
mod owner_binding;
+
+/// The live writer's fold says what each appended frame meant for the turn;
+/// history it catches up on says nothing.
+mod fold_signals {
+ use super::*;
+ use crate::domain::ports::AgentSessionLogWriter as _;
+ use agent_fold::domain::model::{StopReason as FoldStop, TurnSignal};
+ use agent_fold::testing::parse_log_as;
+ use agent_runtime_protocol::domain::schema::v0::SystemEvent;
+
+ #[tokio::test]
+ async fn appending_a_turn_signals_its_end_once_with_its_last_text() {
+ let repo = InMemoryAgentSessionRepo::new();
+ let session = test_session();
+ repo.insert_session(test_agent_session(session));
+ let mut logs = LiveSessionLogWriter::new(repo.clone(), NoOpRealtime);
+
+ let mut signals = Vec::new();
+ for frame in parse_log_as(session, TURN) {
+ signals.extend(logs.append(frame).await.expect("append succeeds").signals);
+ }
+
+ assert!(
+ matches!(
+ signals.as_slice(),
+ [TurnSignal::TurnEnded { stop: FoldStop::EndTurn, last_text: Some(text), .. }]
+ if !text.is_empty()
+ ),
+ "{signals:#?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_writer_catching_up_on_a_stored_turn_signals_nothing_for_it() {
+ let repo = InMemoryAgentSessionRepo::new();
+ let session = test_session();
+ repo.insert_session(test_agent_session(session));
+ let mut first = LiveSessionLogWriter::new(repo.clone(), NoOpRealtime);
+ for frame in parse_log_as(session, TURN) {
+ first.append(frame).await.expect("append succeeds");
+ }
+
+ // A reconnect: a fresh writer over the same stored log. Its first
+ // frame is the runtime coming back, not a turn ending.
+ let mut second = LiveSessionLogWriter::new(repo.clone(), NoOpRealtime);
+ let appended = second
+ .append(AgentSessionLog {
+ agent_session_id: session,
+ user_id: None,
+ content: Message::ToServer(ToServerMessage::Event {
+ event: SystemEvent::AcpReady,
+ }),
+ })
+ .await
+ .expect("append succeeds");
+
+ assert!(appended.signals.is_empty(), "{:#?}", appended.signals);
+ }
+}
diff --git a/crates/agent_session/src/domain/session/actors.rs b/crates/agent_session/src/domain/session/actors.rs
index a9ebb3238a..ee43461719 100644
--- a/crates/agent_session/src/domain/session/actors.rs
+++ b/crates/agent_session/src/domain/session/actors.rs
@@ -32,8 +32,11 @@ use agent_runtime_protocol::domain::ports::{TransportReceiver, TransportSender};
use crate::domain::ports::{
AgentConnector, AgentSessionLogWriter, AgentSessionRepo, SessionTurnObserver,
};
+use agent_fold::domain::model::TurnSignal;
-use super::{CloseReason, Effect, HandshakeStatus, Input, RuntimeStatus, SessionMachine};
+use super::{
+ CloseReason, Effect, HandshakeStatus, Input, RuntimeStatus, SessionMachine, StopReason,
+};
/// How long the ACP handshake has to finish before the session is declared dead.
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(60);
@@ -56,12 +59,12 @@ pub(crate) struct SessionCompletion {
}
/// Whether a [`SessionActor`] has more steps to take.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Stepped {
/// Keep stepping.
Continue,
- /// The machine stopped; clean up.
- Stopped,
+ /// The machine stopped for this reason; clean up.
+ Stopped(StopReason),
}
/// One session connection's imperative shell: pulls one input, runs the
@@ -339,15 +342,18 @@ where
),
},
};
- if let Err(error) = result {
- tracing::error!(
- error = ?error,
- id = %self.machine.id(),
- "agent session failed to persist an inbound message"
- );
- self.fail_remaining_completions(&mut effects, error);
- effects.extend(self.machine.handle(Input::Closed(close_reason)));
- self.finish_handshake_if_complete();
+ match result {
+ Ok(appended) => self.forward_signals(appended.signals),
+ Err(error) => {
+ tracing::error!(
+ error = ?error,
+ id = %self.machine.id(),
+ "agent session failed to persist an inbound message"
+ );
+ self.fail_remaining_completions(&mut effects, error);
+ effects.extend(self.machine.handle(Input::Closed(close_reason)));
+ self.finish_handshake_if_complete();
+ }
}
}
Effect::EstablishInitialization { context } => {
@@ -359,7 +365,8 @@ where
user_id: None,
content: Message::ToRuntime(context.request.clone()),
})
- .await?;
+ .await?
+ .log_id;
self.machine.initialization_persisted(id);
self.log(None, Message::ToServer(context.response.clone()))
.await
@@ -407,24 +414,6 @@ where
}),
});
}
- Effect::TurnEnded { action_id } => {
- // The counterpart to `agent.session.disconnect`: a turn
- // that ended here reached its stop reason, so a session
- // whose last turn has this span and no disconnect after
- // it finished cleanly. One per turn.
- let _ended = tracing::info_span!(
- "agent.session.turn_ended",
- agent.session.id = %self.machine.id(),
- agent.action.id = %action_id,
- )
- .entered();
- tracing::info!(
- id = %self.machine.id(),
- %action_id,
- "agent session turn ended"
- );
- self.turn_observer.turn_ended(self.machine.id());
- }
Effect::Complete { token, result } => {
if let Err(error) = &result {
token.span.record("otel.status_code", "ERROR");
@@ -478,7 +467,7 @@ where
}
}
tracing::info!(id = %self.machine.id(), %reason, "agent session stopped");
- stepped = Stepped::Stopped;
+ stepped = Stepped::Stopped(reason);
}
}
}
@@ -507,7 +496,7 @@ where
tracing::Span::current().record("rpc.system.name", "jsonrpc");
tracing::Span::current().record("rpc.method", method);
}
- let id = self
+ let appended = self
.logs
.append(AgentSessionLog {
agent_session_id: self.machine.id(),
@@ -516,10 +505,13 @@ where
})
.await?;
if acp_method(&message) == Some("initialize") {
- self.machine.initialization_persisted(id);
+ self.machine.initialization_persisted(appended.log_id);
self.initialization_request = Some(message.clone());
}
self.outbound.send(message).await?;
+ // After the send, so a signal never describes a frame the runtime has
+ // not seen: an answer to a question clears it once it is on the wire.
+ self.forward_signals(appended.signals);
Ok(())
}
@@ -528,14 +520,59 @@ where
user_id: Option<MacroUserIdStr<'static>>,
content: Message,
) -> Result<()> {
- self.logs
+ let appended = self
+ .logs
.append(AgentSessionLog {
agent_session_id: self.machine.id(),
user_id,
content,
})
- .await
- .map(|_| ())
+ .await?;
+ self.forward_signals(appended.signals);
+ Ok(())
+ }
+
+ /// Hand the fold's turn signals to the observer, one span per turn end.
+ ///
+ /// The counterpart to `agent.session.disconnect`: a turn that ended here
+ /// reached its stop reason, so a session whose last turn has this span
+ /// and no disconnect after it finished cleanly.
+ fn forward_signals(&self, signals: Vec<TurnSignal>) {
+ for signal in signals {
+ match &signal {
+ TurnSignal::TurnEnded {
+ turn,
+ action_id,
+ stop,
+ ..
+ } => {
+ let _ended = tracing::info_span!(
+ "agent.session.turn_ended",
+ agent.session.id = %self.machine.id(),
+ agent.turn.id = turn.0,
+ agent.action.id = action_id.map(tracing::field::display),
+ agent.turn.stop_reason = ?stop,
+ )
+ .entered();
+ tracing::info!(id = %self.machine.id(), "agent session turn ended");
+ }
+ TurnSignal::ElicitationRaised { request_id, .. } => {
+ tracing::info!(
+ id = %self.machine.id(),
+ ?request_id,
+ "agent session is waiting for input"
+ );
+ }
+ TurnSignal::ElicitationCleared { request_id, .. } => {
+ tracing::info!(
+ id = %self.machine.id(),
+ ?request_id,
+ "agent session elicitation cleared"
+ );
+ }
+ }
+ self.turn_observer.signal(self.machine.id(), signal);
+ }
}
async fn persist_acp_session(&self, acp_session_id: SessionId) -> Result<()> {
@@ -585,8 +622,7 @@ where
| Effect::Log { .. }
| Effect::EstablishInitialization { .. }
| Effect::PersistAcpSession { .. }
- | Effect::Initialized { .. }
- | Effect::TurnEnded { .. } => {}
+ | Effect::Initialized { .. } => {}
}
}
if let Some(stop) = stop {
diff --git a/crates/agent_session/src/domain/session/session.rs b/crates/agent_session/src/domain/session/session.rs
index dba63a6c19..c8391dd5f1 100644
--- a/crates/agent_session/src/domain/session/session.rs
+++ b/crates/agent_session/src/domain/session/session.rs
@@ -345,15 +345,12 @@ impl<Token> SessionMachine<Token> {
if matches!(self.phase, SessionPhase::Live { .. }) {
// The in-flight turn's answer ends the turn whichever shape it
// takes: a result carries the stop reason, an error is the agent
- // refusing the prompt. Either way the agent can take another.
+ // refusing the prompt. The fold reads the frame from the log and
+ // signals the end; the machine only lets go of the turn.
if let Some((request_id, _)) = &self.in_flight_turn
&& frame.response_id() == Some(request_id)
{
- let (_, action_id) = self
- .in_flight_turn
- .take()
- .expect("checked just above; nothing between the check and the take");
- effects.push(Effect::TurnEnded { action_id });
+ self.in_flight_turn = None;
if self.reload_required {
self.begin_reload(effects);
}
diff --git a/crates/agent_session/src/domain/session/tests.rs b/crates/agent_session/src/domain/session/tests.rs
index 9ed18b7f38..edb81e648f 100644
--- a/crates/agent_session/src/domain/session/tests.rs
+++ b/crates/agent_session/src/domain/session/tests.rs
@@ -173,7 +173,8 @@ fn recovery_waits_for_prompt_then_loads_with_a_new_durable_boundary() {
assert!(
effects
.iter()
- .any(|effect| matches!(effect, Effect::TurnEnded { .. }))
+ .any(|effect| matches!(effect, Effect::Log { .. })),
+ "the answer is logged; the fold reads the turn's end from there"
);
}
assert_eq!(sent_methods(&effects), ["initialize"]);
@@ -760,39 +761,41 @@ fn machine_with_turn_in_flight(action_id: AgentActionId) -> SessionMachine<u32>
machine
}
+/// The machine lets go of the turn on the prompt's answer, whatever shape
+/// the answer takes. What the turn *meant* - its stop reason, its last words
+/// - is the fold's to say, from the same logged frame.
#[test]
-fn the_prompts_response_ends_its_turn() {
- let action_id = AgentActionId::mint();
- let mut machine = machine_with_turn_in_flight(action_id);
-
- let effects = machine.handle(turn_answered(action_id.to_request_id()));
-
- assert!(
- matches!(
- effects[..],
- [Effect::Log { .. }, Effect::TurnEnded { action_id: ended }] if ended == action_id
+fn the_prompts_response_releases_the_turn() {
+ for answer in [
+ RawJsonRpcMessage::response(
+ AgentActionId::mint().to_request_id(),
+ Ok(serde_json::json!({"stopReason":"end_turn"})),
),
- "the answer is logged and the turn ends: {effects:?}"
- );
-}
-
-#[test]
-fn a_refused_prompt_ends_its_turn_too() {
- let action_id = AgentActionId::mint();
- let mut machine = machine_with_turn_in_flight(action_id);
+ RawJsonRpcMessage::response(
+ AgentActionId::mint().to_request_id(),
+ Err(agent_client_protocol::Error::internal_error()),
+ ),
+ RawJsonRpcMessage::response(
+ AgentActionId::mint().to_request_id(),
+ Ok(serde_json::json!({})),
+ ),
+ ] {
+ let action_id =
+ AgentActionId::from_request_id(answer.response_id().expect("a response has an id"))
+ .expect("the test minted a uuid id");
+ let mut machine = machine_with_turn_in_flight(action_id);
- let effects = machine.handle(frame(RawJsonRpcMessage::response(
- action_id.to_request_id(),
- Err(agent_client_protocol::Error::internal_error()),
- )));
+ let effects = machine.handle(frame(answer));
- assert!(
- matches!(
- effects[..],
- [Effect::Log { .. }, Effect::TurnEnded { action_id: ended }] if ended == action_id
- ),
- "a refusal ends the turn the same way: {effects:?}"
- );
+ assert!(
+ matches!(effects[..], [Effect::Log { .. }]),
+ "the answer is logged and nothing else happens here: {effects:?}"
+ );
+ // Released: the next prompt goes straight out rather than queueing
+ // behind a turn the machine still thinks is running.
+ let effects = machine.handle(command("next", 9));
+ assert_eq!(sent_methods(&effects), ["session/prompt"]);
+ }
}
#[test]
@@ -810,12 +813,11 @@ fn another_requests_response_does_not_end_the_turn() {
"only logged: {effects:?}"
);
- // The turn is still in flight: its own answer still ends it.
+ // The turn is still in flight: its own answer still releases it.
let effects = machine.handle(turn_answered(action_id.to_request_id()));
- assert!(matches!(effects[..], [
- Effect::Log { .. },
- Effect::TurnEnded { action_id: ended }
- ] if ended == action_id));
+ assert!(matches!(effects[..], [Effect::Log { .. }]));
+ let effects = machine.handle(command("next", 9));
+ assert_eq!(sent_methods(&effects), ["session/prompt"]);
}
#[test]
@@ -826,12 +828,9 @@ fn a_death_mid_turn_is_not_a_turn_end() {
let effects = machine.handle(Input::Closed(CloseReason::TransportClosed));
assert!(
- !effects
- .iter()
- .any(|effect| matches!(effect, Effect::TurnEnded { .. })),
- "the session stopped; the turn did not end: {effects:?}"
+ matches!(effects[..], [Effect::Stop { .. }]),
+ "the session stopped; nothing else was answered: {effects:?}"
);
- assert!(matches!(effects[..], [Effect::Stop { .. }]));
assert_eq!(machine.status(), RuntimeStatus::Dead);
}
diff --git a/crates/agent_session/src/domain/session/types.rs b/crates/agent_session/src/domain/session/types.rs
index cd089e7675..f1768bfbfa 100644
--- a/crates/agent_session/src/domain/session/types.rs
+++ b/crates/agent_session/src/domain/session/types.rs
@@ -236,13 +236,6 @@ pub enum Effect<Token> {
/// Whether the action reached the transport.
result: Result<()>,
},
- /// The runtime answered the in-flight turn's `session/prompt` - however it
- /// ended, including cancelled and refused. What the harness drains its
- /// queue on: the agent can take another prompt now.
- TurnEnded {
- /// The action whose turn this was.
- action_id: AgentActionId,
- },
/// Tear the connection down. Always the final effect of its batch; the
/// machine is [`RuntimeStatus::Dead`] once it appears.
Stop {
diff --git a/crates/agent_session/src/lib.rs b/crates/agent_session/src/lib.rs
index 3ebd6d8256..4e9245f2b7 100644
--- a/crates/agent_session/src/lib.rs
+++ b/crates/agent_session/src/lib.rs
@@ -1,7 +1,9 @@
use agent_client_protocol::schema::ProtocolVersion;
pub mod domain;
+#[cfg(feature = "inbound")]
pub mod inbound;
+#[cfg(feature = "outbound")]
pub mod outbound;
/// The ACP version spoken by agent sessions.
diff --git a/crates/agent_session/src/outbound/broker_lifecycle_publisher.rs b/crates/agent_session/src/outbound/broker_lifecycle_publisher.rs
new file mode 100644
index 0000000000..2a27f28c4b
--- /dev/null
+++ b/crates/agent_session/src/outbound/broker_lifecycle_publisher.rs
@@ -0,0 +1,65 @@
+//! [`AgentSessionLifecyclePublisher`] over the Macro event broker.
+
+#[cfg(test)]
+mod test;
+
+use std::pin::Pin;
+
+use crate::domain::events::{AgentSessionLifecycleEvent, AgentSessionLifecycleMacroEvent};
+use macro_event_broker::MacroEventBroker;
+
+use crate::domain::ports::AgentSessionLifecyclePublisher;
+
+/// Publishes each fact to `macro.agent_session_lifecycle`, keyed by session
+/// id, and waits for the broker to accept it.
+///
+/// Waiting - rather than fire-and-forget - is what lets the caller's span
+/// show a publish that failed. The result is still only logged: nothing about
+/// the session went wrong.
+#[derive(Debug, Clone)]
+pub struct BrokerLifecyclePublisher<Broker> {
+ broker: Broker,
+}
+
+impl<Broker> BrokerLifecyclePublisher<Broker> {
+ /// Publish through `broker`.
+ pub fn new(broker: Broker) -> Self {
+ Self { broker }
+ }
+}
+
+impl<Broker> AgentSessionLifecyclePublisher for BrokerLifecyclePublisher<Broker>
+where
+ Broker: MacroEventBroker,
+{
+ fn publish(
+ &self,
+ event: AgentSessionLifecycleEvent,
+ ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
+ Box::pin(async move {
+ let event_type = event.name();
+ let session_id = event.session_id();
+ let macro_event = AgentSessionLifecycleMacroEvent::new(event);
+ let published = match self.broker.send_event(&macro_event) {
+ Ok(handle) => match handle.await {
+ Ok(result) => result.map_err(|error| error.to_string()),
+ Err(join_error) => Err(join_error.to_string()),
+ },
+ Err(error) => Err(error.to_string()),
+ };
+ match published {
+ Ok(()) => tracing::debug!(
+ %session_id,
+ macro.event.type = event_type,
+ "published agent session lifecycle event"
+ ),
+ Err(error) => tracing::warn!(
+ %error,
+ %session_id,
+ macro.event.type = event_type,
+ "failed to publish agent session lifecycle event"
+ ),
+ }
+ })
+ }
+}
diff --git a/crates/agent_session/src/outbound/broker_lifecycle_publisher/test.rs b/crates/agent_session/src/outbound/broker_lifecycle_publisher/test.rs
new file mode 100644
index 0000000000..79a0518b9d
--- /dev/null
+++ b/crates/agent_session/src/outbound/broker_lifecycle_publisher/test.rs
@@ -0,0 +1,103 @@
+use std::sync::{Arc, Mutex};
+
+use crate::domain::events::{AgentSessionLifecycleEvent, SessionDeletedMetadata, SessionIdentity};
+use bots::domain::models::BotId;
+use macro_event_broker::{EventBrokerError, MacroEvent, MacroEventBroker};
+use macro_user_id::cowlike::CowLike as _;
+use macro_user_id::user_id::MacroUserIdStr;
+
+use super::BrokerLifecyclePublisher;
+use crate::domain::model::AgentSessionId;
+use crate::domain::ports::AgentSessionLifecyclePublisher as _;
+
+#[derive(Debug, Clone)]
+struct Published {
+ topic: String,
+ key: String,
+ envelope: serde_json::Value,
+}
+
+/// Records what was handed to the broker, or refuses everything.
+#[derive(Clone, Default)]
+struct FakeBroker {
+ published: Arc<Mutex<Vec<Published>>>,
+ refuses: bool,
+}
+
+impl MacroEventBroker for FakeBroker {
+ fn send_event<E: MacroEvent + ?Sized>(
+ &self,
+ event: &E,
+ ) -> Result<tokio::task::JoinHandle<Result<(), EventBrokerError>>, EventBrokerError> {
+ self.published
+ .lock()
+ .expect("fake broker is not poisoned")
+ .push(Published {
+ topic: event.topic().to_string(),
+ key: event.key().to_string(),
+ envelope: serde_json::to_value(event.event())?,
+ });
+ let refuses = self.refuses;
+ Ok(tokio::spawn(async move {
+ if refuses {
+ Err(EventBrokerError::UnknownTopic("refused".to_owned()))
+ } else {
+ Ok(())
+ }
+ }))
+ }
+}
+
+fn deleted() -> AgentSessionLifecycleEvent {
+ AgentSessionLifecycleEvent::Deleted(SessionDeletedMetadata {
+ identity: SessionIdentity {
+ session_id: AgentSessionId::TEST_A,
+ session_name: "Agent Session".to_owned(),
+ bot_id: BotId::TEST_A,
+ bot_name: "Test Agent".to_owned(),
+ owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .expect("valid user id")
+ .into_owned(),
+ origin: None,
+ },
+ })
+}
+
+#[tokio::test]
+async fn publishes_on_the_lifecycle_topic_keyed_by_session_id() {
+ let broker = FakeBroker::default();
+ let publisher = BrokerLifecyclePublisher::new(broker.clone());
+
+ publisher.publish(deleted()).await;
+
+ let published = broker
+ .published
+ .lock()
+ .expect("fake broker is not poisoned");
+ assert_eq!(published.len(), 1);
+ assert_eq!(published[0].topic, "macro.agent_session_lifecycle");
+ assert_eq!(published[0].key, AgentSessionId::TEST_A.to_string());
+ assert_eq!(published[0].envelope["event_type"], "agent_session.deleted");
+ assert_eq!(published[0].envelope["schema_version"], 1);
+}
+
+#[tokio::test]
+async fn a_refused_publish_is_swallowed() {
+ let broker = FakeBroker {
+ refuses: true,
+ ..FakeBroker::default()
+ };
+ let publisher = BrokerLifecyclePublisher::new(broker.clone());
+
+ // Best effort by contract: the caller never learns, and never fails.
+ publisher.publish(deleted()).await;
+
+ assert_eq!(
+ broker
+ .published
+ .lock()
+ .expect("fake broker is not poisoned")
+ .len(),
+ 1
+ );
+}
diff --git a/crates/agent_session/src/outbound/mod.rs b/crates/agent_session/src/outbound/mod.rs
index 6fa4463a98..6c30b8dc66 100644
--- a/crates/agent_session/src/outbound/mod.rs
+++ b/crates/agent_session/src/outbound/mod.rs
@@ -7,3 +7,6 @@ pub mod name_generator;
/// Streaming a live session's log to a channel's viewers.
pub mod connection_gateway_realtime;
+
+/// Publishing lifecycle facts to the event broker.
+pub mod broker_lifecycle_publisher;
diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rs
index 4f3cc7892e..0f39dadd3c 100644
--- a/crates/agent_session/src/testing.rs
+++ b/crates/agent_session/src/testing.rs
@@ -5,6 +5,7 @@
//! [`AgentSessionLogRepo`] contract without a database.
use crate::domain::error::{AgentSessionError, Result};
+use crate::domain::events::AgentSessionLifecycleEvent;
use crate::domain::model::{
AgentMcpServers, AgentSession, AgentSessionId, AgentSessionLog, ChannelSession, ClaimOutcome,
CreateAgentSessionParams, DEFAULT_AGENT_SESSION_NAME, LogAppended, ManagerFence,
@@ -12,8 +13,8 @@ use crate::domain::model::{
SessionStatus, StoredAgentSessionLog,
};
use crate::domain::ports::{
- AgentSessionLogRepo, AgentSessionRealtime, AgentSessionRepo, REPLICA_STALE_AFTER,
- SessionOwnership,
+ AgentSessionLifecyclePublisher, AgentSessionLogRepo, AgentSessionRealtime, AgentSessionRepo,
+ REPLICA_STALE_AFTER, SessionOwnership,
};
use agent_client_protocol::schema::v1::SessionId;
use agent_runtime_protocol::domain::schema::v0::ToServerMessage;
@@ -665,3 +666,64 @@ impl AgentSessionRealtime for RecordingRealtime {
#[cfg(test)]
mod test;
+
+/// An [`AgentSessionLifecyclePublisher`] that keeps every event, for
+/// asserting what a flow published and in what order.
+///
+/// Cheap to clone - clones share one store. `wait_for_published` is a real
+/// wait on a `watch`: a publish that lands before the waiter subscribes is
+/// counted, and nothing polls.
+#[derive(Debug, Clone)]
+pub struct RecordingLifecyclePublisher {
+ published: Arc<Mutex<Vec<AgentSessionLifecycleEvent>>>,
+ count: tokio::sync::watch::Sender<usize>,
+}
+
+impl Default for RecordingLifecyclePublisher {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl RecordingLifecyclePublisher {
+ /// A publisher that records everything.
+ #[must_use]
+ pub fn new() -> Self {
+ Self {
+ published: Arc::default(),
+ count: tokio::sync::watch::Sender::new(0),
+ }
+ }
+
+ /// Everything published, in order.
+ #[must_use]
+ pub fn published(&self) -> Vec<AgentSessionLifecycleEvent> {
+ self.published
+ .lock()
+ .expect("in-memory lifecycle store is not poisoned")
+ .clone()
+ }
+
+ /// Resolve once at least `count` events have been published.
+ pub async fn wait_for_published(&self, count: usize) {
+ let mut receiver = self.count.subscribe();
+ receiver
+ .wait_for(|published| *published >= count)
+ .await
+ .expect("the recording publisher holds the sender");
+ }
+}
+
+impl AgentSessionLifecyclePublisher for RecordingLifecyclePublisher {
+ fn publish(
+ &self,
+ event: AgentSessionLifecycleEvent,
+ ) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send + '_>> {
+ self.published
+ .lock()
+ .expect("in-memory lifecycle store is not poisoned")
+ .push(event);
+ self.count.send_modify(|published| *published += 1);
+ Box::pin(async {})
+ }
+}
diff --git a/crates/agent_trigger/Cargo.toml b/crates/agent_trigger/Cargo.toml
index 9b2d4ac333..0fa83fd55f 100644
--- a/crates/agent_trigger/Cargo.toml
+++ b/crates/agent_trigger/Cargo.toml
@@ -13,7 +13,7 @@ outbound = ["dep:agent", "dep:ai_usage", "dep:lexical_client"]
[dependencies]
agent = { path = "../agent", optional = true }
-agent_session = { path = "../agent_session" }
+agent_session = { path = "../agent_session", default-features = false }
ai_usage = { path = "../ai_usage", optional = true }
anyhow = { workspace = true }
bot_id = { path = "../bot_id" }
diff --git a/crates/entity_access/src/domain/service.rs b/crates/entity_access/src/domain/service.rs
index 802bfa737e..8628f898f4 100644
--- a/crates/entity_access/src/domain/service.rs
+++ b/crates/entity_access/src/domain/service.rs
@@ -591,10 +591,14 @@ where
entity_type: EntityType,
) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {
match entity_type {
+ // Agent sessions grant their owner directly and their originating
+ // channel as a channel source, both of which the generic accessor
+ // query expands.
EntityType::Document
| EntityType::Chat
| EntityType::Project
- | EntityType::EmailThread => {
+ | EntityType::EmailThread
+ | EntityType::AgentSession => {
let entity_id = Uuid::parse_str(entity_id).map_err(|_| {
AccessError::BadRequest("invalid entity_id for get_users_by_entity")
})?;
diff --git a/crates/entity_access/src/domain/service/test.rs b/crates/entity_access/src/domain/service/test.rs
index c1a3be3ac0..28a2c4963d 100644
--- a/crates/entity_access/src/domain/service/test.rs
+++ b/crates/entity_access/src/domain/service/test.rs
@@ -46,6 +46,7 @@ struct MockRepo {
chat_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
project_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
thread_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
+ agent_session_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
channel_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
call_channel: Arc<Mutex<Option<CallChannelInfo>>>,
user_team: Arc<Mutex<Option<UserTeamInfo>>>,
@@ -81,6 +82,7 @@ impl MockRepo {
chat_users: Arc::new(Mutex::new(vec![])),
project_users: Arc::new(Mutex::new(vec![])),
thread_users: Arc::new(Mutex::new(vec![])),
+ agent_session_users: Arc::new(Mutex::new(Vec::new())),
channel_users: Arc::new(Mutex::new(vec![])),
call_channel: Arc::new(Mutex::new(None)),
user_team: Arc::new(Mutex::new(None)),
@@ -205,6 +207,11 @@ impl MockRepo {
self
}
+ fn with_agent_session_users(mut self, users: Vec<MacroUserIdStr<'static>>) -> Self {
+ self.agent_session_users = Arc::new(Mutex::new(users));
+ self
+ }
+
fn with_user_team(mut self, user_team: UserTeamInfo) -> Self {
self.user_team = Arc::new(Mutex::new(Some(user_team)));
self
@@ -405,6 +412,7 @@ impl AccessRepository for MockRepo {
EntityType::Chat => Ok(self.chat_users.lock().await.clone()),
EntityType::Project => Ok(self.project_users.lock().await.clone()),
EntityType::EmailThread => Ok(self.thread_users.lock().await.clone()),
+ EntityType::AgentSession => Ok(self.agent_session_users.lock().await.clone()),
_ => Err(AccessError::BadRequest("unsupported entity type")),
}
}
@@ -1926,6 +1934,28 @@ async fn test_get_users_by_entity_document_returns_users() {
assert_eq!(result[1].to_string(), "macro|[email protected]");
}
+/// Sessions grant their owner and their originating channel, both of which
+/// the generic accessor expansion reads, so they fan out like documents do.
+#[tokio::test]
+async fn test_get_users_by_entity_agent_session_returns_users() {
+ let users = vec![
+ user_id("macro|[email protected]"),
+ user_id("macro|[email protected]"),
+ ];
+ let repo = MockRepo::new().with_agent_session_users(users.clone());
+ let service = EntityAccessServiceImpl::new(repo);
+
+ let result = service
+ .get_users_by_entity(
+ "00000000-0000-0000-0000-00000000000a",
+ EntityType::AgentSession,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(result, users);
+}
+
#[tokio::test]
async fn test_get_users_by_entity_document_returns_empty_when_no_users() {
let repo = MockRepo::new();
diff --git a/crates/macro_event_topics/src/lib.rs b/crates/macro_event_topics/src/lib.rs
index 3f1ceca7c5..2935f76a94 100644
--- a/crates/macro_event_topics/src/lib.rs
+++ b/crates/macro_event_topics/src/lib.rs
@@ -77,4 +77,6 @@ topics! {
MacroChatsTopic => "macro.chats",
/// Calendar event changes, from provider sync and user mutations alike.
MacroCalendarTopic => "macro.calendar",
+ /// Agent session lifecycle facts: opened, turns, waiting for input, settled, stopped, renamed, deleted.
+ MacroAgentSessionLifecycleTopic => "macro.agent_session_lifecycle",
}
diff --git a/crates/macro_event_topics/src/test.rs b/crates/macro_event_topics/src/test.rs
index 6cd8ba73d2..6010067560 100644
--- a/crates/macro_event_topics/src/test.rs
+++ b/crates/macro_event_topics/src/test.rs
@@ -31,4 +31,5 @@ fn all_topic_names_includes_declared_topics() {
assert!(all_topic_names().contains(&MacroNotificationsTopic::TOPIC_STR));
assert!(all_topic_names().contains(&MacroChatsTopic::TOPIC_STR));
assert!(all_topic_names().contains(&MacroAgentSessionsTopic::TOPIC_STR));
+ assert!(all_topic_names().contains(&MacroAgentSessionLifecycleTopic::TOPIC_STR));
}
diff --git a/crates/webhook/Cargo.toml b/crates/webhook/Cargo.toml
index ea197d345d..1fdef20ec9 100644
--- a/crates/webhook/Cargo.toml
+++ b/crates/webhook/Cargo.toml
@@ -25,12 +25,14 @@ inbound = [
"dep:rate_limit",
"dep:serde_json",
"dep:utoipa",
+ "agent_session/schema",
"channels/schema",
"documents/schema",
"ports",
"rate_limit/axum",
]
ingestion = [
+ "dep:agent_session",
"dep:agent_trigger",
"dep:channels",
"dep:documents",
@@ -65,6 +67,7 @@ worker = ["dep:tokio", "ports"]
anyhow = { workspace = true }
axum = { workspace = true, optional = true }
axum-extra = { workspace = true, optional = true }
+agent_session = { path = "../agent_session", default-features = false, optional = true }
agent_trigger = { path = "../agent_trigger", optional = true }
channels = { path = "../channels", default-features = false, optional = true }
chrono = { workspace = true }
@@ -103,7 +106,11 @@ uuid = { workspace = true, optional = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
-agent_session = { path = "../agent_session", features = ["test-utils"] }
+agent_fold = { path = "../agent_fold" }
+agent_runtime_protocol = { path = "../agent_runtime_protocol", default-features = false }
+agent_session = { path = "../agent_session", default-features = false, features = [
+ "test-utils",
+] }
bot_id = { path = "../bot_id", features = ["test-utils"] }
channel_sender = { path = "../channel_sender" }
macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/crates/webhook/README.md b/crates/webhook/README.md
index da209badde..c76c9fc402 100644
--- a/crates/webhook/README.md
+++ b/crates/webhook/README.md
@@ -76,7 +76,8 @@ bookkeeping (including success/failure timestamp updates) do not produce them.
## Event ingestion and matching
The `webhook-event-ingestion` Kafka consumer reads `macro.documents`,
-`macro.channels`, and `macro.webhooks`. It supports these event names:
+`macro.channels`, `macro.webhooks`, `macro.agent_sessions`, and
+`macro.agent_session_lifecycle`. It supports these event names:
- Documents: `document.created`, `document.updated`, `document.deleted`, and
`document.copied`.
@@ -87,6 +88,12 @@ The `webhook-event-ingestion` Kafka consumer reads `macro.documents`,
`channel.participant_removed`, and `channel.mentioned`.
- Webhooks: `webhook.created`, `webhook.updated`, `webhook.deleted`, and
`webhook.validated`.
+- Agent triggers: `agent_trigger.new` and `agent_trigger.existing`.
+- Agent sessions: `agent_session.opened`, `agent_session.turn_started`,
+ `agent_session.turn_ended`, `agent_session.settled`,
+ `agent_session.waiting_for_input`, `agent_session.input_received`,
+ `agent_session.stopped`, `agent_session.renamed`, and
+ `agent_session.deleted`.
For document and channel events, ingestion asks `EntityAccessService` for the
people who currently have access to the entity. The matching workspace set
@@ -103,6 +110,18 @@ containing the message, and the mentioned entity travels in the payload's
`mentioned` field for consumers to filter on (e.g. the SDK's
`events.onSelfMention`).
+Agent trigger events use `entity_type = "bot"`: a filter's `ids` selects one
+bot's whole trigger stream. Access is gated by the channel the mention sits in
+for `agent_trigger.new`, and by the session for `agent_trigger.existing`.
+
+Agent session lifecycle events use `entity_type = "agent_session"` with the
+session as entity and ordering key, so `ids` selects one session and events of
+one session arrive in order. Access is gated by the session's own grants: its
+owner, plus the members of the channel it was opened from. Subscribers who want
+every session's facts filter by event name alone. `agent_session.settled` is
+emitted when a turn ends with nothing queued behind it; a session that dies
+mid-turn emits `agent_session.stopped` with the interrupted turn instead.
+
Webhook events use `entity_type = "webhook"` and take the event metadata's
`workspace_id` as the sole matching workspace. This is a strict owner-workspace
rule: ingestion does not perform an entity-access lookup or personal/team
diff --git a/crates/webhook/src/domain/events.rs b/crates/webhook/src/domain/events.rs
index 58f726c7ea..c4ce4a5a4d 100644
--- a/crates/webhook/src/domain/events.rs
+++ b/crates/webhook/src/domain/events.rs
@@ -198,4 +198,7 @@ pub enum WebhookEvent {
Document(documents::domain::events::DocumentTopicEvent),
/// Channel and message events from the `macro.channels` topic.
Channel(channels::domain::broker_events::ChannelTopicEvent),
+ /// Agent session lifecycle events from the `macro.agent_session_lifecycle`
+ /// topic.
+ AgentSession(agent_session::domain::events::AgentSessionLifecycleEvent),
}
diff --git a/crates/webhook/src/domain/ingestion.rs b/crates/webhook/src/domain/ingestion.rs
index b0cce0b670..90797698b7 100644
--- a/crates/webhook/src/domain/ingestion.rs
+++ b/crates/webhook/src/domain/ingestion.rs
@@ -15,6 +15,7 @@ use crate::domain::{
models::{NormalizedWebhookEvent, WebhookEventQueueMessage},
ports::{WebhookEventEnqueuer, WebhookRepo, WebhookWorkspaceResolver},
};
+use agent_session::domain::events::{AgentSessionLifecycleEvent, AgentSessionLifecycleEventName};
use agent_trigger::domain::broker_events::AgentTriggerTopicEvent;
use channels::domain::broker_events::ChannelTopicEvent;
use chrono::Utc;
@@ -32,6 +33,7 @@ use uuid::Uuid;
const DOCUMENT_ENTITY_TYPE: &str = "document";
const CHANNEL_ENTITY_TYPE: &str = "channel";
const WEBHOOK_ENTITY_TYPE: &str = "webhook";
+const AGENT_SESSION_ENTITY_TYPE: &str = "agent_session";
/// Webhook event ingestion error.
#[derive(Debug, thiserror::Error)]
@@ -108,6 +110,12 @@ pub trait WebhookEventIngestionService: Clone + Send + Sync + 'static {
&self,
event: Event<AgentTriggerTopicEvent>,
) -> impl Future<Output = Result<(), WebhookEventIngestionError>> + Send;
+
+ /// Ingest one `macro.agent_session_lifecycle` event envelope.
+ fn ingest_agent_session_lifecycle_event(
+ &self,
+ event: Event<AgentSessionLifecycleEvent>,
+ ) -> impl Future<Output = Result<(), WebhookEventIngestionError>> + Send;
}
/// Webhook event ingestion service implementation.
@@ -446,6 +454,65 @@ pub(crate) fn normalized_agent_trigger_event(
))
}
+/// Normalize one agent-session lifecycle event.
+///
+/// Unlike a trigger, whose entity is the bot, a lifecycle stream is about one
+/// session: the entity and the ordering key are the session, mirroring the
+/// broker's partition key, and the session's own grants - its owner and the
+/// channel it came from - decide who may see it.
+pub(crate) fn normalized_agent_session_lifecycle_event(
+ event: &Event<AgentSessionLifecycleEvent>,
+) -> Result<NormalizedWebhookEvent, WebhookEventIngestionError> {
+ let event_name: &'static str = AgentSessionLifecycleEventName::from(&event.event).into();
+ let broker_envelope = serde_json::to_value(event)?;
+ let session_id = event.event.session_id().to_string();
+ Ok(normalized_event(
+ event.event_id,
+ event.schema_version,
+ event_name,
+ AGENT_SESSION_ENTITY_TYPE,
+ &session_id,
+ broker_envelope,
+ ))
+}
+
+/// Whose access gates one lifecycle event.
+///
+/// A live session carries its own grants. A deleted one does not: its access
+/// rows go with the row, so asking who may see the session answers nobody.
+/// The event itself still knows who the session belonged to, and that is the
+/// audience the last fact about it is delivered to.
+pub(crate) enum LifecycleAudience {
+ /// Everyone with access to the session.
+ Session,
+ /// The session is gone: its owner, plus the channel it was opened from.
+ Departed {
+ owner: MacroUserIdStr<'static>,
+ origin_channel_id: Option<Uuid>,
+ },
+}
+
+pub(crate) fn lifecycle_audience(event: &AgentSessionLifecycleEvent) -> LifecycleAudience {
+ match event {
+ AgentSessionLifecycleEvent::Deleted(deleted) => LifecycleAudience::Departed {
+ owner: deleted.identity.owner_id.clone(),
+ origin_channel_id: deleted
+ .identity
+ .origin
+ .as_ref()
+ .map(|origin| origin.channel_id),
+ },
+ AgentSessionLifecycleEvent::Opened(_)
+ | AgentSessionLifecycleEvent::TurnStarted(_)
+ | AgentSessionLifecycleEvent::TurnEnded(_)
+ | AgentSessionLifecycleEvent::Settled(_)
+ | AgentSessionLifecycleEvent::WaitingForInput(_)
+ | AgentSessionLifecycleEvent::InputReceived(_)
+ | AgentSessionLifecycleEvent::Stopped(_)
+ | AgentSessionLifecycleEvent::Renamed(_) => LifecycleAudience::Session,
+ }
+}
+
impl<A, R, Q> WebhookEventIngestionService for WebhookEventIngestionServiceImpl<A, R, Q>
where
A: EntityAccessService,
@@ -499,4 +566,38 @@ where
.map_err(|error| WebhookEventIngestionError::WorkspaceResolution(error.into()))?;
self.match_and_enqueue(event, workspace_ids).await
}
+
+ #[tracing::instrument(skip(self, event), fields(event_id = %event.event_id), err)]
+ async fn ingest_agent_session_lifecycle_event(
+ &self,
+ event: Event<AgentSessionLifecycleEvent>,
+ ) -> Result<(), WebhookEventIngestionError> {
+ let normalized = normalized_agent_session_lifecycle_event(&event)?;
+ match lifecycle_audience(&event.event) {
+ LifecycleAudience::Session => {
+ self.resolve_entity_access_and_enqueue(normalized, EntityType::AgentSession)
+ .await
+ }
+ LifecycleAudience::Departed {
+ owner,
+ origin_channel_id,
+ } => {
+ let mut accessors = vec![owner];
+ if let Some(channel_id) = origin_channel_id {
+ accessors.extend(
+ self.users_with_access(&channel_id.to_string(), EntityType::Channel)
+ .await?,
+ );
+ }
+ let workspace_ids = self
+ .repository
+ .resolve_workspace_ids(accessors)
+ .await
+ .map_err(|error| {
+ WebhookEventIngestionError::WorkspaceResolution(error.into())
+ })?;
+ self.match_and_enqueue(normalized, workspace_ids).await
+ }
+ }
+ }
}
diff --git a/crates/webhook/src/domain/ingestion/stream.rs b/crates/webhook/src/domain/ingestion/stream.rs
index aaa3e1d1fc..9fe54162e3 100644
--- a/crates/webhook/src/domain/ingestion/stream.rs
+++ b/crates/webhook/src/domain/ingestion/stream.rs
@@ -1,13 +1,15 @@
//! Stream-candidate adapters over shared webhook event normalization.
use super::{
- WebhookEventIngestionError, normalized_agent_trigger_event, normalized_channel_event,
- normalized_document_event, normalized_webhook_event,
+ LifecycleAudience, WebhookEventIngestionError, lifecycle_audience,
+ normalized_agent_session_lifecycle_event, normalized_agent_trigger_event,
+ normalized_channel_event, normalized_document_event, normalized_webhook_event,
};
use crate::domain::{
events::WebhookTopicEvent,
stream::{StreamAudience, StreamCandidateEvent},
};
+use agent_session::domain::events::AgentSessionLifecycleEvent;
use agent_trigger::domain::broker_events::AgentTriggerTopicEvent;
use channels::domain::broker_events::ChannelTopicEvent;
use documents::domain::events::DocumentTopicEvent;
@@ -63,3 +65,38 @@ pub(crate) fn agent_trigger_stream_candidate(
event: normalized,
})
}
+
+pub(crate) fn agent_session_lifecycle_stream_candidate(
+ event: &Event<AgentSessionLifecycleEvent>,
+) -> Result<StreamCandidateEvent, WebhookEventIngestionError> {
+ let normalized = normalized_agent_session_lifecycle_event(event)?;
+ let audience = match lifecycle_audience(&event.event) {
+ LifecycleAudience::Session => StreamAudience::Entity {
+ entity_id: normalized.entity_id.clone(),
+ entity_type: EntityType::AgentSession,
+ },
+ // The session's grants are gone with it; the channel it came from
+ // still knows its audience, and a session without one was its
+ // owner's alone.
+ LifecycleAudience::Departed {
+ owner,
+ origin_channel_id: Some(channel_id),
+ } => {
+ drop(owner);
+ StreamAudience::Entity {
+ entity_id: channel_id.to_string(),
+ entity_type: EntityType::Channel,
+ }
+ }
+ LifecycleAudience::Departed {
+ owner,
+ origin_channel_id: None,
+ } => StreamAudience::Workspace {
+ workspace_id: owner.to_string(),
+ },
+ };
+ Ok(StreamCandidateEvent {
+ audience,
+ event: normalized,
+ })
+}
diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rs
index d16406ca2c..dae593a572 100644
--- a/crates/webhook/src/domain/ingestion/test.rs
+++ b/crates/webhook/src/domain/ingestion/test.rs
@@ -1456,3 +1456,200 @@ async fn agent_trigger_events_are_scoped_by_the_channel_but_named_by_the_bot() {
serde_json::to_value(&event).expect("a serializable envelope"),
);
}
+
+fn agent_session_lifecycle_event(
+ event: fn(
+ agent_session::domain::events::SessionIdentity,
+ ) -> agent_session::domain::events::AgentSessionLifecycleEvent,
+) -> Event<agent_session::domain::events::AgentSessionLifecycleEvent> {
+ use agent_session::domain::events::{SessionIdentity, ThreadOrigin};
+ use macro_user_id::cowlike::CowLike as _;
+
+ Event::new(event(SessionIdentity {
+ session_id: agent_session::domain::model::AgentSessionId::TEST_A,
+ session_name: "Fix the flaky test".to_owned(),
+ bot_id: bot_id::BotId::new_from_uuid(uuid::Uuid::from_u128(0xB07)),
+ bot_name: "Macro Coder".to_owned(),
+ owner_id: macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .expect("valid user id")
+ .into_owned(),
+ origin: Some(ThreadOrigin {
+ channel_id: uuid::Uuid::from_u128(1),
+ thread_id: uuid::Uuid::from_u128(2),
+ originating_message_id: uuid::Uuid::from_u128(3),
+ }),
+ }))
+}
+
+/// A lifecycle fact is about one session: the session is the entity, the
+/// ordering key, and whose grants gate it - not the bot, unlike a trigger.
+#[tokio::test]
+async fn agent_session_lifecycle_events_are_scoped_and_named_by_the_session() {
+ use agent_session::domain::events::{
+ AgentSessionLifecycleEvent, SessionSettledMetadata, TurnSummary,
+ };
+
+ let access = MockAccessService::with_users(vec![user_id(PERSONAL_WORKSPACE_ID)]);
+ let repository = MockRepository::new(
+ vec![PERSONAL_WORKSPACE_ID.to_string()],
+ vec![webhook("wh_agent_feed", PERSONAL_WORKSPACE_ID)],
+ );
+ let enqueuer = MockEnqueuer::default();
+ let service = service(access.clone(), repository.clone(), enqueuer.clone());
+ let event = agent_session_lifecycle_event(|identity| {
+ AgentSessionLifecycleEvent::Settled(SessionSettledMetadata {
+ identity,
+ last_turn: Some(TurnSummary {
+ turn: agent_fold::domain::model::TurnId(0),
+ action_id: agent_runtime_protocol::domain::action::AgentActionId::mint(),
+ actor: None,
+ announcement_message_id: None,
+ stop_reason: "end_turn".to_owned(),
+ excerpt: Some("Done.".to_owned()),
+ }),
+ })
+ });
+ let session_id = agent_session::domain::model::AgentSessionId::TEST_A.to_string();
+
+ service
+ .ingest_agent_session_lifecycle_event(event.clone())
+ .await
+ .expect("lifecycle events are ingested");
+
+ assert_eq!(
+ lock(&access.calls).as_slice(),
+ &[(session_id.clone(), EntityType::AgentSession)],
+ );
+ let repository_state = lock(&repository.state);
+ assert_eq!(repository_state.match_calls.len(), 1);
+ assert_eq!(repository_state.match_calls[0].entity_id, session_id);
+ assert_eq!(
+ repository_state.match_calls[0].event_name,
+ "agent_session.settled"
+ );
+ drop(repository_state);
+
+ let enqueuer_state = lock(&enqueuer.state);
+ assert_eq!(enqueuer_state.attempted_messages.len(), 1);
+ let normalized = &enqueuer_state.attempted_messages[0].event;
+ assert_eq!(normalized.event_name, "agent_session.settled");
+ assert_eq!(normalized.entity_type, "agent_session");
+ assert_eq!(normalized.entity_id, session_id);
+ assert_eq!(normalized.ordering_key, session_id);
+ assert_eq!(
+ normalized.broker_envelope,
+ serde_json::to_value(&event).expect("a serializable envelope"),
+ );
+}
+
+#[tokio::test]
+async fn every_agent_session_lifecycle_variant_is_named_by_its_wire_tag() {
+ use agent_session::domain::events::{
+ AgentSessionLifecycleEvent, SessionDeletedMetadata, WaitingForInputMetadata,
+ };
+
+ let access = MockAccessService::with_users(vec![user_id(PERSONAL_WORKSPACE_ID)]);
+ let repository = MockRepository::new(
+ vec![PERSONAL_WORKSPACE_ID.to_string()],
+ vec![webhook("wh_agent_feed", PERSONAL_WORKSPACE_ID)],
+ );
+ let service = service(access, repository.clone(), MockEnqueuer::default());
+
+ service
+ .ingest_agent_session_lifecycle_event(agent_session_lifecycle_event(|identity| {
+ AgentSessionLifecycleEvent::WaitingForInput(WaitingForInputMetadata {
+ identity,
+ turn: agent_fold::domain::model::TurnId(1),
+ action_id: agent_runtime_protocol::domain::action::AgentActionId::mint(),
+ announcement_message_id: None,
+ question: "Which approach?".to_owned(),
+ })
+ }))
+ .await
+ .expect("lifecycle events are ingested");
+ service
+ .ingest_agent_session_lifecycle_event(agent_session_lifecycle_event(|identity| {
+ AgentSessionLifecycleEvent::Deleted(SessionDeletedMetadata { identity })
+ }))
+ .await
+ .expect("lifecycle events are ingested");
+
+ let names: Vec<String> = lock(&repository.state)
+ .match_calls
+ .iter()
+ .map(|call| call.event_name.clone())
+ .collect();
+ assert_eq!(
+ names,
+ ["agent_session.waiting_for_input", "agent_session.deleted"]
+ );
+}
+
+/// A deleted session has no access rows left to ask, so its audience comes
+/// from the event: the owner, plus the channel it was opened from.
+#[tokio::test]
+async fn a_deleted_session_is_delivered_to_its_owner_and_origin_channel() {
+ use agent_session::domain::events::{AgentSessionLifecycleEvent, SessionDeletedMetadata};
+
+ let access = MockAccessService::with_users(vec![user_id("macro|[email protected]")]);
+ let repository = MockRepository::new(
+ vec![PERSONAL_WORKSPACE_ID.to_string()],
+ vec![webhook("wh_agent_feed", PERSONAL_WORKSPACE_ID)],
+ );
+ let enqueuer = MockEnqueuer::default();
+ let service = service(access.clone(), repository.clone(), enqueuer.clone());
+
+ service
+ .ingest_agent_session_lifecycle_event(agent_session_lifecycle_event(|identity| {
+ AgentSessionLifecycleEvent::Deleted(SessionDeletedMetadata { identity })
+ }))
+ .await
+ .expect("lifecycle events are ingested");
+
+ // The session is never asked about; the origin channel is.
+ assert_eq!(
+ lock(&access.calls).as_slice(),
+ &[(uuid::Uuid::from_u128(1).to_string(), EntityType::Channel)],
+ );
+ let repository_state = lock(&repository.state);
+ assert_eq!(repository_state.match_calls.len(), 1);
+ assert_eq!(
+ repository_state.match_calls[0].event_name,
+ "agent_session.deleted"
+ );
+ assert_eq!(
+ repository_state.workspace_calls.last().map(Vec::len),
+ Some(2),
+ "the owner and the channel's member both resolve to workspaces"
+ );
+}
+
+#[tokio::test]
+async fn a_deleted_session_without_an_origin_is_its_owners_alone() {
+ use agent_session::domain::events::{AgentSessionLifecycleEvent, SessionDeletedMetadata};
+
+ let access = MockAccessService::with_users(vec![user_id("macro|[email protected]")]);
+ let repository = MockRepository::new(
+ vec![PERSONAL_WORKSPACE_ID.to_string()],
+ vec![webhook("wh_agent_feed", PERSONAL_WORKSPACE_ID)],
+ );
+ let service = service(access.clone(), repository.clone(), MockEnqueuer::default());
+
+ let mut event = agent_session_lifecycle_event(|identity| {
+ AgentSessionLifecycleEvent::Deleted(SessionDeletedMetadata { identity })
+ });
+ if let AgentSessionLifecycleEvent::Deleted(deleted) = &mut event.event {
+ deleted.identity.origin = None;
+ }
+
+ service
+ .ingest_agent_session_lifecycle_event(event)
+ .await
+ .expect("lifecycle events are ingested");
+
+ assert!(lock(&access.calls).is_empty(), "nothing is looked up");
+ assert_eq!(
+ lock(&repository.state).workspace_calls.last().map(Vec::len),
+ Some(1)
+ );
+}
diff --git a/crates/webhook/src/inbound/kafka_consumer.rs b/crates/webhook/src/inbound/kafka_consumer.rs
index a7f4cdeca1..8f1c2bad16 100644
--- a/crates/webhook/src/inbound/kafka_consumer.rs
+++ b/crates/webhook/src/inbound/kafka_consumer.rs
@@ -113,6 +113,11 @@ async fn ingest_with_retry<S: WebhookEventIngestionService>(
.ingest_agent_trigger_event(event.event().clone())
.await
}
+ DeclaredMacroEvent::AgentSessionLifecycleMacroEvent(event) => {
+ service
+ .ingest_agent_session_lifecycle_event(event.event().clone())
+ .await
+ }
};
match &result {
diff --git a/crates/webhook/src/inbound/kafka_consumer/test.rs b/crates/webhook/src/inbound/kafka_consumer/test.rs
index 179f3a1b92..fd01d13707 100644
--- a/crates/webhook/src/inbound/kafka_consumer/test.rs
+++ b/crates/webhook/src/inbound/kafka_consumer/test.rs
@@ -68,7 +68,8 @@ fn subscribes_to_all_ingestion_topics() {
"macro.documents",
"macro.channels",
"macro.webhooks",
- "macro.agent_sessions"
+ "macro.agent_sessions",
+ "macro.agent_session_lifecycle"
]
);
}
@@ -190,6 +191,13 @@ impl WebhookEventIngestionService for FlakyIngestionService {
) -> Result<(), WebhookEventIngestionError> {
self.ingest()
}
+
+ async fn ingest_agent_session_lifecycle_event(
+ &self,
+ _event: Event<agent_session::domain::events::AgentSessionLifecycleEvent>,
+ ) -> Result<(), WebhookEventIngestionError> {
+ self.ingest()
+ }
}
fn flaky_service(failures: u32, transient: bool) -> (FlakyIngestionService, Arc<AtomicU32>) {
diff --git a/crates/webhook/src/inbound/kafka_stream_consumer.rs b/crates/webhook/src/inbound/kafka_stream_consumer.rs
index 28d777eecb..086088c038 100644
--- a/crates/webhook/src/inbound/kafka_stream_consumer.rs
+++ b/crates/webhook/src/inbound/kafka_stream_consumer.rs
@@ -3,8 +3,8 @@
use crate::domain::ingestion::{
WebhookEventIngestionError,
stream::{
- agent_trigger_stream_candidate, channel_stream_candidate, document_stream_candidate,
- webhook_stream_candidate,
+ agent_session_lifecycle_stream_candidate, agent_trigger_stream_candidate,
+ channel_stream_candidate, document_stream_candidate, webhook_stream_candidate,
},
};
use crate::domain::stream::StreamCandidateEvent;
@@ -73,5 +73,8 @@ fn candidate_from(
DeclaredMacroEvent::AgentSessionMacroEvent(event) => {
agent_trigger_stream_candidate(event.event()).map(Some)
}
+ DeclaredMacroEvent::AgentSessionLifecycleMacroEvent(event) => {
+ agent_session_lifecycle_stream_candidate(event.event()).map(Some)
+ }
}
}
diff --git a/crates/webhook/src/topics.rs b/crates/webhook/src/topics.rs
index fe53a4c3e3..979495d643 100644
--- a/crates/webhook/src/topics.rs
+++ b/crates/webhook/src/topics.rs
@@ -6,6 +6,7 @@
//! different topic sets.
use crate::domain::events::WebhookMacroEvent;
+use agent_session::domain::events::AgentSessionLifecycleMacroEvent;
use agent_trigger::domain::broker_events::AgentSessionMacroEvent;
use channels::domain::broker_events::ChannelMacroEvent;
use documents::domain::events::DocumentMacroEvent;
@@ -15,4 +16,5 @@ macro_event_broker::declare_topics!(
ChannelMacroEvent,
WebhookMacroEvent,
AgentSessionMacroEvent,
+ AgentSessionLifecycleMacroEvent,
);
diff --git a/docs/AGENT_GUIDE/observability.md b/docs/AGENT_GUIDE/observability.md
index ef8e9d5503..62e47713c3 100644
--- a/docs/AGENT_GUIDE/observability.md
+++ b/docs/AGENT_GUIDE/observability.md
@@ -79,7 +79,7 @@ identifier spaces and must not be confused.
| --- | --- |
| `agent.turn` | Did a Cursor turn run, and how did it end? `agent.turn.stop_reason` / `agent.turn.outcome`, plus `cursor.agent.id` / `cursor.run.id`. |
| `cursor.run.poll` | Is a turn still alive? One per poll, at DEBUG. |
-| `agent.session.turn_ended` | The turn reached a stop reason. |
+| `agent.session.turn_ended` | The connection's live fold closed the turn on a logged frame; carries `agent.turn.id`, `agent.turn.stop_reason`, and `agent.action.id` when a local prompt opened it. |
| `agent.session.disconnect` | The session's actor wrote a `disconnected` event, and `agent.session.close_reason` says why. |
| `agent.session.mark_disconnected` | The session was marked dead by its opener because the runtime never came up. |
| `agent.pipe.reap` | A Cursor pipe was closed for idleness, with `agent.pipe.idle_ms`. |
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index 5e2732d16a..475735a000 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -202,6 +202,22 @@ replay if you disconnect.
Handlers receive the same hydrated payloads as webhook deliveries — ORM
handles for every entity the event names.
+Three families are delivered: `document.*`, `channel.*`, and `agent_session.*`.
+Agent-session events describe a coding agent's life: `opened`, `turn_started`,
+`turn_ended`, `settled` (a turn ended with nothing queued behind it),
+`waiting_for_input` (the agent asked its owner a question), `input_received`,
+`stopped`, `renamed`, and `deleted`. Each carries the session's identity and
+hydrates to an `AgentSession` handle, the owner `User`, and, for a session
+opened from a channel thread, the `Channel`, `Thread`, and magic-chip
+`Message` the turn renders into.
+
+```ts
+macro.events.on('agent_session.settled', async ({ metadata, session, thread }) => {
+ console.log(`${metadata.identity.bot_name} finished: ${metadata.last_turn?.excerpt}`);
+ await thread?.reply(msg`Done — see ${session}`);
+});
+```
+
### Persisted webhooks
To receive the same events as HTTPS POSTs instead of (or in addition to) SSE,
diff --git a/packages/sdk/examples/webhook-events.ts b/packages/sdk/examples/webhook-events.ts
index 1e82b5d089..39fdc2173e 100644
--- a/packages/sdk/examples/webhook-events.ts
+++ b/packages/sdk/examples/webhook-events.ts
@@ -19,6 +19,15 @@ const macro = bot.requestedAs(bot.users.byId(actAs));
// `as const` keeps the literal types so `.on()` infers each event's payload;
// `satisfies` makes a typo in this list a compile error.
const ALL_EVENTS = [
+ 'agent_session.deleted',
+ 'agent_session.input_received',
+ 'agent_session.opened',
+ 'agent_session.renamed',
+ 'agent_session.settled',
+ 'agent_session.stopped',
+ 'agent_session.turn_ended',
+ 'agent_session.turn_started',
+ 'agent_session.waiting_for_input',
'channel.created',
'channel.deleted',
'channel.message_attachment_created',
diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.ts
index 25309b78b9..a3bd83d1a9 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, AgentMcpServer, AgentMcpServers, 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, CalendarEventSourceContent, 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, CrmStageInput, CrmStageResponse, CrmStagesResponse, 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, GetChannelMessagesCatchUpData, GetChannelMessagesCatchUpError, GetChannelMessagesCatchUpErrors, GetChannelMessagesCatchUpResponse, GetChannelMessagesCatchUpResponses, 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, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, NewChannelAttachment, NotificationFilters, NotificationState, 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, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, 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, ReplaceCrmStagesRequest, RequestedHarnessScope, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, 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, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, 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, AgentActionId, AgentChannelScope, AgentMcpServer, AgentMcpServers, AgentSessionLifecycleEvent, 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, CalendarEventSourceContent, 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, CrmStageInput, CrmStageResponse, CrmStagesResponse, 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, GetChannelMessagesCatchUpData, GetChannelMessagesCatchUpError, GetChannelMessagesCatchUpErrors, GetChannelMessagesCatchUpResponse, GetChannelMessagesCatchUpResponses, 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, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InputReceivedMetadata, 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, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, NewChannelAttachment, NotificationFilters, NotificationState, 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, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, 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, ReplaceCrmStagesRequest, RequestedHarnessScope, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, 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, SessionDeletedMetadata, SessionIdentity, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionStoppedMetadata, 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, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, Thread, ThreadOrigin, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, 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, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index e90682fd09..791efb3480 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -121,6 +121,20 @@ export type Agent = {
mcp: AgentMcpServers;
};
+/**
+ * Identifies one accepted [`AgentAction`] end to end: returned by the
+ * control endpoint, written as the JSON-RPC request id on the action's wire
+ * frame, and read back off that frame as `request_id` on the folded message
+ * it derives.
+ *
+ * Minted only by the server at accept time, as a v7 uuid so ids sort by mint
+ * time. On the wire and in JSON it is the bare uuid, and a uuid-shaped
+ * request id is the whole ownership test: the server is the only writer of
+ * runtime-bound frames. The machine's own handshake request ids
+ * (`agent_session:{session}:{n}`) are not uuids and stay `None`.
+ */
+export type AgentActionId = string;
+
/**
* Whether an agent is available everywhere or only in selected channels.
*/
@@ -160,6 +174,70 @@ export type AgentMcpServers = {
servers: Array<AgentMcpServer>;
};
+/**
+ * Events publishable to [`MacroAgentSessionLifecycleTopic`].
+ *
+ * The serde tag and [`AgentSessionLifecycleEventName`] spell the same wire
+ * names: subscribers filter on them, so they are API. The
+ * `event_names_match_the_wire` test holds the two in step. Exhaustive on
+ * purpose: a consumer's match should break when a variant is added.
+ */
+export type AgentSessionLifecycleEvent = {
+ event_type: 'agent_session.opened';
+ /**
+ * A session was created.
+ */
+ metadata: SessionOpenedMetadata;
+} | {
+ event_type: 'agent_session.turn_started';
+ /**
+ * A prompt was delivered to the runtime.
+ */
+ metadata: TurnStartedMetadata;
+} | {
+ event_type: 'agent_session.turn_ended';
+ /**
+ * The runtime answered a turn.
+ */
+ metadata: TurnEndedMetadata;
+} | {
+ event_type: 'agent_session.settled';
+ /**
+ * A turn ended with nothing queued behind it.
+ */
+ metadata: SessionSettledMetadata;
+} | {
+ event_type: 'agent_session.waiting_for_input';
+ /**
+ * The agent is blocked on a question to its owner.
+ */
+ metadata: WaitingForInputMetadata;
+} | {
+ event_type: 'agent_session.input_received';
+ /**
+ * The question was answered or withdrawn.
+ */
+ metadata: InputReceivedMetadata;
+} | {
+ event_type: 'agent_session.stopped';
+ /**
+ * The session's live actor is gone.
+ */
+ metadata: SessionStoppedMetadata;
+} | {
+ event_type: 'agent_session.renamed';
+ /**
+ * The session was renamed.
+ */
+ metadata: SessionRenamedMetadata;
+} | {
+ event_type: 'agent_session.deleted';
+ /**
+ * The session was deleted.
+ */
+ metadata: SessionDeletedMetadata;
+};
+
export type Anchor = PdfAnchor;
export type AnchorId = PdfAnchorId & {
@@ -6145,6 +6223,43 @@ export type HashMap = {
export type HighlightType = 1 | 2 | 3;
+/**
+ * A turn the runtime never answered: the session stopped underneath it.
+ */
+export type InFlightTurnSummary = {
+ /**
+ * The action that opened the turn.
+ */
+ action_id: AgentActionId;
+ actor?: null | MacroUserIdStr;
+ /**
+ * The magic-chip message posted for this turn, when one was.
+ */
+ announcement_message_id?: string | null;
+ /**
+ * Position in the session's log.
+ */
+ turn: number;
+};
+
+/**
+ * The pending question was answered or withdrawn.
+ */
+export type InputReceivedMetadata = {
+ /**
+ * The action that opened the turn.
+ */
+ action_id: AgentActionId;
+ /**
+ * The session.
+ */
+ identity: SessionIdentity;
+ /**
+ * The turn that was asking.
+ */
+ turn: number;
+};
+
/**
* Why a document interaction was reported.
*/
@@ -7260,6 +7375,98 @@ export type SaveDocumentResponseData = {
presignedUrl?: string | null;
};
+/**
+ * The session was deleted.
+ */
+export type SessionDeletedMetadata = {
+ /**
+ * The session as it was.
+ */
+ identity: SessionIdentity;
+};
+
+/**
+ * Who and what a session is; carried by every lifecycle event so a
+ * consumer never has to look the session up.
+ */
+export type SessionIdentity = {
+ /**
+ * Bot the session runs for.
+ */
+ bot_id: BotId;
+ /**
+ * The bot's display name at the time of the event.
+ */
+ bot_name: string;
+ origin?: null | ThreadOrigin;
+ /**
+ * User who owns the session.
+ */
+ owner_id: MacroUserIdStr;
+ /**
+ * The session.
+ */
+ session_id: string;
+ /**
+ * User-facing session name at the time of the event.
+ */
+ session_name: string;
+};
+
+/**
+ * A session was created.
+ */
+export type SessionOpenedMetadata = {
+ /**
+ * Harness slug the session runs on.
+ */
+ harness: string;
+ /**
+ * The session.
+ */
+ identity: SessionIdentity;
+ /**
+ * Model slug the session runs with.
+ */
+ model: string;
+};
+
+/**
+ * The session was renamed; `identity` carries the new name.
+ */
+export type SessionRenamedMetadata = {
+ /**
+ * The session, with its new name.
+ */
+ identity: SessionIdentity;
+};
+
+/**
+ * A turn ended and nothing is queued: the agent has stopped working.
+ */
+export type SessionSettledMetadata = {
+ /**
+ * The session.
+ */
+ identity: SessionIdentity;
+ last_turn?: null | TurnSummary;
+};
+
+/**
+ * The session's live actor is gone: idle teardown, transport loss, or crash.
+ */
+export type SessionStoppedMetadata = {
+ /**
+ * The session.
+ */
+ identity: SessionIdentity;
+ /**
+ * Why it stopped, as the session machine reported it.
+ */
+ reason: string;
+ turn_in_flight?: null | InFlightTurnSummary;
+};
+
/**
* Request body for `PUT /companies/{company_id}/hidden`.
*/
@@ -8708,6 +8915,24 @@ export type Thread = {
updatedAt?: string | null;
};
+/**
+ * The channel thread a session was opened from, when it was.
+ */
+export type ThreadOrigin = {
+ /**
+ * Channel the thread lives in.
+ */
+ channel_id: string;
+ /**
+ * The message whose mention opened the session.
+ */
+ originating_message_id: string;
+ /**
+ * Root message of the thread.
+ */
+ thread_id: string;
+};
+
export type ThreadResponse = {
data: Array<CommentThread>;
};
@@ -8763,6 +8988,89 @@ export type TranscriptSegmentRequest = {
streamStartedAt?: string | null;
};
+/**
+ * The runtime answered a turn. Another prompt may follow at once; see
+ * [`SessionSettledMetadata`] for "nothing left to do".
+ */
+export type TurnEndedMetadata = {
+ /**
+ * The action that opened the turn.
+ */
+ action_id: AgentActionId;
+ actor?: null | MacroUserIdStr;
+ /**
+ * The magic-chip message posted for this turn, when one was.
+ */
+ announcement_message_id?: string | null;
+ /**
+ * The session.
+ */
+ identity: SessionIdentity;
+ /**
+ * Prompts still waiting behind this turn.
+ */
+ queued_remaining: number;
+ /**
+ * The ACP stop reason, or `"error"` when the runtime refused the prompt.
+ */
+ stop_reason: string;
+ /**
+ * Position in the session's log.
+ */
+ turn: number;
+};
+
+/**
+ * A prompt was delivered to the runtime.
+ */
+export type TurnStartedMetadata = {
+ /**
+ * The action that opened the turn.
+ */
+ action_id: AgentActionId;
+ actor?: null | MacroUserIdStr;
+ /**
+ * The magic-chip message posted for this turn, when one was.
+ */
+ announcement_message_id?: string | null;
+ /**
+ * The session.
+ */
+ identity: SessionIdentity;
+ /**
+ * Position in the session's log.
+ */
+ turn: number;
+};
+
+/**
+ * A turn the runtime answered.
+ */
+export type TurnSummary = {
+ /**
+ * The action that opened the turn.
+ */
+ action_id: AgentActionId;
+ actor?: null | MacroUserIdStr;
+ /**
+ * The magic-chip message posted for this turn, when one was.
+ */
+ announcement_message_id?: string | null;
+ /**
+ * The agent's last text in the turn, whole; what the magic chip shows
+ * once the turn ends. `None` when the turn produced no prose.
+ */
+ excerpt?: string | null;
+ /**
+ * The ACP stop reason, or `"error"` when the runtime refused the prompt.
+ */
+ stop_reason: string;
+ /**
+ * Position in the session's log.
+ */
+ turn: number;
+};
+
export type TypedSuccessResponse = {
/**
* Data to be returned
@@ -9112,6 +9420,32 @@ export type ViewsResponse = {
views: Array<View>;
};
+/**
+ * The agent asked its owner a question and is blocked on the answer.
+ */
+export type WaitingForInputMetadata = {
+ /**
+ * The action that opened the turn.
+ */
+ action_id: AgentActionId;
+ /**
+ * The magic-chip message posted for this turn, when one was.
+ */
+ announcement_message_id?: string | null;
+ /**
+ * The session.
+ */
+ identity: SessionIdentity;
+ /**
+ * The question, as the agent phrased it.
+ */
+ question: string;
+ /**
+ * The turn asking.
+ */
+ turn: number;
+};
+
/**
* Webhook row returned by application APIs.
*
@@ -9181,7 +9515,7 @@ export type Webhook = {
* with the event payload. Endpoint validation additionally sends a
* `WebhookValidationTestEvent`, which is not part of this union.
*/
-export type WebhookEvent = DocumentTopicEvent | ChannelTopicEvent;
+export type WebhookEvent = DocumentTopicEvent | ChannelTopicEvent | AgentSessionLifecycleEvent;
/**
* Event and optional entity-id constraints used to match webhook deliveries.
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 40ef448102..357adc5241 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -12923,6 +12923,11 @@
}
}
},
+ "AgentActionId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Identifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives.\n\nMinted only by the server at accept time, as a v7 uuid so ids sort by mint\ntime. On the wire and in JSON it is the bare uuid, and a uuid-shaped\nrequest id is the whole ownership test: the server is the only writer of\nruntime-bound frames. The machine's own handshake request ids\n(`agent_session:{session}:{n}`) are not uuids and stay `None`."
+ },
"AgentChannelScope": {
"type": "string",
"description": "Whether an agent is available everywhere or only in selected channels.",
@@ -12977,6 +12982,146 @@
],
"description": "Which Pipedream MCP servers an agent's sessions are handed.\n\nOne value for the whole choice, so a selection can never travel without\nits scope or a scope without its selection. Serialized with a `scope` tag,\nwhich the generated TypeScript sees as a discriminated union."
},
+ "AgentSessionLifecycleEvent": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "A session was created.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.opened"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/SessionOpenedMetadata",
+ "description": "A session was created."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "A prompt was delivered to the runtime.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.turn_started"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/TurnStartedMetadata",
+ "description": "A prompt was delivered to the runtime."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The runtime answered a turn.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.turn_ended"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/TurnEndedMetadata",
+ "description": "The runtime answered a turn."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "A turn ended with nothing queued behind it.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.settled"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/SessionSettledMetadata",
+ "description": "A turn ended with nothing queued behind it."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The agent is blocked on a question to its owner.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.waiting_for_input"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/WaitingForInputMetadata",
+ "description": "The agent is blocked on a question to its owner."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The question was answered or withdrawn.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.input_received"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/InputReceivedMetadata",
+ "description": "The question was answered or withdrawn."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The session's live actor is gone.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.stopped"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/SessionStoppedMetadata",
+ "description": "The session's live actor is gone."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The session was renamed.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.renamed"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/SessionRenamedMetadata",
+ "description": "The session was renamed."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The session was deleted.",
+ "required": ["metadata", "event_type"],
+ "properties": {
+ "event_type": {
+ "type": "string",
+ "enum": ["agent_session.deleted"]
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/SessionDeletedMetadata",
+ "description": "The session was deleted."
+ }
+ }
+ }
+ ],
+ "description": "Events publishable to [`MacroAgentSessionLifecycleTopic`].\n\nThe serde tag and [`AgentSessionLifecycleEventName`] spell the same wire\nnames: subscribers filter on them, so they are API. The\n`event_names_match_the_wire` test holds the two in step. Exhaustive on\npurpose: a consumer's match should break when a variant is added."
+ },
"Anchor": {
"oneOf": [
{
@@ -22199,6 +22344,60 @@
"type": "integer",
"enum": [1, 2, 3]
},
+ "InFlightTurnSummary": {
+ "type": "object",
+ "description": "A turn the runtime never answered: the session stopped underneath it.",
+ "required": ["turn", "action_id"],
+ "properties": {
+ "action_id": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "The action that opened the turn."
+ },
+ "actor": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "User who prompted it, absent when a bot acted on nobody's behalf."
+ }
+ ]
+ },
+ "announcement_message_id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The magic-chip message posted for this turn, when one was."
+ },
+ "turn": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Position in the session's log.",
+ "minimum": 0
+ }
+ }
+ },
+ "InputReceivedMetadata": {
+ "type": "object",
+ "description": "The pending question was answered or withdrawn.",
+ "required": ["identity", "turn", "action_id"],
+ "properties": {
+ "action_id": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "The action that opened the turn."
+ },
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session."
+ },
+ "turn": {
+ "type": "integer",
+ "format": "int32",
+ "description": "The turn that was asking.",
+ "minimum": 0
+ }
+ }
+ },
"InteractionReason": {
"type": "string",
"description": "Why a document interaction was reported.",
@@ -24291,6 +24490,140 @@
}
}
},
+ "SessionDeletedMetadata": {
+ "type": "object",
+ "description": "The session was deleted.",
+ "required": ["identity"],
+ "properties": {
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session as it was."
+ }
+ }
+ },
+ "SessionIdentity": {
+ "type": "object",
+ "description": "Who and what a session is; carried by every lifecycle event so a\nconsumer never has to look the session up.",
+ "required": [
+ "session_id",
+ "session_name",
+ "bot_id",
+ "bot_name",
+ "owner_id"
+ ],
+ "properties": {
+ "bot_id": {
+ "$ref": "#/components/schemas/BotId",
+ "description": "Bot the session runs for."
+ },
+ "bot_name": {
+ "type": "string",
+ "description": "The bot's display name at the time of the event."
+ },
+ "origin": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ThreadOrigin",
+ "description": "Thread the session was opened from, when it was."
+ }
+ ]
+ },
+ "owner_id": {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "User who owns the session."
+ },
+ "session_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The session."
+ },
+ "session_name": {
+ "type": "string",
+ "description": "User-facing session name at the time of the event."
+ }
+ }
+ },
+ "SessionOpenedMetadata": {
+ "type": "object",
+ "description": "A session was created.",
+ "required": ["identity", "model", "harness"],
+ "properties": {
+ "harness": {
+ "type": "string",
+ "description": "Harness slug the session runs on."
+ },
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session."
+ },
+ "model": {
+ "type": "string",
+ "description": "Model slug the session runs with."
+ }
+ }
+ },
+ "SessionRenamedMetadata": {
+ "type": "object",
+ "description": "The session was renamed; `identity` carries the new name.",
+ "required": ["identity"],
+ "properties": {
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session, with its new name."
+ }
+ }
+ },
+ "SessionSettledMetadata": {
+ "type": "object",
+ "description": "A turn ended and nothing is queued: the agent has stopped working.",
+ "required": ["identity"],
+ "properties": {
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session."
+ },
+ "last_turn": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/TurnSummary",
+ "description": "The turn that just ended, when the emitter still had its record."
+ }
+ ]
+ }
+ }
+ },
+ "SessionStoppedMetadata": {
+ "type": "object",
+ "description": "The session's live actor is gone: idle teardown, transport loss, or crash.",
+ "required": ["identity", "reason"],
+ "properties": {
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session."
+ },
+ "reason": {
+ "type": "string",
+ "description": "Why it stopped, as the session machine reported it."
+ },
+ "turn_in_flight": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/InFlightTurnSummary",
+ "description": "The turn that was running when it stopped, if any."
+ }
+ ]
+ }
+ }
+ },
"SetCompanyHiddenRequest": {
"type": "object",
"description": "Request body for `PUT /companies/{company_id}/hidden`.",
@@ -26470,6 +26803,28 @@
}
}
},
+ "ThreadOrigin": {
+ "type": "object",
+ "description": "The channel thread a session was opened from, when it was.",
+ "required": ["channel_id", "thread_id", "originating_message_id"],
+ "properties": {
+ "channel_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Channel the thread lives in."
+ },
+ "originating_message_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The message whose mention opened the session."
+ },
+ "thread_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Root message of the thread."
+ }
+ }
+ },
"ThreadResponse": {
"type": "object",
"required": ["data"],
@@ -26538,6 +26893,136 @@
}
}
},
+ "TurnEndedMetadata": {
+ "type": "object",
+ "description": "The runtime answered a turn. Another prompt may follow at once; see\n[`SessionSettledMetadata`] for \"nothing left to do\".",
+ "required": [
+ "identity",
+ "turn",
+ "action_id",
+ "stop_reason",
+ "queued_remaining"
+ ],
+ "properties": {
+ "action_id": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "The action that opened the turn."
+ },
+ "actor": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "User who prompted it, absent when a bot acted on nobody's behalf."
+ }
+ ]
+ },
+ "announcement_message_id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The magic-chip message posted for this turn, when one was."
+ },
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session."
+ },
+ "queued_remaining": {
+ "type": "integer",
+ "description": "Prompts still waiting behind this turn.",
+ "minimum": 0
+ },
+ "stop_reason": {
+ "type": "string",
+ "description": "The ACP stop reason, or `\"error\"` when the runtime refused the prompt."
+ },
+ "turn": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Position in the session's log.",
+ "minimum": 0
+ }
+ }
+ },
+ "TurnStartedMetadata": {
+ "type": "object",
+ "description": "A prompt was delivered to the runtime.",
+ "required": ["identity", "turn", "action_id"],
+ "properties": {
+ "action_id": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "The action that opened the turn."
+ },
+ "actor": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "User who prompted it, absent when a bot acted on nobody's behalf."
+ }
+ ]
+ },
+ "announcement_message_id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The magic-chip message posted for this turn, when one was."
+ },
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session."
+ },
+ "turn": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Position in the session's log.",
+ "minimum": 0
+ }
+ }
+ },
+ "TurnSummary": {
+ "type": "object",
+ "description": "A turn the runtime answered.",
+ "required": ["turn", "action_id", "stop_reason"],
+ "properties": {
+ "action_id": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "The action that opened the turn."
+ },
+ "actor": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "User who prompted it, absent when a bot acted on nobody's behalf."
+ }
+ ]
+ },
+ "announcement_message_id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The magic-chip message posted for this turn, when one was."
+ },
+ "excerpt": {
+ "type": ["string", "null"],
+ "description": "The agent's last text in the turn, whole; what the magic chip shows\nonce the turn ends. `None` when the turn produced no prose."
+ },
+ "stop_reason": {
+ "type": "string",
+ "description": "The ACP stop reason, or `\"error\"` when the runtime refused the prompt."
+ },
+ "turn": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Position in the session's log.",
+ "minimum": 0
+ }
+ }
+ },
"TypedSuccessResponse": {
"type": "object",
"required": ["error", "data"],
@@ -27117,6 +27602,36 @@
}
}
},
+ "WaitingForInputMetadata": {
+ "type": "object",
+ "description": "The agent asked its owner a question and is blocked on the answer.",
+ "required": ["identity", "turn", "action_id", "question"],
+ "properties": {
+ "action_id": {
+ "$ref": "#/components/schemas/AgentActionId",
+ "description": "The action that opened the turn."
+ },
+ "announcement_message_id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The magic-chip message posted for this turn, when one was."
+ },
+ "identity": {
+ "$ref": "#/components/schemas/SessionIdentity",
+ "description": "The session."
+ },
+ "question": {
+ "type": "string",
+ "description": "The question, as the agent phrased it."
+ },
+ "turn": {
+ "type": "integer",
+ "format": "int32",
+ "description": "The turn asking.",
+ "minimum": 0
+ }
+ }
+ },
"Webhook": {
"type": "object",
"description": "Webhook row returned by application APIs.\n\nClients deserialize this, so both derives are used.",
@@ -27201,6 +27716,10 @@
{
"$ref": "#/components/schemas/ChannelTopicEvent",
"description": "Channel and message events from the `macro.channels` topic."
+ },
+ {
+ "$ref": "#/components/schemas/AgentSessionLifecycleEvent",
+ "description": "Agent session lifecycle events from the `macro.agent_session_lifecycle`\ntopic."
}
],
"description": "Any entity event deliverable to a webhook endpoint.\n\nSerialized bodies carry an `event_type` tag naming the event (for example\n`document.created` or `channel.message_posted`) and a `metadata` object\nwith the event payload. Endpoint validation additionally sends a\n`WebhookValidationTestEvent`, which is not part of this union."
diff --git a/packages/sdk/src/events/hydrate/agentSession.ts b/packages/sdk/src/events/hydrate/agentSession.ts
new file mode 100644
index 0000000000..210b6921bb
--- /dev/null
+++ b/packages/sdk/src/events/hydrate/agentSession.ts
@@ -0,0 +1,143 @@
+import { match } from 'ts-pattern';
+import type {
+ SessionIdentity,
+ ThreadOrigin,
+} from '../../../generated/storage/types.gen';
+import { AgentSession } from '../../entities/agent-sessions/agent-session';
+import { Channel } from '../../entities/channels/channel';
+import { Message } from '../../entities/channels/message';
+import { Thread } from '../../entities/channels/thread';
+import { User } from '../../entities/users/user';
+import type { MacroClient } from '../../utils/client';
+import type { MacroEvent } from '../types';
+
+export type AgentSessionEvent = Extract<
+ MacroEvent,
+ { event_type: `agent_session.${string}` }
+>;
+
+/** The channel thread a session was opened from, when it was. */
+function originHandles(
+ client: MacroClient,
+ origin: ThreadOrigin | null | undefined,
+) {
+ return origin
+ ? {
+ channel: Channel.byId(client, origin.channel_id),
+ thread: new Thread(client, origin.channel_id, origin.thread_id),
+ }
+ : { channel: undefined, thread: undefined };
+}
+
+/** Handles every lifecycle event carries: the session, its owner, its origin. */
+function sessionHandles(client: MacroClient, identity: SessionIdentity) {
+ return {
+ session: AgentSession.byId(client, identity.session_id),
+ owner: User.byId(client, identity.owner_id),
+ ...originHandles(client, identity.origin),
+ };
+}
+
+/**
+ * The magic-chip message a turn renders into, when one was posted. Lives in
+ * the origin channel, so a session with no origin never has one.
+ */
+function announcementHandle(
+ client: MacroClient,
+ identity: SessionIdentity,
+ announcementMessageId: string | null | undefined,
+) {
+ return identity.origin && announcementMessageId
+ ? Message.byId(client, identity.origin.channel_id, announcementMessageId)
+ : undefined;
+}
+
+function actorHandle(client: MacroClient, actor: string | null | undefined) {
+ return actor ? User.byId(client, actor) : undefined;
+}
+
+/** Attach SDK entity handles to an agent-session lifecycle webhook event. */
+export function hydrateAgentSessionEvent(
+ client: MacroClient,
+ event: AgentSessionEvent,
+) {
+ return match(event)
+ .with({ event_type: 'agent_session.opened' }, ({ metadata }) => ({
+ event_type: 'agent_session.opened' as const,
+ metadata,
+ ...sessionHandles(client, metadata.identity),
+ }))
+ .with({ event_type: 'agent_session.turn_started' }, ({ metadata }) => ({
+ event_type: 'agent_session.turn_started' as const,
+ metadata,
+ ...sessionHandles(client, metadata.identity),
+ actor: actorHandle(client, metadata.actor),
+ announcement: announcementHandle(
+ client,
+ metadata.identity,
+ metadata.announcement_message_id,
+ ),
+ }))
+ .with({ event_type: 'agent_session.turn_ended' }, ({ metadata }) => ({
+ event_type: 'agent_session.turn_ended' as const,
+ metadata,
+ ...sessionHandles(client, metadata.identity),
+ actor: actorHandle(client, metadata.actor),
+ announcement: announcementHandle(
+ client,
+ metadata.identity,
+ metadata.announcement_message_id,
+ ),
+ }))
+ .with({ event_type: 'agent_session.settled' }, ({ metadata }) => ({
+ event_type: 'agent_session.settled' as const,
+ metadata,
+ ...sessionHandles(client, metadata.identity),
+ actor: actorHandle(client, metadata.last_turn?.actor),
+ announcement: announcementHandle(
+ client,
+ metadata.identity,
+ metadata.last_turn?.announcement_message_id,
+ ),
+ }))
+ .with(
+ { event_type: 'agent_session.waiting_for_input' },
+ ({ metadata }) => ({
+ event_type: 'agent_session.waiting_for_input' as const,
+ metadata,
+ ...sessionHandles(client, metadata.identity),
+ announcement: announcementHandle(
+ client,
+ metadata.identity,
+ metadata.announcement_message_id,
+ ),
+ }),
+ )
+ .with({ event_type: 'agent_session.input_received' }, ({ metadata }) => ({
+ event_type: 'agent_session.input_received' as const,
+ metadata,
+ ...sessionHandles(client, metadata.identity),
+ }))
+ .with({ event_type: 'agent_session.stopped' }, ({ metadata }) => ({
+ event_type: 'agent_session.stopped' as const,
+ metadata,
+ ...sessionHandles(client, metadata.identity),
+ actor: actorHandle(client, metadata.turn_in_flight?.actor),
+ announcement: announcementHandle(
+ client,
+ metadata.identity,
+ metadata.turn_in_flight?.announcement_message_id,
+ ),
+ }))
+ .with({ event_type: 'agent_session.renamed' }, ({ metadata }) => ({
+ event_type: 'agent_session.renamed' as const,
+ metadata,
+ ...sessionHandles(client, metadata.identity),
+ }))
+ .with({ event_type: 'agent_session.deleted' }, ({ metadata }) => ({
+ event_type: 'agent_session.deleted' as const,
+ metadata,
+ ...sessionHandles(client, metadata.identity),
+ }))
+ .exhaustive();
+}
diff --git a/packages/sdk/src/events/receiver.ts b/packages/sdk/src/events/receiver.ts
index 98fabd48c3..874010fe16 100644
--- a/packages/sdk/src/events/receiver.ts
+++ b/packages/sdk/src/events/receiver.ts
@@ -5,6 +5,7 @@ import type {
} from '../../generated/storage/types.gen';
import { MacroError } from '../utils';
import type { MacroClient } from '../utils/client';
+import { hydrateAgentSessionEvent } from './hydrate/agentSession';
import { hydrateChannelEvent } from './hydrate/channel';
import { hydrateDocumentEvent } from './hydrate/document';
import type {
@@ -50,6 +51,11 @@ function hydrate(
.with({ event_type: P.string.startsWith('channel.') }, (channelEvent) =>
hydrateChannelEvent(client, channelEvent),
)
+ .with(
+ { event_type: P.string.startsWith('agent_session.') },
+ (agentSessionEvent) =>
+ hydrateAgentSessionEvent(client, agentSessionEvent),
+ )
.otherwise(() => undefined);
}
diff --git a/packages/sdk/src/events/types.ts b/packages/sdk/src/events/types.ts
index bcdb3c4f69..dc20e06c64 100644
--- a/packages/sdk/src/events/types.ts
+++ b/packages/sdk/src/events/types.ts
@@ -4,6 +4,7 @@
// `metadata`, handlers get ORM handles for every entity the payload names.
import type { WebhookEvent } from '../../generated/storage/types.gen';
+import type { hydrateAgentSessionEvent } from './hydrate/agentSession';
import type { hydrateChannelEvent } from './hydrate/channel';
import type { hydrateDocumentEvent } from './hydrate/document';
@@ -27,6 +28,7 @@ export type EventPayload<E extends EventName> = Extract<
* rather than restating the mapping.
*/
type HydratedEvent =
+ | ReturnType<typeof hydrateAgentSessionEvent>
| ReturnType<typeof hydrateChannelEvent>
| ReturnType<typeof hydrateDocumentEvent>;
diff --git a/packages/sdk/tests/agent-session-hydrate.test.ts b/packages/sdk/tests/agent-session-hydrate.test.ts
new file mode 100644
index 0000000000..a1c610e76e
--- /dev/null
+++ b/packages/sdk/tests/agent-session-hydrate.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, test } from 'bun:test';
+import type { AgentSessionLifecycleEvent } from '../generated/storage/types.gen';
+import { hydrateAgentSessionEvent } from '../src/events/hydrate/agentSession';
+import type { MacroClient } from '../src/utils/client';
+
+// Handles are lazy, so hydration never touches the network.
+const client = {} as MacroClient;
+
+const identity = {
+ session_id: '01a00000-0000-7000-8000-00000000000a',
+ session_name: 'Fix the flaky test',
+ bot_id: '01a00000-0000-7000-8000-0000000000b7',
+ bot_name: 'Macro Coder',
+ owner_id: 'macro|[email protected]',
+ origin: {
+ channel_id: '01a00000-0000-7000-8000-000000000001',
+ thread_id: '01a00000-0000-7000-8000-000000000002',
+ originating_message_id: '01a00000-0000-7000-8000-000000000003',
+ },
+};
+
+const settled: AgentSessionLifecycleEvent = {
+ event_type: 'agent_session.settled',
+ metadata: {
+ identity,
+ last_turn: {
+ turn: 0,
+ action_id: '01a00000-0000-7000-8000-000000000004',
+ actor: 'macro|[email protected]',
+ announcement_message_id: '01a00000-0000-7000-8000-000000000005',
+ stop_reason: 'end_turn',
+ excerpt: 'Done.',
+ },
+ },
+};
+
+describe('hydrateAgentSessionEvent', () => {
+ test('settled hands out the session, owner, origin, chip, and actor', () => {
+ const event = hydrateAgentSessionEvent(client, settled);
+ if (event.event_type !== 'agent_session.settled')
+ throw new Error(event.event_type);
+
+ expect(event.session.id).toBe(identity.session_id);
+ expect(event.owner.id).toBe(identity.owner_id);
+ expect(event.channel?.id).toBe(identity.origin.channel_id);
+ expect(event.thread).toBeDefined();
+ expect(event.announcement?.id).toBe('01a00000-0000-7000-8000-000000000005');
+ expect(event.actor?.id).toBe('macro|[email protected]');
+ expect(event.metadata.last_turn?.excerpt).toBe('Done.');
+ });
+
+ test('a session opened outside a channel has no origin handles', () => {
+ const event = hydrateAgentSessionEvent(client, {
+ event_type: 'agent_session.waiting_for_input',
+ metadata: {
+ identity: { ...identity, origin: null },
+ turn: 1,
+ action_id: '01a00000-0000-7000-8000-000000000004',
+ announcement_message_id: '01a00000-0000-7000-8000-000000000005',
+ question: 'Tea or coffee?',
+ },
+ });
+ if (event.event_type !== 'agent_session.waiting_for_input')
+ throw new Error(event.event_type);
+
+ expect(event.session.id).toBe(identity.session_id);
+ expect(event.channel).toBeUndefined();
+ expect(event.thread).toBeUndefined();
+ // The chip lives in the origin channel; without one there is nothing to point at.
+ expect(event.announcement).toBeUndefined();
+ expect(event.metadata.question).toBe('Tea or coffee?');
+ });
+
+ test('deleted carries only the identity handles', () => {
+ const event = hydrateAgentSessionEvent(client, {
+ event_type: 'agent_session.deleted',
+ metadata: { identity },
+ });
+ if (event.event_type !== 'agent_session.deleted')
+ throw new Error(event.event_type);
+
+ expect(event.session.id).toBe(identity.session_id);
+ expect(event.owner.id).toBe(identity.owner_id);
+ expect(event.channel?.id).toBe(identity.origin.channel_id);
+ });
+});
diff --git a/services/agent_harness_service/src/containers/test.rs b/services/agent_harness_service/src/containers/test.rs
index 9474bfd9ce..76a8045ab6 100644
--- a/services/agent_harness_service/src/containers/test.rs
+++ b/services/agent_harness_service/src/containers/test.rs
@@ -2,10 +2,15 @@ use super::*;
use agent_fold::domain::service::FoldedMessageService;
use agent_harness::outbound::daytona::AnthropicApiKey;
use agent_harness::outbound::local::{LocalContainerManager, LocalSettings};
+use agent_session::domain::model::ReplicaId;
use agent_session::domain::ports::NoOpRealtime;
+use agent_session::domain::ports::{
+ NoOpAgentSessionNameGenerator, NoOpTurnObserver, NoopLifecyclePublisher,
+};
use agent_session::domain::service::AgentSessionServiceImpl;
use agent_session::testing::{InMemoryAgentSessionRepo, test_agent_session};
use bot_id::BotId;
+use std::sync::Arc;
/// A sandbox provider the tests never reach: every case here is decided by
/// `route` before the provider is asked for anything.
@@ -32,8 +37,15 @@ fn sessions_with_harness(
session.bot_id = bot;
session.harness = harness.to_owned();
repo.insert_session(session);
- let service =
- AgentSessionServiceImpl::new(repo.clone(), FoldedMessageService::new(repo), NoOpRealtime);
+ let service = AgentSessionServiceImpl::new(
+ repo.clone(),
+ FoldedMessageService::new(repo),
+ NoOpRealtime,
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
+ );
(id, service)
}
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 38732c2594..c54adb4fa7 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -67,6 +67,7 @@ use agent_session::domain::service::AgentSessionServiceImpl;
use agent_session::inbound::axum_router::{
AgentSessionControlState, AgentSessionRouterState, CreateSessionState,
};
+use agent_session::outbound::broker_lifecycle_publisher::BrokerLifecyclePublisher;
use agent_session::outbound::connection_gateway_realtime::ConnectionGatewayAgentSessionRealtime;
use agent_session::outbound::name_generator::HaikuAgentSessionNameGenerator;
use agent_session::outbound::postgres::PgAgentSessionRepo;
@@ -118,6 +119,7 @@ use sqlx::postgres::PgPoolOptions;
use tokio_retry::{Retry, strategy::FixedInterval};
use tracing::Instrument as _;
+use agent_session::domain::ports::{NoOpAgentSessionNameGenerator, NoOpTurnObserver};
use runtime_commands::consume_runtime_commands;
/// Consumer group owning this harness's agent-session offsets.
@@ -223,6 +225,15 @@ async fn run() -> anyhow::Result<()> {
// Bound to the harness once it exists (it is built *from* this service);
// both attach-capable service instances report turns to the same one.
let turn_observer = Arc::new(agent_session::domain::ports::LateBoundTurnObserver::new());
+ // One broker for channel side effects and session lifecycle facts alike;
+ // every session service instance publishes lifecycle through the same
+ // adapter, so a rename from any of them lands on the topic.
+ let broker = MacroEventBrokerService::new(
+ KafkaEventPublisher::new(config.kafka_brokers.as_ref())
+ .context("failed to create kafka event publisher")?,
+ macro_event_broker::GlobalSpawner,
+ );
+ let lifecycle_publisher = Arc::new(BrokerLifecyclePublisher::new(broker.clone()));
let sessions = AgentSessionServiceImpl::new(
session_repo.clone(),
FoldedMessageService::new(session_repo.clone()),
@@ -230,12 +241,11 @@ async fn run() -> anyhow::Result<()> {
connection_gateway.clone(),
session_repo.clone(),
),
- )
- .with_replica(replica)
- .with_turn_observer(turn_observer.clone())
- .with_name_generator(HaikuAgentSessionNameGenerator::new(ai_usage::pg_recorder(
- pool.clone(),
- )));
+ HaikuAgentSessionNameGenerator::new(ai_usage::pg_recorder(pool.clone())),
+ turn_observer.clone(),
+ lifecycle_publisher.clone(),
+ replica,
+ );
// Containers: the sandbox provider (local Docker when a developer has
// opted in, Daytona otherwise) plus Cursor cloud agents for the `@cursor`
@@ -382,9 +392,11 @@ async fn run() -> anyhow::Result<()> {
session_repo.clone(),
FoldedMessageService::new(session_repo.clone()),
NoOpRealtime,
- )
- .with_replica(replica)
- .with_turn_observer(turn_observer.clone());
+ NoOpAgentSessionNameGenerator,
+ turn_observer.clone(),
+ lifecycle_publisher.clone(),
+ replica,
+ );
let sandbox_and_inmem = RoutedContainers::new(sandbox, inmem, inmem_sessions);
// Cursor sessions run on their owner's own Cursor account, so there is no
@@ -469,11 +481,6 @@ async fn run() -> anyhow::Result<()> {
macro_queues::ContactsQueue::new().to_string(),
),
});
- let broker = MacroEventBrokerService::new(
- KafkaEventPublisher::new(config.kafka_brokers.as_ref())
- .context("failed to create kafka event publisher")?,
- macro_event_broker::GlobalSpawner,
- );
let side_effects = ChannelSideEffectService::new(
PgChannelSideEffectContext::new(pool.clone()),
ConnectionGatewayChannelRealtimePublisher::new(connection_gateway.clone()),
@@ -541,6 +548,7 @@ async fn run() -> anyhow::Result<()> {
EgressProvisioner::new(Arc::clone(&mcp_connections), egress_base_url),
RedisCommandForwarder::new(redis.clone()),
defaults,
+ Arc::clone(&lifecycle_publisher),
));
// Close the loop: turn ends observed by the session actors drain the
// harness's prompt queue.
@@ -622,6 +630,10 @@ async fn run() -> anyhow::Result<()> {
session_repo.clone(),
FoldedMessageService::new(session_repo.clone()),
ConnectionGatewayAgentSessionRealtime::new(connection_gateway, session_repo.clone()),
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ lifecycle_publisher,
+ ReplicaId::mint(),
),
entity_access.clone(),
MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
@@ -792,8 +804,8 @@ async fn run() -> anyhow::Result<()> {
// HTTP, and the turn signals are the harness's own.
HarnessCommand::EditQueued { .. }
| HarnessCommand::RemoveQueued { .. }
- | HarnessCommand::TurnEnded
- | HarnessCommand::SessionStopped => "agent_trigger.unexpected",
+ | HarnessCommand::Turn(_)
+ | HarnessCommand::SessionStopped { .. } => "agent_trigger.unexpected",
};
tracing::Span::current().record("macro.event.type", event_type);
let execution_span = tracing::info_span!(