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 Crypto from "effect/Crypto";
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.visited":
117 case "thread.marked-unread":
118 case "thread.runtime-mode-updated":
119 case "thread.interaction-mode-updated":
120 case "run.background-work-cancelled":
121 case "run-attempt.created":
122 case "run-attempt.updated":
123 case "node.updated":
124 case "provider-session.attached":
125 case "provider-session.updated":
126 case "provider-session.detached":
127 case "provider-turn.updated":
128 case "turn-item.updated":
129 return isTurnItemPayload(event.payload) && turnItemUpdateCanEndBackgroundWork(event.payload);
130 case "message.updated":
131 case "plan.updated":
132 case "checkpoint-scope.created":
133 case "checkpoint.captured":
134 case "checkpoint.rollback-requested":
135 case "context-handoff.updated":
136 case "context-transfer.created":
137 case "context-transfer.updated":
138 return false;
139 }
140}
141
142export const makeAgentAwarenessPublishWorker = Effect.fnUntraced(function* <R>(
143 publish: (threadId: ThreadId) => Effect.Effect<void, never, R>,
144) {
145 const queued = new Set<ThreadId>();
146 const worker = yield* makeDrainableWorker((threadId: ThreadId) =>
147 Effect.sync(() => queued.delete(threadId)).pipe(Effect.andThen(publish(threadId))),
148 );
149 const enqueue = (threadId: ThreadId) =>
150 Effect.suspend(() => {
151 if (queued.has(threadId)) return Effect.void;
152 // Remove queued IDs when processing starts so publication can queue one later update.
153 queued.add(threadId);
154 return worker.enqueue(threadId);
155 }).pipe(Effect.uninterruptible);
156 return { enqueue, drain: worker.drain };
157});
158
159function agentAwarenessPublishIdentity(state: RelayAgentActivityState | null): string {
160 if (state === null) {
161 return "null";
162 }
163 const { updatedAt: _updatedAt, ...meaningfulState } = state;
164 return JSON.stringify(meaningfulState);
165}
166
167function resolveAgentActivityPublishingStartupState(input: {
168 readonly relayConfigured: boolean;
169 readonly publishEnabled: boolean;
170}): "waiting-for-link" | "disabled" | "enabled" {
171 if (!input.relayConfigured) {
172 return "waiting-for-link";
173 }
174 return input.publishEnabled ? "enabled" : "disabled";
175}
176
177const RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH = 160;
178const REDACTED_RELAY_AGENT_FAILURE_DETAIL = "The agent run failed.";
179const RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000] as const;
180
181function sanitizeRelayAgentActivityState(
182 state: RelayAgentActivityState | null,
183): RelayAgentActivityState | null {
184 if (state === null) {
185 return null;
186 }
187 const { detail: _detail, ...rest } = state;
188 const detail = (state.phase === "failed" ? REDACTED_RELAY_AGENT_FAILURE_DETAIL : state.detail)
189 ?.trim()
190 .slice(0, RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH)
191 .trim();
192 return detail ? { ...rest, detail } : rest;
193}
194
195function relayEnvironmentClient(token: string) {
196 return HttpClient.mapRequest(HttpClientRequest.setHeader("authorization", `Bearer ${token}`));
197}
198
199function deliveryStats(
200 deliveries: ReadonlyArray<{
201 readonly ok: boolean;
202 readonly queued?: boolean | undefined;
203 readonly kind: string;
204 readonly apnsStatus?: number | null;
205 readonly apnsReason?: string | null;
206 }>,
207) {
208 let queued = 0;
209 let successful = 0;
210 let failed = 0;
211 const failedReasons: string[] = [];
212 const kinds = new Set<string>();
213
214 for (const delivery of deliveries) {
215 kinds.add(delivery.kind);
216 if (delivery.queued) {
217 queued += 1;
218 continue;
219 }
220 if (delivery.ok) {
221 successful += 1;
222 continue;
223 }
224 failed += 1;
225 failedReasons.push(`${delivery.apnsStatus ?? "transport"}:${delivery.apnsReason ?? "unknown"}`);
226 }
227
228 return {
229 total: deliveries.length,
230 queued,
231 successful,
232 failed,
233 kinds: [...kinds],
234 failedReasons,
235 };
236}
237
238function signRelayAgentActivityPublishProof(input: {
239 readonly privateKey: string;
240 readonly payload: RelayAgentActivityPublishProofPayload;
241}) {
242 return signRelayJwt({
243 privateKey: input.privateKey,
244 typ: RELAY_ACTIVITY_PUBLISH_TYP,
245 payload: input.payload,
246 });
247}
248
249const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
250 readonly privateKey: string;
251 readonly relayIssuer: string;
252 readonly environmentId: string;
253 readonly threadId: ThreadId;
254 readonly state: RelayAgentActivityState | null;
255 readonly jti: string;
256}) {
257 const now = yield* DateTime.now;
258 const expiresAt = DateTime.add(now, { minutes: 5 });
259 const payload = {
260 iss: `t3-env:${input.environmentId}`,
261 aud: normalizeRelayIssuer(input.relayIssuer),
262 sub: input.environmentId,
263 jti: input.jti,
264 iat: Math.floor(now.epochMilliseconds / 1_000),
265 exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
266 environmentId: input.environmentId as RelayAgentActivityPublishProofPayload["environmentId"],
267 threadId: input.threadId,
268 state: input.state,
269 } satisfies RelayAgentActivityPublishProofPayload;
270 return yield* signRelayAgentActivityPublishProof({ privateKey: input.privateKey, payload });
271});
272
273function describeThreadShellForAwareness(
274 thread: Option.Option<OrchestrationV2ThreadShell>,
275): Record<string, unknown> {
276 if (Option.isNone(thread)) {
277 return { found: false };
278 }
279 const shell = thread.value;
280 return {
281 found: true,
282 status: shell.status,
283 activityRunStatus: shell.activityRunStatus ?? null,
284 activeRunId: shell.activeRunId ?? null,
285 latestRunId: shell.latestRunId ?? null,
286 pendingRuntimeRequestKind: shell.pendingRuntimeRequest?.kind ?? null,
287 hasActionableProposedPlan: shell.hasActionableProposedPlan,
288 };
289}
290
291function resolveAgentAwarenessRelayPublishSnapshot(input: {
292 readonly environmentId: EnvironmentId;
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 */
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 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 !== null &&
518 !isListedThreadLineage(threadShell.lineage) &&
519 !(yield* Ref.get(publishedStateByThreadRef)).has(threadId)
520 ) {
521 // Subagents and side chats have no relay rows to clear; per-event tombstones would needlessly redeliver user aggregates.
522 return;
523 }
524 const thread =
525 threadShell === null || threadShell.archivedAt !== null
526 ? Option.none<OrchestrationV2ThreadShell>()
527 : Option.some(threadShell);
528 const project = Option.isSome(thread)
529 ? yield* projects.getById(thread.value.projectId)
530 : Option.none<Project>();
531 const snapshot = resolveAgentAwarenessRelayPublishSnapshot({
532 environmentId,
533 thread,
534 project,
535 });
536 const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);
537 const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);
538 if (
539 (snapshot.state?.phase === "completed" || snapshot.state?.phase === "failed") &&
540 !publishedStateByThread.has(threadId)
541 ) {
542 if (Option.isNone(thread) || !terminalWorkSinceStart(thread.value, startedAt)) return;
543 }
544 if (publishedStateByThread.get(threadId) === publishIdentity) {
545 // Clear moot deadlines so later transient nulls cannot skip their deferral window.
546 publishConfirmDeadlines.delete(threadId);
547 heldCompletions.delete(threadId);
548 yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", {
549 environmentId,
550 threadId,
551 reason: snapshot.reason,
552 });
553 return;
554 }
555
556 // Confirm tombstones over live state to avoid removing active cards.
557 // Confirm completion: a run can end moments before its continuation starts, and the relay
558 // alerts on every move into completed.
559 const requiresConfirmation =
560 (snapshot.state === null &&
561 publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) ||
562 snapshot.state?.phase === "completed";
563 if (requiresConfirmation) {
564 if (snapshot.state?.phase === "completed") heldCompletions.add(threadId);
565 const nowMs = (yield* DateTime.now).epochMilliseconds;
566 const deadline = publishConfirmDeadlines.get(threadId);
567 if (deadline === undefined) {
568 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
569 yield* Effect.logInfo("agent activity publish deferred pending confirmation", {
570 environmentId,
571 threadId,
572 reason: snapshot.reason,
573 statePhase: snapshot.state?.phase ?? null,
574 shell: describeThreadShellForAwareness(thread),
575 });
576 yield* schedulePublishConfirm(threadId);
577 return;
578 }
579 if (nowMs < deadline) {
580 return;
581 }
582 yield* Effect.logInfo("agent activity deferred publish confirmed", {
583 environmentId,
584 threadId,
585 reason: snapshot.reason,
586 statePhase: snapshot.state?.phase ?? null,
587 shell: describeThreadShellForAwareness(thread),
588 });
589 // Settled during the hold, not resumed: alert the current completion, then clear the card
590 // on a new window. Only settlement may hide it; queued or silent runs also project to null.
591 const unsettled =
592 snapshot.state === null &&
593 heldCompletions.has(threadId) &&
594 Option.isSome(thread) &&
595 thread.value.settledOverride === "settled"
596 ? resolveAgentAwarenessRelayPublishSnapshot({
597 environmentId,
598 thread: Option.some({ ...thread.value, settledOverride: null }),
599 project,
600 })
601 : null;
602 if (unsettled?.state?.phase === "completed") {
603 const completion = unsettled.state;
604 yield* publishState({
605 projectId: unsettled.projectId,
606 state: completion,
607 reason: unsettled.reason,
608 }).pipe(withRelayClientTracing);
609 heldCompletions.delete(threadId);
610 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
611 yield* Ref.update(publishedStateByThreadRef, (publishedStates) =>
612 new Map(publishedStates).set(threadId, agentAwarenessPublishIdentity(completion)),
613 );
614 yield* schedulePublishConfirm(threadId);
615 return;
616 }
617 } else {
618 publishConfirmDeadlines.delete(threadId);
619 heldCompletions.delete(threadId);
620 }
621
622 if (snapshot.reason === "thread-not-found") {
623 yield* Effect.logDebug("publishing agent activity tombstone; thread not found", {
624 environmentId,
625 threadId,
626 });
627 } else if (snapshot.reason === "project-not-found") {
628 yield* Effect.logDebug("publishing agent activity tombstone; project not found", {
629 environmentId,
630 threadId,
631 projectId: snapshot.projectId,
632 });
633 }
634
635 yield* publishState({
636 projectId: snapshot.projectId,
637 state: snapshot.state,
638 reason: snapshot.reason,
639 }).pipe(withRelayClientTracing);
640 publishConfirmDeadlines.delete(threadId);
641 heldCompletions.delete(threadId);
642 yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {
643 const nextPublishedStates = new Map(publishedStates);
644 if (snapshot.state === null) {
645 nextPublishedStates.delete(threadId);
646 } else {
647 nextPublishedStates.set(threadId, publishIdentity);
648 }
649 return nextPublishedStates;
650 });
651 });
652
653 const processThreadPublish = Effect.fnUntraced(function* (threadId: ThreadId) {
654 const retry = publishRetries.get(threadId);
655 if (retry?.timer !== undefined) {
656 const timer = retry.timer;
657 retry.timer = undefined;
658 yield* Fiber.interrupt(timer);
659 }
660 yield* publishThreadUnsafe(threadId).pipe(
661 Effect.tap(() => cancelPublishRetry(threadId)),
662 Effect.catchCause((cause) => {
663 if (Cause.hasInterruptsOnly(cause)) return Effect.void;
664 return Effect.logWarning("agent activity publish failed", {
665 threadId,
666 cause: Cause.pretty(cause),
667 }).pipe(Effect.andThen(schedulePublishRetry(threadId)));
668 }),
669 Effect.withSpan("AgentAwarenessRelay.publishThread"),
670 );
671 });
672
673 const worker = yield* makeAgentAwarenessPublishWorker(processThreadPublish);
674 const enqueueThreadPublish = (threadId: ThreadId) =>
675 cancelPublishRetry(threadId).pipe(Effect.andThen(worker.enqueue(threadId)));
676 const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
677 enqueueThreadPublish(threadId).pipe(Effect.andThen(worker.drain));
678
679 schedulePublishRetry = Effect.fnUntraced(function* (threadId: ThreadId) {
680 const attempts = publishRetries.get(threadId)?.attempts ?? 0;
681 const delayMs = RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS[attempts];
682 if (delayMs === undefined) {
683 // Retain exhausted budgets until activity or success resets them; old timers must not restart retries.
684 yield* Effect.logWarning("agent activity publish retry budget exhausted", { threadId });
685 return;
686 }
687 const retry = {
688 attempts: attempts + 1,
689 timer: undefined as Fiber.Fiber<void> | undefined,
690 };
691 publishRetries.set(threadId, retry);
692 const timer = yield* Effect.sleep(delayMs).pipe(
693 Effect.andThen(
694 Effect.suspend(() => {
695 if (publishRetries.get(threadId) !== retry) return Effect.void;
696 retry.timer = undefined;
697 return worker.enqueue(threadId);
698 }),
699 ),
700 Effect.forkIn(scope),
701 );
702 if (publishRetries.get(threadId) !== retry) {
703 yield* Fiber.interrupt(timer);
704 } else {
705 retry.timer = timer;
706 }
707 });
708
709 const publishActiveThreadsUnsafe = Effect.gen(function* () {
710 const relayUrl = yield* readSecretString(RELAY_URL_SECRET).pipe(
711 Effect.orElseSucceed(() => null),
712 );
713 if (!relayUrl) {
714 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
715 return "unlinked" as const;
716 }
717 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
718 Effect.orElseSucceed(() => false),
719 );
720 if (!publishAgentActivity) {
721 yield* Effect.logDebug("agent activity snapshot skipped; publication disabled");
722 return "disabled" as const;
723 }
724 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
725 if (!relayConfig) {
726 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
727 return "unlinked" as const;
728 }
729 const environmentId = yield* serverEnvironment.getEnvironmentId;
730 const projectSnapshot = yield* projects.snapshot;
731 // Subagents and side chats never publish awareness, and subagents are most threads.
732 const topLevelThreadIds = (yield* threads.listActiveShellIndex()).flatMap((thread) =>
733 isListedThreadLineage(thread.lineage) ? [thread.id] : [],
734 );
735 const shellSnapshot = yield* threads.getShellSnapshot({
736 location: "active",
737 threadIds: topLevelThreadIds,
738 });
739 const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({
740 environmentId,
741 startedAt,
742 projects: projectSnapshot.projects,
743 threads: shellSnapshot.threads,
744 });
745 if (activeThreadIds.length === 0) {
746 yield* Effect.logDebug("agent activity snapshot has no publishable threads");
747 return "published" as const;
748 }
749 yield* Effect.logInfo("publishing active agent activity snapshot", {
750 count: activeThreadIds.length,
751 });
752 yield* Effect.forEach(activeThreadIds, enqueueThreadPublish, { discard: true });
753 yield* worker.drain;
754 return "published" as const;
755 });
756
757 // Many environments never link, so while unlinked the retry backs off from 5
758 // s to 60 s. A linked environment keeps the 5 s retry, because `t3 connect
759 // publish` can turn publishing on from another process. Keep this untraced:
760 // an unlinked environment can retry for the lifetime of the process.
761 const publishActiveThreadsWhenConfigured = Effect.fnUntraced(function* (
762 logEnabledWhenReady: boolean,
763 ) {
764 let unlinkedRetryDelayMs = 5_000;
765 while (true) {
766 const result = yield* publishActiveThreadsUnsafe.pipe(
767 Effect.orElseSucceed(() => "failed" as const),
768 );
769 if (result === "published") {
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 logEnabledWhenReady = false;
777 unlinkedRetryDelayMs = 5_000;
778 yield* Queue.take(catchUpRequests);
779 continue;
780 }
781 const retryDelayMs = result === "unlinked" ? unlinkedRetryDelayMs : 5_000;
782 yield* Effect.race(Effect.sleep(retryDelayMs), Queue.take(catchUpRequests));
783 if (result === "unlinked") {
784 unlinkedRetryDelayMs = Math.min(unlinkedRetryDelayMs * 2, 60_000);
785 }
786 }
787 });
788
789 schedulePublishConfirm = (threadId) =>
790 Effect.forkIn(
791 Effect.sleep("5 seconds").pipe(
792 Effect.andThen(worker.enqueue(threadId)),
793 Effect.catchCause((cause) =>
794 Effect.logWarning("deferred agent activity confirmation failed", {
795 threadId,
796 cause: Cause.pretty(cause),
797 }),
798 ),
799 ),
800 scope,
801 ).pipe(Effect.asVoid);
802
803 const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
804 function* () {
805 const [relayConfig, publishEnabled] = yield* Effect.all([
806 readRelayConfig.pipe(Effect.orElseSucceed(() => null)),
807 readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),
808 ]);
809 const startupState = resolveAgentActivityPublishingStartupState({
810 relayConfigured: relayConfig !== null,
811 publishEnabled,
812 });
813 switch (startupState) {
814 case "waiting-for-link":
815 yield* Effect.logInfo(
816 "agent activity publishing standby; waiting for T3 Connect link reconciliation",
817 );
818 break;
819 case "disabled":
820 yield* Effect.logInfo("agent activity publishing disabled by T3 Connect configuration");
821 break;
822 case "enabled":
823 yield* Effect.logInfo("agent activity publishing enabled", {
824 relayUrl: relayConfig?.url,
825 });
826 break;
827 }
828 yield* forkParked(
829 Effect.sleep("1 second").pipe(
830 Effect.andThen(publishActiveThreadsWhenConfigured(startupState !== "enabled")),
831 ),
832 );
833 yield* forkParked(
834 Stream.runForEach(threads.streamDomainEvents, (event) => {
835 const threadId = eventThreadId(event);
836 if (!shouldPublishAgentAwarenessEvent(event)) {
837 return Effect.void;
838 }
839 return Effect.logDebug("agent activity publishing queued thread publish", {
840 eventType: event.type,
841 threadId,
842 }).pipe(Effect.andThen(enqueueThreadPublish(threadId)));
843 }),
844 );
845 },
846 );
847
848 return AgentAwarenessRelay.of({
849 publishThread,
850 drain: worker.drain,
851 requestCatchUp: Effect.fn("AgentAwarenessRelay.requestCatchUp")(function () {
852 return Queue.offer(catchUpRequests, undefined).pipe(Effect.asVoid);
853 }),
854 start,
855 });
856});
857
858export const layer = Layer.effect(AgentAwarenessRelay, make);