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 if (event.metadata.historyImport === true) {
71 return false;
72 }
73 switch (event.type) {
74 case "thread.message-sent":
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 resolveAgentActivityPublishingStartupState(input: {
109 readonly relayConfigured: boolean;
110 readonly publishEnabled: boolean;
111}): "waiting-for-link" | "disabled" | "enabled" {
112 if (!input.relayConfigured) {
113 return "waiting-for-link";
114 }
115 return input.publishEnabled ? "enabled" : "disabled";
117​
118const RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH = 160;
119const REDACTED_RELAY_AGENT_FAILURE_DETAIL = "The agent run failed.";
120​
121export function sanitizeRelayAgentActivityState(
122 state: RelayAgentActivityState | null,
123): RelayAgentActivityState | null {
124 if (state === null) {
125 return null;
126 }
127 const { detail: _detail, ...rest } = state;
128 const detail = (state.phase === "failed" ? REDACTED_RELAY_AGENT_FAILURE_DETAIL : state.detail)
129 ?.trim()
130 .slice(0, RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH)
131 .trim();
132 return detail ? { ...rest, detail } : rest;
134​
135function relayEnvironmentClient(token: string) {
136 return HttpClient.mapRequest(HttpClientRequest.setHeader("authorization", `Bearer ${token}`));
138​
139function deliveryStats(
140 deliveries: ReadonlyArray<{
141 readonly ok: boolean;
142 readonly queued?: boolean | undefined;
143 readonly kind: string;
144 readonly apnsStatus?: number | null;
145 readonly apnsReason?: string | null;
146 }>,
147) {
148 let queued = 0;
149 let successful = 0;
150 let failed = 0;
151 const failedReasons: string[] = [];
152 const kinds = new Set<string>();
153​
154 for (const delivery of deliveries) {
155 kinds.add(delivery.kind);
156 if (delivery.queued) {
157 queued += 1;
158 continue;
159 }
160 if (delivery.ok) {
161 successful += 1;
162 continue;
163 }
164 failed += 1;
165 failedReasons.push(`${delivery.apnsStatus ?? "transport"}:${delivery.apnsReason ?? "unknown"}`);
166 }
167​
168 return {
169 total: deliveries.length,
170 queued,
171 successful,
172 failed,
173 kinds: [...kinds],
174 failedReasons,
175 };
177​
178export function signRelayAgentActivityPublishProof(input: {
179 readonly privateKey: string;
180 readonly payload: RelayAgentActivityPublishProofPayload;
181}) {
182 return signRelayJwt({
183 privateKey: input.privateKey,
184 typ: RELAY_ACTIVITY_PUBLISH_TYP,
185 payload: input.payload,
186 });
188​
189const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
190 readonly privateKey: string;
191 readonly relayIssuer: string;
192 readonly environmentId: string;
193 readonly threadId: ThreadId;
194 readonly state: RelayAgentActivityState | null;
195 readonly jti: string;
196}) {
197 const now = yield* DateTime.now;
198 const expiresAt = DateTime.add(now, { minutes: 5 });
199 const payload = {
200 iss: `t3-env:${input.environmentId}`,
201 aud: normalizeRelayIssuer(input.relayIssuer),
202 sub: input.environmentId,
203 jti: input.jti,
204 iat: Math.floor(now.epochMilliseconds / 1_000),
205 exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
206 environmentId: input.environmentId as RelayAgentActivityPublishProofPayload["environmentId"],
207 threadId: input.threadId,
208 state: input.state,
209 } satisfies RelayAgentActivityPublishProofPayload;
210 return yield* signRelayAgentActivityPublishProof({ privateKey: input.privateKey, payload });
211});
212​
213// Compact, log-safe view of the fields the awareness phase ladder reads.
214function describeThreadShellForAwareness(
215 thread: Option.Option<OrchestrationThreadShell>,
216): Record<string, unknown> {
217 if (Option.isNone(thread)) {
218 return { found: false };
219 }
220 const shell = thread.value;
221 return {
222 found: true,
223 sessionStatus: shell.session?.status ?? null,
224 sessionActiveTurnId: shell.session?.activeTurnId ?? null,
225 latestTurnId: shell.latestTurn?.turnId ?? null,
226 latestTurnState: shell.latestTurn?.state ?? null,
227 latestTurnCompletedAt: shell.latestTurn?.completedAt ?? null,
228 hasPendingApprovals: shell.hasPendingApprovals,
229 hasPendingUserInput: shell.hasPendingUserInput,
230 };
232​
233export function resolveAgentAwarenessRelayPublishSnapshot(input: {
234 readonly environmentId: EnvironmentId;
235 readonly threadId: ThreadId;
236 readonly thread: Option.Option<OrchestrationThreadShell>;
237 readonly project: Option.Option<OrchestrationProjectShell>;
238}): {
239 readonly projectId: string | null;
240 readonly state: RelayAgentActivityState | null;
241 readonly reason: "snapshot" | "thread-not-found" | "project-not-found";
242} {
243 if (Option.isNone(input.thread)) {
244 return {
245 projectId: null,
246 state: null,
247 reason: "thread-not-found",
248 };
249 }
250 if (Option.isNone(input.project)) {
251 return {
252 projectId: input.thread.value.projectId,
253 state: null,
254 reason: "project-not-found",
255 };
256 }
257 return {
258 projectId: input.thread.value.projectId,
259 state: sanitizeRelayAgentActivityState(
260 projectThreadAwareness({
261 environmentId: input.environmentId,
262 project: input.project.value,
263 thread: input.thread.value,
264 }),
265 ),
266 reason: "snapshot",
267 };
269​
270export function resolveAgentAwarenessRelayActiveThreadIds(input: {
271 readonly environmentId: EnvironmentId;
272 readonly projects: ReadonlyArray<Pick<OrchestrationProjectShell, "id" | "title">>;
273 readonly threads: ReadonlyArray<OrchestrationThreadShell>;
274}): ReadonlyArray<ThreadId> {
275 const projectById = new Map(input.projects.map((project) => [project.id, project]));
276 return input.threads
277 .filter((thread) => {
278 const project = projectById.get(thread.projectId);
279 if (!project) {
280 return false;
281 }
282 return (
283 projectThreadAwareness({
284 environmentId: input.environmentId,
285 project,
286 thread,
287 }) !== null
288 );
289 })
290 .map((thread) => thread.id);
292​
293/** @public Service construction is part of the canonical Effect module API. */
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(isAgentActivityPublishingEnabledValue),
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);