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";
47import { forkParked } from "../serverActivation.ts";
48
49export class AgentAwarenessRelay extends Context.Service<
50 AgentAwarenessRelay,
51 {
52 readonly publishThread: (threadId: ThreadId) => Effect.Effect<void>;
53 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
54 }
55>()("t3/relay/AgentAwarenessRelay") {}
56
57export function eventThreadId(event: OrchestrationEvent): ThreadId | null {
58 const payload = event.payload as { readonly threadId?: unknown };
59 if (typeof payload.threadId === "string") {
60 return payload.threadId as ThreadId;
61 }
62 if (event.aggregateKind === "thread" && typeof event.aggregateId === "string") {
63 return event.aggregateId as ThreadId;
64 }
65 return null;
66}
67
68export function shouldPublishAgentAwarenessEvent(event: OrchestrationEvent): boolean {
69 switch (event.type) {
70 case "thread.message-sent":
71 case "thread.turn-start-requested":
72 // These events express intent to start work, but the shell still contains
73 // the previous turn's terminal state until the provider acknowledges the
74 // new turn. Publishing that snapshot can queue a fresh "Done" alert just
75 // before the real running state arrives. Provider lifecycle events publish
76 // the authoritative starting/running state instead.
77 return false;
78 case "thread.proposed-plan-upserted":
79 case "thread.runtime-mode-set":
80 case "thread.interaction-mode-set":
81 return false;
82 case "thread.activity-appended":
83 return (
84 event.payload.activity.kind === "approval.requested" ||
85 event.payload.activity.kind === "approval.resolved" ||
86 event.payload.activity.kind === "provider.approval.respond.failed" ||
87 event.payload.activity.kind === "user-input.requested" ||
88 event.payload.activity.kind === "user-input.resolved" ||
89 event.payload.activity.kind === "runtime.error"
90 );
91 default:
92 return true;
93 }
94}
95
96export function agentAwarenessPublishIdentity(state: RelayAgentActivityState | null): string {
97 if (state === null) {
98 return "null";
99 }
100 const { updatedAt: _updatedAt, ...meaningfulState } = state;
101 return JSON.stringify(meaningfulState);
102}
103
104export function isAgentActivityPublishingEnabled(value: string | null): boolean {
105 return value === "true";
106}
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";
116}
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;
133}
134
135function relayEnvironmentClient(token: string) {
136 return HttpClient.mapRequest(HttpClientRequest.setHeader("authorization", `Bearer ${token}`));
137}
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 };
176}
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 });
187}
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.
214export function 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 };
231}
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 };
268}
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);
291}
292
293export const make = Effect.gen(function* () {
294 const secrets = yield* ServerSecretStore.ServerSecretStore;
295 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
296 const snapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
297 const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
298 const crypto = yield* Crypto.Crypto;
299 const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
300 const activeSnapshotPublishedRef = yield* Ref.make(false);
301 const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());
302
303 const readSecretString = (name: string) =>
304 secrets
305 .get(name)
306 .pipe(
307 Effect.map((bytes) =>
308 Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,
309 ),
310 );
311
312 const readRelayConfig = Effect.gen(function* () {
313 const [url, issuer, environmentCredential] = yield* Effect.all([
314 readSecretString(RELAY_URL_SECRET),
315 readSecretString(RELAY_ISSUER_SECRET),
316 readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
317 ]);
318 return url && environmentCredential
319 ? { url, issuer: issuer ?? url, environmentCredential }
320 : null;
321 });
322
323 const readPublishAgentActivityEnabled = readSecretString(PUBLISH_AGENT_ACTIVITY_SECRET).pipe(
324 Effect.map(isAgentActivityPublishingEnabled),
325 );
326
327 const makeRelayClient = (relayConfig: {
328 readonly url: string;
329 readonly environmentCredential: string;
330 }) =>
331 HttpApiClient.make(RelayApi, {
332 baseUrl: relayConfig.url,
333 transformClient: relayEnvironmentClient(relayConfig.environmentCredential),
334 }).pipe(Effect.provide(FetchHttpClient.layer));
335
336 // Deadlines for publishes that need confirmation (tombstones and
337 // first-state completions). The confirming publish is re-enqueued through
338 // the same drainable worker as every other publish, so a confirmed
339 // tombstone can never race an in-flight live update; a recovered state
340 // clears the deadline. Assigned after the worker exists.
341 const publishConfirmDeadlines = new Map<ThreadId, number>();
342 let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
343
344 const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) {
345 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
346 Effect.orElseSucceed(() => false),
347 );
348 if (!publishAgentActivity) {
349 yield* Effect.logDebug("agent activity publish skipped; publication disabled", {
350 threadId,
351 });
352 return;
353 }
354 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
355 if (!relayConfig) {
356 yield* Effect.logDebug("agent activity publish skipped; relay link credentials unavailable", {
357 threadId,
358 });
359 return;
360 }
361 const relayClient = yield* makeRelayClient(relayConfig);
362 const environmentId = yield* serverEnvironment.getEnvironmentId;
363
364 const publishState = (input: {
365 readonly projectId: string | null;
366 readonly state: RelayAgentActivityState | null;
367 readonly reason: string;
368 }) =>
369 Effect.gen(function* () {
370 const proof = yield* makePublishProof({
371 privateKey: cloudLinkKeyPair.privateKey,
372 relayIssuer: relayConfig.issuer,
373 environmentId,
374 threadId,
375 state: input.state,
376 jti: yield* crypto.randomUUIDv4,
377 });
378
379 yield* Effect.logInfo("publishing agent activity for thread", {
380 environmentId,
381 threadId,
382 projectId: input.projectId,
383 statePhase: input.state?.phase ?? null,
384 hasState: input.state !== null,
385 reason: input.reason,
386 });
387
388 const response = yield* relayClient.server.publishAgentActivity({
389 params: {
390 environmentId,
391 threadId,
392 },
393 payload: {
394 state: input.state,
395 proof,
396 },
397 });
398
399 yield* Effect.logInfo("agent activity publish completed", {
400 environmentId,
401 threadId,
402 ok: response.ok,
403 deliveries: deliveryStats(response.deliveries),
404 });
405 });
406
407 const thread = yield* snapshotQuery.getThreadShellById(threadId);
408 const project = Option.isSome(thread)
409 ? yield* snapshotQuery.getProjectShellById(thread.value.projectId)
410 : Option.none<OrchestrationProjectShell>();
411 const snapshot = resolveAgentAwarenessRelayPublishSnapshot({
412 environmentId,
413 threadId,
414 thread,
415 project,
416 });
417 const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);
418 const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);
419 if (publishedStateByThread.get(threadId) === publishIdentity) {
420 // The projection is back at (or never left) the last published state, so
421 // any pending deferred confirmation is moot. Leaving the deadline in
422 // place would let a much later transient null find it already expired
423 // and publish a tombstone immediately, skipping the deferral window.
424 publishConfirmDeadlines.delete(threadId);
425 yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", {
426 environmentId,
427 threadId,
428 reason: snapshot.reason,
429 });
430 return;
431 }
432
433 // Two projections need confirmation before publishing, because both can
434 // appear transiently while the projector is mid-write and publishing them
435 // immediately is destructive or noisy:
436 // - null (tombstone) while the previous published state was live: deletes
437 // the thread from every armed card mid-conversation.
438 // - completed as the thread's FIRST published state: sessions boot at
439 // "ready" before their first turn, which projects as completed for an
440 // instant and sends a spurious Done notification at thread birth.
441 // Defer, schedule a re-publish through the ordinary worker queue, and
442 // only publish if the projection still holds when it drains.
443 const requiresConfirmation =
444 (snapshot.state === null &&
445 publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) ||
446 (snapshot.state?.phase === "completed" && !publishedStateByThread.has(threadId));
447 if (requiresConfirmation) {
448 const nowMs = (yield* DateTime.now).epochMilliseconds;
449 const deadline = publishConfirmDeadlines.get(threadId);
450 if (deadline === undefined) {
451 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
452 yield* Effect.logInfo("agent activity publish deferred pending confirmation", {
453 environmentId,
454 threadId,
455 reason: snapshot.reason,
456 statePhase: snapshot.state?.phase ?? null,
457 shell: describeThreadShellForAwareness(thread),
458 });
459 yield* schedulePublishConfirm(threadId);
460 return;
461 }
462 if (nowMs < deadline) {
463 return;
464 }
465 publishConfirmDeadlines.delete(threadId);
466 yield* Effect.logInfo("agent activity deferred publish confirmed", {
467 environmentId,
468 threadId,
469 reason: snapshot.reason,
470 statePhase: snapshot.state?.phase ?? null,
471 shell: describeThreadShellForAwareness(thread),
472 });
473 } else {
474 publishConfirmDeadlines.delete(threadId);
475 }
476
477 if (snapshot.reason === "thread-not-found") {
478 yield* Effect.logDebug("publishing agent activity tombstone; thread not found", {
479 environmentId,
480 threadId,
481 });
482 } else if (snapshot.reason === "project-not-found") {
483 yield* Effect.logDebug("publishing agent activity tombstone; project not found", {
484 environmentId,
485 threadId,
486 projectId: snapshot.projectId,
487 });
488 }
489
490 yield* publishState({
491 projectId: snapshot.projectId,
492 state: snapshot.state,
493 reason: snapshot.reason,
494 });
495 yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {
496 const nextPublishedStates = new Map(publishedStates);
497 nextPublishedStates.set(threadId, publishIdentity);
498 return nextPublishedStates;
499 });
500 });
501
502 const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
503 publishThreadUnsafe(threadId).pipe(
504 Effect.catchCause((cause) => {
505 return Effect.logWarning("agent activity publish failed", {
506 threadId,
507 cause: Cause.pretty(cause),
508 });
509 }),
510 Effect.withSpan("AgentAwarenessRelay.publishThread"),
511 withRelayClientTracing,
512 );
513
514 const publishActiveThreadsUnsafe = Effect.gen(function* () {
515 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
516 Effect.orElseSucceed(() => false),
517 );
518 if (!publishAgentActivity) {
519 yield* Effect.logDebug("agent activity snapshot skipped; publication disabled");
520 return false;
521 }
522 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
523 if (!relayConfig) {
524 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
525 return false;
526 }
527 const environmentId = yield* serverEnvironment.getEnvironmentId;
528 const snapshot = yield* snapshotQuery.getShellSnapshot();
529 const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({
530 environmentId,
531 projects: snapshot.projects,
532 threads: snapshot.threads,
533 });
534 if (activeThreadIds.length === 0) {
535 yield* Effect.logDebug("agent activity snapshot has no publishable threads");
536 return true;
537 }
538 yield* Effect.logInfo("publishing active agent activity snapshot", {
539 count: activeThreadIds.length,
540 });
541 yield* Effect.forEach(activeThreadIds, publishThread, { concurrency: 4, discard: true });
542 return true;
543 });
544
545 const publishActiveThreadsOnceWhenConfigured = (logEnabledWhenReady: boolean) =>
546 Effect.gen(function* () {
547 while (!(yield* Ref.get(activeSnapshotPublishedRef))) {
548 const published = yield* publishActiveThreadsUnsafe.pipe(Effect.orElseSucceed(() => false));
549 if (published) {
550 yield* Ref.set(activeSnapshotPublishedRef, true);
551 if (logEnabledWhenReady) {
552 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
553 yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
554 relayUrl: relayConfig?.url,
555 });
556 }
557 return;
558 }
559 yield* Effect.sleep("5 seconds");
560 }
561 });
562
563 const worker = yield* makeDrainableWorker(publishThread);
564
565 schedulePublishConfirm = (threadId) =>
566 Effect.forkDetach(
567 Effect.sleep("5 seconds").pipe(
568 Effect.andThen(worker.enqueue(threadId)),
569 Effect.catchCause((cause) =>
570 Effect.logWarning("deferred agent activity confirmation failed", {
571 threadId,
572 cause: Cause.pretty(cause),
573 }),
574 ),
575 ),
576 ).pipe(Effect.asVoid);
577
578 const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
579 function* () {
580 const [relayConfig, publishEnabled] = yield* Effect.all([
581 readRelayConfig.pipe(Effect.orElseSucceed(() => null)),
582 readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),
583 ]);
584 const startupState = resolveAgentActivityPublishingStartupState({
585 relayConfigured: relayConfig !== null,
586 publishEnabled,
587 });
588 switch (startupState) {
589 case "waiting-for-link":
590 yield* Effect.logInfo(
591 "agent activity publishing standby; waiting for T3 Connect link reconciliation",
592 );
593 break;
594 case "disabled":
595 yield* Effect.logInfo("agent activity publishing disabled by T3 Connect configuration");
596 break;
597 case "enabled":
598 yield* Effect.logInfo("agent activity publishing enabled", {
599 relayUrl: relayConfig?.url,
600 });
601 break;
602 }
603 yield* forkParked(
604 Effect.sleep("1 second").pipe(
605 Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")),
606 ),
607 );
608 yield* forkParked(
609 Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
610 const threadId = eventThreadId(event);
611 if (threadId === null) {
612 return Effect.logDebug("agent activity publishing ignored event without thread id", {
613 eventType: event.type,
614 });
615 }
616 if (!shouldPublishAgentAwarenessEvent(event)) {
617 return Effect.logDebug(
618 "agent activity publishing ignored event without activity changes",
619 {
620 eventType: event.type,
621 threadId,
622 },
623 );
624 }
625 return Effect.logDebug("agent activity publishing queued thread publish", {
626 eventType: event.type,
627 threadId,
628 }).pipe(Effect.andThen(worker.enqueue(threadId)));
629 }),
630 );
631 },
632 );
633
634 return AgentAwarenessRelay.of({
635 publishThread,
636 start,
637 });
638});
639
640export const layer = Layer.effect(AgentAwarenessRelay, make);