Open History to see the last commit
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 Fiber from "effect/Fiber";
27import * as Layer from "effect/Layer";
28import * as Option from "effect/Option";
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 ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
48import * as ProjectService from "../project/ProjectService.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 readonly drain: Effect.Effect<void>;
56 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
57 }
58>()("t3/relay/AgentAwarenessRelay") {}
59
60export function eventThreadId(event: OrchestrationV2DomainEvent): ThreadId {
61 return event.threadId;
62}
63
64export function shouldPublishAgentAwarenessEvent(
65 event: Pick<OrchestrationV2DomainEvent, "type">,
66): boolean {
67 // projectThreadAwarenessV2 reads thread metadata, run status, and pending requests.
68 // Message bodies and tool progress cannot change the published activity.
69 switch (event.type) {
70 case "thread.created":
71 case "thread.archived":
72 case "thread.unarchived":
73 case "thread.deleted":
74 case "thread.metadata-updated":
75 case "thread.model-selection-updated":
76 case "thread.provider-switched":
77 case "run.created":
78 case "run.updated":
79 case "runtime-request.updated":
80 return true;
81 case "thread.settled":
82 case "thread.unsettled":
83 case "thread.snoozed":
84 case "thread.unsnoozed":
85 case "thread.pinned":
86 case "thread.unpinned":
87 case "thread.pin-reordered":
88 case "thread.visited":
89 case "thread.marked-unread":
90 case "thread.runtime-mode-updated":
91 case "thread.interaction-mode-updated":
92 case "run-attempt.created":
93 case "run-attempt.updated":
94 case "node.updated":
95 case "subagent.updated":
96 case "provider-session.attached":
97 case "provider-session.updated":
98 case "provider-session.detached":
99 case "provider-thread.updated":
100 case "provider-turn.updated":
101 case "message.updated":
102 case "turn-item.updated":
103 case "plan.updated":
104 case "checkpoint-scope.created":
105 case "checkpoint.captured":
106 case "checkpoint.rollback-requested":
107 case "context-handoff.updated":
108 case "context-transfer.created":
109 case "context-transfer.updated":
110 return false;
111 }
112}
113
114export const makeAgentAwarenessPublishWorker = Effect.fnUntraced(function* <R>(
115 publish: (threadId: ThreadId) => Effect.Effect<void, never, R>,
116) {
117 const queued = new Set<ThreadId>();
118 const worker = yield* makeDrainableWorker((threadId: ThreadId) =>
119 Effect.sync(() => queued.delete(threadId)).pipe(Effect.andThen(publish(threadId))),
120 );
121 const enqueue = (threadId: ThreadId) =>
122 Effect.suspend(() => {
123 if (queued.has(threadId)) return Effect.void;
124 // Removing the ID when processing starts allows one new queue entry
125 // for updates received while the current snapshot is being published.
126 queued.add(threadId);
127 return worker.enqueue(threadId);
128 }).pipe(Effect.uninterruptible);
129 return { enqueue, drain: worker.drain };
130});
131
132export function agentAwarenessPublishIdentity(state: RelayAgentActivityState | null): string {
133 if (state === null) {
134 return "null";
135 }
136 const { updatedAt: _updatedAt, ...meaningfulState } = state;
137 return JSON.stringify(meaningfulState);
138}
139
140export function isAgentActivityPublishingEnabled(value: string | null): boolean {
141 return isAgentActivityPublishingEnabledValue(value);
142}
143
144export function resolveAgentActivityPublishingStartupState(input: {
145 readonly relayConfigured: boolean;
146 readonly publishEnabled: boolean;
147}): "waiting-for-link" | "disabled" | "enabled" {
148 if (!input.relayConfigured) {
149 return "waiting-for-link";
150 }
151 return input.publishEnabled ? "enabled" : "disabled";
152}
153
154const RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH = 160;
155const REDACTED_RELAY_AGENT_FAILURE_DETAIL = "The agent run failed.";
156const RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000] as const;
157
158export function sanitizeRelayAgentActivityState(
159 state: RelayAgentActivityState | null,
160): RelayAgentActivityState | null {
161 if (state === null) {
162 return null;
163 }
164 const { detail: _detail, ...rest } = state;
165 const detail = (state.phase === "failed" ? REDACTED_RELAY_AGENT_FAILURE_DETAIL : state.detail)
166 ?.trim()
167 .slice(0, RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH)
168 .trim();
169 return detail ? { ...rest, detail } : rest;
170}
171
172function relayEnvironmentClient(token: string) {
173 return HttpClient.mapRequest(HttpClientRequest.setHeader("authorization", `Bearer ${token}`));
174}
175
176function deliveryStats(
177 deliveries: ReadonlyArray<{
178 readonly ok: boolean;
179 readonly queued?: boolean | undefined;
180 readonly kind: string;
181 readonly apnsStatus?: number | null;
182 readonly apnsReason?: string | null;
183 }>,
184) {
185 let queued = 0;
186 let successful = 0;
187 let failed = 0;
188 const failedReasons: string[] = [];
189 const kinds = new Set<string>();
190
191 for (const delivery of deliveries) {
192 kinds.add(delivery.kind);
193 if (delivery.queued) {
194 queued += 1;
195 continue;
196 }
197 if (delivery.ok) {
198 successful += 1;
199 continue;
200 }
201 failed += 1;
202 failedReasons.push(`${delivery.apnsStatus ?? "transport"}:${delivery.apnsReason ?? "unknown"}`);
203 }
204
205 return {
206 total: deliveries.length,
207 queued,
208 successful,
209 failed,
210 kinds: [...kinds],
211 failedReasons,
212 };
213}
214
215export function signRelayAgentActivityPublishProof(input: {
216 readonly privateKey: string;
217 readonly payload: RelayAgentActivityPublishProofPayload;
218}) {
219 return signRelayJwt({
220 privateKey: input.privateKey,
221 typ: RELAY_ACTIVITY_PUBLISH_TYP,
222 payload: input.payload,
223 });
224}
225
226const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
227 readonly privateKey: string;
228 readonly relayIssuer: string;
229 readonly environmentId: string;
230 readonly threadId: ThreadId;
231 readonly state: RelayAgentActivityState | null;
232 readonly jti: string;
233}) {
234 const now = yield* DateTime.now;
235 const expiresAt = DateTime.add(now, { minutes: 5 });
236 const payload = {
237 iss: `t3-env:${input.environmentId}`,
238 aud: normalizeRelayIssuer(input.relayIssuer),
239 sub: input.environmentId,
240 jti: input.jti,
241 iat: Math.floor(now.epochMilliseconds / 1_000),
242 exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
243 environmentId: input.environmentId as RelayAgentActivityPublishProofPayload["environmentId"],
244 threadId: input.threadId,
245 state: input.state,
246 } satisfies RelayAgentActivityPublishProofPayload;
247 return yield* signRelayAgentActivityPublishProof({ privateKey: input.privateKey, payload });
248});
249
250// Compact, log-safe view of the fields the awareness phase ladder reads.
251export function describeThreadShellForAwareness(
252 thread: Option.Option<OrchestrationV2ThreadShell>,
253): Record<string, unknown> {
254 if (Option.isNone(thread)) {
255 return { found: false };
256 }
257 const shell = thread.value;
258 return {
259 found: true,
260 status: shell.status,
261 activityRunStatus: shell.activityRunStatus ?? null,
262 activeRunId: shell.activeRunId ?? null,
263 latestRunId: shell.latestRunId ?? null,
264 pendingRuntimeRequestKind: shell.pendingRuntimeRequest?.kind ?? null,
265 hasActionableProposedPlan: shell.hasActionableProposedPlan,
266 };
267}
268
269export function resolveAgentAwarenessRelayPublishSnapshot(input: {
270 readonly environmentId: EnvironmentId;
271 readonly threadId: ThreadId;
272 readonly thread: Option.Option<OrchestrationV2ThreadShell>;
273 readonly project: Option.Option<Project>;
274}): {
275 readonly projectId: string | null;
276 readonly state: RelayAgentActivityState | null;
277 readonly reason: "snapshot" | "thread-not-found" | "project-not-found";
278} {
279 if (Option.isNone(input.thread)) {
280 return {
281 projectId: null,
282 state: null,
283 reason: "thread-not-found",
284 };
285 }
286 if (Option.isNone(input.project)) {
287 return {
288 projectId: input.thread.value.projectId,
289 state: null,
290 reason: "project-not-found",
291 };
292 }
293 return {
294 projectId: input.thread.value.projectId,
295 state: sanitizeRelayAgentActivityState(
296 projectThreadAwarenessV2({
297 environmentId: input.environmentId,
298 project: input.project.value,
299 thread: input.thread.value,
300 }),
301 ),
302 reason: "snapshot",
303 };
304}
305
306export function resolveAgentAwarenessRelayActiveThreadIds(input: {
307 readonly environmentId: EnvironmentId;
308 readonly projects: ReadonlyArray<Pick<Project, "id" | "title">>;
309 readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;
310}): ReadonlyArray<ThreadId> {
311 const projectById = new Map(input.projects.map((project) => [project.id, project]));
312 return input.threads
313 .filter((thread) => {
314 const project = projectById.get(thread.projectId);
315 if (!project) {
316 return false;
317 }
318 return (
319 projectThreadAwarenessV2({
320 environmentId: input.environmentId,
321 project,
322 thread,
323 }) !== null
324 );
325 })
326 .map((thread) => thread.id);
327}
328
329export const make = Effect.gen(function* () {
330 const secrets = yield* ServerSecretStore.ServerSecretStore;
331 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
332 const threads = yield* ThreadManagement.ThreadManagementService;
333 const projects = yield* ProjectService.ProjectService;
334 const crypto = yield* Crypto.Crypto;
335 const scope = yield* Effect.scope;
336 const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
337 const activeSnapshotPublishedRef = yield* Ref.make(false);
338 const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());
339
340 const readSecretString = (name: string) =>
341 secrets
342 .get(name)
343 .pipe(
344 Effect.map((bytes) =>
345 Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,
346 ),
347 );
348
349 const readRelayConfig = Effect.gen(function* () {
350 const [url, issuer, environmentCredential] = yield* Effect.all([
351 readSecretString(RELAY_URL_SECRET),
352 readSecretString(RELAY_ISSUER_SECRET),
353 readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
354 ]);
355 return url && environmentCredential
356 ? { url, issuer: issuer ?? url, environmentCredential }
357 : null;
358 });
359
360 const readPublishAgentActivityEnabled = readSecretString(PUBLISH_AGENT_ACTIVITY_SECRET).pipe(
361 Effect.map(isAgentActivityPublishingEnabled),
362 );
363
364 const makeRelayClient = (relayConfig: {
365 readonly url: string;
366 readonly environmentCredential: string;
367 }) =>
368 HttpApiClient.make(RelayApi, {
369 baseUrl: relayConfig.url,
370 transformClient: relayEnvironmentClient(relayConfig.environmentCredential),
371 }).pipe(Effect.provide(FetchHttpClient.layer));
372
373 let cachedRelayClient: Effect.Success<ReturnType<typeof makeRelayClient>> | undefined;
374 let publishedRelayConfig: NonNullable<Effect.Success<typeof readRelayConfig>> | undefined;
375
376 // Deadlines for publishes that need confirmation (tombstones and
377 // first-state completions). The confirming publish is re-enqueued through
378 // the same drainable worker as every other publish, so a confirmed
379 // tombstone can never race an in-flight live update; a recovered state
380 // clears the deadline. Assigned after the worker exists.
381 const publishConfirmDeadlines = new Map<ThreadId, number>();
382 let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
383 const publishRetries = new Map<
384 ThreadId,
385 { readonly attempts: number; timer: Fiber.Fiber<void> | undefined }
386 >();
387 const cancelPublishRetry = Effect.fnUntraced(function* (threadId: ThreadId) {
388 const retry = publishRetries.get(threadId);
389 publishRetries.delete(threadId);
390 if (retry?.timer !== undefined) yield* Fiber.interrupt(retry.timer);
391 });
392 const cancelPublishRetries = Effect.suspend(() =>
393 Effect.forEach([...publishRetries.keys()], cancelPublishRetry, { discard: true }),
394 );
395 let schedulePublishRetry: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
396 const resetPublishedConnection = Effect.gen(function* () {
397 publishedRelayConfig = undefined;
398 cachedRelayClient = undefined;
399 publishConfirmDeadlines.clear();
400 yield* Ref.set(publishedStateByThreadRef, new Map());
401 });
402
403 const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) {
404 const publishAgentActivity = yield* readPublishAgentActivityEnabled;
405 if (!publishAgentActivity) {
406 yield* cancelPublishRetries;
407 yield* resetPublishedConnection;
408 yield* Effect.logDebug("agent activity publish skipped; publication disabled", {
409 threadId,
410 });
411 return;
412 }
413 const relayConfig = yield* readRelayConfig;
414 if (!relayConfig) {
415 yield* cancelPublishRetries;
416 yield* resetPublishedConnection;
417 yield* Effect.logDebug("agent activity publish skipped; relay link credentials unavailable", {
418 threadId,
419 });
420 return;
421 }
422 if (
423 publishedRelayConfig?.url !== relayConfig.url ||
424 publishedRelayConfig.issuer !== relayConfig.issuer ||
425 publishedRelayConfig.environmentCredential !== relayConfig.environmentCredential
426 ) {
427 yield* resetPublishedConnection;
428 publishedRelayConfig = relayConfig;
429 }
430 const environmentId = yield* serverEnvironment.getEnvironmentId;
431
432 const publishState = (input: {
433 readonly projectId: string | null;
434 readonly state: RelayAgentActivityState | null;
435 readonly reason: string;
436 }) =>
437 Effect.gen(function* () {
438 if (cachedRelayClient === undefined) {
439 cachedRelayClient = yield* makeRelayClient(relayConfig);
440 }
441 const relayClient = cachedRelayClient;
442 const proof = yield* makePublishProof({
443 privateKey: cloudLinkKeyPair.privateKey,
444 relayIssuer: relayConfig.issuer,
445 environmentId,
446 threadId,
447 state: input.state,
448 jti: yield* crypto.randomUUIDv4,
449 });
450
451 yield* Effect.logInfo("publishing agent activity for thread", {
452 environmentId,
453 threadId,
454 projectId: input.projectId,
455 statePhase: input.state?.phase ?? null,
456 hasState: input.state !== null,
457 reason: input.reason,
458 });
459
460 const response = yield* relayClient.server.publishAgentActivity({
461 params: {
462 environmentId,
463 threadId,
464 },
465 payload: {
466 state: input.state,
467 proof,
468 },
469 });
470
471 yield* Effect.logInfo("agent activity publish completed", {
472 environmentId,
473 threadId,
474 ok: response.ok,
475 deliveries: deliveryStats(response.deliveries),
476 });
477 });
478
479 // Per-thread shell read: this publish runs for every activity-relevant
480 // domain event, so materializing the full shell here would make the cost
481 // of one thread's activity proportional to how many threads exist.
482 const threadShell = yield* threads.getThreadShell(threadId);
483 const thread =
484 threadShell === null || threadShell.archivedAt !== null
485 ? Option.none<OrchestrationV2ThreadShell>()
486 : Option.some(threadShell);
487 const project = Option.isSome(thread)
488 ? yield* projects.getById(thread.value.projectId)
489 : Option.none<Project>();
490 const snapshot = resolveAgentAwarenessRelayPublishSnapshot({
491 environmentId,
492 threadId,
493 thread,
494 project,
495 });
496 const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);
497 const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);
498 if (publishedStateByThread.get(threadId) === publishIdentity) {
499 // The projection is back at (or never left) the last published state, so
500 // any pending deferred confirmation is moot. Leaving the deadline in
501 // place would let a much later transient null find it already expired
502 // and publish a tombstone immediately, skipping the deferral window.
503 publishConfirmDeadlines.delete(threadId);
504 yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", {
505 environmentId,
506 threadId,
507 reason: snapshot.reason,
508 });
509 return;
510 }
511
512 // Two projections need confirmation before publishing, because both can
513 // appear transiently while the projector is mid-write and publishing them
514 // immediately is destructive or noisy:
515 // - null (tombstone) while the previous published state was live: deletes
516 // the thread from every armed card mid-conversation.
517 // - completed as the thread's FIRST published state: sessions boot at
518 // "ready" before their first turn, which projects as completed for an
519 // instant and sends a spurious Done notification at thread birth.
520 // Defer, schedule a re-publish through the ordinary worker queue, and
521 // only publish if the projection still holds when it drains.
522 const requiresConfirmation =
523 (snapshot.state === null &&
524 publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) ||
525 (snapshot.state?.phase === "completed" && !publishedStateByThread.has(threadId));
526 if (requiresConfirmation) {
527 const nowMs = (yield* DateTime.now).epochMilliseconds;
528 const deadline = publishConfirmDeadlines.get(threadId);
529 if (deadline === undefined) {
530 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
531 yield* Effect.logInfo("agent activity publish deferred pending confirmation", {
532 environmentId,
533 threadId,
534 reason: snapshot.reason,
535 statePhase: snapshot.state?.phase ?? null,
536 shell: describeThreadShellForAwareness(thread),
537 });
538 yield* schedulePublishConfirm(threadId);
539 return;
540 }
541 if (nowMs < deadline) {
542 return;
543 }
544 yield* Effect.logInfo("agent activity deferred publish confirmed", {
545 environmentId,
546 threadId,
547 reason: snapshot.reason,
548 statePhase: snapshot.state?.phase ?? null,
549 shell: describeThreadShellForAwareness(thread),
550 });
551 } else {
552 publishConfirmDeadlines.delete(threadId);
553 }
554
555 if (snapshot.reason === "thread-not-found") {
556 yield* Effect.logDebug("publishing agent activity tombstone; thread not found", {
557 environmentId,
558 threadId,
559 });
560 } else if (snapshot.reason === "project-not-found") {
561 yield* Effect.logDebug("publishing agent activity tombstone; project not found", {
562 environmentId,
563 threadId,
564 projectId: snapshot.projectId,
565 });
566 }
567
568 yield* publishState({
569 projectId: snapshot.projectId,
570 state: snapshot.state,
571 reason: snapshot.reason,
572 });
573 publishConfirmDeadlines.delete(threadId);
574 yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {
575 const nextPublishedStates = new Map(publishedStates);
576 nextPublishedStates.set(threadId, publishIdentity);
577 return nextPublishedStates;
578 });
579 });
580
581 const processThreadPublish = Effect.fnUntraced(function* (threadId: ThreadId) {
582 const retry = publishRetries.get(threadId);
583 if (retry?.timer !== undefined) {
584 const timer = retry.timer;
585 retry.timer = undefined;
586 yield* Fiber.interrupt(timer);
587 }
588 yield* publishThreadUnsafe(threadId).pipe(
589 Effect.tap(() => cancelPublishRetry(threadId)),
590 Effect.catchCause((cause) => {
591 if (Cause.hasInterruptsOnly(cause)) return Effect.void;
592 return Effect.logWarning("agent activity publish failed", {
593 threadId,
594 cause: Cause.pretty(cause),
595 }).pipe(Effect.andThen(schedulePublishRetry(threadId)));
596 }),
597 Effect.withSpan("AgentAwarenessRelay.publishThread"),
598 withRelayClientTracing,
599 );
600 });
601
602 const worker = yield* makeAgentAwarenessPublishWorker(processThreadPublish);
603 const enqueueThreadPublish = (threadId: ThreadId) =>
604 cancelPublishRetry(threadId).pipe(Effect.andThen(worker.enqueue(threadId)));
605 const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
606 enqueueThreadPublish(threadId).pipe(Effect.andThen(worker.drain));
607
608 schedulePublishRetry = Effect.fnUntraced(function* (threadId: ThreadId) {
609 const attempts = publishRetries.get(threadId)?.attempts ?? 0;
610 const delayMs = RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS[attempts];
611 if (delayMs === undefined) {
612 // Keep the exhausted budget until fresh activity or a successful publish
613 // clears it; an old confirmation timer must not start another retry series.
614 yield* Effect.logWarning("agent activity publish retry budget exhausted", { threadId });
615 return;
616 }
617 const retry = {
618 attempts: attempts + 1,
619 timer: undefined as Fiber.Fiber<void> | undefined,
620 };
621 publishRetries.set(threadId, retry);
622 const timer = yield* Effect.sleep(delayMs).pipe(
623 Effect.andThen(
624 Effect.suspend(() => {
625 if (publishRetries.get(threadId) !== retry) return Effect.void;
626 retry.timer = undefined;
627 return worker.enqueue(threadId);
628 }),
629 ),
630 Effect.forkIn(scope),
631 );
632 if (publishRetries.get(threadId) !== retry) {
633 yield* Fiber.interrupt(timer);
634 } else {
635 retry.timer = timer;
636 }
637 });
638
639 const publishActiveThreadsUnsafe = Effect.gen(function* () {
640 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
641 Effect.orElseSucceed(() => false),
642 );
643 if (!publishAgentActivity) {
644 yield* Effect.logDebug("agent activity snapshot skipped; publication disabled");
645 return false;
646 }
647 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
648 if (!relayConfig) {
649 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
650 return false;
651 }
652 const environmentId = yield* serverEnvironment.getEnvironmentId;
653 const [projectSnapshot, shellSnapshot] = yield* Effect.all([
654 projects.snapshot,
655 threads.getShellSnapshot(),
656 ]);
657 const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({
658 environmentId,
659 projects: projectSnapshot.projects,
660 threads: shellSnapshot.threads,
661 });
662 if (activeThreadIds.length === 0) {
663 yield* Effect.logDebug("agent activity snapshot has no publishable threads");
664 return true;
665 }
666 yield* Effect.logInfo("publishing active agent activity snapshot", {
667 count: activeThreadIds.length,
668 });
669 yield* Effect.forEach(activeThreadIds, enqueueThreadPublish, { discard: true });
670 yield* worker.drain;
671 return true;
672 });
673
674 const publishActiveThreadsOnceWhenConfigured = (logEnabledWhenReady: boolean) =>
675 Effect.gen(function* () {
676 while (!(yield* Ref.get(activeSnapshotPublishedRef))) {
677 const published = yield* publishActiveThreadsUnsafe.pipe(Effect.orElseSucceed(() => false));
678 if (published) {
679 yield* Ref.set(activeSnapshotPublishedRef, true);
680 if (logEnabledWhenReady) {
681 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
682 yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
683 relayUrl: relayConfig?.url,
684 });
685 }
686 return;
687 }
688 yield* Effect.sleep("5 seconds");
689 }
690 });
691
692 schedulePublishConfirm = (threadId) =>
693 Effect.forkIn(
694 Effect.sleep("5 seconds").pipe(
695 Effect.andThen(worker.enqueue(threadId)),
696 Effect.catchCause((cause) =>
697 Effect.logWarning("deferred agent activity confirmation failed", {
698 threadId,
699 cause: Cause.pretty(cause),
700 }),
701 ),
702 ),
703 scope,
704 ).pipe(Effect.asVoid);
705
706 const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
707 function* () {
708 const [relayConfig, publishEnabled] = yield* Effect.all([
709 readRelayConfig.pipe(Effect.orElseSucceed(() => null)),
710 readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),
711 ]);
712 const startupState = resolveAgentActivityPublishingStartupState({
713 relayConfigured: relayConfig !== null,
714 publishEnabled,
715 });
716 switch (startupState) {
717 case "waiting-for-link":
718 yield* Effect.logInfo(
719 "agent activity publishing standby; waiting for T3 Connect link reconciliation",
720 );
721 break;
722 case "disabled":
723 yield* Effect.logInfo("agent activity publishing disabled by T3 Connect configuration");
724 break;
725 case "enabled":
726 yield* Effect.logInfo("agent activity publishing enabled", {
727 relayUrl: relayConfig?.url,
728 });
729 break;
730 }
731 yield* forkParked(
732 Effect.sleep("1 second").pipe(
733 Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")),
734 ),
735 );
736 yield* forkParked(
737 Stream.runForEach(threads.streamDomainEvents, (event) => {
738 const threadId = eventThreadId(event);
739 if (!shouldPublishAgentAwarenessEvent(event)) {
740 return Effect.void;
741 }
742 return Effect.logDebug("agent activity publishing queued thread publish", {
743 eventType: event.type,
744 threadId,
745 }).pipe(Effect.andThen(enqueueThreadPublish(threadId)));
746 }),
747 );
748 },
749 );
750
751 return AgentAwarenessRelay.of({
752 publishThread,
753 drain: worker.drain,
754 start,
755 });
756});
757
758export const layer = Layer.effect(AgentAwarenessRelay, make);