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
76function 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.guest-share-updated":
108 case "thread.snoozed":
109 case "thread.unsnoozed":
110 case "thread.auto-settle-set":
111 case "thread.pinned":
112 case "thread.unpinned":
113 case "thread.pin-reordered":
114 case "thread.active-reordered":
115 case "thread.visited":
116 case "thread.marked-unread":
117 case "thread.runtime-mode-updated":
118 case "thread.interaction-mode-updated":
119 case "run.background-work-cancelled":
120 case "run-attempt.created":
121 case "run-attempt.updated":
122 case "node.updated":
123 case "provider-session.attached":
124 case "provider-session.updated":
125 case "provider-session.detached":
126 case "provider-turn.updated":
127 case "turn-item.updated":
128 return isTurnItemPayload(event.payload) && turnItemUpdateCanEndBackgroundWork(event.payload);
129 case "message.updated":
130 case "plan.updated":
131 case "checkpoint-scope.created":
132 case "checkpoint.captured":
133 case "checkpoint.rollback-requested":
134 case "context-handoff.updated":
135 case "context-transfer.created":
136 case "context-transfer.updated":
137 return false;
138 }
139}
140
141export const makeAgentAwarenessPublishWorker = Effect.fnUntraced(function* <R>(
142 publish: (threadId: ThreadId) => Effect.Effect<void, never, R>,
143) {
144 const queued = new Set<ThreadId>();
145 const worker = yield* makeDrainableWorker((threadId: ThreadId) =>
146 Effect.sync(() => queued.delete(threadId)).pipe(Effect.andThen(publish(threadId))),
147 );
148 const enqueue = (threadId: ThreadId) =>
149 Effect.suspend(() => {
150 if (queued.has(threadId)) return Effect.void;
151 // Remove queued IDs when processing starts so publication can queue one later update.
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 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 */
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 // Confirm through the same worker so tombstones cannot race live updates; recovery clears the deadline.
412 const publishConfirmDeadlines = new Map<ThreadId, number>();
413 // Threads whose confirmation holds a completion, so a thread that settles during the hold still alerts.
414 const heldCompletions = new Set<ThreadId>();
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 heldCompletions.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 // Read only this thread; full shell reads would make each activity event scale with all threads.
515 const threadShell = yield* threads.getThreadShell(threadId);
516 if (
517 threadShell?.lineage.relationshipToParent === "subagent" &&
518 !(yield* Ref.get(publishedStateByThreadRef)).has(threadId)
519 ) {
520 // Subagents have no relay rows to clear; per-event tombstones would needlessly redeliver user aggregates.
521 return;
522 }
523 const thread =
524 threadShell === null || threadShell.archivedAt !== null
525 ? Option.none<OrchestrationV2ThreadShell>()
526 : Option.some(threadShell);
527 const project = Option.isSome(thread)
528 ? yield* projects.getById(thread.value.projectId)
529 : Option.none<Project>();
530 const snapshot = resolveAgentAwarenessRelayPublishSnapshot({
531 environmentId,
532 thread,
533 project,
534 });
535 const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);
536 const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);
537 if (
538 (snapshot.state?.phase === "completed" || snapshot.state?.phase === "failed") &&
539 !publishedStateByThread.has(threadId)
540 ) {
541 if (Option.isNone(thread) || !terminalWorkSinceStart(thread.value, startedAt)) return;
542 }
543 if (publishedStateByThread.get(threadId) === publishIdentity) {
544 // Clear moot deadlines so later transient nulls cannot skip their deferral window.
545 publishConfirmDeadlines.delete(threadId);
546 heldCompletions.delete(threadId);
547 yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", {
548 environmentId,
549 threadId,
550 reason: snapshot.reason,
551 });
552 return;
553 }
554
555 // Confirm tombstones over live state to avoid removing active cards.
556 // Confirm completion: a run can end moments before its continuation starts, and the relay
557 // alerts on every move into completed.
558 const requiresConfirmation =
559 (snapshot.state === null &&
560 publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) ||
561 snapshot.state?.phase === "completed";
562 if (requiresConfirmation) {
563 if (snapshot.state?.phase === "completed") heldCompletions.add(threadId);
564 const nowMs = (yield* DateTime.now).epochMilliseconds;
565 const deadline = publishConfirmDeadlines.get(threadId);
566 if (deadline === undefined) {
567 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
568 yield* Effect.logInfo("agent activity publish deferred pending confirmation", {
569 environmentId,
570 threadId,
571 reason: snapshot.reason,
572 statePhase: snapshot.state?.phase ?? null,
573 shell: describeThreadShellForAwareness(thread),
574 });
575 yield* schedulePublishConfirm(threadId);
576 return;
577 }
578 if (nowMs < deadline) {
579 return;
580 }
581 yield* Effect.logInfo("agent activity deferred publish confirmed", {
582 environmentId,
583 threadId,
584 reason: snapshot.reason,
585 statePhase: snapshot.state?.phase ?? null,
586 shell: describeThreadShellForAwareness(thread),
587 });
588 // Settled during the hold, not resumed: alert the current completion, then clear the card
589 // on a new window. Only settlement may hide it; queued or silent runs also project to null.
590 const unsettled =
591 snapshot.state === null &&
592 heldCompletions.has(threadId) &&
593 Option.isSome(thread) &&
594 thread.value.settledOverride === "settled"
595 ? resolveAgentAwarenessRelayPublishSnapshot({
596 environmentId,
597 thread: Option.some({ ...thread.value, settledOverride: null }),
598 project,
599 })
600 : null;
601 if (unsettled?.state?.phase === "completed") {
602 const completion = unsettled.state;
603 yield* publishState({
604 projectId: unsettled.projectId,
605 state: completion,
606 reason: unsettled.reason,
607 }).pipe(withRelayClientTracing);
608 heldCompletions.delete(threadId);
609 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
610 yield* Ref.update(publishedStateByThreadRef, (publishedStates) =>
611 new Map(publishedStates).set(threadId, agentAwarenessPublishIdentity(completion)),
612 );
613 yield* schedulePublishConfirm(threadId);
614 return;
615 }
616 } else {
617 publishConfirmDeadlines.delete(threadId);
618 heldCompletions.delete(threadId);
619 }
620
621 if (snapshot.reason === "thread-not-found") {
622 yield* Effect.logDebug("publishing agent activity tombstone; thread not found", {
623 environmentId,
624 threadId,
625 });
626 } else if (snapshot.reason === "project-not-found") {
627 yield* Effect.logDebug("publishing agent activity tombstone; project not found", {
628 environmentId,
629 threadId,
630 projectId: snapshot.projectId,
631 });
632 }
633
634 yield* publishState({
635 projectId: snapshot.projectId,
636 state: snapshot.state,
637 reason: snapshot.reason,
638 }).pipe(withRelayClientTracing);
639 publishConfirmDeadlines.delete(threadId);
640 heldCompletions.delete(threadId);
641 yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {
642 const nextPublishedStates = new Map(publishedStates);
643 if (snapshot.state === null) {
644 nextPublishedStates.delete(threadId);
645 } else {
646 nextPublishedStates.set(threadId, publishIdentity);
647 }
648 return nextPublishedStates;
649 });
650 });
651
652 const processThreadPublish = Effect.fnUntraced(function* (threadId: ThreadId) {
653 const retry = publishRetries.get(threadId);
654 if (retry?.timer !== undefined) {
655 const timer = retry.timer;
656 retry.timer = undefined;
657 yield* Fiber.interrupt(timer);
658 }
659 yield* publishThreadUnsafe(threadId).pipe(
660 Effect.tap(() => cancelPublishRetry(threadId)),
661 Effect.catchCause((cause) => {
662 if (Cause.hasInterruptsOnly(cause)) return Effect.void;
663 return Effect.logWarning("agent activity publish failed", {
664 threadId,
665 cause: Cause.pretty(cause),
666 }).pipe(Effect.andThen(schedulePublishRetry(threadId)));
667 }),
668 Effect.withSpan("AgentAwarenessRelay.publishThread"),
669 );
670 });
671
672 const worker = yield* makeAgentAwarenessPublishWorker(processThreadPublish);
673 const enqueueThreadPublish = (threadId: ThreadId) =>
674 cancelPublishRetry(threadId).pipe(Effect.andThen(worker.enqueue(threadId)));
675 const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
676 enqueueThreadPublish(threadId).pipe(Effect.andThen(worker.drain));
677
678 schedulePublishRetry = Effect.fnUntraced(function* (threadId: ThreadId) {
679 const attempts = publishRetries.get(threadId)?.attempts ?? 0;
680 const delayMs = RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS[attempts];
681 if (delayMs === undefined) {
682 // Retain exhausted budgets until activity or success resets them; old timers must not restart retries.
683 yield* Effect.logWarning("agent activity publish retry budget exhausted", { threadId });
684 return;
685 }
686 const retry = {
687 attempts: attempts + 1,
688 timer: undefined as Fiber.Fiber<void> | undefined,
689 };
690 publishRetries.set(threadId, retry);
691 const timer = yield* Effect.sleep(delayMs).pipe(
692 Effect.andThen(
693 Effect.suspend(() => {
694 if (publishRetries.get(threadId) !== retry) return Effect.void;
695 retry.timer = undefined;
696 return worker.enqueue(threadId);
697 }),
698 ),
699 Effect.forkIn(scope),
700 );
701 if (publishRetries.get(threadId) !== retry) {
702 yield* Fiber.interrupt(timer);
703 } else {
704 retry.timer = timer;
705 }
706 });
707
708 const publishActiveThreadsUnsafe = Effect.gen(function* () {
709 const relayUrl = yield* readSecretString(RELAY_URL_SECRET).pipe(
710 Effect.orElseSucceed(() => null),
711 );
712 if (!relayUrl) {
713 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
714 return "unlinked" as const;
715 }
716 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
717 Effect.orElseSucceed(() => false),
718 );
719 if (!publishAgentActivity) {
720 yield* Effect.logDebug("agent activity snapshot skipped; publication disabled");
721 return "disabled" as const;
722 }
723 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
724 if (!relayConfig) {
725 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
726 return "unlinked" as const;
727 }
728 const environmentId = yield* serverEnvironment.getEnvironmentId;
729 const projectSnapshot = yield* projects.snapshot;
730 // Subagents never publish awareness, and they are most threads.
731 const topLevelThreadIds = (yield* threads.listActiveShellIndex()).flatMap((thread) =>
732 thread.lineage.relationshipToParent === "subagent" ? [] : [thread.id],
733 );
734 const shellSnapshot = yield* threads.getShellSnapshot({
735 location: "active",
736 threadIds: topLevelThreadIds,
737 });
738 const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({
739 environmentId,
740 startedAt,
741 projects: projectSnapshot.projects,
742 threads: shellSnapshot.threads,
743 });
744 if (activeThreadIds.length === 0) {
745 yield* Effect.logDebug("agent activity snapshot has no publishable threads");
746 return "published" as const;
747 }
748 yield* Effect.logInfo("publishing active agent activity snapshot", {
749 count: activeThreadIds.length,
750 });
751 yield* Effect.forEach(activeThreadIds, enqueueThreadPublish, { discard: true });
752 yield* worker.drain;
753 return "published" as const;
754 });
755
756 // Many environments never link, so while unlinked the retry backs off from 5
757 // s to 60 s. A linked environment keeps the 5 s retry, because `t3 connect
758 // publish` can turn publishing on from another process. Keep this untraced:
759 // an unlinked environment can retry for the lifetime of the process.
760 const publishActiveThreadsOnceWhenConfigured = Effect.fnUntraced(function* (
761 logEnabledWhenReady: boolean,
762 ) {
763 let unlinkedRetryDelayMs = 5_000;
764 while (!(yield* Ref.get(activeSnapshotPublishedRef))) {
765 const result = yield* publishActiveThreadsUnsafe.pipe(
766 Effect.orElseSucceed(() => "failed" as const),
767 );
768 if (result === "published") {
769 yield* Ref.set(activeSnapshotPublishedRef, true);
770 if (logEnabledWhenReady) {
771 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
772 yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
773 relayUrl: relayConfig?.url,
774 });
775 }
776 return;
777 }
778 const retryDelayMs = result === "unlinked" ? unlinkedRetryDelayMs : 5_000;
779 yield* Effect.race(Effect.sleep(retryDelayMs), Queue.take(catchUpRequests));
780 if (result === "unlinked") {
781 unlinkedRetryDelayMs = Math.min(unlinkedRetryDelayMs * 2, 60_000);
782 }
783 }
784 });
785
786 schedulePublishConfirm = (threadId) =>
787 Effect.forkIn(
788 Effect.sleep("5 seconds").pipe(
789 Effect.andThen(worker.enqueue(threadId)),
790 Effect.catchCause((cause) =>
791 Effect.logWarning("deferred agent activity confirmation failed", {
792 threadId,
793 cause: Cause.pretty(cause),
794 }),
795 ),
796 ),
797 scope,
798 ).pipe(Effect.asVoid);
799
800 const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
801 function* () {
802 const [relayConfig, publishEnabled] = yield* Effect.all([
803 readRelayConfig.pipe(Effect.orElseSucceed(() => null)),
804 readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),
805 ]);
806 const startupState = resolveAgentActivityPublishingStartupState({
807 relayConfigured: relayConfig !== null,
808 publishEnabled,
809 });
810 switch (startupState) {
811 case "waiting-for-link":
812 yield* Effect.logInfo(
813 "agent activity publishing standby; waiting for T3 Connect link reconciliation",
814 );
815 break;
816 case "disabled":
817 yield* Effect.logInfo("agent activity publishing disabled by T3 Connect configuration");
818 break;
819 case "enabled":
820 yield* Effect.logInfo("agent activity publishing enabled", {
821 relayUrl: relayConfig?.url,
822 });
823 break;
824 }
825 yield* forkParked(
826 Effect.sleep("1 second").pipe(
827 Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")),
828 ),
829 );
830 yield* forkParked(
831 Stream.runForEach(threads.streamDomainEvents, (event) => {
832 const threadId = eventThreadId(event);
833 if (!shouldPublishAgentAwarenessEvent(event)) {
834 return Effect.void;
835 }
836 return Effect.logDebug("agent activity publishing queued thread publish", {
837 eventType: event.type,
838 threadId,
839 }).pipe(Effect.andThen(enqueueThreadPublish(threadId)));
840 }),
841 );
842 },
843 );
844
845 return AgentAwarenessRelay.of({
846 publishThread,
847 drain: worker.drain,
848 requestCatchUp: Effect.fn("AgentAwarenessRelay.requestCatchUp")(function () {
849 return Queue.offer(catchUpRequests, undefined).pipe(Effect.asVoid);
850 }),
851 start,
852 });
853});
854
855export const layer = Layer.effect(AgentAwarenessRelay, make);