Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AgentActivityPublisher.ts

233 lines8.1 KB

1import type {
2 RelayAgentActivityAggregateState,
3 RelayAgentActivityState,
4 RelayDeliveryResult,
5 RelayPublishResponse,
6} from "@t3tools/contracts/relay";
7import * as Context from "effect/Context";
8import * as DateTime from "effect/DateTime";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11​
12import { sanitizeAgentActivityAggregateState } from "./agentActivityPayloads.ts";
13import * as AgentActivityRows from "./AgentActivityRows.ts";
14import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
15import * as LiveActivities from "./LiveActivities.ts";
16import * as ApnsDeliveries from "./ApnsDeliveries.ts";
17​
18export type AgentActivityPublishError =
19 | AgentActivityRows.AgentActivityRowUpsertPersistenceError
20 | AgentActivityRows.AgentActivityRowDeletePersistenceError
21 | AgentActivityRows.AgentActivityRowListPersistenceError
22 | EnvironmentLinks.EnvironmentLinkUserListPersistenceError
23 | LiveActivities.LiveActivityTargetListPersistenceError
24 | ApnsDeliveries.ApnsDeliveryError;
25​
26export class AgentActivityPublisher extends Context.Service<
27 AgentActivityPublisher,
28 {
29 readonly publish: (input: {
30 readonly environmentId: string;
31 readonly environmentPublicKey: string;
32 readonly threadId: string;
33 readonly state: RelayAgentActivityState | null;
34 }) => Effect.Effect<RelayPublishResponse, AgentActivityPublishError>;
35 readonly replayForLiveActivityRegistration: (input: {
36 readonly userId: string;
37 readonly deviceId: string;
38 }) => Effect.Effect<RelayDeliveryResult | null, AgentActivityPublishError>;
39 }
40>()("t3code-relay/agentActivity/AgentActivityPublisher") {}
41​
42export const make = Effect.gen(function* () {
43 const rows = yield* AgentActivityRows.AgentActivityRows;
44 const links = yield* EnvironmentLinks.EnvironmentLinks;
45 const liveActivities = yield* LiveActivities.LiveActivities;
46 const apnsDeliveries = yield* ApnsDeliveries.ApnsDeliveries;
47​
48 const publishForDeliveryUser = Effect.fnUntraced(function* (input: {
49 readonly deliveryUser: EnvironmentLinks.AgentAwarenessDeliveryUserRecord;
50 readonly state: RelayAgentActivityState | null;
51 readonly nowMs: number;
52 }) {
53 const activeStates = yield* rows.listForUser({ userId: input.deliveryUser.userId });
54 const liveActivityAggregate = input.deliveryUser.liveActivitiesEnabled
55 ? makeAggregateState({
56 activeStates,
57 terminalState: input.state && isTerminalPhase(input.state) ? input.state : null,
58 })
59 : null;
60 const notificationOnlyAggregate =
61 input.deliveryUser.notificationsEnabled &&
62 !input.deliveryUser.liveActivitiesEnabled &&
63 input.state !== null
64 ? makeAggregateState({
65 activeStates: isTerminalPhase(input.state) ? [] : [input.state],
66 terminalState: isTerminalPhase(input.state) ? input.state : null,
67 })
68 : null;
69 const targets = yield* liveActivities.listTargets({ userId: input.deliveryUser.userId });
70 const deliveriesByTarget = yield* Effect.forEach(
71 targets,
72 (target) =>
73 Effect.all(
74 [
75 apnsDeliveries.sendForTarget({
76 target,
77 aggregate: liveActivityAggregate,
78 nowMs: input.nowMs,
79 }),
80 notificationOnlyAggregate === null
81 ? Effect.succeed(null)
82 : apnsDeliveries.sendPushNotificationForTarget({
83 target,
84 aggregate: notificationOnlyAggregate,
85 }),
86 ],
87 { concurrency: 2 },
88 ),
89 { concurrency: 4 },
90 );
91 return deliveriesByTarget.flat();
92 });
93​
94 return AgentActivityPublisher.of({
95 replayForLiveActivityRegistration: Effect.fn(
96 "relay.agent_activity_publisher.replay_for_live_activity_registration",
97 )(function* (input) {
98 yield* Effect.annotateCurrentSpan({
99 "relay.mobile.device_id": input.deviceId,
100 "relay.operation": "replayForLiveActivityRegistration",
101 });
102 const { activeStates, targets } = yield* Effect.all(
103 {
104 activeStates: rows.listForUser({ userId: input.userId }),
105 targets: liveActivities.listTargets({ userId: input.userId }),
106 },
107 { concurrency: 2 },
108 );
109 const target = targets.find((row) => row.device_id === input.deviceId) ?? null;
110 if (target === null) {
111 return null;
112 }
113 const aggregate = makeAggregateState({ activeStates, terminalState: null });
114 const now = yield* DateTime.now;
115 return yield* apnsDeliveries.sendForTarget({
116 target,
117 aggregate,
118 nowMs: now.epochMilliseconds,
119 });
120 }),
121 publish: Effect.fn("relay.agent_activity_publisher.publish")(function* (input) {
122 yield* Effect.annotateCurrentSpan({
123 "relay.environment_id": input.environmentId,
124 "relay.thread_id": input.threadId,
125 "relay.agent_activity.phase": input.state?.phase ?? "deleted",
126 });
127 if (input.state && !isTerminalPhase(input.state)) {
128 yield* rows.upsert({
129 environmentPublicKey: input.environmentPublicKey,
130 state: input.state,
131 });
132 } else {
133 yield* rows.remove({
134 environmentId: input.environmentId,
135 environmentPublicKey: input.environmentPublicKey,
136 threadId: input.threadId,
137 });
138 }
139​
140 const deliveryUsers = yield* links.listDeliveryUsersForEnvironment({
141 environmentId: input.environmentId,
142 environmentPublicKey: input.environmentPublicKey,
143 });
144 const now = yield* DateTime.now;
145 const deliveriesByUser = yield* Effect.forEach(
146 deliveryUsers,
147 (deliveryUser) =>
148 publishForDeliveryUser({
149 deliveryUser,
150 state: input.state,
151 nowMs: now.epochMilliseconds,
152 }),
153 { concurrency: 4 },
154 );
155 const deliveries = deliveriesByUser.flat();
156 return {
157 ok: true,
158 deliveries: deliveries.filter(
159 (delivery): delivery is RelayDeliveryResult => delivery !== null,
160 ),
161 };
162 }),
163 });
164});
165​
166function statusForPhase(phase: RelayAgentActivityState["phase"]): string {
167 switch (phase) {
168 case "waiting_for_approval":
169 return "Approval";
170 case "waiting_for_input":
171 return "Input";
172 case "completed":
173 return "Done";
174 case "failed":
175 return "Failed";
176 case "starting":
177 return "Starting";
178 case "running":
179 return "Working";
180 case "stale":
181 return "Waiting";
182 }
184​
185function isTerminalPhase(state: RelayAgentActivityState): boolean {
186 return state.phase === "completed" || state.phase === "failed";
188​
189function aggregateRowForState(state: RelayAgentActivityState) {
190 return {
191 environmentId: state.environmentId,
192 threadId: state.threadId,
193 projectTitle: state.projectTitle,
194 threadTitle: state.threadTitle,
195 modelTitle: state.modelTitle,
196 phase: state.phase,
197 status: statusForPhase(state.phase),
198 updatedAt: state.updatedAt,
199 deepLink: state.deepLink,
200 };
202​
203function terminalAggregateState(state: RelayAgentActivityState): RelayAgentActivityAggregateState {
204 return sanitizeAgentActivityAggregateState({
205 title: "T3 Code",
206 subtitle: state.phase === "failed" ? "Agent work failed" : "Agent work completed",
207 activeCount: 0,
208 updatedAt: state.updatedAt,
209 activities: [aggregateRowForState(state)],
210 });
212​
213function makeAggregateState(input: {
214 readonly activeStates: ReadonlyArray<RelayAgentActivityState>;
215 readonly terminalState: RelayAgentActivityState | null;
216}): RelayAgentActivityAggregateState | null {
217 const activeStates = input.activeStates.filter((state) => !isTerminalPhase(state));
218 if (activeStates.length === 0) {
219 return input.terminalState === null ? null : terminalAggregateState(input.terminalState);
220 }
221 const updatedAt = activeStates.reduce((latest, state) =>
222 state.updatedAt.localeCompare(latest.updatedAt) > 0 ? state : latest,
223 ).updatedAt;
224 return sanitizeAgentActivityAggregateState({
225 title: "T3 Code",
226 subtitle: "Agent work in progress",
227 activeCount: activeStates.length,
228 updatedAt,
229 activities: activeStates.slice(0, 3).map(aggregateRowForState),
230 });
232​
233export const layer = Layer.effect(AgentActivityPublisher, make);