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

AgentAwarenessRelay.ts

644 lines22.7 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 isAgentActivityPublishingEnabledValue,
39 PUBLISH_AGENT_ACTIVITY_SECRET,
40 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
41 RELAY_ISSUER_SECRET,
42 RELAY_URL_SECRET,
43} from "../cloud/config.ts";
44import { getOrCreateEnvironmentKeyPairFromSecretStore } from "../cloud/environmentKeys.ts";
45import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
46import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";
47import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
48import { forkParked } from "../serverActivation.ts";
49​
50export class AgentAwarenessRelay extends Context.Service<
51 AgentAwarenessRelay,
52 {
53 readonly publishThread: (threadId: ThreadId) => Effect.Effect<void>;
54 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
55 }
56>()("t3/relay/AgentAwarenessRelay") {}
57​
58export function eventThreadId(event: OrchestrationEvent): ThreadId | null {
59 const payload = event.payload as { readonly threadId?: unknown };
60 if (typeof payload.threadId === "string") {
61 return payload.threadId as ThreadId;
62 }
63 if (event.aggregateKind === "thread" && typeof event.aggregateId === "string") {
64 return event.aggregateId as ThreadId;
65 }
66 return null;
68​
69export function shouldPublishAgentAwarenessEvent(event: OrchestrationEvent): boolean {
70 switch (event.type) {
71 case "thread.message-sent":
72 case "thread.turn-queued":
73 case "thread.queued-turn-dispatched":
74 case "thread.queued-turn-cancelled":
75 case "thread.turn-start-requested":
76 // These events express intent to start work, but the shell still contains
77 // the previous turn's terminal state until the provider acknowledges the
78 // new turn. Publishing that snapshot can queue a fresh "Done" alert just
79 // before the real running state arrives. Provider lifecycle events publish
80 // the authoritative starting/running state instead.
81 return false;
82 case "thread.proposed-plan-upserted":
83 case "thread.runtime-mode-set":
84 case "thread.interaction-mode-set":
85 return false;
86 case "thread.activity-appended":
87 return (
88 event.payload.activity.kind === "approval.requested" ||
89 event.payload.activity.kind === "approval.resolved" ||
90 event.payload.activity.kind === "provider.approval.respond.failed" ||
91 event.payload.activity.kind === "user-input.requested" ||
92 event.payload.activity.kind === "user-input.resolved" ||
93 event.payload.activity.kind === "runtime.error"
94 );
95 default:
96 return true;
97 }
99​
100export function agentAwarenessPublishIdentity(state: RelayAgentActivityState | null): string {
101 if (state === null) {
102 return "null";
103 }
104 const { updatedAt: _updatedAt, ...meaningfulState } = state;
105 return JSON.stringify(meaningfulState);
107​
108export function isAgentActivityPublishingEnabled(value: string | null): boolean {
109 return isAgentActivityPublishingEnabledValue(value);
111​
112export function resolveAgentActivityPublishingStartupState(input: {
113 readonly relayConfigured: boolean;
114 readonly publishEnabled: boolean;
115}): "waiting-for-link" | "disabled" | "enabled" {
116 if (!input.relayConfigured) {
117 return "waiting-for-link";
118 }
119 return input.publishEnabled ? "enabled" : "disabled";
121​
122const RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH = 160;
123const REDACTED_RELAY_AGENT_FAILURE_DETAIL = "The agent run failed.";
124​
125export function sanitizeRelayAgentActivityState(
126 state: RelayAgentActivityState | null,
127): RelayAgentActivityState | null {
128 if (state === null) {
129 return null;
130 }
131 const { detail: _detail, ...rest } = state;
132 const detail = (state.phase === "failed" ? REDACTED_RELAY_AGENT_FAILURE_DETAIL : state.detail)
133 ?.trim()
134 .slice(0, RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH)
135 .trim();
136 return detail ? { ...rest, detail } : rest;
138​
139function relayEnvironmentClient(token: string) {
140 return HttpClient.mapRequest(HttpClientRequest.setHeader("authorization", `Bearer ${token}`));
142​
143function deliveryStats(
144 deliveries: ReadonlyArray<{
145 readonly ok: boolean;
146 readonly queued?: boolean | undefined;
147 readonly kind: string;
148 readonly apnsStatus?: number | null;
149 readonly apnsReason?: string | null;
150 }>,
151) {
152 let queued = 0;
153 let successful = 0;
154 let failed = 0;
155 const failedReasons: string[] = [];
156 const kinds = new Set<string>();
157​
158 for (const delivery of deliveries) {
159 kinds.add(delivery.kind);
160 if (delivery.queued) {
161 queued += 1;
162 continue;
163 }
164 if (delivery.ok) {
165 successful += 1;
166 continue;
167 }
168 failed += 1;
169 failedReasons.push(`${delivery.apnsStatus ?? "transport"}:${delivery.apnsReason ?? "unknown"}`);
170 }
171​
172 return {
173 total: deliveries.length,
174 queued,
175 successful,
176 failed,
177 kinds: [...kinds],
178 failedReasons,
179 };
181​
182export function signRelayAgentActivityPublishProof(input: {
183 readonly privateKey: string;
184 readonly payload: RelayAgentActivityPublishProofPayload;
185}) {
186 return signRelayJwt({
187 privateKey: input.privateKey,
188 typ: RELAY_ACTIVITY_PUBLISH_TYP,
189 payload: input.payload,
190 });
192​
193const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
194 readonly privateKey: string;
195 readonly relayIssuer: string;
196 readonly environmentId: string;
197 readonly threadId: ThreadId;
198 readonly state: RelayAgentActivityState | null;
199 readonly jti: string;
200}) {
201 const now = yield* DateTime.now;
202 const expiresAt = DateTime.add(now, { minutes: 5 });
203 const payload = {
204 iss: `t3-env:${input.environmentId}`,
205 aud: normalizeRelayIssuer(input.relayIssuer),
206 sub: input.environmentId,
207 jti: input.jti,
208 iat: Math.floor(now.epochMilliseconds / 1_000),
209 exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
210 environmentId: input.environmentId as RelayAgentActivityPublishProofPayload["environmentId"],
211 threadId: input.threadId,
212 state: input.state,
213 } satisfies RelayAgentActivityPublishProofPayload;
214 return yield* signRelayAgentActivityPublishProof({ privateKey: input.privateKey, payload });
215});
216​
217// Compact, log-safe view of the fields the awareness phase ladder reads.
218export function describeThreadShellForAwareness(
219 thread: Option.Option<OrchestrationThreadShell>,
220): Record<string, unknown> {
221 if (Option.isNone(thread)) {
222 return { found: false };
223 }
224 const shell = thread.value;
225 return {
226 found: true,
227 sessionStatus: shell.session?.status ?? null,
228 sessionActiveTurnId: shell.session?.activeTurnId ?? null,
229 latestTurnId: shell.latestTurn?.turnId ?? null,
230 latestTurnState: shell.latestTurn?.state ?? null,
231 latestTurnCompletedAt: shell.latestTurn?.completedAt ?? null,
232 hasPendingApprovals: shell.hasPendingApprovals,
233 hasPendingUserInput: shell.hasPendingUserInput,
234 };
236​
237export function resolveAgentAwarenessRelayPublishSnapshot(input: {
238 readonly environmentId: EnvironmentId;
239 readonly threadId: ThreadId;
240 readonly thread: Option.Option<OrchestrationThreadShell>;
241 readonly project: Option.Option<OrchestrationProjectShell>;
242}): {
243 readonly projectId: string | null;
244 readonly state: RelayAgentActivityState | null;
245 readonly reason: "snapshot" | "thread-not-found" | "project-not-found";
246} {
247 if (Option.isNone(input.thread)) {
248 return {
249 projectId: null,
250 state: null,
251 reason: "thread-not-found",
252 };
253 }
254 if (Option.isNone(input.project)) {
255 return {
256 projectId: input.thread.value.projectId,
257 state: null,
258 reason: "project-not-found",
259 };
260 }
261 return {
262 projectId: input.thread.value.projectId,
263 state: sanitizeRelayAgentActivityState(
264 projectThreadAwareness({
265 environmentId: input.environmentId,
266 project: input.project.value,
267 thread: input.thread.value,
268 }),
269 ),
270 reason: "snapshot",
271 };
273​
274export function resolveAgentAwarenessRelayActiveThreadIds(input: {
275 readonly environmentId: EnvironmentId;
276 readonly projects: ReadonlyArray<Pick<OrchestrationProjectShell, "id" | "title">>;
277 readonly threads: ReadonlyArray<OrchestrationThreadShell>;
278}): ReadonlyArray<ThreadId> {
279 const projectById = new Map(input.projects.map((project) => [project.id, project]));
280 return input.threads
281 .filter((thread) => {
282 const project = projectById.get(thread.projectId);
283 if (!project) {
284 return false;
285 }
286 return (
287 projectThreadAwareness({
288 environmentId: input.environmentId,
289 project,
290 thread,
291 }) !== null
292 );
293 })
294 .map((thread) => thread.id);
296​
297export const make = Effect.gen(function* () {
298 const secrets = yield* ServerSecretStore.ServerSecretStore;
299 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
300 const snapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
301 const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
302 const crypto = yield* Crypto.Crypto;
303 const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
304 const activeSnapshotPublishedRef = yield* Ref.make(false);
305 const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());
306​
307 const readSecretString = (name: string) =>
308 secrets
309 .get(name)
310 .pipe(
311 Effect.map((bytes) =>
312 Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,
313 ),
314 );
315​
316 const readRelayConfig = Effect.gen(function* () {
317 const [url, issuer, environmentCredential] = yield* Effect.all([
318 readSecretString(RELAY_URL_SECRET),
319 readSecretString(RELAY_ISSUER_SECRET),
320 readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
321 ]);
322 return url && environmentCredential
323 ? { url, issuer: issuer ?? url, environmentCredential }
324 : null;
325 });
326​
327 const readPublishAgentActivityEnabled = readSecretString(PUBLISH_AGENT_ACTIVITY_SECRET).pipe(
328 Effect.map(isAgentActivityPublishingEnabled),
329 );
330​
331 const makeRelayClient = (relayConfig: {
332 readonly url: string;
333 readonly environmentCredential: string;
334 }) =>
335 HttpApiClient.make(RelayApi, {
336 baseUrl: relayConfig.url,
337 transformClient: relayEnvironmentClient(relayConfig.environmentCredential),
338 }).pipe(Effect.provide(FetchHttpClient.layer));
339​
340 // Deadlines for publishes that need confirmation (tombstones and
341 // first-state completions). The confirming publish is re-enqueued through
342 // the same drainable worker as every other publish, so a confirmed
343 // tombstone can never race an in-flight live update; a recovered state
344 // clears the deadline. Assigned after the worker exists.
345 const publishConfirmDeadlines = new Map<ThreadId, number>();
346 let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
347​
348 const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) {
349 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
350 Effect.orElseSucceed(() => false),
351 );
352 if (!publishAgentActivity) {
353 yield* Effect.logDebug("agent activity publish skipped; publication disabled", {
354 threadId,
355 });
356 return;
357 }
358 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
359 if (!relayConfig) {
360 yield* Effect.logDebug("agent activity publish skipped; relay link credentials unavailable", {
361 threadId,
362 });
363 return;
364 }
365 const relayClient = yield* makeRelayClient(relayConfig);
366 const environmentId = yield* serverEnvironment.getEnvironmentId;
367​
368 const publishState = (input: {
369 readonly projectId: string | null;
370 readonly state: RelayAgentActivityState | null;
371 readonly reason: string;
372 }) =>
373 Effect.gen(function* () {
374 const proof = yield* makePublishProof({
375 privateKey: cloudLinkKeyPair.privateKey,
376 relayIssuer: relayConfig.issuer,
377 environmentId,
378 threadId,
379 state: input.state,
380 jti: yield* crypto.randomUUIDv4,
381 });
382​
383 yield* Effect.logInfo("publishing agent activity for thread", {
384 environmentId,
385 threadId,
386 projectId: input.projectId,
387 statePhase: input.state?.phase ?? null,
388 hasState: input.state !== null,
389 reason: input.reason,
390 });
391​
392 const response = yield* relayClient.server.publishAgentActivity({
393 params: {
394 environmentId,
395 threadId,
396 },
397 payload: {
398 state: input.state,
399 proof,
400 },
401 });
402​
403 yield* Effect.logInfo("agent activity publish completed", {
404 environmentId,
405 threadId,
406 ok: response.ok,
407 deliveries: deliveryStats(response.deliveries),
408 });
409 });
410​
411 const thread = yield* snapshotQuery.getThreadShellById(threadId);
412 const project = Option.isSome(thread)
413 ? yield* snapshotQuery.getProjectShellById(thread.value.projectId)
414 : Option.none<OrchestrationProjectShell>();
415 const snapshot = resolveAgentAwarenessRelayPublishSnapshot({
416 environmentId,
417 threadId,
418 thread,
419 project,
420 });
421 const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);
422 const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);
423 if (publishedStateByThread.get(threadId) === publishIdentity) {
424 // The projection is back at (or never left) the last published state, so
425 // any pending deferred confirmation is moot. Leaving the deadline in
426 // place would let a much later transient null find it already expired
427 // and publish a tombstone immediately, skipping the deferral window.
428 publishConfirmDeadlines.delete(threadId);
429 yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", {
430 environmentId,
431 threadId,
432 reason: snapshot.reason,
433 });
434 return;
435 }
436​
437 // Two projections need confirmation before publishing, because both can
438 // appear transiently while the projector is mid-write and publishing them
439 // immediately is destructive or noisy:
440 // - null (tombstone) while the previous published state was live: deletes
441 // the thread from every armed card mid-conversation.
442 // - completed as the thread's FIRST published state: sessions boot at
443 // "ready" before their first turn, which projects as completed for an
444 // instant and sends a spurious Done notification at thread birth.
445 // Defer, schedule a re-publish through the ordinary worker queue, and
446 // only publish if the projection still holds when it drains.
447 const requiresConfirmation =
448 (snapshot.state === null &&
449 publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) ||
450 (snapshot.state?.phase === "completed" && !publishedStateByThread.has(threadId));
451 if (requiresConfirmation) {
452 const nowMs = (yield* DateTime.now).epochMilliseconds;
453 const deadline = publishConfirmDeadlines.get(threadId);
454 if (deadline === undefined) {
455 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
456 yield* Effect.logInfo("agent activity publish deferred pending confirmation", {
457 environmentId,
458 threadId,
459 reason: snapshot.reason,
460 statePhase: snapshot.state?.phase ?? null,
461 shell: describeThreadShellForAwareness(thread),
462 });
463 yield* schedulePublishConfirm(threadId);
464 return;
465 }
466 if (nowMs < deadline) {
467 return;
468 }
469 publishConfirmDeadlines.delete(threadId);
470 yield* Effect.logInfo("agent activity deferred publish confirmed", {
471 environmentId,
472 threadId,
473 reason: snapshot.reason,
474 statePhase: snapshot.state?.phase ?? null,
475 shell: describeThreadShellForAwareness(thread),
476 });
477 } else {
478 publishConfirmDeadlines.delete(threadId);
479 }
480​
481 if (snapshot.reason === "thread-not-found") {
482 yield* Effect.logDebug("publishing agent activity tombstone; thread not found", {
483 environmentId,
484 threadId,
485 });
486 } else if (snapshot.reason === "project-not-found") {
487 yield* Effect.logDebug("publishing agent activity tombstone; project not found", {
488 environmentId,
489 threadId,
490 projectId: snapshot.projectId,
491 });
492 }
493​
494 yield* publishState({
495 projectId: snapshot.projectId,
496 state: snapshot.state,
497 reason: snapshot.reason,
498 });
499 yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {
500 const nextPublishedStates = new Map(publishedStates);
501 nextPublishedStates.set(threadId, publishIdentity);
502 return nextPublishedStates;
503 });
504 });
505​
506 const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
507 publishThreadUnsafe(threadId).pipe(
508 Effect.catchCause((cause) => {
509 return Effect.logWarning("agent activity publish failed", {
510 threadId,
511 cause: Cause.pretty(cause),
512 });
513 }),
514 Effect.withSpan("AgentAwarenessRelay.publishThread"),
515 withRelayClientTracing,
516 );
517​
518 const publishActiveThreadsUnsafe = Effect.gen(function* () {
519 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
520 Effect.orElseSucceed(() => false),
521 );
522 if (!publishAgentActivity) {
523 yield* Effect.logDebug("agent activity snapshot skipped; publication disabled");
524 return false;
525 }
526 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
527 if (!relayConfig) {
528 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
529 return false;
530 }
531 const environmentId = yield* serverEnvironment.getEnvironmentId;
532 const snapshot = yield* snapshotQuery.getShellSnapshot();
533 const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({
534 environmentId,
535 projects: snapshot.projects,
536 threads: snapshot.threads,
537 });
538 if (activeThreadIds.length === 0) {
539 yield* Effect.logDebug("agent activity snapshot has no publishable threads");
540 return true;
541 }
542 yield* Effect.logInfo("publishing active agent activity snapshot", {
543 count: activeThreadIds.length,
544 });
545 yield* Effect.forEach(activeThreadIds, publishThread, { concurrency: 4, discard: true });
546 return true;
547 });
548​
549 const publishActiveThreadsOnceWhenConfigured = (logEnabledWhenReady: boolean) =>
550 Effect.gen(function* () {
551 while (!(yield* Ref.get(activeSnapshotPublishedRef))) {
552 const published = yield* publishActiveThreadsUnsafe.pipe(Effect.orElseSucceed(() => false));
553 if (published) {
554 yield* Ref.set(activeSnapshotPublishedRef, true);
555 if (logEnabledWhenReady) {
556 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
557 yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
558 relayUrl: relayConfig?.url,
559 });
560 }
561 return;
562 }
563 yield* Effect.sleep("5 seconds");
564 }
565 });
566​
567 const worker = yield* makeDrainableWorker(publishThread);
568​
569 schedulePublishConfirm = (threadId) =>
570 Effect.forkDetach(
571 Effect.sleep("5 seconds").pipe(
572 Effect.andThen(worker.enqueue(threadId)),
573 Effect.catchCause((cause) =>
574 Effect.logWarning("deferred agent activity confirmation failed", {
575 threadId,
576 cause: Cause.pretty(cause),
577 }),
578 ),
579 ),
580 ).pipe(Effect.asVoid);
581​
582 const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
583 function* () {
584 const [relayConfig, publishEnabled] = yield* Effect.all([
585 readRelayConfig.pipe(Effect.orElseSucceed(() => null)),
586 readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),
587 ]);
588 const startupState = resolveAgentActivityPublishingStartupState({
589 relayConfigured: relayConfig !== null,
590 publishEnabled,
591 });
592 switch (startupState) {
593 case "waiting-for-link":
594 yield* Effect.logInfo(
595 "agent activity publishing standby; waiting for T3 Connect link reconciliation",
596 );
597 break;
598 case "disabled":
599 yield* Effect.logInfo("agent activity publishing disabled by T3 Connect configuration");
600 break;
601 case "enabled":
602 yield* Effect.logInfo("agent activity publishing enabled", {
603 relayUrl: relayConfig?.url,
604 });
605 break;
606 }
607 yield* forkParked(
608 Effect.sleep("1 second").pipe(
609 Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")),
610 ),
611 );
612 yield* forkParked(
613 Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
614 const threadId = eventThreadId(event);
615 if (threadId === null) {
616 return Effect.logDebug("agent activity publishing ignored event without thread id", {
617 eventType: event.type,
618 });
619 }
620 if (!shouldPublishAgentAwarenessEvent(event)) {
621 return Effect.logDebug(
622 "agent activity publishing ignored event without activity changes",
623 {
624 eventType: event.type,
625 threadId,
626 },
627 );
628 }
629 return Effect.logDebug("agent activity publishing queued thread publish", {
630 eventType: event.type,
631 threadId,
632 }).pipe(Effect.andThen(worker.enqueue(threadId)));
633 }),
634 );
635 },
636 );
637​
638 return AgentAwarenessRelay.of({
639 publishThread,
640 start,
641 });
642});
643​
644export const layer = Layer.effect(AgentAwarenessRelay, make);