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 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 */
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 // Confirm through the same worker so tombstones cannot race live updates; recovery clears the deadline.
413 const publishConfirmDeadlines = new Map<ThreadId, number>();
414 // Threads whose confirmation holds a completion, so a thread that settles during the hold still alerts.
415 const heldCompletions = new Set<ThreadId>();
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 heldCompletions.clear();
435 yield* Ref.set(publishedStateByThreadRef, new Map());
436 });
437
438 const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) {
439 const publishAgentActivity = yield* readPublishAgentActivityEnabled;
440 if (!publishAgentActivity) {
441 yield* cancelPublishRetries;
442 yield* resetPublishedConnection;
443 yield* Effect.logDebug("agent activity publish skipped; publication disabled", {
444 threadId,
445 });
446 return;
447 }
448 const relayConfig = yield* readRelayConfig;
449 if (!relayConfig) {
450 yield* cancelPublishRetries;
451 yield* resetPublishedConnection;
452 yield* Effect.logDebug("agent activity publish skipped; relay link credentials unavailable", {
453 threadId,
454 });
455 return;
456 }
457 if (
458 publishedRelayConfig?.url !== relayConfig.url ||
459 publishedRelayConfig.issuer !== relayConfig.issuer ||
460 publishedRelayConfig.environmentCredential !== relayConfig.environmentCredential
461 ) {
462 yield* resetPublishedConnection;
463 publishedRelayConfig = relayConfig;
464 }
465 const environmentId = yield* serverEnvironment.getEnvironmentId;
466
467 const publishState = Effect.fn("relay.agent_activity.publish")(function* (input: {
468 readonly projectId: string | null;
469 readonly state: RelayAgentActivityState | null;
470 readonly reason: string;
471 }) {
472 if (cachedRelayClient === undefined) {
473 cachedRelayClient = yield* makeRelayClient(relayConfig);
474 }
475 const relayClient = cachedRelayClient;
476 const proof = yield* makePublishProof({
477 privateKey: cloudLinkKeyPair.privateKey,
478 relayIssuer: relayConfig.issuer,
479 environmentId,
480 threadId,
481 state: input.state,
482 jti: yield* crypto.randomUUIDv4(),
483 });
484
485 yield* Effect.logInfo("publishing agent activity for thread", {
486 environmentId,
487 threadId,
488 projectId: input.projectId,
489 statePhase: input.state?.phase ?? null,
490 hasState: input.state !== null,
491 reason: input.reason,
492 });
493
494 const response = yield* relayClient.server
495 .publishAgentActivity({
496 params: {
497 environmentId,
498 threadId,
499 },
500 payload: {
501 state: input.state,
502 proof,
503 },
504 })
505 .pipe(Effect.timeout("10 seconds"));
506
507 yield* Effect.logInfo("agent activity publish completed", {
508 environmentId,
509 threadId,
510 ok: response.ok,
511 deliveries: deliveryStats(response.deliveries),
512 });
513 });
514
515 // Read only this thread; full shell reads would make each activity event scale with all threads.
516 const threadShell = yield* threads.getThreadShell(threadId);
517 if (
518 threadShell?.lineage.relationshipToParent === "subagent" &&
519 !(yield* Ref.get(publishedStateByThreadRef)).has(threadId)
520 ) {
521 // Subagents 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 threadId,
534 thread,
535 project,
536 });
537 const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);
538 const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);
539 if (
540 (snapshot.state?.phase === "completed" || snapshot.state?.phase === "failed") &&
541 !publishedStateByThread.has(threadId)
542 ) {
543 if (Option.isNone(thread) || !terminalWorkSinceStart(thread.value, startedAt)) return;
544 }
545 if (publishedStateByThread.get(threadId) === publishIdentity) {
546 // Clear moot deadlines so later transient nulls cannot skip their deferral window.
547 publishConfirmDeadlines.delete(threadId);
548 heldCompletions.delete(threadId);
549 yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", {
550 environmentId,
551 threadId,
552 reason: snapshot.reason,
553 });
554 return;
555 }
556
557 // Confirm tombstones over live state to avoid removing active cards.
558 // Confirm completion: a run can end moments before its continuation starts, and the relay
559 // alerts on every move into completed.
560 const requiresConfirmation =
561 (snapshot.state === null &&
562 publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) ||
563 snapshot.state?.phase === "completed";
564 if (requiresConfirmation) {
565 if (snapshot.state?.phase === "completed") heldCompletions.add(threadId);
566 const nowMs = (yield* DateTime.now).epochMilliseconds;
567 const deadline = publishConfirmDeadlines.get(threadId);
568 if (deadline === undefined) {
569 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
570 yield* Effect.logInfo("agent activity publish deferred pending confirmation", {
571 environmentId,
572 threadId,
573 reason: snapshot.reason,
574 statePhase: snapshot.state?.phase ?? null,
575 shell: describeThreadShellForAwareness(thread),
576 });
577 yield* schedulePublishConfirm(threadId);
578 return;
579 }
580 if (nowMs < deadline) {
581 return;
582 }
583 yield* Effect.logInfo("agent activity deferred publish confirmed", {
584 environmentId,
585 threadId,
586 reason: snapshot.reason,
587 statePhase: snapshot.state?.phase ?? null,
588 shell: describeThreadShellForAwareness(thread),
589 });
590 // Settled during the hold, not resumed: alert the current completion, then clear the card
591 // on a new window. Only settlement may hide it; queued or silent runs also project to null.
592 const unsettled =
593 snapshot.state === null &&
594 heldCompletions.has(threadId) &&
595 Option.isSome(thread) &&
596 thread.value.settledOverride === "settled"
597 ? resolveAgentAwarenessRelayPublishSnapshot({
598 environmentId,
599 threadId,
600 thread: Option.some({ ...thread.value, settledOverride: null }),
601 project,
602 })
603 : null;
604 if (unsettled?.state?.phase === "completed") {
605 const completion = unsettled.state;
606 yield* publishState({
607 projectId: unsettled.projectId,
608 state: completion,
609 reason: unsettled.reason,
610 }).pipe(withRelayClientTracing);
611 heldCompletions.delete(threadId);
612 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
613 yield* Ref.update(publishedStateByThreadRef, (publishedStates) =>
614 new Map(publishedStates).set(threadId, agentAwarenessPublishIdentity(completion)),
615 );
616 yield* schedulePublishConfirm(threadId);
617 return;
618 }
619 } else {
620 publishConfirmDeadlines.delete(threadId);
621 heldCompletions.delete(threadId);
622 }
623
624 if (snapshot.reason === "thread-not-found") {
625 yield* Effect.logDebug("publishing agent activity tombstone; thread not found", {
626 environmentId,
627 threadId,
628 });
629 } else if (snapshot.reason === "project-not-found") {
630 yield* Effect.logDebug("publishing agent activity tombstone; project not found", {
631 environmentId,
632 threadId,
633 projectId: snapshot.projectId,
634 });
635 }
636
637 yield* publishState({
638 projectId: snapshot.projectId,
639 state: snapshot.state,
640 reason: snapshot.reason,
641 }).pipe(withRelayClientTracing);
642 publishConfirmDeadlines.delete(threadId);
643 heldCompletions.delete(threadId);
644 yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {
645 const nextPublishedStates = new Map(publishedStates);
646 if (snapshot.state === null) {
647 nextPublishedStates.delete(threadId);
648 } else {
649 nextPublishedStates.set(threadId, publishIdentity);
650 }
651 return nextPublishedStates;
652 });
653 });
654
655 const processThreadPublish = Effect.fnUntraced(function* (threadId: ThreadId) {
656 const retry = publishRetries.get(threadId);
657 if (retry?.timer !== undefined) {
658 const timer = retry.timer;
659 retry.timer = undefined;
660 yield* Fiber.interrupt(timer);
661 }
662 yield* publishThreadUnsafe(threadId).pipe(
663 Effect.tap(() => cancelPublishRetry(threadId)),
664 Effect.catchCause((cause) => {
665 if (Cause.hasInterruptsOnly(cause)) return Effect.void;
666 return Effect.logWarning("agent activity publish failed", {
667 threadId,
668 cause: Cause.pretty(cause),
669 }).pipe(Effect.andThen(schedulePublishRetry(threadId)));
670 }),
671 Effect.withSpan("AgentAwarenessRelay.publishThread"),
672 );
673 });
674
675 const worker = yield* makeAgentAwarenessPublishWorker(processThreadPublish);
676 const enqueueThreadPublish = (threadId: ThreadId) =>
677 cancelPublishRetry(threadId).pipe(Effect.andThen(worker.enqueue(threadId)));
678 const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
679 enqueueThreadPublish(threadId).pipe(Effect.andThen(worker.drain));
680
681 schedulePublishRetry = Effect.fnUntraced(function* (threadId: ThreadId) {
682 const attempts = publishRetries.get(threadId)?.attempts ?? 0;
683 const delayMs = RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS[attempts];
684 if (delayMs === undefined) {
685 // Retain exhausted budgets until activity or success resets them; old timers must not restart retries.
686 yield* Effect.logWarning("agent activity publish retry budget exhausted", { threadId });
687 return;
688 }
689 const retry = {
690 attempts: attempts + 1,
691 timer: undefined as Fiber.Fiber<void> | undefined,
692 };
693 publishRetries.set(threadId, retry);
694 const timer = yield* Effect.sleep(delayMs).pipe(
695 Effect.andThen(
696 Effect.suspend(() => {
697 if (publishRetries.get(threadId) !== retry) return Effect.void;
698 retry.timer = undefined;
699 return worker.enqueue(threadId);
700 }),
701 ),
702 Effect.forkIn(scope),
703 );
704 if (publishRetries.get(threadId) !== retry) {
705 yield* Fiber.interrupt(timer);
706 } else {
707 retry.timer = timer;
708 }
709 });
710
711 const publishActiveThreadsUnsafe = Effect.gen(function* () {
712 const relayUrl = yield* readSecretString(RELAY_URL_SECRET).pipe(
713 Effect.orElseSucceed(() => null),
714 );
715 if (!relayUrl) {
716 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
717 return "unlinked" as const;
718 }
719 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
720 Effect.orElseSucceed(() => false),
721 );
722 if (!publishAgentActivity) {
723 yield* Effect.logDebug("agent activity snapshot skipped; publication disabled");
724 return "disabled" as const;
725 }
726 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
727 if (!relayConfig) {
728 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
729 return "unlinked" as const;
730 }
731 const environmentId = yield* serverEnvironment.getEnvironmentId;
732 const [projectSnapshot, shellSnapshot] = yield* Effect.all([
733 projects.snapshot,
734 threads.getShellSnapshot(),
735 ]);
736 const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({
737 environmentId,
738 startedAt,
739 projects: projectSnapshot.projects,
740 threads: shellSnapshot.threads,
741 });
742 if (activeThreadIds.length === 0) {
743 yield* Effect.logDebug("agent activity snapshot has no publishable threads");
744 return "published" as const;
745 }
746 yield* Effect.logInfo("publishing active agent activity snapshot", {
747 count: activeThreadIds.length,
748 });
749 yield* Effect.forEach(activeThreadIds, enqueueThreadPublish, { discard: true });
750 yield* worker.drain;
751 return "published" as const;
752 });
753
754 // Many environments never link, so while unlinked the retry backs off from 5
755 // s to 60 s. A linked environment keeps the 5 s retry, because `t3 connect
756 // publish` can turn publishing on from another process. Keep this untraced:
757 // an unlinked environment can retry for the lifetime of the process.
758 const publishActiveThreadsOnceWhenConfigured = Effect.fnUntraced(function* (
759 logEnabledWhenReady: boolean,
760 ) {
761 let unlinkedRetryDelayMs = 5_000;
762 while (!(yield* Ref.get(activeSnapshotPublishedRef))) {
763 const result = yield* publishActiveThreadsUnsafe.pipe(
764 Effect.orElseSucceed(() => "failed" as const),
765 );
766 if (result === "published") {
767 yield* Ref.set(activeSnapshotPublishedRef, true);
768 if (logEnabledWhenReady) {
769 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
770 yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
771 relayUrl: relayConfig?.url,
772 });
773 }
774 return;
775 }
776 const retryDelayMs = result === "unlinked" ? unlinkedRetryDelayMs : 5_000;
777 yield* Effect.race(Effect.sleep(retryDelayMs), Queue.take(catchUpRequests));
778 if (result === "unlinked") {
779 unlinkedRetryDelayMs = Math.min(unlinkedRetryDelayMs * 2, 60_000);
780 }
781 }
782 });
783
784 schedulePublishConfirm = (threadId) =>
785 Effect.forkIn(
786 Effect.sleep("5 seconds").pipe(
787 Effect.andThen(worker.enqueue(threadId)),
788 Effect.catchCause((cause) =>
789 Effect.logWarning("deferred agent activity confirmation failed", {
790 threadId,
791 cause: Cause.pretty(cause),
792 }),
793 ),
794 ),
795 scope,
796 ).pipe(Effect.asVoid);
797
798 const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
799 function* () {
800 const [relayConfig, publishEnabled] = yield* Effect.all([
801 readRelayConfig.pipe(Effect.orElseSucceed(() => null)),
802 readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),
803 ]);
804 const startupState = resolveAgentActivityPublishingStartupState({
805 relayConfigured: relayConfig !== null,
806 publishEnabled,
807 });
808 switch (startupState) {
809 case "waiting-for-link":
810 yield* Effect.logInfo(
811 "agent activity publishing standby; waiting for T3 Connect link reconciliation",
812 );
813 break;
814 case "disabled":
815 yield* Effect.logInfo("agent activity publishing disabled by T3 Connect configuration");
816 break;
817 case "enabled":
818 yield* Effect.logInfo("agent activity publishing enabled", {
819 relayUrl: relayConfig?.url,
820 });
821 break;
822 }
823 yield* forkParked(
824 Effect.sleep("1 second").pipe(
825 Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")),
826 ),
827 );
828 yield* forkParked(
829 Stream.runForEach(threads.streamDomainEvents, (event) => {
830 const threadId = eventThreadId(event);
831 if (!shouldPublishAgentAwarenessEvent(event)) {
832 return Effect.void;
833 }
834 return Effect.logDebug("agent activity publishing queued thread publish", {
835 eventType: event.type,
836 threadId,
837 }).pipe(Effect.andThen(enqueueThreadPublish(threadId)));
838 }),
839 );
840 },
841 );
842
843 return AgentAwarenessRelay.of({
844 publishThread,
845 drain: worker.drain,
846 requestCatchUp: Effect.fn("AgentAwarenessRelay.requestCatchUp")(function () {
847 return Queue.offer(catchUpRequests, undefined).pipe(Effect.asVoid);
848 }),
849 start,
850 });
851});
852
853export const layer = Layer.effect(AgentAwarenessRelay, make);