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

AgentAwarenessRelay.ts

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