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

AgentAwarenessRelay.ts

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