Open History to see the last commit
1import type { AgentAwarenessThread } from "../orchestration-v2/ProjectionStore.ts";
2import {
3 isListedThreadLineage,
4 type EnvironmentId,
5 type OrchestrationV2DomainEvent,
6 type OrchestrationV2TurnItem,
7 type Project,
8 type ThreadId,
9} from "@t3tools/contracts";
10import {
11 RelayApi,
12 type RelayAgentActivityPublishProofPayload,
13 type RelayAgentActivityState,
14} from "@t3tools/contracts/relay";
15import { projectThreadAwarenessV2 } from "@t3tools/shared/agentAwareness";
16import { turnItemUpdateCanEndBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
17import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
18import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
19import { normalizeRelayIssuer, RELAY_ACTIVITY_PUBLISH_TYP } from "@t3tools/shared/relayJwt";
20import * as Cause from "effect/Cause";
21import * as Context from "effect/Context";
22import * as SecureRandom from "effect/crypto/SecureRandom";
23import * as DateTime from "effect/DateTime";
24import * as Effect from "effect/Effect";
25import * as Fiber from "effect/Fiber";
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/http/FetchHttpClient";
33import * as HttpClient from "effect/http/HttpClient";
34import * as HttpClientRequest from "effect/http/HttpClientRequest";
35import * as HttpApiClient from "effect/http-api/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 { EnvironmentSigningKey } 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 requestCatchUp: () => Effect.Effect<void>;
57 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
58 }
59>()("t3/relay/AgentAwarenessRelay") {}
60
61function eventThreadId(event: OrchestrationV2DomainEvent): ThreadId {
62 return event.threadId;
63}
64
65function isTurnItemPayload(
66 payload: unknown,
67): payload is Pick<OrchestrationV2TurnItem, "type" | "status"> {
68 return (
69 typeof payload === "object" && payload !== null && "type" in payload && "status" in payload
70 );
71}
72
73function shouldPublishAgentAwarenessEvent(
74 event: Pick<OrchestrationV2DomainEvent, "type"> & { readonly payload?: unknown },
75): boolean {
76 if (
77 event.type === "thread.created" &&
78 typeof event.payload === "object" &&
79 event.payload !== null &&
80 "historyOrigin" in event.payload &&
81 event.payload.historyOrigin === "v1_import"
82 ) {
83 return false;
84 }
85 switch (event.type) {
86 case "thread.created":
87 case "thread.archived":
88 case "thread.unarchived":
89 case "thread.deleted":
90 case "thread.metadata-updated":
91 case "thread.pull-request-link-updated":
92 case "thread.pull-request-synced":
93 case "thread.settled":
94 case "thread.model-selection-updated":
95 case "thread.provider-switched":
96 case "run.created":
97 case "run.updated":
98 case "runtime-request.updated":
99 case "subagent.updated":
100 case "provider-thread.updated":
101 return true;
102 // Unsettling must not re-alert a dismissed result.
103 case "thread.unsettled":
104 case "thread.guest-share-updated":
105 case "thread.snoozed":
106 case "thread.unsnoozed":
107 case "thread.auto-settle-set":
108 case "thread.pinned":
109 case "thread.unpinned":
110 case "thread.pin-reordered":
111 case "thread.active-reordered":
112 case "thread.tags-updated":
113 case "thread.visited":
114 case "thread.marked-unread":
115 case "thread.runtime-mode-updated":
116 case "thread.interaction-mode-updated":
117 case "run.background-work-cancelled":
118 case "run-attempt.created":
119 case "run-attempt.updated":
120 case "node.updated":
121 case "provider-session.attached":
122 case "provider-session.updated":
123 case "provider-session.detached":
124 case "provider-turn.updated":
125 case "turn-item.updated":
126 return isTurnItemPayload(event.payload) && turnItemUpdateCanEndBackgroundWork(event.payload);
127 case "message.updated":
128 case "plan.updated":
129 case "checkpoint-scope.created":
130 case "checkpoint.captured":
131 case "checkpoint.rollback-requested":
132 case "context-handoff.updated":
133 case "context-transfer.created":
134 case "context-transfer.updated":
135 return false;
136 }
137}
138
139export const makeAgentAwarenessPublishWorker = Effect.fnUntraced(function* <R>(
140 publish: (threadId: ThreadId) => Effect.Effect<void, never, R>,
141) {
142 const queued = new Set<ThreadId>();
143 const worker = yield* makeDrainableWorker((threadId: ThreadId) =>
144 Effect.sync(() => queued.delete(threadId)).pipe(Effect.andThen(publish(threadId))),
145 );
146 const enqueue = (threadId: ThreadId) =>
147 Effect.suspend(() => {
148 if (queued.has(threadId)) return Effect.void;
149 // Remove queued IDs when processing starts so publication can queue one later update.
150 queued.add(threadId);
151 return worker.enqueue(threadId);
152 }).pipe(Effect.uninterruptible);
153 return { enqueue, drain: worker.drain };
154});
155
156function agentAwarenessPublishIdentity(state: RelayAgentActivityState | null): string {
157 if (state === null) {
158 return "null";
159 }
160 const { updatedAt: _updatedAt, ...meaningfulState } = state;
161 return JSON.stringify(meaningfulState);
162}
163
164const CLEARED_PUBLISH_IDENTITY = agentAwarenessPublishIdentity(null);
165
166// A published tombstone stays recorded so repeats are skipped, but it is not live state.
167function hasLivePublishedState(
168 publishedStateByThread: ReadonlyMap<ThreadId, string>,
169 threadId: ThreadId,
170): boolean {
171 const identity = publishedStateByThread.get(threadId);
172 return identity !== undefined && identity !== CLEARED_PUBLISH_IDENTITY;
173}
174
175function resolveAgentActivityPublishingStartupState(input: {
176 readonly relayConfigured: boolean;
177 readonly publishEnabled: boolean;
178}): "waiting-for-link" | "disabled" | "enabled" {
179 if (!input.relayConfigured) {
180 return "waiting-for-link";
181 }
182 return input.publishEnabled ? "enabled" : "disabled";
183}
184
185const RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH = 160;
186const REDACTED_RELAY_AGENT_FAILURE_DETAIL = "The agent run failed.";
187const RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000] as const;
188
189function sanitizeRelayAgentActivityState(
190 state: RelayAgentActivityState | null,
191): RelayAgentActivityState | null {
192 if (state === null) {
193 return null;
194 }
195 const { detail: _detail, ...rest } = state;
196 const detail = (state.phase === "failed" ? REDACTED_RELAY_AGENT_FAILURE_DETAIL : state.detail)
197 ?.trim()
198 .slice(0, RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH)
199 .trim();
200 return detail ? { ...rest, detail } : rest;
201}
202
203function relayEnvironmentClient(token: string) {
204 return HttpClient.mapRequest(HttpClientRequest.setHeader("authorization", `Bearer ${token}`));
205}
206
207function deliveryStats(
208 deliveries: ReadonlyArray<{
209 readonly ok: boolean;
210 readonly queued?: boolean | undefined;
211 readonly kind: string;
212 readonly apnsStatus?: number | null;
213 readonly apnsReason?: string | null;
214 }>,
215) {
216 let queued = 0;
217 let successful = 0;
218 let failed = 0;
219 const failedReasons: string[] = [];
220 const kinds = new Set<string>();
221
222 for (const delivery of deliveries) {
223 kinds.add(delivery.kind);
224 if (delivery.queued) {
225 queued += 1;
226 continue;
227 }
228 if (delivery.ok) {
229 successful += 1;
230 continue;
231 }
232 failed += 1;
233 failedReasons.push(`${delivery.apnsStatus ?? "transport"}:${delivery.apnsReason ?? "unknown"}`);
234 }
235
236 return {
237 total: deliveries.length,
238 queued,
239 successful,
240 failed,
241 kinds: [...kinds],
242 failedReasons,
243 };
244}
245
246const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
247 readonly relayIssuer: string;
248 readonly environmentId: string;
249 readonly threadId: ThreadId;
250 readonly state: RelayAgentActivityState | null;
251 readonly jti: string;
252}) {
253 const now = yield* DateTime.now;
254 const expiresAt = DateTime.add(now, { minutes: 5 });
255 const payload = {
256 iss: `t3-env:${input.environmentId}`,
257 aud: normalizeRelayIssuer(input.relayIssuer),
258 sub: input.environmentId,
259 jti: input.jti,
260 iat: Math.floor(now.epochMilliseconds / 1_000),
261 exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
262 environmentId: input.environmentId as RelayAgentActivityPublishProofPayload["environmentId"],
263 threadId: input.threadId,
264 state: input.state,
265 } satisfies RelayAgentActivityPublishProofPayload;
266 const signingKey = yield* EnvironmentSigningKey;
267 return yield* signingKey.sign({ typ: RELAY_ACTIVITY_PUBLISH_TYP, payload });
268});
269
270function describeThreadShellForAwareness(
271 thread: Option.Option<AgentAwarenessThread>,
272): Record<string, unknown> {
273 if (Option.isNone(thread)) {
274 return { found: false };
275 }
276 const shell = thread.value;
277 return {
278 found: true,
279 status: shell.status,
280 activityRunStatus: shell.activityRunStatus ?? null,
281 activeRunId: shell.activeRunId ?? null,
282 latestRunId: shell.latestRunId ?? null,
283 pendingRuntimeRequestKind: shell.pendingRuntimeRequest?.kind ?? null,
284 hasActionableProposedPlan: shell.hasActionableProposedPlan,
285 };
286}
287
288function resolveAgentAwarenessRelayPublishSnapshot(input: {
289 readonly environmentId: EnvironmentId;
290 readonly thread: Option.Option<AgentAwarenessThread>;
291 readonly project: Option.Option<Project>;
292}): {
293 readonly projectId: string | null;
294 readonly state: RelayAgentActivityState | null;
295 readonly reason: "snapshot" | "thread-not-found" | "project-not-found";
296} {
297 if (Option.isNone(input.thread)) {
298 return {
299 projectId: null,
300 state: null,
301 reason: "thread-not-found",
302 };
303 }
304 if (Option.isNone(input.project)) {
305 return {
306 projectId: input.thread.value.projectId,
307 state: null,
308 reason: "project-not-found",
309 };
310 }
311 return {
312 projectId: input.thread.value.projectId,
313 state: sanitizeRelayAgentActivityState(
314 projectThreadAwarenessV2({
315 environmentId: input.environmentId,
316 project: input.project.value,
317 thread: input.thread.value,
318 }),
319 ),
320 reason: "snapshot",
321 };
322}
323
324function terminalWorkSinceStart(thread: AgentAwarenessThread, startedAt: number): boolean {
325 return (
326 thread.latestRunCompletedAt != null &&
327 DateTime.toEpochMillis(thread.latestRunCompletedAt) > startedAt
328 );
329}
330
331export function resolveAgentAwarenessRelayActiveThreadIds(input: {
332 readonly environmentId: EnvironmentId;
333 readonly startedAt: number;
334 readonly projects: ReadonlyArray<Pick<Project, "id" | "title">>;
335 readonly threads: ReadonlyArray<AgentAwarenessThread>;
336}): ReadonlyArray<ThreadId> {
337 const projectById = new Map(input.projects.map((project) => [project.id, project]));
338 return input.threads
339 .filter((thread) => {
340 const project = projectById.get(thread.projectId);
341 if (!project) {
342 return false;
343 }
344 const state = projectThreadAwarenessV2({
345 environmentId: input.environmentId,
346 project,
347 thread,
348 });
349 return (
350 state !== null &&
351 (state.phase !== "completed" && state.phase !== "failed"
352 ? true
353 : terminalWorkSinceStart(thread, input.startedAt))
354 );
355 })
356 .map((thread) => thread.id);
357}
358
359/** @public */
360export const make = Effect.gen(function* () {
361 const secrets = yield* ServerSecretStore.ServerSecretStore;
362 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
363 const threads = yield* ThreadManagement.ThreadManagementService;
364 const projects = yield* ProjectService.ProjectService;
365 const random = yield* SecureRandom.SecureRandom;
366 const signingKey = yield* EnvironmentSigningKey;
367 const scope = yield* Effect.scope;
368 const startedAt = (yield* DateTime.now).epochMilliseconds;
369 const catchUpRequests = yield* Queue.dropping<void>(1);
370 const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());
371
372 const readSecretString = (name: string) =>
373 secrets
374 .get(name)
375 .pipe(
376 Effect.map((bytes) =>
377 Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,
378 ),
379 );
380
381 const readRelayConfig = Effect.gen(function* () {
382 const [url, issuer, environmentCredential] = yield* Effect.all([
383 readSecretString(RELAY_URL_SECRET),
384 readSecretString(RELAY_ISSUER_SECRET),
385 readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
386 ]);
387 return url && environmentCredential
388 ? { url, issuer: issuer ?? url, environmentCredential }
389 : null;
390 });
391
392 const readPublishAgentActivityEnabled = readSecretString(PUBLISH_AGENT_ACTIVITY_SECRET).pipe(
393 Effect.map(isAgentActivityPublishingEnabledValue),
394 );
395
396 const makeRelayClient = (relayConfig: {
397 readonly url: string;
398 readonly environmentCredential: string;
399 }) =>
400 HttpApiClient.make(RelayApi, {
401 baseUrl: relayConfig.url,
402 transformClient: relayEnvironmentClient(relayConfig.environmentCredential),
403 }).pipe(Effect.provide(FetchHttpClient.layer));
404
405 let cachedRelayClient: Effect.Success<ReturnType<typeof makeRelayClient>> | undefined;
406 let publishedRelayConfig: NonNullable<Effect.Success<typeof readRelayConfig>> | undefined;
407
408 // Confirm through the same worker so tombstones cannot race live updates; recovery clears the deadline.
409 const publishConfirmDeadlines = new Map<ThreadId, number>();
410 // Threads whose confirmation holds a completion, so a thread that settles during the hold still alerts.
411 const heldCompletions = new Set<ThreadId>();
412 let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
413 const publishRetries = new Map<
414 ThreadId,
415 { readonly attempts: number; timer: Fiber.Fiber<void> | undefined }
416 >();
417 const cancelPublishRetry = Effect.fnUntraced(function* (threadId: ThreadId) {
418 const retry = publishRetries.get(threadId);
419 publishRetries.delete(threadId);
420 if (retry?.timer !== undefined) yield* Fiber.interrupt(retry.timer);
421 });
422 const cancelPublishRetries = Effect.suspend(() =>
423 Effect.forEach([...publishRetries.keys()], cancelPublishRetry, { discard: true }),
424 );
425 let schedulePublishRetry: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
426 const resetPublishedConnection = Effect.gen(function* () {
427 publishedRelayConfig = undefined;
428 cachedRelayClient = undefined;
429 publishConfirmDeadlines.clear();
430 heldCompletions.clear();
431 yield* Ref.set(publishedStateByThreadRef, new Map());
432 });
433
434 const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) {
435 const publishAgentActivity = yield* readPublishAgentActivityEnabled;
436 if (!publishAgentActivity) {
437 yield* cancelPublishRetries;
438 yield* resetPublishedConnection;
439 yield* Effect.logDebug("agent activity publish skipped; publication disabled", {
440 threadId,
441 });
442 return;
443 }
444 const relayConfig = yield* readRelayConfig;
445 if (!relayConfig) {
446 yield* cancelPublishRetries;
447 yield* resetPublishedConnection;
448 yield* Effect.logDebug("agent activity publish skipped; relay link credentials unavailable", {
449 threadId,
450 });
451 return;
452 }
453 if (
454 publishedRelayConfig?.url !== relayConfig.url ||
455 publishedRelayConfig.issuer !== relayConfig.issuer ||
456 publishedRelayConfig.environmentCredential !== relayConfig.environmentCredential
457 ) {
458 yield* resetPublishedConnection;
459 publishedRelayConfig = relayConfig;
460 }
461 const environmentId = yield* serverEnvironment.getEnvironmentId;
462
463 const publishState = Effect.fn("relay.agent_activity.publish")(function* (input: {
464 readonly projectId: string | null;
465 readonly state: RelayAgentActivityState | null;
466 readonly reason: string;
467 }) {
468 if (cachedRelayClient === undefined) {
469 cachedRelayClient = yield* makeRelayClient(relayConfig);
470 }
471 const relayClient = cachedRelayClient;
472 const proof = yield* makePublishProof({
473 relayIssuer: relayConfig.issuer,
474 environmentId,
475 threadId,
476 state: input.state,
477 jti: yield* random.uuidV4(),
478 }).pipe(Effect.provideService(EnvironmentSigningKey, signingKey));
479
480 yield* Effect.logInfo("publishing agent activity for thread", {
481 environmentId,
482 threadId,
483 projectId: input.projectId,
484 statePhase: input.state?.phase ?? null,
485 hasState: input.state !== null,
486 reason: input.reason,
487 });
488
489 const response = yield* relayClient.server
490 .publishAgentActivity({
491 params: {
492 environmentId,
493 threadId,
494 },
495 payload: {
496 state: input.state,
497 proof,
498 },
499 })
500 .pipe(Effect.timeout("10 seconds"));
501
502 yield* Effect.logInfo("agent activity publish completed", {
503 environmentId,
504 threadId,
505 ok: response.ok,
506 deliveries: deliveryStats(response.deliveries),
507 });
508 });
509
510 // Read only this thread; full shell reads would make each activity event scale with all threads.
511 const threadShell = (yield* threads.getAgentAwarenessSnapshot(threadId)).threads[0] ?? null;
512 if (
513 threadShell !== null &&
514 !isListedThreadLineage(threadShell.lineage) &&
515 !hasLivePublishedState(yield* Ref.get(publishedStateByThreadRef), threadId)
516 ) {
517 // Subagents and side chats have no relay rows to clear; per-event tombstones would needlessly redeliver user aggregates.
518 return;
519 }
520 const thread =
521 threadShell === null || threadShell.archivedAt !== null
522 ? Option.none<AgentAwarenessThread>()
523 : Option.some(threadShell);
524 const project = Option.isSome(thread)
525 ? yield* projects.getById(thread.value.projectId)
526 : Option.none<Project>();
527 const snapshot = resolveAgentAwarenessRelayPublishSnapshot({
528 environmentId,
529 thread,
530 project,
531 });
532 const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);
533 const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);
534 if (
535 (snapshot.state?.phase === "completed" || snapshot.state?.phase === "failed") &&
536 !hasLivePublishedState(publishedStateByThread, threadId)
537 ) {
538 if (Option.isNone(thread) || !terminalWorkSinceStart(thread.value, startedAt)) return;
539 }
540 if (
541 publishedStateByThread.get(threadId) === publishIdentity &&
542 // A held completion settled after an earlier clear still has to alert.
543 !(snapshot.state === null && heldCompletions.has(threadId))
544 ) {
545 // Clear moot deadlines so later transient nulls cannot skip their deferral window.
546 publishConfirmDeadlines.delete(threadId);
547 heldCompletions.delete(threadId);
548 yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", {
549 environmentId,
550 threadId,
551 reason: snapshot.reason,
552 });
553 return;
554 }
555
556 // Confirm tombstones over live state to avoid removing active cards.
557 // Confirm completion: a run can end moments before its continuation starts, and the relay
558 // alerts on every move into completed.
559 const requiresConfirmation = snapshot.state === null || snapshot.state?.phase === "completed";
560 if (requiresConfirmation) {
561 if (snapshot.state?.phase === "completed") heldCompletions.add(threadId);
562 const nowMs = (yield* DateTime.now).epochMilliseconds;
563 const deadline = publishConfirmDeadlines.get(threadId);
564 if (deadline === undefined) {
565 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
566 yield* Effect.logInfo("agent activity publish deferred pending confirmation", {
567 environmentId,
568 threadId,
569 reason: snapshot.reason,
570 statePhase: snapshot.state?.phase ?? null,
571 shell: describeThreadShellForAwareness(thread),
572 });
573 yield* schedulePublishConfirm(threadId);
574 return;
575 }
576 if (nowMs < deadline) {
577 return;
578 }
579 yield* Effect.logInfo("agent activity deferred publish confirmed", {
580 environmentId,
581 threadId,
582 reason: snapshot.reason,
583 statePhase: snapshot.state?.phase ?? null,
584 shell: describeThreadShellForAwareness(thread),
585 });
586 // Settled during the hold, not resumed: alert the current completion, then clear the card
587 // on a new window. Only settlement may hide it; queued or silent runs also project to null.
588 const unsettled =
589 snapshot.state === null &&
590 heldCompletions.has(threadId) &&
591 Option.isSome(thread) &&
592 thread.value.settledOverride === "settled"
593 ? resolveAgentAwarenessRelayPublishSnapshot({
594 environmentId,
595 thread: Option.some({ ...thread.value, settledOverride: null }),
596 project,
597 })
598 : null;
599 if (unsettled?.state?.phase === "completed") {
600 const completion = unsettled.state;
601 yield* publishState({
602 projectId: unsettled.projectId,
603 state: completion,
604 reason: unsettled.reason,
605 }).pipe(withRelayClientTracing);
606 heldCompletions.delete(threadId);
607 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
608 yield* Ref.update(publishedStateByThreadRef, (publishedStates) =>
609 new Map(publishedStates).set(threadId, agentAwarenessPublishIdentity(completion)),
610 );
611 yield* schedulePublishConfirm(threadId);
612 return;
613 }
614 } else {
615 publishConfirmDeadlines.delete(threadId);
616 heldCompletions.delete(threadId);
617 }
618
619 if (snapshot.reason === "thread-not-found") {
620 yield* Effect.logDebug("publishing agent activity tombstone; thread not found", {
621 environmentId,
622 threadId,
623 });
624 } else if (snapshot.reason === "project-not-found") {
625 yield* Effect.logDebug("publishing agent activity tombstone; project not found", {
626 environmentId,
627 threadId,
628 projectId: snapshot.projectId,
629 });
630 }
631
632 yield* publishState({
633 projectId: snapshot.projectId,
634 state: snapshot.state,
635 reason: snapshot.reason,
636 }).pipe(withRelayClientTracing);
637 publishConfirmDeadlines.delete(threadId);
638 heldCompletions.delete(threadId);
639 yield* Ref.update(publishedStateByThreadRef, (publishedStates) =>
640 new Map(publishedStates).set(threadId, publishIdentity),
641 );
642 });
643
644 const processThreadPublish = Effect.fnUntraced(function* (threadId: ThreadId) {
645 const retry = publishRetries.get(threadId);
646 if (retry?.timer !== undefined) {
647 const timer = retry.timer;
648 retry.timer = undefined;
649 yield* Fiber.interrupt(timer);
650 }
651 yield* publishThreadUnsafe(threadId).pipe(
652 Effect.tap(() => cancelPublishRetry(threadId)),
653 Effect.catchCause((cause) => {
654 if (Cause.hasInterruptsOnly(cause)) return Effect.void;
655 return Effect.logWarning("agent activity publish failed", {
656 threadId,
657 cause: Cause.pretty(cause),
658 }).pipe(Effect.andThen(schedulePublishRetry(threadId)));
659 }),
660 Effect.withSpan("AgentAwarenessRelay.publishThread"),
661 );
662 });
663
664 const worker = yield* makeAgentAwarenessPublishWorker(processThreadPublish);
665 const enqueueThreadPublish = (threadId: ThreadId) =>
666 cancelPublishRetry(threadId).pipe(Effect.andThen(worker.enqueue(threadId)));
667 const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
668 enqueueThreadPublish(threadId).pipe(Effect.andThen(worker.drain));
669
670 schedulePublishRetry = Effect.fnUntraced(function* (threadId: ThreadId) {
671 const attempts = publishRetries.get(threadId)?.attempts ?? 0;
672 const delayMs = RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS[attempts];
673 if (delayMs === undefined) {
674 // Retain exhausted budgets until activity or success resets them; old timers must not restart retries.
675 yield* Effect.logWarning("agent activity publish retry budget exhausted", { threadId });
676 return;
677 }
678 const retry = {
679 attempts: attempts + 1,
680 timer: undefined as Fiber.Fiber<void> | undefined,
681 };
682 publishRetries.set(threadId, retry);
683 const timer = yield* Effect.sleep(delayMs).pipe(
684 Effect.andThen(
685 Effect.suspend(() => {
686 if (publishRetries.get(threadId) !== retry) return Effect.void;
687 retry.timer = undefined;
688 return worker.enqueue(threadId);
689 }),
690 ),
691 Effect.forkIn(scope),
692 );
693 if (publishRetries.get(threadId) !== retry) {
694 yield* Fiber.interrupt(timer);
695 } else {
696 retry.timer = timer;
697 }
698 });
699
700 const publishActiveThreadsUnsafe = Effect.gen(function* () {
701 const relayUrl = yield* readSecretString(RELAY_URL_SECRET).pipe(
702 Effect.orElseSucceed(() => null),
703 );
704 if (!relayUrl) {
705 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
706 return "unlinked" as const;
707 }
708 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
709 Effect.orElseSucceed(() => false),
710 );
711 if (!publishAgentActivity) {
712 yield* Effect.logDebug("agent activity snapshot skipped; publication disabled");
713 return "disabled" as const;
714 }
715 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
716 if (!relayConfig) {
717 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
718 return "unlinked" as const;
719 }
720 const environmentId = yield* serverEnvironment.getEnvironmentId;
721 const projectSnapshot = yield* projects.snapshot;
722 const activitySnapshot = yield* threads.getAgentAwarenessSnapshot();
723 const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({
724 environmentId,
725 startedAt,
726 projects: projectSnapshot.projects,
727 threads: activitySnapshot.threads,
728 });
729 if (activeThreadIds.length === 0) {
730 yield* Effect.logDebug("agent activity snapshot has no publishable threads");
731 return "published" as const;
732 }
733 yield* Effect.logInfo("publishing active agent activity snapshot", {
734 count: activeThreadIds.length,
735 });
736 yield* Effect.forEach(activeThreadIds, enqueueThreadPublish, { discard: true });
737 yield* worker.drain;
738 return "published" as const;
739 });
740
741 // Many environments never link, so while unlinked the retry backs off from 5
742 // s to 60 s. A linked environment keeps the 5 s retry, because `t3 connect
743 // publish` can turn publishing on from another process. Keep this untraced:
744 // an unlinked environment can retry for the lifetime of the process.
745 const publishActiveThreadsWhenConfigured = Effect.fnUntraced(function* (
746 logEnabledWhenReady: boolean,
747 ) {
748 let unlinkedRetryDelayMs = 5_000;
749 while (true) {
750 const result = yield* publishActiveThreadsUnsafe.pipe(
751 Effect.orElseSucceed(() => "failed" as const),
752 );
753 if (result === "published") {
754 if (logEnabledWhenReady) {
755 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
756 yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
757 relayUrl: relayConfig?.url,
758 });
759 }
760 logEnabledWhenReady = false;
761 unlinkedRetryDelayMs = 5_000;
762 yield* Queue.take(catchUpRequests);
763 continue;
764 }
765 const retryDelayMs = result === "unlinked" ? unlinkedRetryDelayMs : 5_000;
766 yield* Effect.race(Effect.sleep(retryDelayMs), Queue.take(catchUpRequests));
767 if (result === "unlinked") {
768 unlinkedRetryDelayMs = Math.min(unlinkedRetryDelayMs * 2, 60_000);
769 }
770 }
771 });
772
773 schedulePublishConfirm = (threadId) =>
774 Effect.forkIn(
775 Effect.sleep("5 seconds").pipe(
776 Effect.andThen(worker.enqueue(threadId)),
777 Effect.catchCause((cause) =>
778 Effect.logWarning("deferred agent activity confirmation failed", {
779 threadId,
780 cause: Cause.pretty(cause),
781 }),
782 ),
783 ),
784 scope,
785 ).pipe(Effect.asVoid);
786
787 const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
788 function* () {
789 const [relayConfig, publishEnabled] = yield* Effect.all([
790 readRelayConfig.pipe(Effect.orElseSucceed(() => null)),
791 readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),
792 ]);
793 const startupState = resolveAgentActivityPublishingStartupState({
794 relayConfigured: relayConfig !== null,
795 publishEnabled,
796 });
797 switch (startupState) {
798 case "waiting-for-link":
799 yield* Effect.logInfo(
800 "agent activity publishing standby; waiting for T3 Connect link reconciliation",
801 );
802 break;
803 case "disabled":
804 yield* Effect.logInfo("agent activity publishing disabled by T3 Connect configuration");
805 break;
806 case "enabled":
807 yield* Effect.logInfo("agent activity publishing enabled", {
808 relayUrl: relayConfig?.url,
809 });
810 break;
811 }
812 yield* forkParked(
813 Effect.sleep("1 second").pipe(
814 Effect.andThen(publishActiveThreadsWhenConfigured(startupState !== "enabled")),
815 ),
816 );
817 yield* forkParked(
818 Stream.runForEach(threads.streamDomainEvents, (event) => {
819 const threadId = eventThreadId(event);
820 if (!shouldPublishAgentAwarenessEvent(event)) {
821 return Effect.void;
822 }
823 return Effect.logDebug("agent activity publishing queued thread publish", {
824 eventType: event.type,
825 threadId,
826 }).pipe(Effect.andThen(enqueueThreadPublish(threadId)));
827 }),
828 );
829 },
830 );
831
832 return AgentAwarenessRelay.of({
833 publishThread,
834 drain: worker.drain,
835 requestCatchUp: Effect.fn("AgentAwarenessRelay.requestCatchUp")(function () {
836 return Queue.offer(catchUpRequests, undefined).pipe(Effect.asVoid);
837 }),
838 start,
839 });
840});
841
842export const layer = Layer.effect(AgentAwarenessRelay, make);