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

AgentAwarenessRelay.ts

999 lines36.6 KB

1import type { AgentAwarenessThread } from "../orchestration-v2/ProjectionStore.ts";
2import {
3 isListedThreadLineage,
4 type EnvironmentId,
5 type OrchestrationV2DomainEvent,
6 type OrchestrationV2TurnItem,
7 type Project,
8 type RuntimeRequestId,
9 type ThreadId,
10} from "@t3tools/contracts";
11import {
12 RelayApi,
13 type RelayAgentActivityPublishProofPayload,
14 type RelayAgentActivityState,
15} from "@t3tools/contracts/relay";
16import {
17 type SubagentRequestAwareness,
18 projectThreadAwarenessV2,
19 subagentAwaitsUser,
20 turnItemCanChangeUserWait,
21} from "@t3tools/shared/agentAwareness";
22import { turnItemUpdateCanEndBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
23import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
24import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
25import { normalizeRelayIssuer, RELAY_ACTIVITY_PUBLISH_TYP } from "@t3tools/shared/relayJwt";
26import * as Cause from "effect/Cause";
27import * as Context from "effect/Context";
28import * as SecureRandom from "effect/crypto/SecureRandom";
29import * as DateTime from "effect/DateTime";
30import * as Effect from "effect/Effect";
31import * as Fiber from "effect/Fiber";
32import * as Layer from "effect/Layer";
33import * as Option from "effect/Option";
34import * as Queue from "effect/Queue";
35import * as Ref from "effect/Ref";
36import type * as Scope from "effect/Scope";
37import * as Stream from "effect/Stream";
38import * as FetchHttpClient from "effect/http/FetchHttpClient";
39import * as HttpClient from "effect/http/HttpClient";
40import * as HttpClientRequest from "effect/http/HttpClientRequest";
41import * as HttpApiClient from "effect/http-api/HttpApiClient";
42​
43import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
44import {
45 isAgentActivityPublishingEnabledValue,
46 PUBLISH_AGENT_ACTIVITY_SECRET,
47 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
48 RELAY_ISSUER_SECRET,
49 RELAY_URL_SECRET,
50} from "../cloud/config.ts";
51import { EnvironmentSigningKey } from "../cloud/environmentKeys.ts";
52import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
53import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
54import { isSnoozed } from "../orchestration-v2/ThreadSettlementService.ts";
55import * as ProjectService from "../project/ProjectService.ts";
56import { forkParked } from "../serverActivation.ts";
57​
58export class AgentAwarenessRelay extends Context.Service<
59 AgentAwarenessRelay,
60 {
61 readonly publishThread: (threadId: ThreadId) => Effect.Effect<void>;
62 readonly drain: Effect.Effect<void>;
63 readonly requestCatchUp: () => Effect.Effect<void>;
64 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
65 }
66>()("t3/relay/AgentAwarenessRelay") {}
67​
68function eventThreadId(event: OrchestrationV2DomainEvent): ThreadId {
69 return event.threadId;
71​
72function isTurnItemPayload(
73 payload: unknown,
74): payload is Pick<OrchestrationV2TurnItem, "type" | "status"> {
75 return (
76 typeof payload === "object" && payload !== null && "type" in payload && "status" in payload
77 );
79​
80function shouldPublishAgentAwarenessEvent(
81 event: Pick<OrchestrationV2DomainEvent, "type"> & { readonly payload?: unknown },
82): boolean {
83 if (
84 event.type === "thread.created" &&
85 typeof event.payload === "object" &&
86 event.payload !== null &&
87 "historyOrigin" in event.payload &&
88 event.payload.historyOrigin === "v1_import"
89 ) {
90 return false;
91 }
92 switch (event.type) {
93 case "thread.created":
94 case "thread.archived":
95 case "thread.unarchived":
96 case "thread.deleted":
97 case "thread.metadata-updated":
98 case "thread.pull-request-link-updated":
99 case "thread.pull-request-synced":
100 case "thread.settled":
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 // Unsettling must not re-alert a dismissed result.
110 case "thread.unsettled":
111 case "thread.guest-share-updated":
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.tags-updated":
120 case "thread.visited":
121 case "thread.visit-recorded":
122 case "thread.marked-unread":
123 case "thread.runtime-mode-updated":
124 case "thread.interaction-mode-updated":
125 case "run.background-work-cancelled":
126 case "run-attempt.created":
127 case "run-attempt.updated":
128 case "node.updated":
129 case "provider-session.attached":
130 case "provider-session.updated":
131 case "provider-session.detached":
132 case "provider-turn.updated":
133 case "turn-item.updated":
134 return (
135 isTurnItemPayload(event.payload) &&
136 (turnItemUpdateCanEndBackgroundWork(event.payload) ||
137 turnItemCanChangeUserWait(event.payload))
138 );
139 case "message.updated":
140 case "plan.updated":
141 case "checkpoint-scope.created":
142 case "checkpoint.captured":
143 case "checkpoint.rollback-requested":
144 case "context-handoff.updated":
145 case "context-transfer.created":
146 case "context-transfer.updated":
147 return false;
148 }
150​
151export const makeAgentAwarenessPublishWorker = Effect.fnUntraced(function* <R>(
152 publish: (threadId: ThreadId) => Effect.Effect<void, never, R>,
153) {
154 const queued = new Set<ThreadId>();
155 const worker = yield* makeDrainableWorker((threadId: ThreadId) =>
156 Effect.sync(() => queued.delete(threadId)).pipe(Effect.andThen(publish(threadId))),
157 );
158 const enqueue = (threadId: ThreadId) =>
159 Effect.suspend(() => {
160 if (queued.has(threadId)) return Effect.void;
161 // Remove queued IDs when processing starts so publication can queue one later update.
162 queued.add(threadId);
163 return worker.enqueue(threadId);
164 }).pipe(Effect.uninterruptible);
165 return { enqueue, drain: worker.drain };
166});
167​
168function agentAwarenessPublishIdentity(
169 state: RelayAgentActivityState | null,
170 subagentRequest: SubagentRequestAwareness | null = null,
171): string {
172 if (state === null) {
173 return "null";
174 }
175 const { updatedAt: _updatedAt, ...meaningfulState } = state;
176 // A child's next request reads the same as its last one, but it is a new
177 // wait and must reach the phone.
178 return JSON.stringify(
179 subagentRequest === null ? meaningfulState : [meaningfulState, subagentRequest.requestId],
180 );
182​
183const CLEARED_PUBLISH_IDENTITY = agentAwarenessPublishIdentity(null);
184​
185// A published tombstone stays recorded so repeats are skipped, but it is not live state.
186function hasLivePublishedState(
187 publishedStateByThread: ReadonlyMap<ThreadId, string>,
188 threadId: ThreadId,
189): boolean {
190 const identity = publishedStateByThread.get(threadId);
191 return identity !== undefined && identity !== CLEARED_PUBLISH_IDENTITY;
193​
194function resolveAgentActivityPublishingStartupState(input: {
195 readonly relayConfigured: boolean;
196 readonly publishEnabled: boolean;
197}): "waiting-for-link" | "disabled" | "enabled" {
198 if (!input.relayConfigured) {
199 return "waiting-for-link";
200 }
201 return input.publishEnabled ? "enabled" : "disabled";
203​
204const RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH = 160;
205const REDACTED_RELAY_AGENT_FAILURE_DETAIL = "The agent run failed.";
206const RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000] as const;
207​
208function sanitizeRelayAgentActivityState(
209 state: RelayAgentActivityState | null,
210): RelayAgentActivityState | null {
211 if (state === null) {
212 return null;
213 }
214 const { detail: _detail, ...rest } = state;
215 const detail = (state.phase === "failed" ? REDACTED_RELAY_AGENT_FAILURE_DETAIL : state.detail)
216 ?.trim()
217 .slice(0, RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH)
218 .trim();
219 return detail ? { ...rest, detail } : rest;
221​
222function relayEnvironmentClient(token: string) {
223 return HttpClient.mapRequest(HttpClientRequest.setHeader("authorization", `Bearer ${token}`));
225​
226function deliveryStats(
227 deliveries: ReadonlyArray<{
228 readonly ok: boolean;
229 readonly queued?: boolean | undefined;
230 readonly kind: string;
231 readonly apnsStatus?: number | null;
232 readonly apnsReason?: string | null;
233 }>,
234) {
235 let queued = 0;
236 let successful = 0;
237 let failed = 0;
238 const failedReasons: string[] = [];
239 const kinds = new Set<string>();
240​
241 for (const delivery of deliveries) {
242 kinds.add(delivery.kind);
243 if (delivery.queued) {
244 queued += 1;
245 continue;
246 }
247 if (delivery.ok) {
248 successful += 1;
249 continue;
250 }
251 failed += 1;
252 failedReasons.push(`${delivery.apnsStatus ?? "transport"}:${delivery.apnsReason ?? "unknown"}`);
253 }
254​
255 return {
256 total: deliveries.length,
257 queued,
258 successful,
259 failed,
260 kinds: [...kinds],
261 failedReasons,
262 };
264​
265const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
266 readonly relayIssuer: string;
267 readonly environmentId: string;
268 readonly threadId: ThreadId;
269 readonly state: RelayAgentActivityState | null;
270 readonly jti: string;
271}) {
272 const now = yield* DateTime.now;
273 const expiresAt = DateTime.add(now, { minutes: 5 });
274 const payload = {
275 iss: `t3-env:${input.environmentId}`,
276 aud: normalizeRelayIssuer(input.relayIssuer),
277 sub: input.environmentId,
278 jti: input.jti,
279 iat: Math.floor(now.epochMilliseconds / 1_000),
280 exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
281 environmentId: input.environmentId as RelayAgentActivityPublishProofPayload["environmentId"],
282 threadId: input.threadId,
283 state: input.state,
284 } satisfies RelayAgentActivityPublishProofPayload;
285 const signingKey = yield* EnvironmentSigningKey;
286 return yield* signingKey.sign({ typ: RELAY_ACTIVITY_PUBLISH_TYP, payload });
287});
288​
289function describeThreadShellForAwareness(
290 thread: Option.Option<AgentAwarenessThread>,
291): Record<string, unknown> {
292 if (Option.isNone(thread)) {
293 return { found: false };
294 }
295 const shell = thread.value;
296 return {
297 found: true,
298 status: shell.status,
299 activityRunStatus: shell.activityRunStatus ?? null,
300 activeRunId: shell.activeRunId ?? null,
301 latestRunId: shell.latestRunId ?? null,
302 pendingRuntimeRequestKind: shell.pendingRuntimeRequest?.kind ?? null,
303 hasActionableProposedPlan: shell.hasActionableProposedPlan,
304 };
306​
307interface SubagentRequest {
308 readonly topLevelThreadId: ThreadId;
309 readonly requestId: RuntimeRequestId;
311​
312interface SubagentAlert {
313 readonly requestId: RuntimeRequestId;
314 readonly updatedAt: string;
316​
317const waitingApprovalId = (thread: AgentAwarenessThread | null) =>
318 thread !== null && thread.archivedAt === null && subagentAwaitsUser(thread)
319 ? thread.pendingRuntimeRequest?.id
320 : undefined;
321​
322function resolveAgentAwarenessRelayPublishSnapshot(input: {
323 readonly environmentId: EnvironmentId;
324 readonly thread: Option.Option<AgentAwarenessThread>;
325 readonly project: Option.Option<Project>;
326 readonly pendingSubagentRequest: SubagentRequestAwareness | null;
327}): {
328 readonly projectId: string | null;
329 readonly state: RelayAgentActivityState | null;
330 /** The child request behind the state's wait, when the parent isn't waiting itself. */
331 readonly subagentWait: SubagentRequestAwareness | null;
332 readonly reason: "snapshot" | "thread-not-found" | "project-not-found";
333} {
334 if (Option.isNone(input.thread)) {
335 return {
336 projectId: null,
337 state: null,
338 subagentWait: null,
339 reason: "thread-not-found",
340 };
341 }
342 if (Option.isNone(input.project)) {
343 return {
344 projectId: input.thread.value.projectId,
345 state: null,
346 subagentWait: null,
347 reason: "project-not-found",
348 };
349 }
350 const awarenessInput = {
351 environmentId: input.environmentId,
352 project: input.project.value,
353 thread: input.thread.value,
354 };
355 const state = projectThreadAwarenessV2({
356 ...awarenessInput,
357 pendingSubagentRequest: input.pendingSubagentRequest,
358 });
359 const childDrivesWait =
360 input.pendingSubagentRequest !== null &&
361 state?.phase !== projectThreadAwarenessV2(awarenessInput)?.phase;
362 return {
363 projectId: input.thread.value.projectId,
364 state: snoozedCompletion(input.thread.value, state)
365 ? null
366 : sanitizeRelayAgentActivityState(state),
367 subagentWait: childDrivesWait ? input.pendingSubagentRequest : null,
368 reason: "snapshot",
369 };
371​
372// Checked at completion time, so a completion processed after the wake stays silent too.
373function snoozedCompletion(
374 thread: AgentAwarenessThread,
375 state: { readonly phase: string } | null,
376): boolean {
377 if (state?.phase !== "completed" || thread.latestRunCompletedAt == null) return false;
378 const completedAt = DateTime.toEpochMillis(thread.latestRunCompletedAt);
379 if (thread.snoozedAt != null && completedAt < DateTime.toEpochMillis(thread.snoozedAt)) {
380 return false;
381 }
382 return isSnoozed(thread, completedAt);
384​
385function terminalWorkSinceStart(thread: AgentAwarenessThread, startedAt: number): boolean {
386 return (
387 thread.latestRunCompletedAt != null &&
388 DateTime.toEpochMillis(thread.latestRunCompletedAt) > startedAt
389 );
391​
392export function resolveAgentAwarenessRelayActiveThreadIds(input: {
393 readonly environmentId: EnvironmentId;
394 readonly startedAt: number;
395 readonly projects: ReadonlyArray<Pick<Project, "id" | "title">>;
396 readonly threads: ReadonlyArray<AgentAwarenessThread>;
397}): ReadonlyArray<ThreadId> {
398 const projectById = new Map(input.projects.map((project) => [project.id, project]));
399 return input.threads
400 .filter((thread) => {
401 // Publishing a waiting subagent republishes its top-level thread.
402 if (subagentAwaitsUser(thread)) return true;
403 const project = projectById.get(thread.projectId);
404 if (!project) {
405 return false;
406 }
407 const state = projectThreadAwarenessV2({
408 environmentId: input.environmentId,
409 project,
410 thread,
411 });
412 return (
413 state !== null &&
414 (state.phase !== "completed" && state.phase !== "failed"
415 ? true
416 : terminalWorkSinceStart(thread, input.startedAt))
417 );
418 })
419 .map((thread) => thread.id);
421​
422/** @public */
423export const make = Effect.gen(function* () {
424 const secrets = yield* ServerSecretStore.ServerSecretStore;
425 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
426 const threads = yield* ThreadManagement.ThreadManagementService;
427 const projects = yield* ProjectService.ProjectService;
428 const random = yield* SecureRandom.SecureRandom;
429 const signingKey = yield* EnvironmentSigningKey;
430 const scope = yield* Effect.scope;
431 const startedAt = (yield* DateTime.now).epochMilliseconds;
432 const catchUpRequests = yield* Queue.dropping<void>(1);
433 const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());
434 // Android keys alerts by phase and time, so a child's unchanged request keeps
435 // its first alert time through parent renames, relinks and the parent's own requests.
436 const childAlertByThread = new Map<ThreadId, SubagentAlert>();
437 const subagentRequests = new Map<ThreadId, SubagentRequest>();
438​
439 const readSecretString = (name: string) =>
440 secrets
441 .get(name)
442 .pipe(
443 Effect.map((bytes) =>
444 Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,
445 ),
446 );
447​
448 const readRelayConfig = Effect.gen(function* () {
449 const [url, issuer, environmentCredential] = yield* Effect.all([
450 readSecretString(RELAY_URL_SECRET),
451 readSecretString(RELAY_ISSUER_SECRET),
452 readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
453 ]);
454 return url && environmentCredential
455 ? { url, issuer: issuer ?? url, environmentCredential }
456 : null;
457 });
458​
459 const readPublishAgentActivityEnabled = readSecretString(PUBLISH_AGENT_ACTIVITY_SECRET).pipe(
460 Effect.map(isAgentActivityPublishingEnabledValue),
461 );
462​
463 const makeRelayClient = (relayConfig: {
464 readonly url: string;
465 readonly environmentCredential: string;
466 }) =>
467 HttpApiClient.make(RelayApi, {
468 baseUrl: relayConfig.url,
469 transformClient: relayEnvironmentClient(relayConfig.environmentCredential),
470 }).pipe(Effect.provide(FetchHttpClient.layer));
471​
472 let cachedRelayClient: Effect.Success<ReturnType<typeof makeRelayClient>> | undefined;
473 let publishedRelayConfig: NonNullable<Effect.Success<typeof readRelayConfig>> | undefined;
474​
475 // Confirm through the same worker so tombstones cannot race live updates; recovery clears the deadline.
476 const publishConfirmDeadlines = new Map<ThreadId, number>();
477 // Threads whose confirmation holds a completion, so a thread that settles during the hold still alerts.
478 const heldCompletions = new Set<ThreadId>();
479 let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
480 const publishRetries = new Map<
481 ThreadId,
482 { readonly attempts: number; timer: Fiber.Fiber<void> | undefined }
483 >();
484 const cancelPublishRetry = Effect.fnUntraced(function* (threadId: ThreadId) {
485 const retry = publishRetries.get(threadId);
486 publishRetries.delete(threadId);
487 if (retry?.timer !== undefined) yield* Fiber.interrupt(retry.timer);
488 });
489 const cancelPublishRetries = Effect.suspend(() =>
490 Effect.forEach([...publishRetries.keys()], cancelPublishRetry, { discard: true }),
491 );
492 let schedulePublishRetry: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
493 let enqueueTopLevelPublish: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
494 const resetPublishedConnection = Effect.gen(function* () {
495 publishedRelayConfig = undefined;
496 cachedRelayClient = undefined;
497 publishConfirmDeadlines.clear();
498 heldCompletions.clear();
499 yield* Ref.set(publishedStateByThreadRef, new Map());
500 });
501​
502 const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) {
503 const publishAgentActivity = yield* readPublishAgentActivityEnabled;
504 if (!publishAgentActivity) {
505 yield* cancelPublishRetries;
506 yield* resetPublishedConnection;
507 yield* Effect.logDebug("agent activity publish skipped; publication disabled", {
508 threadId,
509 });
510 return;
511 }
512 const relayConfig = yield* readRelayConfig;
513 if (!relayConfig) {
514 yield* cancelPublishRetries;
515 yield* resetPublishedConnection;
516 yield* Effect.logDebug("agent activity publish skipped; relay link credentials unavailable", {
517 threadId,
518 });
519 return;
520 }
521 if (
522 publishedRelayConfig?.url !== relayConfig.url ||
523 publishedRelayConfig.issuer !== relayConfig.issuer ||
524 publishedRelayConfig.environmentCredential !== relayConfig.environmentCredential
525 ) {
526 yield* resetPublishedConnection;
527 publishedRelayConfig = relayConfig;
528 }
529 const environmentId = yield* serverEnvironment.getEnvironmentId;
530​
531 const publishState = Effect.fn("relay.agent_activity.publish")(function* (input: {
532 readonly projectId: string | null;
533 readonly state: RelayAgentActivityState | null;
534 readonly reason: string;
535 }) {
536 if (cachedRelayClient === undefined) {
537 cachedRelayClient = yield* makeRelayClient(relayConfig);
538 }
539 const relayClient = cachedRelayClient;
540 const proof = yield* makePublishProof({
541 relayIssuer: relayConfig.issuer,
542 environmentId,
543 threadId,
544 state: input.state,
545 jti: yield* random.uuidV4(),
546 }).pipe(Effect.provideService(EnvironmentSigningKey, signingKey));
547​
548 yield* Effect.logInfo("publishing agent activity for thread", {
549 environmentId,
550 threadId,
551 projectId: input.projectId,
552 statePhase: input.state?.phase ?? null,
553 hasState: input.state !== null,
554 reason: input.reason,
555 });
556​
557 const response = yield* relayClient.server
558 .publishAgentActivity({
559 params: {
560 environmentId,
561 threadId,
562 },
563 payload: {
564 state: input.state,
565 proof,
566 },
567 })
568 .pipe(Effect.timeout("10 seconds"));
569​
570 yield* Effect.logInfo("agent activity publish completed", {
571 environmentId,
572 threadId,
573 ok: response.ok,
574 deliveries: deliveryStats(response.deliveries),
575 });
576 });
577​
578 // Read only this thread; full shell reads would make each activity event scale with all threads.
579 const threadShell = yield* readAwarenessThread(threadId);
580 yield* trackSubagentRequest(threadId, threadShell);
581 if (
582 threadShell !== null &&
583 !isListedThreadLineage(threadShell.lineage) &&
584 !hasLivePublishedState(yield* Ref.get(publishedStateByThreadRef), threadId)
585 ) {
586 // Subagents and side chats have no relay rows to clear; per-event tombstones would needlessly redeliver user aggregates.
587 return;
588 }
589 const thread =
590 threadShell === null || threadShell.archivedAt !== null
591 ? Option.none<AgentAwarenessThread>()
592 : Option.some(threadShell);
593 const project = Option.isSome(thread)
594 ? yield* projects.getById(thread.value.projectId)
595 : Option.none<Project>();
596 const snapshot = resolveAgentAwarenessRelayPublishSnapshot({
597 environmentId,
598 thread,
599 project,
600 pendingSubagentRequest: yield* currentSubagentRequestFor(threadId),
601 });
602 const publishIdentity = agentAwarenessPublishIdentity(snapshot.state, snapshot.subagentWait);
603 const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);
604 if (
605 (snapshot.state?.phase === "completed" || snapshot.state?.phase === "failed") &&
606 !hasLivePublishedState(publishedStateByThread, threadId)
607 ) {
608 if (Option.isNone(thread) || !terminalWorkSinceStart(thread.value, startedAt)) return;
609 }
610 if (
611 publishedStateByThread.get(threadId) === publishIdentity &&
612 // A held completion settled after an earlier clear still has to alert.
613 !(snapshot.state === null && heldCompletions.has(threadId))
614 ) {
615 // Clear moot deadlines so later transient nulls cannot skip their deferral window.
616 publishConfirmDeadlines.delete(threadId);
617 heldCompletions.delete(threadId);
618 yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", {
619 environmentId,
620 threadId,
621 reason: snapshot.reason,
622 });
623 return;
624 }
625​
626 // Confirm tombstones over live state to avoid removing active cards.
627 // Confirm completion: a run can end moments before its continuation starts, and the relay
628 // alerts on every move into completed.
629 const requiresConfirmation = snapshot.state === null || snapshot.state?.phase === "completed";
630 if (requiresConfirmation) {
631 if (snapshot.state?.phase === "completed") heldCompletions.add(threadId);
632 const nowMs = (yield* DateTime.now).epochMilliseconds;
633 const deadline = publishConfirmDeadlines.get(threadId);
634 if (deadline === undefined) {
635 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
636 yield* Effect.logInfo("agent activity publish deferred pending confirmation", {
637 environmentId,
638 threadId,
639 reason: snapshot.reason,
640 statePhase: snapshot.state?.phase ?? null,
641 shell: describeThreadShellForAwareness(thread),
642 });
643 yield* schedulePublishConfirm(threadId);
644 return;
645 }
646 if (nowMs < deadline) {
647 return;
648 }
649 yield* Effect.logInfo("agent activity deferred publish confirmed", {
650 environmentId,
651 threadId,
652 reason: snapshot.reason,
653 statePhase: snapshot.state?.phase ?? null,
654 shell: describeThreadShellForAwareness(thread),
655 });
656 // Settled during the hold, not resumed: alert the current completion, then clear the card
657 // on a new window. Only settlement may hide it; queued or silent runs also project to null.
658 const unsettled =
659 snapshot.state === null &&
660 heldCompletions.has(threadId) &&
661 Option.isSome(thread) &&
662 thread.value.settledOverride === "settled"
663 ? resolveAgentAwarenessRelayPublishSnapshot({
664 environmentId,
665 thread: Option.some({ ...thread.value, settledOverride: null }),
666 project,
667 pendingSubagentRequest: null,
668 })
669 : null;
670 if (unsettled?.state?.phase === "completed") {
671 const completion = unsettled.state;
672 yield* publishState({
673 projectId: unsettled.projectId,
674 state: completion,
675 reason: unsettled.reason,
676 }).pipe(withRelayClientTracing);
677 heldCompletions.delete(threadId);
678 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
679 yield* Ref.update(publishedStateByThreadRef, (publishedStates) =>
680 new Map(publishedStates).set(threadId, agentAwarenessPublishIdentity(completion)),
681 );
682 yield* schedulePublishConfirm(threadId);
683 return;
684 }
685 } else {
686 publishConfirmDeadlines.delete(threadId);
687 heldCompletions.delete(threadId);
688 }
689​
690 if (snapshot.reason === "thread-not-found") {
691 yield* Effect.logDebug("publishing agent activity tombstone; thread not found", {
692 environmentId,
693 threadId,
694 });
695 } else if (snapshot.reason === "project-not-found") {
696 yield* Effect.logDebug("publishing agent activity tombstone; project not found", {
697 environmentId,
698 threadId,
699 projectId: snapshot.projectId,
700 });
701 }
702​
703 const childRequestId = snapshot.subagentWait?.requestId;
704 const childAlert = childAlertByThread.get(threadId);
705 const state =
706 snapshot.state !== null &&
707 childRequestId !== undefined &&
708 childAlert?.requestId === childRequestId
709 ? { ...snapshot.state, updatedAt: childAlert.updatedAt }
710 : snapshot.state;
711 yield* publishState({
712 projectId: snapshot.projectId,
713 state,
714 reason: snapshot.reason,
715 }).pipe(withRelayClientTracing);
716 if (state !== null && childRequestId !== undefined) {
717 childAlertByThread.set(threadId, { requestId: childRequestId, updatedAt: state.updatedAt });
718 }
719 publishConfirmDeadlines.delete(threadId);
720 heldCompletions.delete(threadId);
721 yield* Ref.update(publishedStateByThreadRef, (publishedStates) =>
722 new Map(publishedStates).set(threadId, publishIdentity),
723 );
724 });
725​
726 const readAwarenessThread = (threadId: ThreadId) =>
727 threads
728 .getAgentAwarenessSnapshot(threadId)
729 .pipe(Effect.map((snapshot) => snapshot.threads[0] ?? null));
730​
731 // The subagent helpers below are untraced: they run per event inside
732 // publishThreadUnsafe, whose span already covers them.
733 const findTopLevelThreadId = Effect.fnUntraced(function* (child: AgentAwarenessThread) {
734 const seen = new Set<ThreadId>([child.id]);
735 let current: AgentAwarenessThread | null = child;
736 while (
737 current?.lineage.relationshipToParent === "subagent" ||
738 current?.lineage.sideChat === true
739 ) {
740 const parentId: ThreadId | null = current.lineage.parentThreadId;
741 if (parentId === null || seen.has(parentId)) return null;
742 seen.add(parentId);
743 current = yield* readAwarenessThread(parentId);
744 }
745 return current?.id ?? null;
746 });
747​
748 const trackSubagentRequest = Effect.fnUntraced(function* (
749 threadId: ThreadId,
750 threadShell: AgentAwarenessThread | null,
751 ) {
752 const requestId = waitingApprovalId(threadShell);
753 const previous = subagentRequests.get(threadId);
754 // An unchanged wait still republishes its parent: a relink catch-up reaches it only here.
755 if (threadShell === null || requestId === undefined) {
756 if (previous === undefined) return;
757 subagentRequests.delete(threadId);
758 yield* enqueueTopLevelPublish(previous.topLevelThreadId);
759 return;
760 }
761 const topLevelThreadId =
762 previous?.topLevelThreadId ?? (yield* findTopLevelThreadId(threadShell));
763 if (topLevelThreadId === null) return;
764 subagentRequests.set(threadId, { topLevelThreadId, requestId });
765 yield* enqueueTopLevelPublish(topLevelThreadId);
766 });
767​
768 // The map can miss a child's update while publishing is off or the relay is
769 // unlinked, so each waiting child is re-read before its parent is published.
770 const currentSubagentRequestFor = Effect.fnUntraced(function* (topLevelThreadId: ThreadId) {
771 let pending: SubagentRequestAwareness | null = null;
772 for (const [childId, entry] of subagentRequests) {
773 if (entry.topLevelThreadId !== topLevelThreadId) continue;
774 const child = yield* readAwarenessThread(childId);
775 const requestId = waitingApprovalId(child);
776 if (child === null || requestId === undefined) {
777 subagentRequests.delete(childId);
778 continue;
779 }
780 if (requestId !== entry.requestId) subagentRequests.set(childId, { ...entry, requestId });
781 // The newest wait is the one to announce.
782 if (pending === null || DateTime.isGreaterThan(child.updatedAt, pending.updatedAt)) {
783 pending = {
784 requestId,
785 updatedAt: child.updatedAt,
786 waitsForInput: child.pendingRuntimeRequest?.kind === "user_input",
787 };
788 }
789 }
790 return pending;
791 });
792​
793 const processThreadPublish = Effect.fnUntraced(function* (threadId: ThreadId) {
794 const retry = publishRetries.get(threadId);
795 if (retry?.timer !== undefined) {
796 const timer = retry.timer;
797 retry.timer = undefined;
798 yield* Fiber.interrupt(timer);
799 }
800 yield* publishThreadUnsafe(threadId).pipe(
801 Effect.tap(() => cancelPublishRetry(threadId)),
802 Effect.catchCause((cause) => {
803 if (Cause.hasInterruptsOnly(cause)) return Effect.void;
804 return Effect.logWarning("agent activity publish failed", {
805 threadId,
806 cause: Cause.pretty(cause),
807 }).pipe(Effect.andThen(schedulePublishRetry(threadId)));
808 }),
809 Effect.withSpan("AgentAwarenessRelay.publishThread"),
810 );
811 });
812​
813 const worker = yield* makeAgentAwarenessPublishWorker(processThreadPublish);
814 const enqueueThreadPublish = (threadId: ThreadId) =>
815 cancelPublishRetry(threadId).pipe(Effect.andThen(worker.enqueue(threadId)));
816 enqueueTopLevelPublish = enqueueThreadPublish;
817 const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
818 enqueueThreadPublish(threadId).pipe(Effect.andThen(worker.drain));
819​
820 schedulePublishRetry = Effect.fnUntraced(function* (threadId: ThreadId) {
821 const attempts = publishRetries.get(threadId)?.attempts ?? 0;
822 const delayMs = RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS[attempts];
823 if (delayMs === undefined) {
824 // Retain exhausted budgets until activity or success resets them; old timers must not restart retries.
825 yield* Effect.logWarning("agent activity publish retry budget exhausted", { threadId });
826 return;
827 }
828 const retry = {
829 attempts: attempts + 1,
830 timer: undefined as Fiber.Fiber<void> | undefined,
831 };
832 publishRetries.set(threadId, retry);
833 const timer = yield* Effect.sleep(delayMs).pipe(
834 Effect.andThen(
835 Effect.suspend(() => {
836 if (publishRetries.get(threadId) !== retry) return Effect.void;
837 retry.timer = undefined;
838 return worker.enqueue(threadId);
839 }),
840 ),
841 Effect.forkIn(scope),
842 );
843 if (publishRetries.get(threadId) !== retry) {
844 yield* Fiber.interrupt(timer);
845 } else {
846 retry.timer = timer;
847 }
848 });
849​
850 const publishActiveThreadsUnsafe = Effect.gen(function* () {
851 const relayUrl = yield* readSecretString(RELAY_URL_SECRET).pipe(
852 Effect.orElseSucceed(() => null),
853 );
854 if (!relayUrl) {
855 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
856 return "unlinked" as const;
857 }
858 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
859 Effect.orElseSucceed(() => false),
860 );
861 if (!publishAgentActivity) {
862 yield* Effect.logDebug("agent activity snapshot skipped; publication disabled");
863 return "disabled" as const;
864 }
865 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
866 if (!relayConfig) {
867 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
868 return "unlinked" as const;
869 }
870 const environmentId = yield* serverEnvironment.getEnvironmentId;
871 const projectSnapshot = yield* projects.snapshot;
872 const activitySnapshot = yield* threads.getAgentAwarenessSnapshot();
873 // Live children aren't listed, but a waiting one makes its top-level thread wait.
874 const liveChildren = yield* Effect.forEach(
875 (yield* threads.listActiveShellIndex()).filter(
876 (thread) => thread.lineage.relationshipToParent === "subagent" && thread.mayBeLive,
877 ),
878 (thread) => readAwarenessThread(thread.id),
879 );
880 const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({
881 environmentId,
882 startedAt,
883 projects: projectSnapshot.projects,
884 threads: [...activitySnapshot.threads, ...liveChildren.filter((thread) => thread !== null)],
885 });
886 if (activeThreadIds.length === 0) {
887 yield* Effect.logDebug("agent activity snapshot has no publishable threads");
888 return "published" as const;
889 }
890 yield* Effect.logInfo("publishing active agent activity snapshot", {
891 count: activeThreadIds.length,
892 });
893 yield* Effect.forEach(activeThreadIds, enqueueThreadPublish, { discard: true });
894 yield* worker.drain;
895 return "published" as const;
896 });
897​
898 // Many environments never link, so while unlinked the retry backs off from 5
899 // s to 60 s. A linked environment keeps the 5 s retry, because `t3 connect
900 // publish` can turn publishing on from another process. Keep this untraced:
901 // an unlinked environment can retry for the lifetime of the process.
902 const publishActiveThreadsWhenConfigured = Effect.fnUntraced(function* (
903 logEnabledWhenReady: boolean,
904 ) {
905 let unlinkedRetryDelayMs = 5_000;
906 while (true) {
907 const result = yield* publishActiveThreadsUnsafe.pipe(
908 Effect.orElseSucceed(() => "failed" as const),
909 );
910 if (result === "published") {
911 if (logEnabledWhenReady) {
912 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
913 yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
914 relayUrl: relayConfig?.url,
915 });
916 }
917 logEnabledWhenReady = false;
918 unlinkedRetryDelayMs = 5_000;
919 yield* Queue.take(catchUpRequests);
920 continue;
921 }
922 const retryDelayMs = result === "unlinked" ? unlinkedRetryDelayMs : 5_000;
923 yield* Effect.race(Effect.sleep(retryDelayMs), Queue.take(catchUpRequests));
924 if (result === "unlinked") {
925 unlinkedRetryDelayMs = Math.min(unlinkedRetryDelayMs * 2, 60_000);
926 }
927 }
928 });
929​
930 schedulePublishConfirm = (threadId) =>
931 Effect.forkIn(
932 Effect.sleep("5 seconds").pipe(
933 Effect.andThen(worker.enqueue(threadId)),
934 Effect.catchCause((cause) =>
935 Effect.logWarning("deferred agent activity confirmation failed", {
936 threadId,
937 cause: Cause.pretty(cause),
938 }),
939 ),
940 ),
941 scope,
942 ).pipe(Effect.asVoid);
943​
944 const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
945 function* () {
946 const [relayConfig, publishEnabled] = yield* Effect.all([
947 readRelayConfig.pipe(Effect.orElseSucceed(() => null)),
948 readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),
949 ]);
950 const startupState = resolveAgentActivityPublishingStartupState({
951 relayConfigured: relayConfig !== null,
952 publishEnabled,
953 });
954 switch (startupState) {
955 case "waiting-for-link":
956 yield* Effect.logInfo(
957 "agent activity publishing standby; waiting for T3 Connect link reconciliation",
958 );
959 break;
960 case "disabled":
961 yield* Effect.logInfo("agent activity publishing disabled by T3 Connect configuration");
962 break;
963 case "enabled":
964 yield* Effect.logInfo("agent activity publishing enabled", {
965 relayUrl: relayConfig?.url,
966 });
967 break;
968 }
969 yield* forkParked(
970 Effect.sleep("1 second").pipe(
971 Effect.andThen(publishActiveThreadsWhenConfigured(startupState !== "enabled")),
972 ),
973 );
974 yield* forkParked(
975 Stream.runForEach(threads.streamDomainEvents, (event) => {
976 const threadId = eventThreadId(event);
977 if (!shouldPublishAgentAwarenessEvent(event)) {
978 return Effect.void;
979 }
980 return Effect.logDebug("agent activity publishing queued thread publish", {
981 eventType: event.type,
982 threadId,
983 }).pipe(Effect.andThen(enqueueThreadPublish(threadId)));
984 }),
985 );
986 },
987 );
988​
989 return AgentAwarenessRelay.of({
990 publishThread,
991 drain: worker.drain,
992 requestCatchUp: Effect.fn("AgentAwarenessRelay.requestCatchUp")(function () {
993 return Queue.offer(catchUpRequests, undefined).pipe(Effect.asVoid);
994 }),
995 start,
996 });
997});
998​
999export const layer = Layer.effect(AgentAwarenessRelay, make);