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

AgentAwarenessRelay.ts

827 lines29.3 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/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;
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 );
75​
76export function 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.pull-request-link-synced":
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 case "thread.settled":
106 case "thread.unsettled":
107 case "thread.snoozed":
108 case "thread.unsnoozed":
109 case "thread.auto-settle-set":
110 case "thread.pinned":
111 case "thread.unpinned":
112 case "thread.pin-reordered":
113 case "thread.active-reordered":
114 case "thread.visited":
115 case "thread.visit-recorded":
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 }
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 // Removing the ID when processing starts allows one new queue entry
152 // for updates received while the current snapshot is being published.
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);
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";
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;
194​
195function relayEnvironmentClient(token: string) {
196 return HttpClient.mapRequest(HttpClientRequest.setHeader("authorization", `Bearer ${token}`));
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 };
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 });
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 };
290​
291function resolveAgentAwarenessRelayPublishSnapshot(input: {
292 readonly environmentId: EnvironmentId;
293 readonly threadId: ThreadId;
294 readonly thread: Option.Option<OrchestrationV2ThreadShell>;
295 readonly project: Option.Option<Project>;
296}): {
297 readonly projectId: string | null;
298 readonly state: RelayAgentActivityState | null;
299 readonly reason: "snapshot" | "thread-not-found" | "project-not-found";
300} {
301 if (Option.isNone(input.thread)) {
302 return {
303 projectId: null,
304 state: null,
305 reason: "thread-not-found",
306 };
307 }
308 if (Option.isNone(input.project)) {
309 return {
310 projectId: input.thread.value.projectId,
311 state: null,
312 reason: "project-not-found",
313 };
314 }
315 return {
316 projectId: input.thread.value.projectId,
317 state: sanitizeRelayAgentActivityState(
318 projectThreadAwarenessV2({
319 environmentId: input.environmentId,
320 project: input.project.value,
321 thread: input.thread.value,
322 }),
323 ),
324 reason: "snapshot",
325 };
327​
328function terminalWorkSinceStart(thread: OrchestrationV2ThreadShell, startedAt: number): boolean {
329 return (
330 thread.latestRunCompletedAt != null &&
331 DateTime.toEpochMillis(thread.latestRunCompletedAt) > startedAt
332 );
334​
335export function resolveAgentAwarenessRelayActiveThreadIds(input: {
336 readonly environmentId: EnvironmentId;
337 readonly startedAt: number;
338 readonly projects: ReadonlyArray<Pick<Project, "id" | "title">>;
339 readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;
340}): ReadonlyArray<ThreadId> {
341 const projectById = new Map(input.projects.map((project) => [project.id, project]));
342 return input.threads
343 .filter((thread) => {
344 const project = projectById.get(thread.projectId);
345 if (!project) {
346 return false;
347 }
348 const state = projectThreadAwarenessV2({
349 environmentId: input.environmentId,
350 project,
351 thread,
352 });
353 return (
354 state !== null &&
355 (state.phase !== "completed" && state.phase !== "failed"
356 ? true
357 : terminalWorkSinceStart(thread, input.startedAt))
358 );
359 })
360 .map((thread) => thread.id);
362​
363/** @public Service construction is part of the canonical Effect module API. */
364export const make = Effect.gen(function* () {
365 const secrets = yield* ServerSecretStore.ServerSecretStore;
366 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
367 const threads = yield* ThreadManagement.ThreadManagementService;
368 const projects = yield* ProjectService.ProjectService;
369 const crypto = yield* Crypto.Crypto;
370 const scope = yield* Effect.scope;
371 const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
372 const startedAt = (yield* DateTime.now).epochMilliseconds;
373 const activeSnapshotPublishedRef = yield* Ref.make(false);
374 const catchUpRequests = yield* Queue.dropping<void>(1);
375 const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());
376​
377 const readSecretString = (name: string) =>
378 secrets
379 .get(name)
380 .pipe(
381 Effect.map((bytes) =>
382 Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,
383 ),
384 );
385​
386 const readRelayConfig = Effect.gen(function* () {
387 const [url, issuer, environmentCredential] = yield* Effect.all([
388 readSecretString(RELAY_URL_SECRET),
389 readSecretString(RELAY_ISSUER_SECRET),
390 readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
391 ]);
392 return url && environmentCredential
393 ? { url, issuer: issuer ?? url, environmentCredential }
394 : null;
395 });
396​
397 const readPublishAgentActivityEnabled = readSecretString(PUBLISH_AGENT_ACTIVITY_SECRET).pipe(
398 Effect.map(isAgentActivityPublishingEnabledValue),
399 );
400​
401 const makeRelayClient = (relayConfig: {
402 readonly url: string;
403 readonly environmentCredential: string;
404 }) =>
405 HttpApiClient.make(RelayApi, {
406 baseUrl: relayConfig.url,
407 transformClient: relayEnvironmentClient(relayConfig.environmentCredential),
408 }).pipe(Effect.provide(FetchHttpClient.layer));
409​
410 let cachedRelayClient: Effect.Success<ReturnType<typeof makeRelayClient>> | undefined;
411 let publishedRelayConfig: NonNullable<Effect.Success<typeof readRelayConfig>> | undefined;
412​
413 // The confirming publish is re-enqueued through the same drainable worker as
414 // every other publish, so a confirmed tombstone can never race an in-flight
415 // live update; a recovered state clears the deadline.
416 const publishConfirmDeadlines = new Map<ThreadId, number>();
417 let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
418 const publishRetries = new Map<
419 ThreadId,
420 { readonly attempts: number; timer: Fiber.Fiber<void> | undefined }
421 >();
422 const cancelPublishRetry = Effect.fnUntraced(function* (threadId: ThreadId) {
423 const retry = publishRetries.get(threadId);
424 publishRetries.delete(threadId);
425 if (retry?.timer !== undefined) yield* Fiber.interrupt(retry.timer);
426 });
427 const cancelPublishRetries = Effect.suspend(() =>
428 Effect.forEach([...publishRetries.keys()], cancelPublishRetry, { discard: true }),
429 );
430 let schedulePublishRetry: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
431 const resetPublishedConnection = Effect.gen(function* () {
432 publishedRelayConfig = undefined;
433 cachedRelayClient = undefined;
434 publishConfirmDeadlines.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 = (input: {
468 readonly projectId: string | null;
469 readonly state: RelayAgentActivityState | null;
470 readonly reason: string;
471 }) =>
472 Effect.gen(function* () {
473 if (cachedRelayClient === undefined) {
474 cachedRelayClient = yield* makeRelayClient(relayConfig);
475 }
476 const relayClient = cachedRelayClient;
477 const proof = yield* makePublishProof({
478 privateKey: cloudLinkKeyPair.privateKey,
479 relayIssuer: relayConfig.issuer,
480 environmentId,
481 threadId,
482 state: input.state,
483 jti: yield* crypto.randomUUIDv4(),
484 });
485​
486 yield* Effect.logInfo("publishing agent activity for thread", {
487 environmentId,
488 threadId,
489 projectId: input.projectId,
490 statePhase: input.state?.phase ?? null,
491 hasState: input.state !== null,
492 reason: input.reason,
493 });
494​
495 const response = yield* relayClient.server
496 .publishAgentActivity({
497 params: {
498 environmentId,
499 threadId,
500 },
501 payload: {
502 state: input.state,
503 proof,
504 },
505 })
506 .pipe(Effect.timeout("10 seconds"));
507​
508 yield* Effect.logInfo("agent activity publish completed", {
509 environmentId,
510 threadId,
511 ok: response.ok,
512 deliveries: deliveryStats(response.deliveries),
513 });
514 }).pipe(Effect.withSpan("relay.agent_activity.publish"), withRelayClientTracing);
515​
516 // Per-thread shell read: this publish runs for every activity-relevant
517 // domain event, so materializing the full shell here would make the cost
518 // of one thread's activity proportional to how many threads exist.
519 const threadShell = yield* threads.getThreadShell(threadId);
520 if (
521 threadShell?.lineage.relationshipToParent === "subagent" &&
522 !(yield* Ref.get(publishedStateByThreadRef)).has(threadId)
523 ) {
524 // Subagents never project activity, so the relay holds no row to clear.
525 // Their events would otherwise publish a tombstone each, and every
526 // publish re-delivers the user's aggregate.
527 return;
528 }
529 const thread =
530 threadShell === null || threadShell.archivedAt !== null
531 ? Option.none<OrchestrationV2ThreadShell>()
532 : Option.some(threadShell);
533 const project = Option.isSome(thread)
534 ? yield* projects.getById(thread.value.projectId)
535 : Option.none<Project>();
536 const snapshot = resolveAgentAwarenessRelayPublishSnapshot({
537 environmentId,
538 threadId,
539 thread,
540 project,
541 });
542 const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);
543 const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);
544 if (
545 (snapshot.state?.phase === "completed" || snapshot.state?.phase === "failed") &&
546 !publishedStateByThread.has(threadId)
547 ) {
548 if (Option.isNone(thread) || !terminalWorkSinceStart(thread.value, startedAt)) return;
549 }
550 if (publishedStateByThread.get(threadId) === publishIdentity) {
551 // The projection is back at (or never left) the last published state, so
552 // any pending deferred confirmation is moot. Leaving the deadline in
553 // place would let a much later transient null find it already expired
554 // and publish a tombstone immediately, skipping the deferral window.
555 publishConfirmDeadlines.delete(threadId);
556 yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", {
557 environmentId,
558 threadId,
559 reason: snapshot.reason,
560 });
561 return;
562 }
563​
564 // - null (tombstone) while the previous published state was live: deletes
565 // the thread from every armed card mid-conversation.
566 // - completed as the thread's FIRST published state: sessions boot at
567 // "ready" before their first turn, which projects as completed for an
568 // instant and sends a spurious Done notification at thread birth.
569 const requiresConfirmation =
570 (snapshot.state === null &&
571 publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) ||
572 (snapshot.state?.phase === "completed" && !publishedStateByThread.has(threadId));
573 if (requiresConfirmation) {
574 const nowMs = (yield* DateTime.now).epochMilliseconds;
575 const deadline = publishConfirmDeadlines.get(threadId);
576 if (deadline === undefined) {
577 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
578 yield* Effect.logInfo("agent activity publish deferred pending confirmation", {
579 environmentId,
580 threadId,
581 reason: snapshot.reason,
582 statePhase: snapshot.state?.phase ?? null,
583 shell: describeThreadShellForAwareness(thread),
584 });
585 yield* schedulePublishConfirm(threadId);
586 return;
587 }
588 if (nowMs < deadline) {
589 return;
590 }
591 yield* Effect.logInfo("agent activity deferred publish confirmed", {
592 environmentId,
593 threadId,
594 reason: snapshot.reason,
595 statePhase: snapshot.state?.phase ?? null,
596 shell: describeThreadShellForAwareness(thread),
597 });
598 } else {
599 publishConfirmDeadlines.delete(threadId);
600 }
601​
602 if (snapshot.reason === "thread-not-found") {
603 yield* Effect.logDebug("publishing agent activity tombstone; thread not found", {
604 environmentId,
605 threadId,
606 });
607 } else if (snapshot.reason === "project-not-found") {
608 yield* Effect.logDebug("publishing agent activity tombstone; project not found", {
609 environmentId,
610 threadId,
611 projectId: snapshot.projectId,
612 });
613 }
614​
615 yield* publishState({
616 projectId: snapshot.projectId,
617 state: snapshot.state,
618 reason: snapshot.reason,
619 });
620 publishConfirmDeadlines.delete(threadId);
621 yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {
622 const nextPublishedStates = new Map(publishedStates);
623 if (snapshot.state === null) {
624 nextPublishedStates.delete(threadId);
625 } else {
626 nextPublishedStates.set(threadId, publishIdentity);
627 }
628 return nextPublishedStates;
629 });
630 });
631​
632 const processThreadPublish = Effect.fnUntraced(function* (threadId: ThreadId) {
633 const retry = publishRetries.get(threadId);
634 if (retry?.timer !== undefined) {
635 const timer = retry.timer;
636 retry.timer = undefined;
637 yield* Fiber.interrupt(timer);
638 }
639 yield* publishThreadUnsafe(threadId).pipe(
640 Effect.tap(() => cancelPublishRetry(threadId)),
641 Effect.catchCause((cause) => {
642 if (Cause.hasInterruptsOnly(cause)) return Effect.void;
643 return Effect.logWarning("agent activity publish failed", {
644 threadId,
645 cause: Cause.pretty(cause),
646 }).pipe(Effect.andThen(schedulePublishRetry(threadId)));
647 }),
648 Effect.withSpan("AgentAwarenessRelay.publishThread"),
649 );
650 });
651​
652 const worker = yield* makeAgentAwarenessPublishWorker(processThreadPublish);
653 const enqueueThreadPublish = (threadId: ThreadId) =>
654 cancelPublishRetry(threadId).pipe(Effect.andThen(worker.enqueue(threadId)));
655 const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
656 enqueueThreadPublish(threadId).pipe(Effect.andThen(worker.drain));
657​
658 schedulePublishRetry = Effect.fnUntraced(function* (threadId: ThreadId) {
659 const attempts = publishRetries.get(threadId)?.attempts ?? 0;
660 const delayMs = RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS[attempts];
661 if (delayMs === undefined) {
662 // Keep the exhausted budget until fresh activity or a successful publish
663 // clears it; an old confirmation timer must not start another retry series.
664 yield* Effect.logWarning("agent activity publish retry budget exhausted", { threadId });
665 return;
666 }
667 const retry = {
668 attempts: attempts + 1,
669 timer: undefined as Fiber.Fiber<void> | undefined,
670 };
671 publishRetries.set(threadId, retry);
672 const timer = yield* Effect.sleep(delayMs).pipe(
673 Effect.andThen(
674 Effect.suspend(() => {
675 if (publishRetries.get(threadId) !== retry) return Effect.void;
676 retry.timer = undefined;
677 return worker.enqueue(threadId);
678 }),
679 ),
680 Effect.forkIn(scope),
681 );
682 if (publishRetries.get(threadId) !== retry) {
683 yield* Fiber.interrupt(timer);
684 } else {
685 retry.timer = timer;
686 }
687 });
688​
689 const publishActiveThreadsUnsafe = Effect.gen(function* () {
690 const relayUrl = yield* readSecretString(RELAY_URL_SECRET).pipe(
691 Effect.orElseSucceed(() => null),
692 );
693 if (!relayUrl) {
694 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
695 return "unlinked" as const;
696 }
697 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
698 Effect.orElseSucceed(() => false),
699 );
700 if (!publishAgentActivity) {
701 yield* Effect.logDebug("agent activity snapshot skipped; publication disabled");
702 return "disabled" as const;
703 }
704 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
705 if (!relayConfig) {
706 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
707 return "unlinked" as const;
708 }
709 const environmentId = yield* serverEnvironment.getEnvironmentId;
710 const [projectSnapshot, shellSnapshot] = yield* Effect.all([
711 projects.snapshot,
712 threads.getShellSnapshot(),
713 ]);
714 const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({
715 environmentId,
716 startedAt,
717 projects: projectSnapshot.projects,
718 threads: shellSnapshot.threads,
719 });
720 if (activeThreadIds.length === 0) {
721 yield* Effect.logDebug("agent activity snapshot has no publishable threads");
722 return "published" as const;
723 }
724 yield* Effect.logInfo("publishing active agent activity snapshot", {
725 count: activeThreadIds.length,
726 });
727 yield* Effect.forEach(activeThreadIds, enqueueThreadPublish, { discard: true });
728 yield* worker.drain;
729 return "published" as const;
730 });
731​
732 // Many environments never link, so while unlinked the retry backs off from 5
733 // s to 60 s. A linked environment keeps the 5 s retry, because `t3 connect
734 // publish` can turn publishing on from another process.
735 const publishActiveThreadsOnceWhenConfigured = (logEnabledWhenReady: boolean) =>
736 Effect.gen(function* () {
737 let unlinkedRetryDelayMs = 5_000;
738 while (!(yield* Ref.get(activeSnapshotPublishedRef))) {
739 const result = yield* publishActiveThreadsUnsafe.pipe(
740 Effect.orElseSucceed(() => "failed" as const),
741 );
742 if (result === "published") {
743 yield* Ref.set(activeSnapshotPublishedRef, true);
744 if (logEnabledWhenReady) {
745 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
746 yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
747 relayUrl: relayConfig?.url,
748 });
749 }
750 return;
751 }
752 const retryDelayMs = result === "unlinked" ? unlinkedRetryDelayMs : 5_000;
753 yield* Effect.race(Effect.sleep(retryDelayMs), Queue.take(catchUpRequests));
754 if (result === "unlinked") {
755 unlinkedRetryDelayMs = Math.min(unlinkedRetryDelayMs * 2, 60_000);
756 }
757 }
758 });
759​
760 schedulePublishConfirm = (threadId) =>
761 Effect.forkIn(
762 Effect.sleep("5 seconds").pipe(
763 Effect.andThen(worker.enqueue(threadId)),
764 Effect.catchCause((cause) =>
765 Effect.logWarning("deferred agent activity confirmation failed", {
766 threadId,
767 cause: Cause.pretty(cause),
768 }),
769 ),
770 ),
771 scope,
772 ).pipe(Effect.asVoid);
773​
774 const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
775 function* () {
776 const [relayConfig, publishEnabled] = yield* Effect.all([
777 readRelayConfig.pipe(Effect.orElseSucceed(() => null)),
778 readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),
779 ]);
780 const startupState = resolveAgentActivityPublishingStartupState({
781 relayConfigured: relayConfig !== null,
782 publishEnabled,
783 });
784 switch (startupState) {
785 case "waiting-for-link":
786 yield* Effect.logInfo(
787 "agent activity publishing standby; waiting for T3 Connect link reconciliation",
788 );
789 break;
790 case "disabled":
791 yield* Effect.logInfo("agent activity publishing disabled by T3 Connect configuration");
792 break;
793 case "enabled":
794 yield* Effect.logInfo("agent activity publishing enabled", {
795 relayUrl: relayConfig?.url,
796 });
797 break;
798 }
799 yield* forkParked(
800 Effect.sleep("1 second").pipe(
801 Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")),
802 ),
803 );
804 yield* forkParked(
805 Stream.runForEach(threads.streamDomainEvents, (event) => {
806 const threadId = eventThreadId(event);
807 if (!shouldPublishAgentAwarenessEvent(event)) {
808 return Effect.void;
809 }
810 return Effect.logDebug("agent activity publishing queued thread publish", {
811 eventType: event.type,
812 threadId,
813 }).pipe(Effect.andThen(enqueueThreadPublish(threadId)));
814 }),
815 );
816 },
817 );
818​
819 return AgentAwarenessRelay.of({
820 publishThread,
821 drain: worker.drain,
822 requestCatchUp: () => Queue.offer(catchUpRequests, undefined).pipe(Effect.asVoid),
823 start,
824 });
825});
826​
827export const layer = Layer.effect(AgentAwarenessRelay, make);