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

AgentAwarenessRelay.ts

664 lines23.5 KB

1import type {
2 EnvironmentId,
3 OrchestrationEvent,
4 OrchestrationProjectShell,
5 OrchestrationThreadShell,
6 ThreadId,
7} from "@t3tools/contracts";
8import {
9 RelayApi,
10 type RelayAgentActivityPublishProofPayload,
11 type RelayAgentActivityState,
12} from "@t3tools/contracts/relay";
13import { projectThreadAwareness } from "@t3tools/shared/agentAwareness";
14import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
15import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
16import {
17 normalizeRelayIssuer,
18 RELAY_ACTIVITY_PUBLISH_TYP,
19 signRelayJwt,
20} from "@t3tools/shared/relayJwt";
21import * as Cause from "effect/Cause";
22import * as Context from "effect/Context";
23import * as Crypto from "effect/Crypto";
24import * as DateTime from "effect/DateTime";
25import * as Effect from "effect/Effect";
26import * as Layer from "effect/Layer";
27import * as Option from "effect/Option";
28import * as Ref from "effect/Ref";
29import type * as Scope from "effect/Scope";
30import * as Stream from "effect/Stream";
31import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";
32import * as HttpClient from "effect/unstable/http/HttpClient";
33import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
34import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
35​
36import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
37import {
38 isAgentActivityPublishingEnabledValue,
39 PUBLISH_AGENT_ACTIVITY_SECRET,
40 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
41 RELAY_ISSUER_SECRET,
42 RELAY_URL_SECRET,
43} from "../cloud/config.ts";
44import { getOrCreateEnvironmentKeyPairFromSecretStore } from "../cloud/environmentKeys.ts";
45import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
46import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";
47import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
48import { forkParked } from "../serverActivation.ts";
49​
50export class AgentAwarenessRelay extends Context.Service<
51 AgentAwarenessRelay,
52 {
53 readonly publishThread: (threadId: ThreadId) => Effect.Effect<void>;
54 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
55 }
56>()("t3/relay/AgentAwarenessRelay") {}
57​
58export function eventThreadId(event: OrchestrationEvent): ThreadId | null {
59 const payload = event.payload as { readonly threadId?: unknown };
60 if (typeof payload.threadId === "string") {
61 return payload.threadId as ThreadId;
62 }
63 if (event.aggregateKind === "thread" && typeof event.aggregateId === "string") {
64 return event.aggregateId as ThreadId;
65 }
66 return null;
68​
69export function shouldPublishAgentAwarenessEvent(event: OrchestrationEvent): boolean {
70 if (event.metadata.historyImport === true) {
71 return false;
72 }
73 switch (event.type) {
74 case "thread.message-sent":
75 case "thread.turn-start-requested":
76 // These events express intent to start work, but the shell still contains
77 // the previous turn's terminal state until the provider acknowledges the
78 // new turn. Publishing that snapshot can queue a fresh "Done" alert just
79 // before the real running state arrives. Provider lifecycle events publish
80 // the authoritative starting/running state instead.
81 return false;
82 case "thread.proposed-plan-upserted":
83 case "thread.runtime-mode-set":
84 case "thread.interaction-mode-set":
85 return false;
86 case "thread.activity-appended":
87 return (
88 event.payload.activity.kind === "approval.requested" ||
89 event.payload.activity.kind === "approval.resolved" ||
90 event.payload.activity.kind === "provider.approval.respond.failed" ||
91 event.payload.activity.kind === "user-input.requested" ||
92 event.payload.activity.kind === "user-input.resolved" ||
93 event.payload.activity.kind === "runtime.error"
94 );
95 default:
96 return true;
97 }
99​
100export function agentAwarenessPublishIdentity(state: RelayAgentActivityState | null): string {
101 if (state === null) {
102 return "null";
103 }
104 const { updatedAt: _updatedAt, ...meaningfulState } = state;
105 return JSON.stringify(meaningfulState);
107​
108export function resolveAgentActivityPublishingStartupState(input: {
109 readonly relayConfigured: boolean;
110 readonly publishEnabled: boolean;
111}): "waiting-for-link" | "disabled" | "enabled" {
112 if (!input.relayConfigured) {
113 return "waiting-for-link";
114 }
115 return input.publishEnabled ? "enabled" : "disabled";
117​
118const RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH = 160;
119const REDACTED_RELAY_AGENT_FAILURE_DETAIL = "The agent run failed.";
120​
121export function sanitizeRelayAgentActivityState(
122 state: RelayAgentActivityState | null,
123): RelayAgentActivityState | null {
124 if (state === null) {
125 return null;
126 }
127 const { detail: _detail, ...rest } = state;
128 const detail = (state.phase === "failed" ? REDACTED_RELAY_AGENT_FAILURE_DETAIL : state.detail)
129 ?.trim()
130 .slice(0, RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH)
131 .trim();
132 return detail ? { ...rest, detail } : rest;
134​
135function relayEnvironmentClient(token: string) {
136 return HttpClient.mapRequest(HttpClientRequest.setHeader("authorization", `Bearer ${token}`));
138​
139function deliveryStats(
140 deliveries: ReadonlyArray<{
141 readonly ok: boolean;
142 readonly queued?: boolean | undefined;
143 readonly kind: string;
144 readonly apnsStatus?: number | null;
145 readonly apnsReason?: string | null;
146 }>,
147) {
148 let queued = 0;
149 let successful = 0;
150 let failed = 0;
151 const failedReasons: string[] = [];
152 const kinds = new Set<string>();
153​
154 for (const delivery of deliveries) {
155 kinds.add(delivery.kind);
156 if (delivery.queued) {
157 queued += 1;
158 continue;
159 }
160 if (delivery.ok) {
161 successful += 1;
162 continue;
163 }
164 failed += 1;
165 failedReasons.push(`${delivery.apnsStatus ?? "transport"}:${delivery.apnsReason ?? "unknown"}`);
166 }
167​
168 return {
169 total: deliveries.length,
170 queued,
171 successful,
172 failed,
173 kinds: [...kinds],
174 failedReasons,
175 };
177​
178export function signRelayAgentActivityPublishProof(input: {
179 readonly privateKey: string;
180 readonly payload: RelayAgentActivityPublishProofPayload;
181}) {
182 return signRelayJwt({
183 privateKey: input.privateKey,
184 typ: RELAY_ACTIVITY_PUBLISH_TYP,
185 payload: input.payload,
186 });
188​
189const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
190 readonly privateKey: string;
191 readonly relayIssuer: string;
192 readonly environmentId: string;
193 readonly threadId: ThreadId;
194 readonly state: RelayAgentActivityState | null;
195 readonly jti: string;
196}) {
197 const now = yield* DateTime.now;
198 const expiresAt = DateTime.add(now, { minutes: 5 });
199 const payload = {
200 iss: `t3-env:${input.environmentId}`,
201 aud: normalizeRelayIssuer(input.relayIssuer),
202 sub: input.environmentId,
203 jti: input.jti,
204 iat: Math.floor(now.epochMilliseconds / 1_000),
205 exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
206 environmentId: input.environmentId as RelayAgentActivityPublishProofPayload["environmentId"],
207 threadId: input.threadId,
208 state: input.state,
209 } satisfies RelayAgentActivityPublishProofPayload;
210 return yield* signRelayAgentActivityPublishProof({ privateKey: input.privateKey, payload });
211});
212​
213// Compact, log-safe view of the fields the awareness phase ladder reads.
214function describeThreadShellForAwareness(
215 thread: Option.Option<OrchestrationThreadShell>,
216): Record<string, unknown> {
217 if (Option.isNone(thread)) {
218 return { found: false };
219 }
220 const shell = thread.value;
221 return {
222 found: true,
223 sessionStatus: shell.session?.status ?? null,
224 sessionActiveTurnId: shell.session?.activeTurnId ?? null,
225 latestTurnId: shell.latestTurn?.turnId ?? null,
226 latestTurnState: shell.latestTurn?.state ?? null,
227 latestTurnCompletedAt: shell.latestTurn?.completedAt ?? null,
228 hasPendingApprovals: shell.hasPendingApprovals,
229 hasPendingUserInput: shell.hasPendingUserInput,
230 };
232​
233export function resolveAgentAwarenessRelayPublishSnapshot(input: {
234 readonly environmentId: EnvironmentId;
235 readonly threadId: ThreadId;
236 readonly thread: Option.Option<OrchestrationThreadShell>;
237 readonly project: Option.Option<OrchestrationProjectShell>;
238}): {
239 readonly projectId: string | null;
240 readonly state: RelayAgentActivityState | null;
241 readonly reason: "snapshot" | "thread-not-found" | "project-not-found";
242} {
243 if (Option.isNone(input.thread)) {
244 return {
245 projectId: null,
246 state: null,
247 reason: "thread-not-found",
248 };
249 }
250 if (Option.isNone(input.project)) {
251 return {
252 projectId: input.thread.value.projectId,
253 state: null,
254 reason: "project-not-found",
255 };
256 }
257 return {
258 projectId: input.thread.value.projectId,
259 state: sanitizeRelayAgentActivityState(
260 projectThreadAwareness({
261 environmentId: input.environmentId,
262 project: input.project.value,
263 thread: input.thread.value,
264 }),
265 ),
266 reason: "snapshot",
267 };
269​
270function terminalWorkSinceStart(thread: OrchestrationThreadShell, startedAt: number): boolean {
271 return Date.parse(thread.latestTurn?.completedAt ?? "") > startedAt;
273​
274export function resolveAgentAwarenessRelayActiveThreadIds(input: {
275 readonly environmentId: EnvironmentId;
276 readonly startedAt: number;
277 readonly projects: ReadonlyArray<Pick<OrchestrationProjectShell, "id" | "title">>;
278 readonly threads: ReadonlyArray<OrchestrationThreadShell>;
279}): ReadonlyArray<ThreadId> {
280 const projectById = new Map(input.projects.map((project) => [project.id, project]));
281 return input.threads
282 .filter((thread) => {
283 const project = projectById.get(thread.projectId);
284 if (!project) {
285 return false;
286 }
287 const state = projectThreadAwareness({
288 environmentId: input.environmentId,
289 project,
290 thread,
291 });
292 return (
293 state !== null &&
294 (state.phase !== "completed" && state.phase !== "failed"
295 ? true
296 : terminalWorkSinceStart(thread, input.startedAt))
297 );
298 })
299 .map((thread) => thread.id);
301​
302/** @public Service construction is part of the canonical Effect module API. */
303export const make = Effect.gen(function* () {
304 const secrets = yield* ServerSecretStore.ServerSecretStore;
305 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
306 const snapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
307 const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
308 const crypto = yield* Crypto.Crypto;
309 const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
310 const startedAt = (yield* DateTime.now).epochMilliseconds;
311 const activeSnapshotPublishedRef = yield* Ref.make(false);
312 const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());
313​
314 const readSecretString = (name: string) =>
315 secrets
316 .get(name)
317 .pipe(
318 Effect.map((bytes) =>
319 Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,
320 ),
321 );
322​
323 const readRelayConfig = Effect.gen(function* () {
324 const [url, issuer, environmentCredential] = yield* Effect.all([
325 readSecretString(RELAY_URL_SECRET),
326 readSecretString(RELAY_ISSUER_SECRET),
327 readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
328 ]);
329 return url && environmentCredential
330 ? { url, issuer: issuer ?? url, environmentCredential }
331 : null;
332 });
333​
334 const readPublishAgentActivityEnabled = readSecretString(PUBLISH_AGENT_ACTIVITY_SECRET).pipe(
335 Effect.map(isAgentActivityPublishingEnabledValue),
336 );
337​
338 const makeRelayClient = (relayConfig: {
339 readonly url: string;
340 readonly environmentCredential: string;
341 }) =>
342 HttpApiClient.make(RelayApi, {
343 baseUrl: relayConfig.url,
344 transformClient: relayEnvironmentClient(relayConfig.environmentCredential),
345 }).pipe(Effect.provide(FetchHttpClient.layer));
346​
347 // Deadlines for publishes that need confirmation (tombstones and
348 // first-state completions). The confirming publish is re-enqueued through
349 // the same drainable worker as every other publish, so a confirmed
350 // tombstone can never race an in-flight live update; a recovered state
351 // clears the deadline. Assigned after the worker exists.
352 const publishConfirmDeadlines = new Map<ThreadId, number>();
353 let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
354​
355 const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) {
356 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
357 Effect.orElseSucceed(() => false),
358 );
359 if (!publishAgentActivity) {
360 yield* Effect.logDebug("agent activity publish skipped; publication disabled", {
361 threadId,
362 });
363 return;
364 }
365 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
366 if (!relayConfig) {
367 yield* Effect.logDebug("agent activity publish skipped; relay link credentials unavailable", {
368 threadId,
369 });
370 return;
371 }
372 const relayClient = yield* makeRelayClient(relayConfig);
373 const environmentId = yield* serverEnvironment.getEnvironmentId;
374​
375 const publishState = (input: {
376 readonly projectId: string | null;
377 readonly state: RelayAgentActivityState | null;
378 readonly reason: string;
379 }) =>
380 Effect.gen(function* () {
381 const proof = yield* makePublishProof({
382 privateKey: cloudLinkKeyPair.privateKey,
383 relayIssuer: relayConfig.issuer,
384 environmentId,
385 threadId,
386 state: input.state,
387 jti: yield* crypto.randomUUIDv4,
388 });
389​
390 yield* Effect.logInfo("publishing agent activity for thread", {
391 environmentId,
392 threadId,
393 projectId: input.projectId,
394 statePhase: input.state?.phase ?? null,
395 hasState: input.state !== null,
396 reason: input.reason,
397 });
398​
399 const response = yield* relayClient.server.publishAgentActivity({
400 params: {
401 environmentId,
402 threadId,
403 },
404 payload: {
405 state: input.state,
406 proof,
407 },
408 });
409​
410 yield* Effect.logInfo("agent activity publish completed", {
411 environmentId,
412 threadId,
413 ok: response.ok,
414 deliveries: deliveryStats(response.deliveries),
415 });
416 });
417​
418 const thread = yield* snapshotQuery.getThreadShellById(threadId);
419 const project = Option.isSome(thread)
420 ? yield* snapshotQuery.getProjectShellById(thread.value.projectId)
421 : Option.none<OrchestrationProjectShell>();
422 const snapshot = resolveAgentAwarenessRelayPublishSnapshot({
423 environmentId,
424 threadId,
425 thread,
426 project,
427 });
428 const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);
429 const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);
430 if (
431 (snapshot.state?.phase === "completed" || snapshot.state?.phase === "failed") &&
432 !publishedStateByThread.has(threadId)
433 ) {
434 // Startup has no publish history. Only work from this server process may
435 // produce an initial terminal alert; historical threads remain quiet.
436 if (Option.isNone(thread) || !terminalWorkSinceStart(thread.value, startedAt)) return;
437 }
438 if (publishedStateByThread.get(threadId) === publishIdentity) {
439 // The projection is back at (or never left) the last published state, so
440 // any pending deferred confirmation is moot. Leaving the deadline in
441 // place would let a much later transient null find it already expired
442 // and publish a tombstone immediately, skipping the deferral window.
443 publishConfirmDeadlines.delete(threadId);
444 yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", {
445 environmentId,
446 threadId,
447 reason: snapshot.reason,
448 });
449 return;
450 }
451​
452 // Two projections need confirmation before publishing, because both can
453 // appear transiently while the projector is mid-write and publishing them
454 // immediately is destructive or noisy:
455 // - null (tombstone) while the previous published state was live: deletes
456 // the thread from every armed card mid-conversation.
457 // - completed as the thread's FIRST published state: sessions boot at
458 // "ready" before their first turn, which projects as completed for an
459 // instant and sends a spurious Done notification at thread birth.
460 // Defer, schedule a re-publish through the ordinary worker queue, and
461 // only publish if the projection still holds when it drains.
462 const requiresConfirmation =
463 (snapshot.state === null &&
464 publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) ||
465 (snapshot.state?.phase === "completed" && !publishedStateByThread.has(threadId));
466 if (requiresConfirmation) {
467 const nowMs = (yield* DateTime.now).epochMilliseconds;
468 const deadline = publishConfirmDeadlines.get(threadId);
469 if (deadline === undefined) {
470 publishConfirmDeadlines.set(threadId, nowMs + 5_000);
471 yield* Effect.logInfo("agent activity publish deferred pending confirmation", {
472 environmentId,
473 threadId,
474 reason: snapshot.reason,
475 statePhase: snapshot.state?.phase ?? null,
476 shell: describeThreadShellForAwareness(thread),
477 });
478 yield* schedulePublishConfirm(threadId);
479 return;
480 }
481 if (nowMs < deadline) {
482 return;
483 }
484 publishConfirmDeadlines.delete(threadId);
485 yield* Effect.logInfo("agent activity deferred publish confirmed", {
486 environmentId,
487 threadId,
488 reason: snapshot.reason,
489 statePhase: snapshot.state?.phase ?? null,
490 shell: describeThreadShellForAwareness(thread),
491 });
492 } else {
493 publishConfirmDeadlines.delete(threadId);
494 }
495​
496 if (snapshot.reason === "thread-not-found") {
497 yield* Effect.logDebug("publishing agent activity tombstone; thread not found", {
498 environmentId,
499 threadId,
500 });
501 } else if (snapshot.reason === "project-not-found") {
502 yield* Effect.logDebug("publishing agent activity tombstone; project not found", {
503 environmentId,
504 threadId,
505 projectId: snapshot.projectId,
506 });
507 }
508​
509 yield* publishState({
510 projectId: snapshot.projectId,
511 state: snapshot.state,
512 reason: snapshot.reason,
513 });
514 yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {
515 const nextPublishedStates = new Map(publishedStates);
516 if (snapshot.state === null) {
517 nextPublishedStates.delete(threadId);
518 } else {
519 nextPublishedStates.set(threadId, publishIdentity);
520 }
521 return nextPublishedStates;
522 });
523 });
524​
525 const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
526 publishThreadUnsafe(threadId).pipe(
527 Effect.catchCause((cause) => {
528 return Effect.logWarning("agent activity publish failed", {
529 threadId,
530 cause: Cause.pretty(cause),
531 });
532 }),
533 Effect.withSpan("AgentAwarenessRelay.publishThread"),
534 withRelayClientTracing,
535 );
536​
537 const publishActiveThreadsUnsafe = Effect.gen(function* () {
538 const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
539 Effect.orElseSucceed(() => false),
540 );
541 if (!publishAgentActivity) {
542 yield* Effect.logDebug("agent activity snapshot skipped; publication disabled");
543 return false;
544 }
545 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
546 if (!relayConfig) {
547 yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");
548 return false;
549 }
550 const environmentId = yield* serverEnvironment.getEnvironmentId;
551 const snapshot = yield* snapshotQuery.getShellSnapshot();
552 const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({
553 environmentId,
554 startedAt,
555 projects: snapshot.projects,
556 threads: snapshot.threads,
557 });
558 if (activeThreadIds.length === 0) {
559 yield* Effect.logDebug("agent activity snapshot has no publishable threads");
560 return true;
561 }
562 yield* Effect.logInfo("publishing active agent activity snapshot", {
563 count: activeThreadIds.length,
564 });
565 yield* Effect.forEach(activeThreadIds, publishThread, { concurrency: 4, discard: true });
566 return true;
567 });
568​
569 const publishActiveThreadsOnceWhenConfigured = (logEnabledWhenReady: boolean) =>
570 Effect.gen(function* () {
571 while (!(yield* Ref.get(activeSnapshotPublishedRef))) {
572 const published = yield* publishActiveThreadsUnsafe.pipe(Effect.orElseSucceed(() => false));
573 if (published) {
574 yield* Ref.set(activeSnapshotPublishedRef, true);
575 if (logEnabledWhenReady) {
576 const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
577 yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
578 relayUrl: relayConfig?.url,
579 });
580 }
581 return;
582 }
583 yield* Effect.sleep("5 seconds");
584 }
585 });
586​
587 const worker = yield* makeDrainableWorker(publishThread);
588​
589 schedulePublishConfirm = (threadId) =>
590 Effect.forkDetach(
591 Effect.sleep("5 seconds").pipe(
592 Effect.andThen(worker.enqueue(threadId)),
593 Effect.catchCause((cause) =>
594 Effect.logWarning("deferred agent activity confirmation failed", {
595 threadId,
596 cause: Cause.pretty(cause),
597 }),
598 ),
599 ),
600 ).pipe(Effect.asVoid);
601​
602 const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
603 function* () {
604 const [relayConfig, publishEnabled] = yield* Effect.all([
605 readRelayConfig.pipe(Effect.orElseSucceed(() => null)),
606 readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),
607 ]);
608 const startupState = resolveAgentActivityPublishingStartupState({
609 relayConfigured: relayConfig !== null,
610 publishEnabled,
611 });
612 switch (startupState) {
613 case "waiting-for-link":
614 yield* Effect.logInfo(
615 "agent activity publishing standby; waiting for T3 Connect link reconciliation",
616 );
617 break;
618 case "disabled":
619 yield* Effect.logInfo("agent activity publishing disabled by T3 Connect configuration");
620 break;
621 case "enabled":
622 yield* Effect.logInfo("agent activity publishing enabled", {
623 relayUrl: relayConfig?.url,
624 });
625 break;
626 }
627 yield* forkParked(
628 Effect.sleep("1 second").pipe(
629 Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")),
630 ),
631 );
632 yield* forkParked(
633 Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
634 const threadId = eventThreadId(event);
635 if (threadId === null) {
636 return Effect.logDebug("agent activity publishing ignored event without thread id", {
637 eventType: event.type,
638 });
639 }
640 if (!shouldPublishAgentAwarenessEvent(event)) {
641 return Effect.logDebug(
642 "agent activity publishing ignored event without activity changes",
643 {
644 eventType: event.type,
645 threadId,
646 },
647 );
648 }
649 return Effect.logDebug("agent activity publishing queued thread publish", {
650 eventType: event.type,
651 threadId,
652 }).pipe(Effect.andThen(worker.enqueue(threadId)));
653 }),
654 );
655 },
656 );
657​
658 return AgentAwarenessRelay.of({
659 publishThread,
660 start,
661 });
662});
663​
664export const layer = Layer.effect(AgentAwarenessRelay, make);