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