Open History to see the last commit
1import { Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
2import {
3 type GitActionProgressEvent,
4 type GitManagerServiceError,
5 OrchestrationDispatchCommandError,
6 type OrchestrationEvent,
7 OrchestrationGetFullThreadDiffError,
8 OrchestrationGetSnapshotError,
9 OrchestrationGetTurnDiffError,
10 ORCHESTRATION_WS_METHODS,
11 ProjectSearchEntriesError,
12 ProjectWriteFileError,
13 OrchestrationReplayEventsError,
14 type TerminalEvent,
15 WS_METHODS,
16 WsRpcGroup,
17} from "@t3tools/contracts";
18import { clamp } from "effect/Number";
19import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
20import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
21
22import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
23import { ServerConfig } from "./config";
24import { GitCore } from "./git/Services/GitCore";
25import { GitManager } from "./git/Services/GitManager";
26import { Keybindings } from "./keybindings";
27import { Open, resolveAvailableEditors } from "./open";
28import { normalizeDispatchCommand } from "./orchestration/Normalizer";
29import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
30import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
31import { ProviderRegistry } from "./provider/Services/ProviderRegistry";
32import { ServerLifecycleEvents } from "./serverLifecycleEvents";
33import { ServerRuntimeStartup } from "./serverRuntimeStartup";
34import { ServerSettingsService } from "./serverSettings";
35import { TerminalManager } from "./terminal/Services/Manager";
36import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries";
37import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem";
38import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths";
39
40const WsRpcLayer = WsRpcGroup.toLayer(
41 Effect.gen(function* () {
42 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
43 const orchestrationEngine = yield* OrchestrationEngineService;
44 const checkpointDiffQuery = yield* CheckpointDiffQuery;
45 const keybindings = yield* Keybindings;
46 const open = yield* Open;
47 const gitManager = yield* GitManager;
48 const git = yield* GitCore;
49 const terminalManager = yield* TerminalManager;
50 const providerRegistry = yield* ProviderRegistry;
51 const config = yield* ServerConfig;
52 const lifecycleEvents = yield* ServerLifecycleEvents;
53 const serverSettings = yield* ServerSettingsService;
54 const startup = yield* ServerRuntimeStartup;
55 const workspaceEntries = yield* WorkspaceEntries;
56 const workspaceFileSystem = yield* WorkspaceFileSystem;
57
58 const loadServerConfig = Effect.gen(function* () {
59 const keybindingsConfig = yield* keybindings.loadConfigState;
60 const providers = yield* providerRegistry.getProviders;
61 const settings = yield* serverSettings.getSettings;
62
63 return {
64 cwd: config.cwd,
65 keybindingsConfigPath: config.keybindingsConfigPath,
66 keybindings: keybindingsConfig.keybindings,
67 issues: keybindingsConfig.issues,
68 providers,
69 availableEditors: resolveAvailableEditors(),
70 settings,
71 };
72 });
73
74 return WsRpcGroup.of({
75 [ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) =>
76 projectionSnapshotQuery.getSnapshot().pipe(
77 Effect.mapError(
78 (cause) =>
79 new OrchestrationGetSnapshotError({
80 message: "Failed to load orchestration snapshot",
81 cause,
82 }),
83 ),
84 ),
85 [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
86 Effect.gen(function* () {
87 const normalizedCommand = yield* normalizeDispatchCommand(command);
88 return yield* startup.enqueueCommand(orchestrationEngine.dispatch(normalizedCommand));
89 }).pipe(
90 Effect.mapError((cause) =>
91 Schema.is(OrchestrationDispatchCommandError)(cause)
92 ? cause
93 : new OrchestrationDispatchCommandError({
94 message: "Failed to dispatch orchestration command",
95 cause,
96 }),
97 ),
98 ),
99 [ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) =>
100 checkpointDiffQuery.getTurnDiff(input).pipe(
101 Effect.mapError(
102 (cause) =>
103 new OrchestrationGetTurnDiffError({
104 message: "Failed to load turn diff",
105 cause,
106 }),
107 ),
108 ),
109 [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) =>
110 checkpointDiffQuery.getFullThreadDiff(input).pipe(
111 Effect.mapError(
112 (cause) =>
113 new OrchestrationGetFullThreadDiffError({
114 message: "Failed to load full thread diff",
115 cause,
116 }),
117 ),
118 ),
119 [ORCHESTRATION_WS_METHODS.replayEvents]: (input) =>
120 Stream.runCollect(
121 orchestrationEngine.readEvents(
122 clamp(input.fromSequenceExclusive, { maximum: Number.MAX_SAFE_INTEGER, minimum: 0 }),
123 ),
124 ).pipe(
125 Effect.map((events) => Array.from(events)),
126 Effect.mapError(
127 (cause) =>
128 new OrchestrationReplayEventsError({
129 message: "Failed to replay orchestration events",
130 cause,
131 }),
132 ),
133 ),
134 [WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) =>
135 Stream.unwrap(
136 Effect.gen(function* () {
137 const snapshot = yield* orchestrationEngine.getReadModel();
138 const fromSequenceExclusive = snapshot.snapshotSequence;
139 const replayEvents: Array<OrchestrationEvent> = yield* Stream.runCollect(
140 orchestrationEngine.readEvents(fromSequenceExclusive),
141 ).pipe(
142 Effect.map((events) => Array.from(events)),
143 Effect.catch(() => Effect.succeed([] as Array<OrchestrationEvent>)),
144 );
145 const replayStream = Stream.fromIterable(replayEvents);
146 const source = Stream.merge(replayStream, orchestrationEngine.streamDomainEvents);
147 type SequenceState = {
148 readonly nextSequence: number;
149 readonly pendingBySequence: Map<number, OrchestrationEvent>;
150 };
151 const state = yield* Ref.make<SequenceState>({
152 nextSequence: fromSequenceExclusive + 1,
153 pendingBySequence: new Map<number, OrchestrationEvent>(),
154 });
155
156 return source.pipe(
157 Stream.mapEffect((event) =>
158 Ref.modify(
159 state,
160 ({
161 nextSequence,
162 pendingBySequence,
163 }): [Array<OrchestrationEvent>, SequenceState] => {
164 if (event.sequence < nextSequence || pendingBySequence.has(event.sequence)) {
165 return [[], { nextSequence, pendingBySequence }];
166 }
167
168 const updatedPending = new Map(pendingBySequence);
169 updatedPending.set(event.sequence, event);
170
171 const emit: Array<OrchestrationEvent> = [];
172 let expected = nextSequence;
173 for (;;) {
174 const expectedEvent = updatedPending.get(expected);
175 if (!expectedEvent) {
176 break;
177 }
178 emit.push(expectedEvent);
179 updatedPending.delete(expected);
180 expected += 1;
181 }
182
183 return [emit, { nextSequence: expected, pendingBySequence: updatedPending }];
184 },
185 ),
186 ),
187 Stream.flatMap((events) => Stream.fromIterable(events)),
188 );
189 }),
190 ),
191 [WS_METHODS.serverGetConfig]: (_input) => loadServerConfig,
192 [WS_METHODS.serverRefreshProviders]: (_input) =>
193 providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))),
194 [WS_METHODS.serverUpsertKeybinding]: (rule) =>
195 Effect.gen(function* () {
196 const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);
197 return { keybindings: keybindingsConfig, issues: [] };
198 }),
199 [WS_METHODS.serverGetSettings]: (_input) => serverSettings.getSettings,
200 [WS_METHODS.serverUpdateSettings]: ({ patch }) => serverSettings.updateSettings(patch),
201 [WS_METHODS.projectsSearchEntries]: (input) =>
202 workspaceEntries.search(input).pipe(
203 Effect.mapError(
204 (cause) =>
205 new ProjectSearchEntriesError({
206 message: `Failed to search workspace entries: ${cause.detail}`,
207 cause,
208 }),
209 ),
210 ),
211 [WS_METHODS.projectsWriteFile]: (input) =>
212 workspaceFileSystem.writeFile(input).pipe(
213 Effect.mapError((cause) => {
214 const message = Schema.is(WorkspacePathOutsideRootError)(cause)
215 ? "Workspace file path must stay within the project root."
216 : "Failed to write workspace file";
217 return new ProjectWriteFileError({
218 message,
219 cause,
220 });
221 }),
222 ),
223 [WS_METHODS.shellOpenInEditor]: (input) => open.openInEditor(input),
224 [WS_METHODS.gitStatus]: (input) => gitManager.status(input),
225 [WS_METHODS.gitPull]: (input) => git.pullCurrentBranch(input.cwd),
226 [WS_METHODS.gitRunStackedAction]: (input) =>
227 Stream.callback<GitActionProgressEvent, GitManagerServiceError>((queue) =>
228 gitManager
229 .runStackedAction(input, {
230 actionId: input.actionId,
231 progressReporter: {
232 publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid),
233 },
234 })
235 .pipe(
236 Effect.matchCauseEffect({
237 onFailure: (cause) => Queue.failCause(queue, cause),
238 onSuccess: () => Queue.end(queue).pipe(Effect.asVoid),
239 }),
240 ),
241 ),
242 [WS_METHODS.gitResolvePullRequest]: (input) => gitManager.resolvePullRequest(input),
243 [WS_METHODS.gitPreparePullRequestThread]: (input) =>
244 gitManager.preparePullRequestThread(input),
245 [WS_METHODS.gitListBranches]: (input) => git.listBranches(input),
246 [WS_METHODS.gitCreateWorktree]: (input) => git.createWorktree(input),
247 [WS_METHODS.gitRemoveWorktree]: (input) => git.removeWorktree(input),
248 [WS_METHODS.gitCreateBranch]: (input) => git.createBranch(input),
249 [WS_METHODS.gitCheckout]: (input) => Effect.scoped(git.checkoutBranch(input)),
250 [WS_METHODS.gitInit]: (input) => git.initRepo(input),
251 [WS_METHODS.terminalOpen]: (input) => terminalManager.open(input),
252 [WS_METHODS.terminalWrite]: (input) => terminalManager.write(input),
253 [WS_METHODS.terminalResize]: (input) => terminalManager.resize(input),
254 [WS_METHODS.terminalClear]: (input) => terminalManager.clear(input),
255 [WS_METHODS.terminalRestart]: (input) => terminalManager.restart(input),
256 [WS_METHODS.terminalClose]: (input) => terminalManager.close(input),
257 [WS_METHODS.subscribeTerminalEvents]: (_input) =>
258 Stream.callback<TerminalEvent>((queue) =>
259 Effect.acquireRelease(
260 terminalManager.subscribe((event) => Queue.offer(queue, event)),
261 (unsubscribe) => Effect.sync(unsubscribe),
262 ),
263 ),
264 [WS_METHODS.subscribeServerConfig]: (_input) =>
265 Stream.unwrap(
266 Effect.gen(function* () {
267 const keybindingsUpdates = keybindings.streamChanges.pipe(
268 Stream.map((event) => ({
269 version: 1 as const,
270 type: "keybindingsUpdated" as const,
271 payload: {
272 issues: event.issues,
273 },
274 })),
275 );
276 const providerStatuses = providerRegistry.streamChanges.pipe(
277 Stream.map((providers) => ({
278 version: 1 as const,
279 type: "providerStatuses" as const,
280 payload: { providers },
281 })),
282 );
283 const settingsUpdates = serverSettings.streamChanges.pipe(
284 Stream.map((settings) => ({
285 version: 1 as const,
286 type: "settingsUpdated" as const,
287 payload: { settings },
288 })),
289 );
290
291 return Stream.concat(
292 Stream.make({
293 version: 1 as const,
294 type: "snapshot" as const,
295 config: yield* loadServerConfig,
296 }),
297 Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)),
298 );
299 }),
300 ),
301 [WS_METHODS.subscribeServerLifecycle]: (_input) =>
302 Stream.unwrap(
303 Effect.gen(function* () {
304 const snapshot = yield* lifecycleEvents.snapshot;
305 const snapshotEvents = Array.from(snapshot.events).toSorted(
306 (left, right) => left.sequence - right.sequence,
307 );
308 const liveEvents = lifecycleEvents.stream.pipe(
309 Stream.filter((event) => event.sequence > snapshot.sequence),
310 );
311 return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents);
312 }),
313 ),
314 });
315 }),
316);
317
318export const websocketRpcRouteLayer = Layer.unwrap(
319 Effect.gen(function* () {
320 const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup).pipe(
321 Effect.provide(Layer.mergeAll(WsRpcLayer, RpcSerialization.layerJson)),
322 );
323 return HttpRouter.add(
324 "GET",
325 "/ws",
326 Effect.gen(function* () {
327 const request = yield* HttpServerRequest.HttpServerRequest;
328 const config = yield* ServerConfig;
329 if (config.authToken) {
330 const url = HttpServerRequest.toURL(request);
331 if (Option.isNone(url)) {
332 return HttpServerResponse.text("Invalid WebSocket URL", { status: 400 });
333 }
334 const token = url.value.searchParams.get("token");
335 if (token !== config.authToken) {
336 return HttpServerResponse.text("Unauthorized WebSocket connection", { status: 401 });
337 }
338 }
339 return yield* rpcWebSocketHttpEffect;
340 }),
341 );
342 }),
343);