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