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

AgentAwarenessRelay.ts

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