Open History to see the last commit
1import {
2 type GuestMessageId,
3 type GuestShareId,
4 type MilestoneActor,
5 type MilestoneEvent,
6 MilestoneId,
7 type MilestoneInputKind,
8 type OrchestrationV2AppThread,
9 type OrchestrationV2DomainEvent,
10 type OrchestrationV2RuntimeRequest,
11 type ThreadId,
12} from "@t3tools/contracts";
13import * as Context from "effect/Context";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import type * as Scope from "effect/Scope";
18import * as Stream from "effect/Stream";
19
20import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
21import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
22import { forkParked } from "../serverActivation.ts";
23import * as MilestoneHub from "./MilestoneHub.ts";
24
25const inputKind = (kind: OrchestrationV2RuntimeRequest["kind"]): MilestoneInputKind | null => {
26 switch (kind) {
27 case "user_input":
28 case "mcp-elicitation":
29 return "user_input";
30 case "command":
31 case "file-read":
32 case "file-change":
33 case "permission":
34 return "approval";
35 default:
36 return null;
37 }
38};
39
40/** Turns orchestration events into thread, guest and pull request watch milestones. */
41export class OrchestrationMilestones extends Context.Service<
42 OrchestrationMilestones,
43 {
44 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
45 readonly handle: (event: OrchestrationV2DomainEvent) => Effect.Effect<void>;
46 }
47>()("t3/milestones/OrchestrationMilestones") {}
48
49const make = Effect.gen(function* () {
50 const engine = yield* Orchestrator.OrchestratorV2;
51 const projections = yield* ProjectionStore.ProjectionStoreV2;
52 const hub = yield* MilestoneHub.MilestoneHub;
53 // A record updated again after a restart is not news unless its change is from after it.
54 const since = yield* DateTime.now;
55 const isNew = (at: DateTime.Utc | string) =>
56 DateTime.isGreaterThanOrEqualTo(typeof at === "string" ? DateTime.makeUnsafe(at) : at, since);
57 /** Each thread's waiting guest messages, so a resolution is told once and a closed link is seen. */
58 const guestPending = new Map<ThreadId, Map<GuestMessageId, GuestShareId>>();
59
60 const envelope = (
61 id: string,
62 thread: OrchestrationV2AppThread,
63 occurredAt: DateTime.Utc,
64 actor: MilestoneActor,
65 ) => ({
66 id: MilestoneId.make(id),
67 occurredAt: DateTime.formatIso(occurredAt),
68 projectId: thread.projectId,
69 threadId: thread.id,
70 parentThreadId: thread.lineage.parentThreadId,
71 actor,
72 isSubagentChild: thread.lineage.relationshipToParent === "subagent",
73 ...(thread.workflowRun === undefined ? {} : { workflowRunId: thread.workflowRun.runId }),
74 });
75
76 const guestMilestones = (
77 thread: OrchestrationV2AppThread,
78 occurredAt: DateTime.Utc,
79 ): ReadonlyArray<MilestoneEvent> => {
80 const share = thread.guestShare ?? null;
81 const before = guestPending.get(thread.id) ?? new Map<GuestMessageId, GuestShareId>();
82 const pending = new Map<GuestMessageId, GuestShareId>();
83 const out: Array<MilestoneEvent> = [];
84 const resolved = (
85 shareId: GuestShareId,
86 guestMessageId: GuestMessageId,
87 resolution: "sent" | "dismissed" | "closed",
88 ) =>
89 out.push({
90 ...envelope(`thread.guest_request_resolved:${guestMessageId}`, thread, occurredAt, {
91 type: "user",
92 }),
93 type: "thread.guest_request_resolved",
94 shareId,
95 guestMessageId,
96 resolution,
97 });
98 if (share !== null) {
99 const guest: MilestoneActor = {
100 type: "guest",
101 id: share.id,
102 ...(share.guestName === null ? {} : { label: share.guestName }),
103 };
104 for (const message of share.messages) {
105 if (message.status !== "pending") {
106 if (before.has(message.id)) resolved(share.id, message.id, message.status);
107 continue;
108 }
109 pending.set(message.id, share.id);
110 if (before.has(message.id) || !isNew(message.submittedAt)) continue;
111 out.push({
112 ...envelope(`thread.guest_request:${message.id}`, thread, occurredAt, guest),
113 type: "thread.guest_request",
114 shareId: share.id,
115 guestMessageId: message.id,
116 });
117 }
118 }
119 // Gone from the share without an answer: the link was closed or replaced.
120 for (const [guestMessageId, shareId] of before) {
121 if (share?.messages.some((message) => message.id === guestMessageId) !== true) {
122 resolved(shareId, guestMessageId, "closed");
123 }
124 }
125 if (pending.size === 0) guestPending.delete(thread.id);
126 else guestPending.set(thread.id, pending);
127 return out;
128 };
129
130 // Runs for every domain event, token deltas included; most return before reading anything.
131 const handle: OrchestrationMilestones["Service"]["handle"] = Effect.fnUntraced(
132 function* (event) {
133 const out: Array<MilestoneEvent> = [];
134 switch (event.type) {
135 case "run.updated": {
136 const run = event.payload;
137 // A queued run cancelled before it started did no work worth telling of.
138 if (run.startedAt === null || run.completedAt === null || !isNew(run.completedAt)) return;
139 if (
140 run.status !== "completed" &&
141 run.status !== "failed" &&
142 run.status !== "interrupted" &&
143 run.status !== "cancelled"
144 ) {
145 return;
146 }
147 const thread = yield* projections.getThread(event.threadId);
148 out.push({
149 ...envelope(`thread.run_settled:${run.id}`, thread, run.completedAt, {
150 type: "agent",
151 id: run.providerInstanceId,
152 }),
153 type: "thread.run_settled",
154 runId: run.id,
155 outcome: run.status,
156 });
157 break;
158 }
159 case "runtime-request.updated": {
160 const request = event.payload;
161 const kind = inputKind(request.kind);
162 if (kind === null) return;
163 if (request.status === "pending") {
164 if (!isNew(request.createdAt)) return;
165 const thread = yield* projections.getThread(event.threadId);
166 out.push({
167 ...envelope(`thread.needs_input:${request.id}`, thread, request.createdAt, {
168 type: "agent",
169 }),
170 type: "thread.needs_input",
171 requestId: request.id,
172 kind,
173 });
174 } else {
175 const at = request.resolvedAt ?? event.occurredAt;
176 if (!isNew(at)) return;
177 const thread = yield* projections.getThread(event.threadId);
178 out.push({
179 ...envelope(`thread.input_resolved:${request.id}`, thread, at, {
180 type: request.status === "resolved" ? "user" : "system",
181 }),
182 type: "thread.input_resolved",
183 requestId: request.id,
184 kind,
185 resolution: request.status,
186 });
187 }
188 break;
189 }
190 case "thread.guest-share-updated":
191 out.push(...guestMilestones(event.payload, event.occurredAt));
192 break;
193 case "message.updated": {
194 const message = event.payload;
195 const source = message.notification?.source;
196 if (source?.kind !== "monitor" || source.pullRequest === undefined) return;
197 if (!isNew(message.createdAt)) return;
198 const stamps = [source.pullRequest, ...(source.otherPullRequests ?? [])];
199 const thread = yield* projections.getThread(event.threadId);
200 out.push({
201 ...envelope(`pr.watch_wake:${message.id}`, thread, message.createdAt, {
202 type: "system",
203 label: "pull request watch",
204 }),
205 type: "pr.watch_wake",
206 pullRequests: stamps.map(({ host, repository, number }) => ({
207 host,
208 repository,
209 number,
210 })),
211 outcome: message.notification!.outcome,
212 summary: message.notification!.summary,
213 watchEnded: stamps.some((stamp) => stamp.watchEnded === true),
214 });
215 break;
216 }
217 default:
218 return;
219 }
220 yield* Effect.forEach(out, hub.publish, { discard: true });
221 },
222 (effect, event) =>
223 effect.pipe(
224 Effect.catchCause((cause) =>
225 Effect.logWarning("deriving a milestone failed", { threadId: event.threadId, cause }),
226 ),
227 ),
228 );
229
230 const start: OrchestrationMilestones["Service"]["start"] = Effect.fn(
231 "OrchestrationMilestones.start",
232 )(function* () {
233 yield* forkParked(
234 Stream.runForEach(engine.streamDomainEvents, handle).pipe(
235 Effect.catchCause((cause) =>
236 Effect.logWarning("orchestration milestone stream failed", { cause }),
237 ),
238 ),
239 );
240 });
241
242 return OrchestrationMilestones.of({ start, handle });
243});
244
245export const layer = Layer.effect(OrchestrationMilestones, make);