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

AgentAwarenessRelay.ts

633 lines22.1 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​
206// Compact, log-safe view of the fields the awareness phase ladder reads.
207export function describeThreadShellForAwareness(
208 thread: Option.Option<OrchestrationThreadShell>,
209): Record<string, unknown> {
210 if (Option.isNone(thread)) {
211 return { found: false };
212 }
213 const shell = thread.value;
214 return {
215 found: true,
216 sessionStatus: shell.session?.status ?? null,
217 sessionActiveTurnId: shell.session?.activeTurnId ?? null,
218 latestTurnId: shell.latestTurn?.turnId ?? null,
219 latestTurnState: shell.latestTurn?.state ?? null,
220 latestTurnCompletedAt: shell.latestTurn?.completedAt ?? null,
221 hasPendingApprovals: shell.hasPendingApprovals,
222 hasPendingUserInput: shell.hasPendingUserInput,
223 };
225​
226export function resolveAgentAwarenessRelayPublishSnapshot(input: {
227 readonly environmentId: EnvironmentId;
228 readonly threadId: ThreadId;
229 readonly thread: Option.Option<OrchestrationThreadShell>;
230 readonly project: Option.Option<OrchestrationProjectShell>;
231}): {
232 readonly projectId: string | null;
233 readonly state: RelayAgentActivityState | null;
234 readonly reason: "snapshot" | "thread-not-found" | "project-not-found";
235} {
236 if (Option.isNone(input.thread)) {
237 return {
238 projectId: null,
239 state: null,
240 reason: "thread-not-found",
241 };
242 }
243 if (Option.isNone(input.project)) {
244 return {
245 projectId: input.thread.value.projectId,
246 state: null,
247 reason: "project-not-found",
248 };
249 }
250 return {
251 projectId: input.thread.value.projectId,
252 state: sanitizeRelayAgentActivityState(
253 projectThreadAwareness({
254 environmentId: input.environmentId,
255 project: input.project.value,
256 thread: input.thread.value,
257 }),
258 ),
259 reason: "snapshot",
260 };
262​
263export function resolveAgentAwarenessRelayActiveThreadIds(input: {
264 readonly environmentId: EnvironmentId;
265 readonly projects: ReadonlyArray<Pick<OrchestrationProjectShell, "id" | "title">>;
266 readonly threads: ReadonlyArray<OrchestrationThreadShell>;
267}): ReadonlyArray<ThreadId> {
268 const projectById = new Map(input.projects.map((project) => [project.id, project]));
269 return input.threads
270 .filter((thread) => {
271 const project = projectById.get(thread.projectId);
272 if (!project) {
273 return false;
274 }
275 return (
276 projectThreadAwareness({
277 environmentId: input.environmentId,
278 project,
279 thread,
280 }) !== null
281 );
282 })
283 .map((thread) => thread.id);
285​
286export const make = Effect.gen(function* () {
287 const secrets = yield* ServerSecretStore.ServerSecretStore;
288 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
289 const snapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
290 const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
291 const crypto = yield* Crypto.Crypto;
292 const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
293 const activeSnapshotPublishedRef = yield* Ref.make(false);
294 const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());
295​
296 const readSecretString = (name: string) =>
297 secrets
298 .get(name)
299 .pipe(
300 Effect.map((bytes) =>
301 Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,
302 ),
303 );
304​
305 const readRelayConfig = Effect.gen(function* () {
306 const [url, issuer, environmentCredential] = yield* Effect.all([
307 readSecretString(RELAY_URL_SECRET),
308 readSecretString(RELAY_ISSUER_SECRET),
309 readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
310 ]);
311 return url && environmentCredential
312 ? { url, issuer: issuer ?? url, environmentCredential }
313 : null;
314 });
315​
316 const readPublishAgentActivityEnabled = readSecretString(PUBLISH_AGENT_ACTIVITY_SECRET).pipe(
317 Effect.map(isAgentActivityPublishingEnabled),
318 );
319​
320 const makeRelayClient = (relayConfig: {
321 readonly url: string;
322 readonly environmentCredential: string;
323 }) =>
324 HttpApiClient.make(RelayApi, {
325 baseUrl: relayConfig.url,
326 transformClient: relayEnvironmentClient(relayConfig.environmentCredential),
327 }).pipe(Effect.provide(FetchHttpClient.layer));
328​
329 // Deadlines for publishes that need confirmation (tombstones and
330 // first-state completions). The confirming publish is re-enqueued through
331 // the same drainable worker as every other publish, so a confirmed
332 // tombstone can never race an in-flight live update; a recovered state
333 // clears the deadline. Assigned after the worker exists.
334 const publishConfirmDeadlines = new Map<ThreadId, number>();
335 let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
336​
337 const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) {
338 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
339 Effect.orElseSucceed(() => false),
340 );
341 if (!publishAgentActivity) {
342 yield* Effect.logDebug("agent activity publish skipped; publication disabled", {
343 threadId,
344 });
345 return;
346 }
347 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
348 if (!relayConfig) {
349 yield* Effect.logDebug("agent activity publish skipped; relay link credentials unavailable", {
350 threadId,
351 });
352 return;
353 }
354 const relayClient = yield* makeRelayClient(relayConfig);
355 const environmentId = yield* serverEnvironment.getEnvironmentId;
356​
357 const publishState = (input: {
358 readonly projectId: string | null;
359 readonly state: RelayAgentActivityState | null;
360 readonly reason: string;
361 }) =>
362 Effect.gen(function* () {
363 const proof = yield* makePublishProof({
364 privateKey: cloudLinkKeyPair.privateKey,
365 relayIssuer: relayConfig.issuer,
366 environmentId,
367 threadId,
368 state: input.state,
369 jti: yield* crypto.randomUUIDv4,
370 });
371​
372 yield* Effect.logInfo("publishing agent activity for thread", {
373 environmentId,
374 threadId,
375 projectId: input.projectId,
376 statePhase: input.state?.phase ?? null,
377 hasState: input.state !== null,
378 reason: input.reason,
379 });
380​
381 const response = yield* relayClient.server.publishAgentActivity({
382 params: {
383 environmentId,
384 threadId,
385 },
386 payload: {
387 state: input.state,
388 proof,
389 },
390 });
391​
392 yield* Effect.logInfo("agent activity publish completed", {
393 environmentId,
394 threadId,
395 ok: response.ok,
396 deliveries: deliveryStats(response.deliveries),
397 });
398 });
399​
400 const thread = yield* snapshotQuery.getThreadShellById(threadId);
401 const project = Option.isSome(thread)
402 ? yield* snapshotQuery.getProjectShellById(thread.value.projectId)
403 : Option.none<OrchestrationProjectShell>();
404 const snapshot = resolveAgentAwarenessRelayPublishSnapshot({
405 environmentId,
406 threadId,
407 thread,
408 project,
409 });
410 const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);
411 const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);
412 if (publishedStateByThread.get(threadId) === publishIdentity) {
413 // The projection is back at (or never left) the last published state, so
414 // any pending deferred confirmation is moot. Leaving the deadline in
415 // place would let a much later transient null find it already expired
416 // and publish a tombstone immediately, skipping the deferral window.
417 publishConfirmDeadlines.delete(threadId);
418 yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", {
419 environmentId,
420 threadId,
421 reason: snapshot.reason,
422 });
423 return;
424 }
425​
426 // Two projections need confirmation before publishing, because both can
427 // appear transiently while the projector is mid-write and publishing them
428 // immediately is destructive or noisy:
429 // - null (tombstone) while the previous published state was live: deletes
430 // the thread from every armed card mid-conversation.
431 // - completed as the thread's FIRST published state: sessions boot at
432 // "ready" before their first turn, which projects as completed for an
433 // instant and sends a spurious Done notification at thread birth.
434 // Defer, schedule a re-publish through the ordinary worker queue, and
435 // only publish if the projection still holds when it drains.
436 const requiresConfirmation =
437 (snapshot.state === null &&
438 publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) ||
439 (snapshot.state?.phase === "completed" && !publishedStateByThread.has(threadId));
440 if (requiresConfirmation) {
441 const nowMs = (yield* DateTime.now).epochMilliseconds;
442 const deadline = publishConfirmDeadlines.get(threadId);
443 if (deadline === undefined) {
444 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
445 yield* Effect.logInfo("agent activity publish deferred pending confirmation", {
446 environmentId,
447 threadId,
448 reason: snapshot.reason,
449 statePhase: snapshot.state?.phase ?? null,
450 shell: describeThreadShellForAwareness(thread),
451 });
452 yield* schedulePublishConfirm(threadId);
453 return;
454 }
455 if (nowMs < deadline) {
456 return;
457 }
458 publishConfirmDeadlines.delete(threadId);
459 yield* Effect.logInfo("agent activity deferred publish confirmed", {
460 environmentId,
461 threadId,
462 reason: snapshot.reason,
463 statePhase: snapshot.state?.phase ?? null,
464 shell: describeThreadShellForAwareness(thread),
465 });
466 } else {
467 publishConfirmDeadlines.delete(threadId);
468 }
469​
470 if (snapshot.reason === "thread-not-found") {
471 yield* Effect.logDebug("publishing agent activity tombstone; thread not found", {
472 environmentId,
473 threadId,
474 });
475 } else if (snapshot.reason === "project-not-found") {
476 yield* Effect.logDebug("publishing agent activity tombstone; project not found", {
477 environmentId,
478 threadId,
479 projectId: snapshot.projectId,
480 });
481 }
482​
483 yield* publishState({
484 projectId: snapshot.projectId,
485 state: snapshot.state,
486 reason: snapshot.reason,
487 });
488 yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {
489 const nextPublishedStates = new Map(publishedStates);
490 nextPublishedStates.set(threadId, publishIdentity);
491 return nextPublishedStates;
492 });
493 });
494​
495 const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
496 publishThreadUnsafe(threadId).pipe(
497 Effect.catchCause((cause) => {
498 return Effect.logWarning("agent activity publish failed", {
499 threadId,
500 cause: Cause.pretty(cause),
501 });
502 }),
503 Effect.withSpan("AgentAwarenessRelay.publishThread"),
504 withRelayClientTracing,
505 );
506​
507 const publishActiveThreadsUnsafe = Effect.gen(function* () {
508 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
509 Effect.orElseSucceed(() => false),
510 );
511 if (!publishAgentActivity) {
512 yield* Effect.logDebug("agent activity snapshot skipped; publication disabled");
513 return false;
514 }
515 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
516 if (!relayConfig) {
517 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
518 return false;
519 }
520 const environmentId = yield* serverEnvironment.getEnvironmentId;
521 const snapshot = yield* snapshotQuery.getShellSnapshot();
522 const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({
523 environmentId,
524 projects: snapshot.projects,
525 threads: snapshot.threads,
526 });
527 if (activeThreadIds.length === 0) {
528 yield* Effect.logDebug("agent activity snapshot has no publishable threads");
529 return true;
530 }
531 yield* Effect.logInfo("publishing active agent activity snapshot", {
532 count: activeThreadIds.length,
533 });
534 yield* Effect.forEach(activeThreadIds, publishThread, { concurrency: 4, discard: true });
535 return true;
536 });
537​
538 const publishActiveThreadsOnceWhenConfigured = (logEnabledWhenReady: boolean) =>
539 Effect.gen(function* () {
540 while (!(yield* Ref.get(activeSnapshotPublishedRef))) {
541 const published = yield* publishActiveThreadsUnsafe.pipe(Effect.orElseSucceed(() => false));
542 if (published) {
543 yield* Ref.set(activeSnapshotPublishedRef, true);
544 if (logEnabledWhenReady) {
545 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
546 yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
547 relayUrl: relayConfig?.url,
548 });
549 }
550 return;
551 }
552 yield* Effect.sleep("5 seconds");
553 }
554 });
555​
556 const worker = yield* makeDrainableWorker(publishThread);
557​
558 schedulePublishConfirm = (threadId) =>
559 Effect.forkDetach(
560 Effect.sleep("5 seconds").pipe(
561 Effect.andThen(worker.enqueue(threadId)),
562 Effect.catchCause((cause) =>
563 Effect.logWarning("deferred agent activity confirmation failed", {
564 threadId,
565 cause: Cause.pretty(cause),
566 }),
567 ),
568 ),
569 ).pipe(Effect.asVoid);
570​
571 const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
572 function* () {
573 const [relayConfig, publishEnabled] = yield* Effect.all([
574 readRelayConfig.pipe(Effect.orElseSucceed(() => null)),
575 readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),
576 ]);
577 const startupState = resolveAgentActivityPublishingStartupState({
578 relayConfigured: relayConfig !== null,
579 publishEnabled,
580 });
581 switch (startupState) {
582 case "waiting-for-link":
583 yield* Effect.logInfo(
584 "agent activity publishing standby; waiting for T3 Connect link reconciliation",
585 );
586 break;
587 case "disabled":
588 yield* Effect.logInfo("agent activity publishing disabled by T3 Connect configuration");
589 break;
590 case "enabled":
591 yield* Effect.logInfo("agent activity publishing enabled", {
592 relayUrl: relayConfig?.url,
593 });
594 break;
595 }
596 yield* Effect.forkScoped(
597 Effect.sleep("1 second").pipe(
598 Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")),
599 ),
600 );
601 yield* Effect.forkScoped(
602 Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
603 const threadId = eventThreadId(event);
604 if (threadId === null) {
605 return Effect.logDebug("agent activity publishing ignored event without thread id", {
606 eventType: event.type,
607 });
608 }
609 if (!shouldPublishAgentAwarenessEvent(event)) {
610 return Effect.logDebug(
611 "agent activity publishing ignored event without activity changes",
612 {
613 eventType: event.type,
614 threadId,
615 },
616 );
617 }
618 return Effect.logDebug("agent activity publishing queued thread publish", {
619 eventType: event.type,
620 threadId,
621 }).pipe(Effect.andThen(worker.enqueue(threadId)));
622 }),
623 );
624 },
625 );
626​
627 return AgentAwarenessRelay.of({
628 publishThread,
629 start,
630 });
631});
632​
633export const layer = Layer.effect(AgentAwarenessRelay, make);