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

AgentAwarenessRelay.ts

766 lines27.0 KB

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