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

AgentAwarenessRelay.ts

617 lines21.5 KB

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