Open History to see the last commit
1import type {
2 EnvironmentId,
3 OrchestrationV2DomainEvent,
4 OrchestrationV2ThreadShell,
5 Project,
6 ThreadId,
7} from "@t3tools/contracts";
8import {
9 RelayApi,
10 type RelayAgentActivityPublishProofPayload,
11 type RelayAgentActivityState,
12} from "@t3tools/contracts/relay";
13import { projectThreadAwarenessV2 } from "@t3tools/shared/agentAwareness";
14import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
15import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
16import {
17 normalizeRelayIssuer,
18 RELAY_ACTIVITY_PUBLISH_TYP,
19 signRelayJwt,
20} from "@t3tools/shared/relayJwt";
21import * as Cause from "effect/Cause";
22import * as Context from "effect/Context";
23import * as Crypto from "effect/Crypto";
24import * as DateTime from "effect/DateTime";
25import * as Effect from "effect/Effect";
26import * as Layer from "effect/Layer";
27import * as Option from "effect/Option";
28import * as Ref from "effect/Ref";
29import type * as Scope from "effect/Scope";
30import * as Stream from "effect/Stream";
31import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";
32import * as HttpClient from "effect/unstable/http/HttpClient";
33import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
34import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
35
36import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
37import {
38 PUBLISH_AGENT_ACTIVITY_SECRET,
39 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
40 RELAY_ISSUER_SECRET,
41 RELAY_URL_SECRET,
42} from "../cloud/config.ts";
43import { getOrCreateEnvironmentKeyPairFromSecretStore } from "../cloud/environmentKeys.ts";
44import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
45import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
46import * as ProjectService from "../project/ProjectService.ts";
47
48export class AgentAwarenessRelay extends Context.Service<
49 AgentAwarenessRelay,
50 {
51 readonly publishThread: (threadId: ThreadId) => Effect.Effect<void>;
52 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
53 }
54>()("t3/relay/AgentAwarenessRelay") {}
55
56export function eventThreadId(event: OrchestrationV2DomainEvent): ThreadId {
57 return event.threadId;
58}
59
60export function shouldPublishAgentAwarenessEvent(_event: OrchestrationV2DomainEvent): boolean {
61 // Publishing is identity-deduplicated below. Watching every V2 event keeps
62 // this consumer correct as the shell projection evolves without duplicating
63 // projection-specific relevance rules here.
64 return true;
65}
66
67export function agentAwarenessPublishIdentity(state: RelayAgentActivityState | null): string {
68 if (state === null) {
69 return "null";
70 }
71 const { updatedAt: _updatedAt, ...meaningfulState } = state;
72 return JSON.stringify(meaningfulState);
73}
74
75export function isAgentActivityPublishingEnabled(value: string | null): boolean {
76 return value === "true";
77}
78
79export function resolveAgentActivityPublishingStartupState(input: {
80 readonly relayConfigured: boolean;
81 readonly publishEnabled: boolean;
82}): "waiting-for-link" | "disabled" | "enabled" {
83 if (!input.relayConfigured) {
84 return "waiting-for-link";
85 }
86 return input.publishEnabled ? "enabled" : "disabled";
87}
88
89const RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH = 160;
90const REDACTED_RELAY_AGENT_FAILURE_DETAIL = "The agent run failed.";
91
92export function sanitizeRelayAgentActivityState(
93 state: RelayAgentActivityState | null,
94): RelayAgentActivityState | null {
95 if (state === null) {
96 return null;
97 }
98 const { detail: _detail, ...rest } = state;
99 const detail = (state.phase === "failed" ? REDACTED_RELAY_AGENT_FAILURE_DETAIL : state.detail)
100 ?.trim()
101 .slice(0, RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH)
102 .trim();
103 return detail ? { ...rest, detail } : rest;
104}
105
106function relayEnvironmentClient(token: string) {
107 return HttpClient.mapRequest(HttpClientRequest.setHeader("authorization", `Bearer ${token}`));
108}
109
110function deliveryStats(
111 deliveries: ReadonlyArray<{
112 readonly ok: boolean;
113 readonly queued?: boolean | undefined;
114 readonly kind: string;
115 readonly apnsStatus?: number | null;
116 readonly apnsReason?: string | null;
117 }>,
118) {
119 let queued = 0;
120 let successful = 0;
121 let failed = 0;
122 const failedReasons: string[] = [];
123 const kinds = new Set<string>();
124
125 for (const delivery of deliveries) {
126 kinds.add(delivery.kind);
127 if (delivery.queued) {
128 queued += 1;
129 continue;
130 }
131 if (delivery.ok) {
132 successful += 1;
133 continue;
134 }
135 failed += 1;
136 failedReasons.push(`${delivery.apnsStatus ?? "transport"}:${delivery.apnsReason ?? "unknown"}`);
137 }
138
139 return {
140 total: deliveries.length,
141 queued,
142 successful,
143 failed,
144 kinds: [...kinds],
145 failedReasons,
146 };
147}
148
149export function signRelayAgentActivityPublishProof(input: {
150 readonly privateKey: string;
151 readonly payload: RelayAgentActivityPublishProofPayload;
152}) {
153 return signRelayJwt({
154 privateKey: input.privateKey,
155 typ: RELAY_ACTIVITY_PUBLISH_TYP,
156 payload: input.payload,
157 });
158}
159
160const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
161 readonly privateKey: string;
162 readonly relayIssuer: string;
163 readonly environmentId: string;
164 readonly threadId: ThreadId;
165 readonly state: RelayAgentActivityState | null;
166 readonly jti: string;
167}) {
168 const now = yield* DateTime.now;
169 const expiresAt = DateTime.add(now, { minutes: 5 });
170 const payload = {
171 iss: `t3-env:${input.environmentId}`,
172 aud: normalizeRelayIssuer(input.relayIssuer),
173 sub: input.environmentId,
174 jti: input.jti,
175 iat: Math.floor(now.epochMilliseconds / 1_000),
176 exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
177 environmentId: input.environmentId as RelayAgentActivityPublishProofPayload["environmentId"],
178 threadId: input.threadId,
179 state: input.state,
180 } satisfies RelayAgentActivityPublishProofPayload;
181 return yield* signRelayAgentActivityPublishProof({ privateKey: input.privateKey, payload });
182});
183
184export function resolveAgentAwarenessRelayPublishSnapshot(input: {
185 readonly environmentId: EnvironmentId;
186 readonly threadId: ThreadId;
187 readonly thread: Option.Option<OrchestrationV2ThreadShell>;
188 readonly project: Option.Option<Project>;
189}): {
190 readonly projectId: string | null;
191 readonly state: RelayAgentActivityState | null;
192 readonly reason: "snapshot" | "thread-not-found" | "project-not-found";
193} {
194 if (Option.isNone(input.thread)) {
195 return {
196 projectId: null,
197 state: null,
198 reason: "thread-not-found",
199 };
200 }
201 if (Option.isNone(input.project)) {
202 return {
203 projectId: input.thread.value.projectId,
204 state: null,
205 reason: "project-not-found",
206 };
207 }
208 return {
209 projectId: input.thread.value.projectId,
210 state: sanitizeRelayAgentActivityState(
211 projectThreadAwarenessV2({
212 environmentId: input.environmentId,
213 project: input.project.value,
214 thread: input.thread.value,
215 }),
216 ),
217 reason: "snapshot",
218 };
219}
220
221export function resolveAgentAwarenessRelayActiveThreadIds(input: {
222 readonly environmentId: EnvironmentId;
223 readonly projects: ReadonlyArray<Pick<Project, "id" | "title">>;
224 readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;
225}): ReadonlyArray<ThreadId> {
226 const projectById = new Map(input.projects.map((project) => [project.id, project]));
227 return input.threads
228 .filter((thread) => {
229 const project = projectById.get(thread.projectId);
230 if (!project) {
231 return false;
232 }
233 return (
234 projectThreadAwarenessV2({
235 environmentId: input.environmentId,
236 project,
237 thread,
238 }) !== null
239 );
240 })
241 .map((thread) => thread.id);
242}
243
244export const make = Effect.gen(function* () {
245 const secrets = yield* ServerSecretStore.ServerSecretStore;
246 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
247 const threads = yield* ThreadManagement.ThreadManagementService;
248 const projects = yield* ProjectService.ProjectService;
249 const crypto = yield* Crypto.Crypto;
250 const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
251 const activeSnapshotPublishedRef = yield* Ref.make(false);
252 const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());
253
254 const readSecretString = (name: string) =>
255 secrets
256 .get(name)
257 .pipe(
258 Effect.map((bytes) =>
259 Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,
260 ),
261 );
262
263 const readRelayConfig = Effect.gen(function* () {
264 const [url, issuer, environmentCredential] = yield* Effect.all([
265 readSecretString(RELAY_URL_SECRET),
266 readSecretString(RELAY_ISSUER_SECRET),
267 readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
268 ]);
269 return url && environmentCredential
270 ? { url, issuer: issuer ?? url, environmentCredential }
271 : null;
272 });
273
274 const readPublishAgentActivityEnabled = readSecretString(PUBLISH_AGENT_ACTIVITY_SECRET).pipe(
275 Effect.map(isAgentActivityPublishingEnabled),
276 );
277
278 const makeRelayClient = (relayConfig: {
279 readonly url: string;
280 readonly environmentCredential: string;
281 }) =>
282 HttpApiClient.make(RelayApi, {
283 baseUrl: relayConfig.url,
284 transformClient: relayEnvironmentClient(relayConfig.environmentCredential),
285 }).pipe(Effect.provide(FetchHttpClient.layer));
286
287 const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) {
288 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
289 Effect.orElseSucceed(() => false),
290 );
291 if (!publishAgentActivity) {
292 yield* Effect.logDebug("agent activity publish skipped; publication disabled", {
293 threadId,
294 });
295 return;
296 }
297 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
298 if (!relayConfig) {
299 yield* Effect.logDebug("agent activity publish skipped; relay link credentials unavailable", {
300 threadId,
301 });
302 return;
303 }
304 const relayClient = yield* makeRelayClient(relayConfig);
305 const environmentId = yield* serverEnvironment.getEnvironmentId;
306
307 const publishState = (input: {
308 readonly projectId: string | null;
309 readonly state: RelayAgentActivityState | null;
310 readonly reason: string;
311 }) =>
312 Effect.gen(function* () {
313 const proof = yield* makePublishProof({
314 privateKey: cloudLinkKeyPair.privateKey,
315 relayIssuer: relayConfig.issuer,
316 environmentId,
317 threadId,
318 state: input.state,
319 jti: yield* crypto.randomUUIDv4,
320 });
321
322 yield* Effect.logInfo("publishing agent activity for thread", {
323 environmentId,
324 threadId,
325 projectId: input.projectId,
326 statePhase: input.state?.phase ?? null,
327 hasState: input.state !== null,
328 reason: input.reason,
329 });
330
331 const response = yield* relayClient.server.publishAgentActivity({
332 params: {
333 environmentId,
334 threadId,
335 },
336 payload: {
337 state: input.state,
338 proof,
339 },
340 });
341
342 yield* Effect.logInfo("agent activity publish completed", {
343 environmentId,
344 threadId,
345 ok: response.ok,
346 deliveries: deliveryStats(response.deliveries),
347 });
348 });
349
350 const shell = yield* threads.getShellSnapshot();
351 const threadValue = shell.threads.find((candidate) => candidate.id === threadId);
352 const thread = threadValue === undefined ? Option.none() : Option.some(threadValue);
353 const project = Option.isSome(thread)
354 ? yield* projects.getById(thread.value.projectId)
355 : Option.none<Project>();
356 const snapshot = resolveAgentAwarenessRelayPublishSnapshot({
357 environmentId,
358 threadId,
359 thread,
360 project,
361 });
362 const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);
363 const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);
364 if (publishedStateByThread.get(threadId) === publishIdentity) {
365 yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", {
366 environmentId,
367 threadId,
368 reason: snapshot.reason,
369 });
370 return;
371 }
372
373 if (snapshot.reason === "thread-not-found") {
374 yield* Effect.logDebug("publishing agent activity tombstone; thread not found", {
375 environmentId,
376 threadId,
377 });
378 } else if (snapshot.reason === "project-not-found") {
379 yield* Effect.logDebug("publishing agent activity tombstone; project not found", {
380 environmentId,
381 threadId,
382 projectId: snapshot.projectId,
383 });
384 }
385
386 yield* publishState({
387 projectId: snapshot.projectId,
388 state: snapshot.state,
389 reason: snapshot.reason,
390 });
391 yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {
392 const nextPublishedStates = new Map(publishedStates);
393 nextPublishedStates.set(threadId, publishIdentity);
394 return nextPublishedStates;
395 });
396 });
397
398 const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
399 publishThreadUnsafe(threadId).pipe(
400 Effect.catchCause((cause) => {
401 return Effect.logWarning("agent activity publish failed", {
402 threadId,
403 cause: Cause.pretty(cause),
404 });
405 }),
406 Effect.withSpan("AgentAwarenessRelay.publishThread"),
407 withRelayClientTracing,
408 );
409
410 const publishActiveThreadsUnsafe = Effect.gen(function* () {
411 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
412 Effect.orElseSucceed(() => false),
413 );
414 if (!publishAgentActivity) {
415 yield* Effect.logDebug("agent activity snapshot skipped; publication disabled");
416 return false;
417 }
418 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
419 if (!relayConfig) {
420 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
421 return false;
422 }
423 const environmentId = yield* serverEnvironment.getEnvironmentId;
424 const [projectSnapshot, shellSnapshot] = yield* Effect.all([
425 projects.snapshot,
426 threads.getShellSnapshot(),
427 ]);
428 const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({
429 environmentId,
430 projects: projectSnapshot.projects,
431 threads: shellSnapshot.threads,
432 });
433 if (activeThreadIds.length === 0) {
434 yield* Effect.logDebug("agent activity snapshot has no publishable threads");
435 return true;
436 }
437 yield* Effect.logInfo("publishing active agent activity snapshot", {
438 count: activeThreadIds.length,
439 });
440 yield* Effect.forEach(activeThreadIds, publishThread, { concurrency: 4, discard: true });
441 return true;
442 });
443
444 const publishActiveThreadsOnceWhenConfigured = (logEnabledWhenReady: boolean) =>
445 Effect.gen(function* () {
446 while (!(yield* Ref.get(activeSnapshotPublishedRef))) {
447 const published = yield* publishActiveThreadsUnsafe.pipe(Effect.orElseSucceed(() => false));
448 if (published) {
449 yield* Ref.set(activeSnapshotPublishedRef, true);
450 if (logEnabledWhenReady) {
451 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
452 yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
453 relayUrl: relayConfig?.url,
454 });
455 }
456 return;
457 }
458 yield* Effect.sleep("5 seconds");
459 }
460 });
461
462 const worker = yield* makeDrainableWorker(publishThread);
463
464 const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
465 function* () {
466 const [relayConfig, publishEnabled] = yield* Effect.all([
467 readRelayConfig.pipe(Effect.orElseSucceed(() => null)),
468 readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),
469 ]);
470 const startupState = resolveAgentActivityPublishingStartupState({
471 relayConfigured: relayConfig !== null,
472 publishEnabled,
473 });
474 switch (startupState) {
475 case "waiting-for-link":
476 yield* Effect.logInfo(
477 "agent activity publishing standby; waiting for T3 Connect link reconciliation",
478 );
479 break;
480 case "disabled":
481 yield* Effect.logInfo("agent activity publishing disabled by T3 Connect configuration");
482 break;
483 case "enabled":
484 yield* Effect.logInfo("agent activity publishing enabled", {
485 relayUrl: relayConfig?.url,
486 });
487 break;
488 }
489 yield* Effect.forkScoped(
490 Effect.sleep("1 second").pipe(
491 Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")),
492 ),
493 );
494 yield* Effect.forkScoped(
495 Stream.runForEach(threads.streamDomainEvents, (event) => {
496 const threadId = eventThreadId(event);
497 if (!shouldPublishAgentAwarenessEvent(event)) {
498 return Effect.logDebug(
499 "agent activity publishing ignored event without activity changes",
500 {
501 eventType: event.type,
502 threadId,
503 },
504 );
505 }
506 return Effect.logDebug("agent activity publishing queued thread publish", {
507 eventType: event.type,
508 threadId,
509 }).pipe(Effect.andThen(worker.enqueue(threadId)));
510 }),
511 );
512 },
513 );
514
515 return AgentAwarenessRelay.of({
516 publishThread,
517 start,
518 });
519});
520
521export const layer = Layer.effect(AgentAwarenessRelay, make);