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

AgentAwarenessRelay.ts

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