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