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

AgentAwarenessRelay.ts

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