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

AgentAwarenessRelay.ts

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