Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AgentAwarenessRelay.ts

838 lines30.5 KB

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/unstable/http/FetchHttpClient";
36import * as HttpClient from "effect/unstable/http/HttpClient";
37import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
38import * as HttpApiClient from "effect/unstable/httpapi/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 /** Retries a pending catch-up publish now. Call after this process links or enables publishing. */
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;
68​
69// The filter takes loosely typed events; a turn-item payload carries both fields.
70function isTurnItemPayload(
71 payload: unknown,
72): payload is Pick<OrchestrationV2TurnItem, "type" | "status"> {
73 return (
74 typeof payload === "object" && payload !== null && "type" in payload && "status" in payload
75 );
77​
78export function shouldPublishAgentAwarenessEvent(
79 event: Pick<OrchestrationV2DomainEvent, "type"> & { readonly payload?: unknown },
80): boolean {
81 if (
82 event.type === "thread.created" &&
83 typeof event.payload === "object" &&
84 event.payload !== null &&
85 "historyOrigin" in event.payload &&
86 event.payload.historyOrigin === "v1_import"
87 ) {
88 return false;
89 }
90 // projectThreadAwarenessV2 reads thread metadata, run status, pending requests,
91 // and pending background work (a finished subagent, a cleared roster, or an
92 // ended background item can release a held completion). Message bodies and
93 // tool progress cannot change the published activity.
94 switch (event.type) {
95 case "thread.created":
96 case "thread.archived":
97 case "thread.unarchived":
98 case "thread.deleted":
99 case "thread.metadata-updated":
100 case "thread.pull-request-synced":
101 case "thread.model-selection-updated":
102 case "thread.provider-switched":
103 case "run.created":
104 case "run.updated":
105 case "runtime-request.updated":
106 case "subagent.updated":
107 case "provider-thread.updated":
108 return true;
109 case "thread.settled":
110 case "thread.unsettled":
111 case "thread.snoozed":
112 case "thread.unsnoozed":
113 case "thread.auto-settle-set":
114 case "thread.pinned":
115 case "thread.unpinned":
116 case "thread.pin-reordered":
117 case "thread.active-reordered":
118 case "thread.visited":
119 case "thread.marked-unread":
120 case "thread.runtime-mode-updated":
121 case "thread.interaction-mode-updated":
122 case "run.background-work-cancelled":
123 case "run-attempt.created":
124 case "run-attempt.updated":
125 case "node.updated":
126 case "provider-session.attached":
127 case "provider-session.updated":
128 case "provider-session.detached":
129 case "provider-turn.updated":
130 case "turn-item.updated":
131 return isTurnItemPayload(event.payload) && turnItemUpdateCanEndBackgroundWork(event.payload);
132 case "message.updated":
133 case "plan.updated":
134 case "checkpoint-scope.created":
135 case "checkpoint.captured":
136 case "checkpoint.rollback-requested":
137 case "context-handoff.updated":
138 case "context-transfer.created":
139 case "context-transfer.updated":
140 return false;
141 }
143​
144export const makeAgentAwarenessPublishWorker = Effect.fnUntraced(function* <R>(
145 publish: (threadId: ThreadId) => Effect.Effect<void, never, R>,
146) {
147 const queued = new Set<ThreadId>();
148 const worker = yield* makeDrainableWorker((threadId: ThreadId) =>
149 Effect.sync(() => queued.delete(threadId)).pipe(Effect.andThen(publish(threadId))),
150 );
151 const enqueue = (threadId: ThreadId) =>
152 Effect.suspend(() => {
153 if (queued.has(threadId)) return Effect.void;
154 // Removing the ID when processing starts allows one new queue entry
155 // for updates received while the current snapshot is being published.
156 queued.add(threadId);
157 return worker.enqueue(threadId);
158 }).pipe(Effect.uninterruptible);
159 return { enqueue, drain: worker.drain };
160});
161​
162function agentAwarenessPublishIdentity(state: RelayAgentActivityState | null): string {
163 if (state === null) {
164 return "null";
165 }
166 const { updatedAt: _updatedAt, ...meaningfulState } = state;
167 return JSON.stringify(meaningfulState);
169​
170function resolveAgentActivityPublishingStartupState(input: {
171 readonly relayConfigured: boolean;
172 readonly publishEnabled: boolean;
173}): "waiting-for-link" | "disabled" | "enabled" {
174 if (!input.relayConfigured) {
175 return "waiting-for-link";
176 }
177 return input.publishEnabled ? "enabled" : "disabled";
179​
180const RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH = 160;
181const REDACTED_RELAY_AGENT_FAILURE_DETAIL = "The agent run failed.";
182const RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000] as const;
183​
184function sanitizeRelayAgentActivityState(
185 state: RelayAgentActivityState | null,
186): RelayAgentActivityState | null {
187 if (state === null) {
188 return null;
189 }
190 const { detail: _detail, ...rest } = state;
191 const detail = (state.phase === "failed" ? REDACTED_RELAY_AGENT_FAILURE_DETAIL : state.detail)
192 ?.trim()
193 .slice(0, RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH)
194 .trim();
195 return detail ? { ...rest, detail } : rest;
197​
198function relayEnvironmentClient(token: string) {
199 return HttpClient.mapRequest(HttpClientRequest.setHeader("authorization", `Bearer ${token}`));
201​
202function deliveryStats(
203 deliveries: ReadonlyArray<{
204 readonly ok: boolean;
205 readonly queued?: boolean | undefined;
206 readonly kind: string;
207 readonly apnsStatus?: number | null;
208 readonly apnsReason?: string | null;
209 }>,
210) {
211 let queued = 0;
212 let successful = 0;
213 let failed = 0;
214 const failedReasons: string[] = [];
215 const kinds = new Set<string>();
216​
217 for (const delivery of deliveries) {
218 kinds.add(delivery.kind);
219 if (delivery.queued) {
220 queued += 1;
221 continue;
222 }
223 if (delivery.ok) {
224 successful += 1;
225 continue;
226 }
227 failed += 1;
228 failedReasons.push(`${delivery.apnsStatus ?? "transport"}:${delivery.apnsReason ?? "unknown"}`);
229 }
230​
231 return {
232 total: deliveries.length,
233 queued,
234 successful,
235 failed,
236 kinds: [...kinds],
237 failedReasons,
238 };
240​
241function signRelayAgentActivityPublishProof(input: {
242 readonly privateKey: string;
243 readonly payload: RelayAgentActivityPublishProofPayload;
244}) {
245 return signRelayJwt({
246 privateKey: input.privateKey,
247 typ: RELAY_ACTIVITY_PUBLISH_TYP,
248 payload: input.payload,
249 });
251​
252const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
253 readonly privateKey: string;
254 readonly relayIssuer: string;
255 readonly environmentId: string;
256 readonly threadId: ThreadId;
257 readonly state: RelayAgentActivityState | null;
258 readonly jti: string;
259}) {
260 const now = yield* DateTime.now;
261 const expiresAt = DateTime.add(now, { minutes: 5 });
262 const payload = {
263 iss: `t3-env:${input.environmentId}`,
264 aud: normalizeRelayIssuer(input.relayIssuer),
265 sub: input.environmentId,
266 jti: input.jti,
267 iat: Math.floor(now.epochMilliseconds / 1_000),
268 exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
269 environmentId: input.environmentId as RelayAgentActivityPublishProofPayload["environmentId"],
270 threadId: input.threadId,
271 state: input.state,
272 } satisfies RelayAgentActivityPublishProofPayload;
273 return yield* signRelayAgentActivityPublishProof({ privateKey: input.privateKey, payload });
274});
275​
276// Compact, log-safe view of the fields the awareness phase ladder reads.
277function describeThreadShellForAwareness(
278 thread: Option.Option<OrchestrationV2ThreadShell>,
279): Record<string, unknown> {
280 if (Option.isNone(thread)) {
281 return { found: false };
282 }
283 const shell = thread.value;
284 return {
285 found: true,
286 status: shell.status,
287 activityRunStatus: shell.activityRunStatus ?? null,
288 activeRunId: shell.activeRunId ?? null,
289 latestRunId: shell.latestRunId ?? null,
290 pendingRuntimeRequestKind: shell.pendingRuntimeRequest?.kind ?? null,
291 hasActionableProposedPlan: shell.hasActionableProposedPlan,
292 };
294​
295function resolveAgentAwarenessRelayPublishSnapshot(input: {
296 readonly environmentId: EnvironmentId;
297 readonly threadId: ThreadId;
298 readonly thread: Option.Option<OrchestrationV2ThreadShell>;
299 readonly project: Option.Option<Project>;
300}): {
301 readonly projectId: string | null;
302 readonly state: RelayAgentActivityState | null;
303 readonly reason: "snapshot" | "thread-not-found" | "project-not-found";
304} {
305 if (Option.isNone(input.thread)) {
306 return {
307 projectId: null,
308 state: null,
309 reason: "thread-not-found",
310 };
311 }
312 if (Option.isNone(input.project)) {
313 return {
314 projectId: input.thread.value.projectId,
315 state: null,
316 reason: "project-not-found",
317 };
318 }
319 return {
320 projectId: input.thread.value.projectId,
321 state: sanitizeRelayAgentActivityState(
322 projectThreadAwarenessV2({
323 environmentId: input.environmentId,
324 project: input.project.value,
325 thread: input.thread.value,
326 }),
327 ),
328 reason: "snapshot",
329 };
331​
332function terminalWorkSinceStart(thread: OrchestrationV2ThreadShell, startedAt: number): boolean {
333 return (
334 thread.latestRunCompletedAt != null &&
335 DateTime.toEpochMillis(thread.latestRunCompletedAt) > startedAt
336 );
338​
339export function resolveAgentAwarenessRelayActiveThreadIds(input: {
340 readonly environmentId: EnvironmentId;
341 readonly startedAt: number;
342 readonly projects: ReadonlyArray<Pick<Project, "id" | "title">>;
343 readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;
344}): ReadonlyArray<ThreadId> {
345 const projectById = new Map(input.projects.map((project) => [project.id, project]));
346 return input.threads
347 .filter((thread) => {
348 const project = projectById.get(thread.projectId);
349 if (!project) {
350 return false;
351 }
352 const state = projectThreadAwarenessV2({
353 environmentId: input.environmentId,
354 project,
355 thread,
356 });
357 return (
358 state !== null &&
359 (state.phase !== "completed" && state.phase !== "failed"
360 ? true
361 : terminalWorkSinceStart(thread, input.startedAt))
362 );
363 })
364 .map((thread) => thread.id);
366​
367/** @public Service construction is part of the canonical Effect module API. */
368export const make = Effect.gen(function* () {
369 const secrets = yield* ServerSecretStore.ServerSecretStore;
370 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
371 const threads = yield* ThreadManagement.ThreadManagementService;
372 const projects = yield* ProjectService.ProjectService;
373 const crypto = yield* Crypto.Crypto;
374 const scope = yield* Effect.scope;
375 const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
376 const startedAt = (yield* DateTime.now).epochMilliseconds;
377 const activeSnapshotPublishedRef = yield* Ref.make(false);
378 // Holds at most one pending wake, so a burst of requests costs one retry.
379 const catchUpRequests = yield* Queue.dropping<void>(1);
380 const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());
381​
382 const readSecretString = (name: string) =>
383 secrets
384 .get(name)
385 .pipe(
386 Effect.map((bytes) =>
387 Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,
388 ),
389 );
390​
391 const readRelayConfig = Effect.gen(function* () {
392 const [url, issuer, environmentCredential] = yield* Effect.all([
393 readSecretString(RELAY_URL_SECRET),
394 readSecretString(RELAY_ISSUER_SECRET),
395 readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
396 ]);
397 return url && environmentCredential
398 ? { url, issuer: issuer ?? url, environmentCredential }
399 : null;
400 });
401​
402 const readPublishAgentActivityEnabled = readSecretString(PUBLISH_AGENT_ACTIVITY_SECRET).pipe(
403 Effect.map(isAgentActivityPublishingEnabledValue),
404 );
405​
406 const makeRelayClient = (relayConfig: {
407 readonly url: string;
408 readonly environmentCredential: string;
409 }) =>
410 HttpApiClient.make(RelayApi, {
411 baseUrl: relayConfig.url,
412 transformClient: relayEnvironmentClient(relayConfig.environmentCredential),
413 }).pipe(Effect.provide(FetchHttpClient.layer));
414​
415 let cachedRelayClient: Effect.Success<ReturnType<typeof makeRelayClient>> | undefined;
416 let publishedRelayConfig: NonNullable<Effect.Success<typeof readRelayConfig>> | undefined;
417​
418 // Deadlines for publishes that need confirmation (tombstones and
419 // first-state completions). The confirming publish is re-enqueued through
420 // the same drainable worker as every other publish, so a confirmed
421 // tombstone can never race an in-flight live update; a recovered state
422 // clears the deadline. Assigned after the worker exists.
423 const publishConfirmDeadlines = new Map<ThreadId, number>();
424 let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
425 const publishRetries = new Map<
426 ThreadId,
427 { readonly attempts: number; timer: Fiber.Fiber<void> | undefined }
428 >();
429 const cancelPublishRetry = Effect.fnUntraced(function* (threadId: ThreadId) {
430 const retry = publishRetries.get(threadId);
431 publishRetries.delete(threadId);
432 if (retry?.timer !== undefined) yield* Fiber.interrupt(retry.timer);
433 });
434 const cancelPublishRetries = Effect.suspend(() =>
435 Effect.forEach([...publishRetries.keys()], cancelPublishRetry, { discard: true }),
436 );
437 let schedulePublishRetry: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
438 const resetPublishedConnection = Effect.gen(function* () {
439 publishedRelayConfig = undefined;
440 cachedRelayClient = undefined;
441 publishConfirmDeadlines.clear();
442 yield* Ref.set(publishedStateByThreadRef, new Map());
443 });
444​
445 const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) {
446 const publishAgentActivity = yield* readPublishAgentActivityEnabled;
447 if (!publishAgentActivity) {
448 yield* cancelPublishRetries;
449 yield* resetPublishedConnection;
450 yield* Effect.logDebug("agent activity publish skipped; publication disabled", {
451 threadId,
452 });
453 return;
454 }
455 const relayConfig = yield* readRelayConfig;
456 if (!relayConfig) {
457 yield* cancelPublishRetries;
458 yield* resetPublishedConnection;
459 yield* Effect.logDebug("agent activity publish skipped; relay link credentials unavailable", {
460 threadId,
461 });
462 return;
463 }
464 if (
465 publishedRelayConfig?.url !== relayConfig.url ||
466 publishedRelayConfig.issuer !== relayConfig.issuer ||
467 publishedRelayConfig.environmentCredential !== relayConfig.environmentCredential
468 ) {
469 yield* resetPublishedConnection;
470 publishedRelayConfig = relayConfig;
471 }
472 const environmentId = yield* serverEnvironment.getEnvironmentId;
473​
474 const publishState = (input: {
475 readonly projectId: string | null;
476 readonly state: RelayAgentActivityState | null;
477 readonly reason: string;
478 }) =>
479 Effect.gen(function* () {
480 if (cachedRelayClient === undefined) {
481 cachedRelayClient = yield* makeRelayClient(relayConfig);
482 }
483 const relayClient = cachedRelayClient;
484 const proof = yield* makePublishProof({
485 privateKey: cloudLinkKeyPair.privateKey,
486 relayIssuer: relayConfig.issuer,
487 environmentId,
488 threadId,
489 state: input.state,
490 jti: yield* crypto.randomUUIDv4,
491 });
492​
493 yield* Effect.logInfo("publishing agent activity for thread", {
494 environmentId,
495 threadId,
496 projectId: input.projectId,
497 statePhase: input.state?.phase ?? null,
498 hasState: input.state !== null,
499 reason: input.reason,
500 });
501​
502 const response = yield* relayClient.server.publishAgentActivity({
503 params: {
504 environmentId,
505 threadId,
506 },
507 payload: {
508 state: input.state,
509 proof,
510 },
511 });
512​
513 yield* Effect.logInfo("agent activity publish completed", {
514 environmentId,
515 threadId,
516 ok: response.ok,
517 deliveries: deliveryStats(response.deliveries),
518 });
519 });
520​
521 // Per-thread shell read: this publish runs for every activity-relevant
522 // domain event, so materializing the full shell here would make the cost
523 // of one thread's activity proportional to how many threads exist.
524 const threadShell = yield* threads.getThreadShell(threadId);
525 const thread =
526 threadShell === null || threadShell.archivedAt !== null
527 ? Option.none<OrchestrationV2ThreadShell>()
528 : Option.some(threadShell);
529 const project = Option.isSome(thread)
530 ? yield* projects.getById(thread.value.projectId)
531 : Option.none<Project>();
532 const snapshot = resolveAgentAwarenessRelayPublishSnapshot({
533 environmentId,
534 threadId,
535 thread,
536 project,
537 });
538 const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);
539 const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);
540 if (
541 (snapshot.state?.phase === "completed" || snapshot.state?.phase === "failed") &&
542 !publishedStateByThread.has(threadId)
543 ) {
544 // Startup has no publish history. Only work from this server process may
545 // produce an initial terminal alert; historical threads remain quiet.
546 if (Option.isNone(thread) || !terminalWorkSinceStart(thread.value, startedAt)) return;
547 }
548 if (publishedStateByThread.get(threadId) === publishIdentity) {
549 // The projection is back at (or never left) the last published state, so
550 // any pending deferred confirmation is moot. Leaving the deadline in
551 // place would let a much later transient null find it already expired
552 // and publish a tombstone immediately, skipping the deferral window.
553 publishConfirmDeadlines.delete(threadId);
554 yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", {
555 environmentId,
556 threadId,
557 reason: snapshot.reason,
558 });
559 return;
560 }
561​
562 // Two projections need confirmation before publishing, because both can
563 // appear transiently while the projector is mid-write and publishing them
564 // immediately is destructive or noisy:
565 // - null (tombstone) while the previous published state was live: deletes
566 // the thread from every armed card mid-conversation.
567 // - completed as the thread's FIRST published state: sessions boot at
568 // "ready" before their first turn, which projects as completed for an
569 // instant and sends a spurious Done notification at thread birth.
570 // Defer, schedule a re-publish through the ordinary worker queue, and
571 // only publish if the projection still holds when it drains.
572 const requiresConfirmation =
573 (snapshot.state === null &&
574 publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) ||
575 (snapshot.state?.phase === "completed" && !publishedStateByThread.has(threadId));
576 if (requiresConfirmation) {
577 const nowMs = (yield* DateTime.now).epochMilliseconds;
578 const deadline = publishConfirmDeadlines.get(threadId);
579 if (deadline === undefined) {
580 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
581 yield* Effect.logInfo("agent activity publish deferred pending confirmation", {
582 environmentId,
583 threadId,
584 reason: snapshot.reason,
585 statePhase: snapshot.state?.phase ?? null,
586 shell: describeThreadShellForAwareness(thread),
587 });
588 yield* schedulePublishConfirm(threadId);
589 return;
590 }
591 if (nowMs < deadline) {
592 return;
593 }
594 yield* Effect.logInfo("agent activity deferred publish confirmed", {
595 environmentId,
596 threadId,
597 reason: snapshot.reason,
598 statePhase: snapshot.state?.phase ?? null,
599 shell: describeThreadShellForAwareness(thread),
600 });
601 } else {
602 publishConfirmDeadlines.delete(threadId);
603 }
604​
605 if (snapshot.reason === "thread-not-found") {
606 yield* Effect.logDebug("publishing agent activity tombstone; thread not found", {
607 environmentId,
608 threadId,
609 });
610 } else if (snapshot.reason === "project-not-found") {
611 yield* Effect.logDebug("publishing agent activity tombstone; project not found", {
612 environmentId,
613 threadId,
614 projectId: snapshot.projectId,
615 });
616 }
617​
618 yield* publishState({
619 projectId: snapshot.projectId,
620 state: snapshot.state,
621 reason: snapshot.reason,
622 });
623 publishConfirmDeadlines.delete(threadId);
624 yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {
625 const nextPublishedStates = new Map(publishedStates);
626 if (snapshot.state === null) {
627 nextPublishedStates.delete(threadId);
628 } else {
629 nextPublishedStates.set(threadId, publishIdentity);
630 }
631 return nextPublishedStates;
632 });
633 });
634​
635 const processThreadPublish = Effect.fnUntraced(function* (threadId: ThreadId) {
636 const retry = publishRetries.get(threadId);
637 if (retry?.timer !== undefined) {
638 const timer = retry.timer;
639 retry.timer = undefined;
640 yield* Fiber.interrupt(timer);
641 }
642 yield* publishThreadUnsafe(threadId).pipe(
643 Effect.tap(() => cancelPublishRetry(threadId)),
644 Effect.catchCause((cause) => {
645 if (Cause.hasInterruptsOnly(cause)) return Effect.void;
646 return Effect.logWarning("agent activity publish failed", {
647 threadId,
648 cause: Cause.pretty(cause),
649 }).pipe(Effect.andThen(schedulePublishRetry(threadId)));
650 }),
651 Effect.withSpan("AgentAwarenessRelay.publishThread"),
652 withRelayClientTracing,
653 );
654 });
655​
656 const worker = yield* makeAgentAwarenessPublishWorker(processThreadPublish);
657 const enqueueThreadPublish = (threadId: ThreadId) =>
658 cancelPublishRetry(threadId).pipe(Effect.andThen(worker.enqueue(threadId)));
659 const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
660 enqueueThreadPublish(threadId).pipe(Effect.andThen(worker.drain));
661​
662 schedulePublishRetry = Effect.fnUntraced(function* (threadId: ThreadId) {
663 const attempts = publishRetries.get(threadId)?.attempts ?? 0;
664 const delayMs = RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS[attempts];
665 if (delayMs === undefined) {
666 // Keep the exhausted budget until fresh activity or a successful publish
667 // clears it; an old confirmation timer must not start another retry series.
668 yield* Effect.logWarning("agent activity publish retry budget exhausted", { threadId });
669 return;
670 }
671 const retry = {
672 attempts: attempts + 1,
673 timer: undefined as Fiber.Fiber<void> | undefined,
674 };
675 publishRetries.set(threadId, retry);
676 const timer = yield* Effect.sleep(delayMs).pipe(
677 Effect.andThen(
678 Effect.suspend(() => {
679 if (publishRetries.get(threadId) !== retry) return Effect.void;
680 retry.timer = undefined;
681 return worker.enqueue(threadId);
682 }),
683 ),
684 Effect.forkIn(scope),
685 );
686 if (publishRetries.get(threadId) !== retry) {
687 yield* Fiber.interrupt(timer);
688 } else {
689 retry.timer = timer;
690 }
691 });
692​
693 // Publishes the active threads once. Returns why it did not, so the retry
694 // knows whether it is waiting on a link or on the publish setting.
695 const publishActiveThreadsUnsafe = Effect.gen(function* () {
696 // One secret read settles the common never-linked case; the full link
697 // config is read only once publishing is on.
698 const relayUrl = yield* readSecretString(RELAY_URL_SECRET).pipe(
699 Effect.orElseSucceed(() => null),
700 );
701 if (!relayUrl) {
702 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
703 return "unlinked" as const;
704 }
705 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
706 Effect.orElseSucceed(() => false),
707 );
708 if (!publishAgentActivity) {
709 yield* Effect.logDebug("agent activity snapshot skipped; publication disabled");
710 return "disabled" as const;
711 }
712 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
713 if (!relayConfig) {
714 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
715 return "unlinked" as const;
716 }
717 const environmentId = yield* serverEnvironment.getEnvironmentId;
718 const [projectSnapshot, shellSnapshot] = yield* Effect.all([
719 projects.snapshot,
720 threads.getShellSnapshot(),
721 ]);
722 const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({
723 environmentId,
724 startedAt,
725 projects: projectSnapshot.projects,
726 threads: shellSnapshot.threads,
727 });
728 if (activeThreadIds.length === 0) {
729 yield* Effect.logDebug("agent activity snapshot has no publishable threads");
730 return "published" as const;
731 }
732 yield* Effect.logInfo("publishing active agent activity snapshot", {
733 count: activeThreadIds.length,
734 });
735 yield* Effect.forEach(activeThreadIds, enqueueThreadPublish, { discard: true });
736 yield* worker.drain;
737 return "published" as const;
738 });
739​
740 // Publishes the catch-up snapshot of active threads once the environment is
741 // linked and publishing is enabled. Many environments never link, so while
742 // unlinked the retry backs off from 5 s to 60 s. Only this process writes
743 // the link, and it calls `requestCatchUp`, which ends the wait early. A
744 // linked environment keeps the 5 s retry, because `t3 connect publish` can
745 // turn publishing on from another process.
746 const publishActiveThreadsOnceWhenConfigured = (logEnabledWhenReady: boolean) =>
747 Effect.gen(function* () {
748 let unlinkedRetryDelayMs = 5_000;
749 while (!(yield* Ref.get(activeSnapshotPublishedRef))) {
750 const result = yield* publishActiveThreadsUnsafe.pipe(
751 Effect.orElseSucceed(() => "failed" as const),
752 );
753 if (result === "published") {
754 yield* Ref.set(activeSnapshotPublishedRef, true);
755 if (logEnabledWhenReady) {
756 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
757 yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
758 relayUrl: relayConfig?.url,
759 });
760 }
761 return;
762 }
763 const retryDelayMs = result === "unlinked" ? unlinkedRetryDelayMs : 5_000;
764 yield* Effect.race(Effect.sleep(retryDelayMs), Queue.take(catchUpRequests));
765 if (result === "unlinked") {
766 unlinkedRetryDelayMs = Math.min(unlinkedRetryDelayMs * 2, 60_000);
767 }
768 }
769 });
770​
771 schedulePublishConfirm = (threadId) =>
772 Effect.forkIn(
773 Effect.sleep("5 seconds").pipe(
774 Effect.andThen(worker.enqueue(threadId)),
775 Effect.catchCause((cause) =>
776 Effect.logWarning("deferred agent activity confirmation failed", {
777 threadId,
778 cause: Cause.pretty(cause),
779 }),
780 ),
781 ),
782 scope,
783 ).pipe(Effect.asVoid);
784​
785 const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
786 function* () {
787 const [relayConfig, publishEnabled] = yield* Effect.all([
788 readRelayConfig.pipe(Effect.orElseSucceed(() => null)),
789 readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),
790 ]);
791 const startupState = resolveAgentActivityPublishingStartupState({
792 relayConfigured: relayConfig !== null,
793 publishEnabled,
794 });
795 switch (startupState) {
796 case "waiting-for-link":
797 yield* Effect.logInfo(
798 "agent activity publishing standby; waiting for T3 Connect link reconciliation",
799 );
800 break;
801 case "disabled":
802 yield* Effect.logInfo("agent activity publishing disabled by T3 Connect configuration");
803 break;
804 case "enabled":
805 yield* Effect.logInfo("agent activity publishing enabled", {
806 relayUrl: relayConfig?.url,
807 });
808 break;
809 }
810 yield* forkParked(
811 Effect.sleep("1 second").pipe(
812 Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")),
813 ),
814 );
815 yield* forkParked(
816 Stream.runForEach(threads.streamDomainEvents, (event) => {
817 const threadId = eventThreadId(event);
818 if (!shouldPublishAgentAwarenessEvent(event)) {
819 return Effect.void;
820 }
821 return Effect.logDebug("agent activity publishing queued thread publish", {
822 eventType: event.type,
823 threadId,
824 }).pipe(Effect.andThen(enqueueThreadPublish(threadId)));
825 }),
826 );
827 },
828 );
829​
830 return AgentAwarenessRelay.of({
831 publishThread,
832 drain: worker.drain,
833 requestCatchUp: () => Queue.offer(catchUpRequests, undefined).pipe(Effect.asVoid),
834 start,
835 });
836});
837​
838export const layer = Layer.effect(AgentAwarenessRelay, make);