Open History to see the last commit
1import {
2 ORCHESTRATION_V2_WS_METHODS,
3 type EnvironmentId,
4 type ThreadId,
5 type OrchestrationV2ThreadLinkMetadata,
6 type OrchestrationGetTurnDiffResult,
7} from "@t3tools/contracts";
8import * as Effect from "effect/Effect";
9import * as Option from "effect/Option";
10import * as Stream from "effect/Stream";
11import * as SubscriptionRef from "effect/SubscriptionRef";
12import type { HttpClient } from "effect/http";
13import { Atom } from "effect/reactivity";
14
15import { applyCommandOutputFrame, EMPTY_COMMAND_OUTPUT } from "./commandOutput.ts";
16
17import {
18 createEnvironmentQueryAtomFamily,
19 createEnvironmentRpcCommand,
20 createEnvironmentRpcQueryAtomFamily,
21 createEnvironmentRpcSubscriptionAtomFamily,
22 createEnvironmentCommand,
23 type QueryAnswerHandler,
24} from "./runtime.ts";
25import type { EnvironmentRegistry } from "../connection/registry.ts";
26import * as EnvironmentSupervisor from "../connection/supervisor.ts";
27import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
28import * as ManagedRelayDpopSigner from "../relay/managedRelay.ts";
29import { EnvironmentRpcUnavailableError, request } from "../rpc/client.ts";
30import type { EnvironmentShellState } from "./shell.ts";
31import { fetchEnvironmentThreadTranscript } from "./threadTranscriptHttp.ts";
32
33export function createOrchestrationEnvironmentAtoms<R, E>(
34 runtime: Atom.AtomRuntime<EnvironmentRegistry | HttpClient.HttpClient | R, E>,
35 options: {
36 /** Re-checks `threadTitles` when one of their threads leaves the shell. */
37 readonly shellState?: (
38 environmentId: EnvironmentId,
39 ) => Atom.Atom<Pick<EnvironmentShellState, "removedAt">>;
40 /** Runs on each turn-range and full-thread diff the server answers. */
41 readonly onCheckpointDiffAnswer?: QueryAnswerHandler<
42 { readonly ignoreWhitespace?: boolean },
43 OrchestrationGetTurnDiffResult
44 >;
45 } = {},
46) {
47 const onCheckpointDiffAnswer =
48 options.onCheckpointDiffAnswer === undefined
49 ? {}
50 : { onAnswer: options.onCheckpointDiffAnswer };
51 const shellState = options.shellState;
52 const refreshThreadLookup = ({
53 environmentId,
54 input,
55 }: {
56 readonly environmentId: EnvironmentId;
57 readonly input: { readonly threadIds: ReadonlyArray<ThreadId> };
58 }) => {
59 if (shellState === undefined) return undefined;
60 const state = shellState(environmentId);
61 return Atom.make((get) => {
62 const { removedAt } = get(state);
63 return Math.max(-1, ...input.threadIds.map((threadId) => removedAt.get(threadId) ?? -1));
64 });
65 };
66 return {
67 threadTitles: createEnvironmentRpcQueryAtomFamily(runtime, {
68 label: "environment-data:orchestration:thread-titles",
69 tag: ORCHESTRATION_V2_WS_METHODS.getThreadTitles,
70 staleTimeMs: 0,
71 idleTtlMs: 0,
72 // Deleting a thread the shell already left out keeps these ids, so the query would not rerun.
73 // A removal can also be an archive, so it only prompts a re-check.
74 refreshTrigger: refreshThreadLookup,
75 }),
76 threadLinkMetadata: createEnvironmentQueryAtomFamily(runtime, {
77 label: "environment-data:orchestration:thread-link-metadata",
78 staleTimeMs: 0,
79 idleTtlMs: 0,
80 refreshTrigger: refreshThreadLookup,
81 execute: Effect.fn("orchestration.threadLinkMetadata")(function* (input: {
82 readonly threadIds: ReadonlyArray<ThreadId>;
83 }) {
84 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
85 const session = yield* SubscriptionRef.get(supervisor.session);
86 if (Option.isNone(session)) {
87 return yield* new EnvironmentRpcUnavailableError({
88 environmentId: supervisor.target.environmentId,
89 message: "The environment has no session.",
90 });
91 }
92 const config = yield* session.value.initialConfig;
93 if (config.threadLinkMetadata === true) {
94 return yield* request(ORCHESTRATION_V2_WS_METHODS.getThreadLinkMetadata, input);
95 }
96 const titles = yield* request(ORCHESTRATION_V2_WS_METHODS.getThreadTitles, input);
97 return Object.fromEntries(
98 Object.entries(titles).map(([id, title]) => [
99 id,
100 { title, projectId: null } satisfies OrchestrationV2ThreadLinkMetadata,
101 ]),
102 );
103 }),
104 }),
105 threadTranscript: createEnvironmentCommand(runtime, {
106 label: "environment-data:orchestration:thread-transcript",
107 execute: Effect.fn("orchestration.execute")(function* (input: {
108 readonly threadId: ThreadId;
109 }) {
110 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
111 const prepared = yield* SubscriptionRef.get(supervisor.prepared);
112 if (Option.isNone(prepared)) {
113 return yield* new EnvironmentRpcUnavailableError({
114 environmentId: supervisor.target.environmentId,
115 message: "The source environment is not connected.",
116 });
117 }
118 return yield* fetchEnvironmentThreadTranscript({
119 prepared: prepared.value,
120 threadId: input.threadId,
121 signer: yield* Effect.serviceOption(ManagedRelayDpopSigner.ManagedRelayDpopSigner),
122 remoteAuthorization: yield* Effect.serviceOption(
123 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
124 ),
125 });
126 }),
127 }),
128 v2: {
129 dispatchCommand: createEnvironmentRpcCommand(runtime, {
130 label: "environment-data:orchestration-v2:dispatch-command",
131 tag: ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
132 }),
133 shell: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
134 label: "environment-data:orchestration-v2:shell",
135 tag: ORCHESTRATION_V2_WS_METHODS.subscribeShell,
136 }),
137 thread: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
138 label: "environment-data:orchestration-v2:thread",
139 tag: ORCHESTRATION_V2_WS_METHODS.subscribeThread,
140 idleTtlMs: 0,
141 }),
142 // One expanded command row's output. Mounted only while the row is open,
143 // and released as soon as it closes, so hidden rows receive nothing.
144 commandOutput: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
145 label: "environment-data:orchestration-v2:command-output",
146 tag: ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput,
147 idleTtlMs: 0,
148 // `scan` emits its seed first; skipping it keeps the row "loading" until the first frame.
149 transform: (frames) =>
150 frames.pipe(
151 Stream.scan(() => EMPTY_COMMAND_OUTPUT, applyCommandOutputFrame),
152 Stream.filter((view) => view !== EMPTY_COMMAND_OUTPUT),
153 ),
154 }),
155 // The open thread's predicted next prompt, while its composer is mounted.
156 promptSuggestion: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
157 label: "environment-data:orchestration-v2:prompt-suggestion",
158 tag: ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion,
159 idleTtlMs: 0,
160 }),
161 },
162 turnDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
163 label: "environment-data:orchestration:turn-diff",
164 tag: ORCHESTRATION_V2_WS_METHODS.getTurnDiff,
165 ...onCheckpointDiffAnswer,
166 }),
167 workflowScript: createEnvironmentRpcQueryAtomFamily(runtime, {
168 label: "environment-data:orchestration:workflow-script",
169 tag: ORCHESTRATION_V2_WS_METHODS.getWorkflowScript,
170 staleTimeMs: 300_000,
171 idleTtlMs: 300_000,
172 }),
173 // Mounted only while a subagent inspector is open; running children change between opens.
174 nativeChildWork: createEnvironmentRpcQueryAtomFamily(runtime, {
175 label: "environment-data:orchestration:native-child-work",
176 tag: ORCHESTRATION_V2_WS_METHODS.getNativeChildWork,
177 staleTimeMs: 0,
178 idleTtlMs: 0,
179 }),
180 stopWorkflow: createEnvironmentRpcCommand(runtime, {
181 label: "environment-data:orchestration:stop-workflow",
182 tag: ORCHESTRATION_V2_WS_METHODS.stopWorkflow,
183 }),
184 forceStopThread: createEnvironmentRpcCommand(runtime, {
185 label: "environment-data:orchestration:force-stop-thread",
186 tag: ORCHESTRATION_V2_WS_METHODS.forceStopThread,
187 }),
188 turnItem: createEnvironmentRpcQueryAtomFamily(runtime, {
189 label: "environment-data:orchestration:turn-item",
190 tag: ORCHESTRATION_V2_WS_METHODS.getTurnItem,
191 staleTimeMs: 60_000,
192 idleTtlMs: 60_000,
193 }),
194 fullThreadDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
195 label: "environment-data:orchestration:full-thread-diff",
196 tag: ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff,
197 ...onCheckpointDiffAnswer,
198 }),
199 threadFind: createEnvironmentRpcQueryAtomFamily(runtime, {
200 label: "environment-data:orchestration:thread-find",
201 tag: ORCHESTRATION_V2_WS_METHODS.searchThread,
202 staleTimeMs: 0,
203 idleTtlMs: 0,
204 }),
205 threadFindProgressive: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
206 label: "environment-data:orchestration:thread-find-progressive",
207 tag: ORCHESTRATION_V2_WS_METHODS.searchThreadStream,
208 completeWhen: (result) => result.complete !== false,
209 idleTtlMs: 0,
210 }),
211 threadSearch: createEnvironmentRpcQueryAtomFamily(runtime, {
212 label: "environment-data:orchestration:thread-search",
213 tag: ORCHESTRATION_V2_WS_METHODS.searchThreads,
214 staleTimeMs: 30_000,
215 idleTtlMs: 60_000,
216 }),
217 archivedShellSnapshot: createEnvironmentRpcQueryAtomFamily(runtime, {
218 label: "environment-data:orchestration:archived-shell-snapshot",
219 tag: ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot,
220 }),
221 // Read right before deleting a worktree, so never served from cache.
222 worktreeThreadIds: createEnvironmentRpcQueryAtomFamily(runtime, {
223 label: "environment-data:orchestration:worktree-thread-ids",
224 tag: ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds,
225 staleTimeMs: 0,
226 idleTtlMs: 0,
227 }),
228 };
229}