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