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

AgentAwarenessRelay.ts

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