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

AgentAwarenessRelay.ts

543 lines18.2 KB

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