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.settled":
97 case "thread.model-selection-updated":
98 case "thread.provider-switched":
99 case "run.created":
100 case "run.updated":
101 case "runtime-request.updated":
102 case "subagent.updated":
103 case "provider-thread.updated":
104 return true;
105 // Unsettling must not re-alert a dismissed result.
106 case "thread.unsettled":
107 case "thread.snoozed":
108 case "thread.unsnoozed":
109 case "thread.auto-settle-set":
110 case "thread.pinned":
111 case "thread.unpinned":
112 case "thread.pin-reordered":
113 case "thread.active-reordered":
114 case "thread.visited":
115 case "thread.marked-unread":
116 case "thread.runtime-mode-updated":
117 case "thread.interaction-mode-updated":
118 case "run.background-work-cancelled":
119 case "run-attempt.created":
120 case "run-attempt.updated":
121 case "node.updated":
122 case "provider-session.attached":
123 case "provider-session.updated":
124 case "provider-session.detached":
125 case "provider-turn.updated":
126 case "turn-item.updated":
127 return isTurnItemPayload(event.payload) && turnItemUpdateCanEndBackgroundWork(event.payload);
128 case "message.updated":
129 case "plan.updated":
130 case "checkpoint-scope.created":
131 case "checkpoint.captured":
132 case "checkpoint.rollback-requested":
133 case "context-handoff.updated":
134 case "context-transfer.created":
135 case "context-transfer.updated":
136 return false;
137 }
138}
139
140export const makeAgentAwarenessPublishWorker = Effect.fnUntraced(function* <R>(
141 publish: (threadId: ThreadId) => Effect.Effect<void, never, R>,
142) {
143 const queued = new Set<ThreadId>();
144 const worker = yield* makeDrainableWorker((threadId: ThreadId) =>
145 Effect.sync(() => queued.delete(threadId)).pipe(Effect.andThen(publish(threadId))),
146 );
147 const enqueue = (threadId: ThreadId) =>
148 Effect.suspend(() => {
149 if (queued.has(threadId)) return Effect.void;
150 // Removing the ID when processing starts allows one new queue entry
151 // for updates received while the current snapshot is being published.
152 queued.add(threadId);
153 return worker.enqueue(threadId);
154 }).pipe(Effect.uninterruptible);
155 return { enqueue, drain: worker.drain };
156});
157
158function agentAwarenessPublishIdentity(state: RelayAgentActivityState | null): string {
159 if (state === null) {
160 return "null";
161 }
162 const { updatedAt: _updatedAt, ...meaningfulState } = state;
163 return JSON.stringify(meaningfulState);
164}
165
166function resolveAgentActivityPublishingStartupState(input: {
167 readonly relayConfigured: boolean;
168 readonly publishEnabled: boolean;
169}): "waiting-for-link" | "disabled" | "enabled" {
170 if (!input.relayConfigured) {
171 return "waiting-for-link";
172 }
173 return input.publishEnabled ? "enabled" : "disabled";
174}
175
176const RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH = 160;
177const REDACTED_RELAY_AGENT_FAILURE_DETAIL = "The agent run failed.";
178const RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000] as const;
179
180function sanitizeRelayAgentActivityState(
181 state: RelayAgentActivityState | null,
182): RelayAgentActivityState | null {
183 if (state === null) {
184 return null;
185 }
186 const { detail: _detail, ...rest } = state;
187 const detail = (state.phase === "failed" ? REDACTED_RELAY_AGENT_FAILURE_DETAIL : state.detail)
188 ?.trim()
189 .slice(0, RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH)
190 .trim();
191 return detail ? { ...rest, detail } : rest;
192}
193
194function relayEnvironmentClient(token: string) {
195 return HttpClient.mapRequest(HttpClientRequest.setHeader("authorization", `Bearer ${token}`));
196}
197
198function deliveryStats(
199 deliveries: ReadonlyArray<{
200 readonly ok: boolean;
201 readonly queued?: boolean | undefined;
202 readonly kind: string;
203 readonly apnsStatus?: number | null;
204 readonly apnsReason?: string | null;
205 }>,
206) {
207 let queued = 0;
208 let successful = 0;
209 let failed = 0;
210 const failedReasons: string[] = [];
211 const kinds = new Set<string>();
212
213 for (const delivery of deliveries) {
214 kinds.add(delivery.kind);
215 if (delivery.queued) {
216 queued += 1;
217 continue;
218 }
219 if (delivery.ok) {
220 successful += 1;
221 continue;
222 }
223 failed += 1;
224 failedReasons.push(`${delivery.apnsStatus ?? "transport"}:${delivery.apnsReason ?? "unknown"}`);
225 }
226
227 return {
228 total: deliveries.length,
229 queued,
230 successful,
231 failed,
232 kinds: [...kinds],
233 failedReasons,
234 };
235}
236
237function signRelayAgentActivityPublishProof(input: {
238 readonly privateKey: string;
239 readonly payload: RelayAgentActivityPublishProofPayload;
240}) {
241 return signRelayJwt({
242 privateKey: input.privateKey,
243 typ: RELAY_ACTIVITY_PUBLISH_TYP,
244 payload: input.payload,
245 });
246}
247
248const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
249 readonly privateKey: string;
250 readonly relayIssuer: string;
251 readonly environmentId: string;
252 readonly threadId: ThreadId;
253 readonly state: RelayAgentActivityState | null;
254 readonly jti: string;
255}) {
256 const now = yield* DateTime.now;
257 const expiresAt = DateTime.add(now, { minutes: 5 });
258 const payload = {
259 iss: `t3-env:${input.environmentId}`,
260 aud: normalizeRelayIssuer(input.relayIssuer),
261 sub: input.environmentId,
262 jti: input.jti,
263 iat: Math.floor(now.epochMilliseconds / 1_000),
264 exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
265 environmentId: input.environmentId as RelayAgentActivityPublishProofPayload["environmentId"],
266 threadId: input.threadId,
267 state: input.state,
268 } satisfies RelayAgentActivityPublishProofPayload;
269 return yield* signRelayAgentActivityPublishProof({ privateKey: input.privateKey, payload });
270});
271
272function describeThreadShellForAwareness(
273 thread: Option.Option<OrchestrationV2ThreadShell>,
274): Record<string, unknown> {
275 if (Option.isNone(thread)) {
276 return { found: false };
277 }
278 const shell = thread.value;
279 return {
280 found: true,
281 status: shell.status,
282 activityRunStatus: shell.activityRunStatus ?? null,
283 activeRunId: shell.activeRunId ?? null,
284 latestRunId: shell.latestRunId ?? null,
285 pendingRuntimeRequestKind: shell.pendingRuntimeRequest?.kind ?? null,
286 hasActionableProposedPlan: shell.hasActionableProposedPlan,
287 };
288}
289
290function resolveAgentAwarenessRelayPublishSnapshot(input: {
291 readonly environmentId: EnvironmentId;
292 readonly threadId: ThreadId;
293 readonly thread: Option.Option<OrchestrationV2ThreadShell>;
294 readonly project: Option.Option<Project>;
295}): {
296 readonly projectId: string | null;
297 readonly state: RelayAgentActivityState | null;
298 readonly reason: "snapshot" | "thread-not-found" | "project-not-found";
299} {
300 if (Option.isNone(input.thread)) {
301 return {
302 projectId: null,
303 state: null,
304 reason: "thread-not-found",
305 };
306 }
307 if (Option.isNone(input.project)) {
308 return {
309 projectId: input.thread.value.projectId,
310 state: null,
311 reason: "project-not-found",
312 };
313 }
314 return {
315 projectId: input.thread.value.projectId,
316 state: sanitizeRelayAgentActivityState(
317 projectThreadAwarenessV2({
318 environmentId: input.environmentId,
319 project: input.project.value,
320 thread: input.thread.value,
321 }),
322 ),
323 reason: "snapshot",
324 };
325}
326
327function terminalWorkSinceStart(thread: OrchestrationV2ThreadShell, startedAt: number): boolean {
328 return (
329 thread.latestRunCompletedAt != null &&
330 DateTime.toEpochMillis(thread.latestRunCompletedAt) > startedAt
331 );
332}
333
334export function resolveAgentAwarenessRelayActiveThreadIds(input: {
335 readonly environmentId: EnvironmentId;
336 readonly startedAt: number;
337 readonly projects: ReadonlyArray<Pick<Project, "id" | "title">>;
338 readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;
339}): ReadonlyArray<ThreadId> {
340 const projectById = new Map(input.projects.map((project) => [project.id, project]));
341 return input.threads
342 .filter((thread) => {
343 const project = projectById.get(thread.projectId);
344 if (!project) {
345 return false;
346 }
347 const state = projectThreadAwarenessV2({
348 environmentId: input.environmentId,
349 project,
350 thread,
351 });
352 return (
353 state !== null &&
354 (state.phase !== "completed" && state.phase !== "failed"
355 ? true
356 : terminalWorkSinceStart(thread, input.startedAt))
357 );
358 })
359 .map((thread) => thread.id);
360}
361
362/** @public Service construction is part of the canonical Effect module API. */
363export const make = Effect.gen(function* () {
364 const secrets = yield* ServerSecretStore.ServerSecretStore;
365 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
366 const threads = yield* ThreadManagement.ThreadManagementService;
367 const projects = yield* ProjectService.ProjectService;
368 const crypto = yield* Crypto.Crypto;
369 const scope = yield* Effect.scope;
370 const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
371 const startedAt = (yield* DateTime.now).epochMilliseconds;
372 const activeSnapshotPublishedRef = yield* Ref.make(false);
373 const catchUpRequests = yield* Queue.dropping<void>(1);
374 const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());
375
376 const readSecretString = (name: string) =>
377 secrets
378 .get(name)
379 .pipe(
380 Effect.map((bytes) =>
381 Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,
382 ),
383 );
384
385 const readRelayConfig = Effect.gen(function* () {
386 const [url, issuer, environmentCredential] = yield* Effect.all([
387 readSecretString(RELAY_URL_SECRET),
388 readSecretString(RELAY_ISSUER_SECRET),
389 readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
390 ]);
391 return url && environmentCredential
392 ? { url, issuer: issuer ?? url, environmentCredential }
393 : null;
394 });
395
396 const readPublishAgentActivityEnabled = readSecretString(PUBLISH_AGENT_ACTIVITY_SECRET).pipe(
397 Effect.map(isAgentActivityPublishingEnabledValue),
398 );
399
400 const makeRelayClient = (relayConfig: {
401 readonly url: string;
402 readonly environmentCredential: string;
403 }) =>
404 HttpApiClient.make(RelayApi, {
405 baseUrl: relayConfig.url,
406 transformClient: relayEnvironmentClient(relayConfig.environmentCredential),
407 }).pipe(Effect.provide(FetchHttpClient.layer));
408
409 let cachedRelayClient: Effect.Success<ReturnType<typeof makeRelayClient>> | undefined;
410 let publishedRelayConfig: NonNullable<Effect.Success<typeof readRelayConfig>> | undefined;
411
412 // The confirming publish is re-enqueued through the same drainable worker as
413 // every other publish, so a confirmed tombstone can never race an in-flight
414 // live update; a recovered state clears the deadline.
415 const publishConfirmDeadlines = new Map<ThreadId, number>();
416 let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
417 const publishRetries = new Map<
418 ThreadId,
419 { readonly attempts: number; timer: Fiber.Fiber<void> | undefined }
420 >();
421 const cancelPublishRetry = Effect.fnUntraced(function* (threadId: ThreadId) {
422 const retry = publishRetries.get(threadId);
423 publishRetries.delete(threadId);
424 if (retry?.timer !== undefined) yield* Fiber.interrupt(retry.timer);
425 });
426 const cancelPublishRetries = Effect.suspend(() =>
427 Effect.forEach([...publishRetries.keys()], cancelPublishRetry, { discard: true }),
428 );
429 let schedulePublishRetry: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
430 const resetPublishedConnection = Effect.gen(function* () {
431 publishedRelayConfig = undefined;
432 cachedRelayClient = undefined;
433 publishConfirmDeadlines.clear();
434 yield* Ref.set(publishedStateByThreadRef, new Map());
435 });
436
437 const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) {
438 const publishAgentActivity = yield* readPublishAgentActivityEnabled;
439 if (!publishAgentActivity) {
440 yield* cancelPublishRetries;
441 yield* resetPublishedConnection;
442 yield* Effect.logDebug("agent activity publish skipped; publication disabled", {
443 threadId,
444 });
445 return;
446 }
447 const relayConfig = yield* readRelayConfig;
448 if (!relayConfig) {
449 yield* cancelPublishRetries;
450 yield* resetPublishedConnection;
451 yield* Effect.logDebug("agent activity publish skipped; relay link credentials unavailable", {
452 threadId,
453 });
454 return;
455 }
456 if (
457 publishedRelayConfig?.url !== relayConfig.url ||
458 publishedRelayConfig.issuer !== relayConfig.issuer ||
459 publishedRelayConfig.environmentCredential !== relayConfig.environmentCredential
460 ) {
461 yield* resetPublishedConnection;
462 publishedRelayConfig = relayConfig;
463 }
464 const environmentId = yield* serverEnvironment.getEnvironmentId;
465
466 const publishState = Effect.fn("relay.agent_activity.publish")(function* (input: {
467 readonly projectId: string | null;
468 readonly state: RelayAgentActivityState | null;
469 readonly reason: string;
470 }) {
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 });
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 }).pipe(withRelayClientTracing);
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. Keep this untraced:
733 // an unlinked environment can retry for the lifetime of the process.
734 const publishActiveThreadsOnceWhenConfigured = Effect.fnUntraced(function* (
735 logEnabledWhenReady: boolean,
736 ) {
737 let unlinkedRetryDelayMs = 5_000;
738 while (!(yield* Ref.get(activeSnapshotPublishedRef))) {
739 const result = yield* publishActiveThreadsUnsafe.pipe(
740 Effect.orElseSucceed(() => "failed" as const),
741 );
742 if (result === "published") {
743 yield* Ref.set(activeSnapshotPublishedRef, true);
744 if (logEnabledWhenReady) {
745 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
746 yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
747 relayUrl: relayConfig?.url,
748 });
749 }
750 return;
751 }
752 const retryDelayMs = result === "unlinked" ? unlinkedRetryDelayMs : 5_000;
753 yield* Effect.race(Effect.sleep(retryDelayMs), Queue.take(catchUpRequests));
754 if (result === "unlinked") {
755 unlinkedRetryDelayMs = Math.min(unlinkedRetryDelayMs * 2, 60_000);
756 }
757 }
758 });
759
760 schedulePublishConfirm = (threadId) =>
761 Effect.forkIn(
762 Effect.sleep("5 seconds").pipe(
763 Effect.andThen(worker.enqueue(threadId)),
764 Effect.catchCause((cause) =>
765 Effect.logWarning("deferred agent activity confirmation failed", {
766 threadId,
767 cause: Cause.pretty(cause),
768 }),
769 ),
770 ),
771 scope,
772 ).pipe(Effect.asVoid);
773
774 const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
775 function* () {
776 const [relayConfig, publishEnabled] = yield* Effect.all([
777 readRelayConfig.pipe(Effect.orElseSucceed(() => null)),
778 readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),
779 ]);
780 const startupState = resolveAgentActivityPublishingStartupState({
781 relayConfigured: relayConfig !== null,
782 publishEnabled,
783 });
784 switch (startupState) {
785 case "waiting-for-link":
786 yield* Effect.logInfo(
787 "agent activity publishing standby; waiting for T3 Connect link reconciliation",
788 );
789 break;
790 case "disabled":
791 yield* Effect.logInfo("agent activity publishing disabled by T3 Connect configuration");
792 break;
793 case "enabled":
794 yield* Effect.logInfo("agent activity publishing enabled", {
795 relayUrl: relayConfig?.url,
796 });
797 break;
798 }
799 yield* forkParked(
800 Effect.sleep("1 second").pipe(
801 Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")),
802 ),
803 );
804 yield* forkParked(
805 Stream.runForEach(threads.streamDomainEvents, (event) => {
806 const threadId = eventThreadId(event);
807 if (!shouldPublishAgentAwarenessEvent(event)) {
808 return Effect.void;
809 }
810 return Effect.logDebug("agent activity publishing queued thread publish", {
811 eventType: event.type,
812 threadId,
813 }).pipe(Effect.andThen(enqueueThreadPublish(threadId)));
814 }),
815 );
816 },
817 );
818
819 return AgentAwarenessRelay.of({
820 publishThread,
821 drain: worker.drain,
822 requestCatchUp: () => Queue.offer(catchUpRequests, undefined).pipe(Effect.asVoid),
823 start,
824 });
825});
826
827export const layer = Layer.effect(AgentAwarenessRelay, make);