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