Open History to see the last commit
1import {
2 AuthSessionId,
3 type MilestoneEvent as MilestoneEventValue,
4 MilestoneEvent,
5 type MilestoneFilter,
6 ProjectId,
7 ThreadId,
8 TrimmedNonEmptyString,
9} from "@t3tools/contracts";
10import * as Digest from "effect/crypto/Digest";
11import * as Effect from "effect/Effect";
12import * as Base64Url from "effect/encoding/Base64Url";
13import * as Option from "effect/Option";
14import * as Schema from "effect/Schema";
15import * as Stream from "effect/Stream";
16import { McpSchema, type McpServer } from "effect/ai";
17
18import * as SessionStore from "../auth/SessionStore.ts";
19import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
20import * as MilestoneHub from "./MilestoneHub.ts";
21
22// Matches the hub's buffer, so a poll can drain everything it keeps at once.
23const MAX_EVENTS = 1_000;
24const DEFAULT_EVENTS = 100;
25
26const includeSubagentChildren = Schema.optional(
27 Schema.Boolean.annotate({
28 description: "Also subagent threads and runs another run invoked.",
29 }),
30);
31const workflowRunIds = Schema.optional(Schema.Array(TrimmedNonEmptyString));
32
33const Parameters = Schema.Struct({
34 projectIds: Schema.optional(Schema.Array(ProjectId)),
35 threadIds: Schema.optional(Schema.Array(ThreadId)),
36 workflowRunIds: Schema.optional(
37 Schema.Array(TrimmedNonEmptyString).annotate({
38 description: "Workflow runs, for the threads that are their agent steps.",
39 }),
40 ),
41 includeSubagentChildren,
42});
43
44const WorkflowParameters = Schema.Struct({
45 workflows: Schema.optional(
46 Schema.Array(TrimmedNonEmptyString).annotate({ description: "Workflow names." }),
47 ),
48 workflowRunIds,
49 includeSubagentChildren,
50});
51
52const DESCRIPTIONS: Record<MilestoneEventValue["type"], string> = {
53 "thread.run_settled": "A thread's turn ended: completed, failed, interrupted or cancelled.",
54 "thread.needs_input": "An agent waits on a person to answer a question or approve an action.",
55 "thread.input_resolved": "A question or approval an agent waited on was answered, or lapsed.",
56 "thread.guest_request": "A guest on a shared thread asked for something.",
57 "thread.guest_request_resolved": "A guest's request was sent, dismissed, or its link closed.",
58 "pr.watch_wake": "A watched pull request changed and woke its thread.",
59 "workflow.run_started": "A workflow run started.",
60 "workflow.needs_input": "A workflow run asks a person a question.",
61 "workflow.input_resolved":
62 "A workflow run's question was answered, timed out, or ended with its run.",
63 "workflow.run_paused": "A workflow run paused: a step failed, or someone paused it.",
64 "workflow.run_resumed": "A paused workflow run went on again.",
65 "workflow.run_ended": "A workflow run ended: completed, stopped, skipped or cancelled.",
66};
67
68/**
69 * Each milestone type as an MCP event type (SEP-3415), for outside clients to poll, stream or
70 * receive by webhook. Cursors are the hub's, so a client that was away catches up on what the
71 * hub still keeps. Workflow runs have no project or thread, so their types are narrowed by
72 * workflow and run.
73 */
74export const make = Effect.gen(function* () {
75 const hub = yield* MilestoneHub.MilestoneHub;
76 const sessions = yield* Effect.serviceOption(SessionStore.SessionStore);
77 // A webhook subscription outlives its request, so it ends itself when the client's session does.
78 const untilRevoked = Effect.fnUntraced(function* <A>(items: Stream.Stream<A>) {
79 const scope = yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext);
80 const sessionId = Option.getOrUndefined(scope)?.client?.sessionId;
81 if (sessionId === undefined || Option.isNone(sessions)) return items;
82 const revoked = sessions.value.awaitInvalidation(AuthSessionId.make(sessionId)).pipe(
83 Effect.ignore,
84 Effect.andThen(
85 Effect.fail(
86 new McpSchema.Forbidden({
87 message: "Access revoked",
88 data: { reason: "Access revoked" },
89 }),
90 ),
91 ),
92 );
93 return items.pipe(Stream.interruptWhen(revoked));
94 });
95 const digest = yield* Effect.service(Digest.Digest).pipe(Effect.provide(Digest.layerWebCrypto));
96 // TODO(#41158): drop this bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp).
97 // They take an event's eventId as its webhook-id, which allows only [A-Za-z0-9_-], so the
98 // eventId is a hash of the milestone id, the same in every delivery mode.
99 const occurrence = ({ event }: MilestoneHub.PositionedMilestone) =>
100 Effect.map(digest.digest(Digest.sha256, new TextEncoder().encode(event.id)), (hash) => ({
101 eventId: `evt_${Base64Url.encode(hash).slice(0, 22)}`,
102 timestamp: event.occurredAt,
103 data: event,
104 }));
105 const context = { hub, untilRevoked, occurrence };
106 const isWorkflow = (payload: (typeof MilestoneEvent.members)[number]) =>
107 payload.fields.type.literal.startsWith("workflow.");
108 return {
109 threads: MilestoneEvent.members
110 .filter((payload) => !isWorkflow(payload))
111 .map((payload) => eventOf(context, payload, Parameters)),
112 workflows: MilestoneEvent.members
113 .filter(isWorkflow)
114 .map((payload) => eventOf(context, payload, WorkflowParameters)),
115 };
116});
117
118const eventOf = <P extends typeof Parameters | typeof WorkflowParameters>(
119 {
120 hub,
121 untilRevoked,
122 occurrence,
123 }: {
124 readonly hub: MilestoneHub.MilestoneHub["Service"];
125 readonly occurrence: (milestone: MilestoneHub.PositionedMilestone) => Effect.Effect<{
126 readonly eventId: string;
127 readonly timestamp: string;
128 readonly data: MilestoneEventValue;
129 }>;
130 readonly untilRevoked: <A>(
131 items: Stream.Stream<A>,
132 ) => Effect.Effect<Stream.Stream<A, McpSchema.Forbidden>>;
133 },
134 payload: (typeof MilestoneEvent.members)[number],
135 parameters: P,
136) => {
137 const type = payload.fields.type.literal;
138 const filterOf = (args: P["Type"]): MilestoneFilter => ({ ...args, types: [type] });
139 return {
140 name: type,
141 description: DESCRIPTIONS[type],
142 parameters,
143 payload,
144 poll: (args, request) =>
145 hub
146 .read({
147 cursor: request.cursor,
148 maxAgeMs: request.maxAgeMs,
149 filter: filterOf(args),
150 limit: Math.min(request.maxEvents ?? DEFAULT_EVENTS, MAX_EVENTS),
151 })
152 .pipe(
153 Effect.flatMap((page) =>
154 Effect.map(Effect.forEach(page.events, occurrence), (events) => ({
155 ...page,
156 events,
157 })),
158 ),
159 ),
160 stream: Effect.fn("MilestoneEvents.stream")(function* (
161 args: P["Type"],
162 request: McpServer.EventStreamRequest,
163 ) {
164 const { cursor, truncated, items } = yield* hub.follow({
165 cursor: request.cursor,
166 maxAgeMs: request.maxAgeMs,
167 filter: filterOf(args),
168 });
169 return {
170 cursor,
171 truncated,
172 items: yield* untilRevoked(
173 items.pipe(
174 Stream.mapEffect(
175 (item): Effect.Effect<McpServer.EventStreamItem<MilestoneEventValue>> =>
176 item._tag === "Milestone"
177 ? Effect.map(occurrence(item), (event) => ({
178 _tag: "Event" as const,
179 cursor: item.cursor,
180 ...event,
181 }))
182 : Effect.succeed(item),
183 ),
184 ),
185 ),
186 };
187 }),
188 } satisfies McpServer.EventOptions<P, typeof payload, never>;
189};