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

AgentAwarenessRelay.ts

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