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