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