The best way to control Claude Code, Codex and more from any computer or phone

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