-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathwsServer.ts
More file actions
2089 lines (1873 loc) · 71.8 KB
/
wsServer.ts
File metadata and controls
2089 lines (1873 loc) · 71.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Server - HTTP/WebSocket server service interface.
*
* Owns startup and shutdown lifecycle of the HTTP server, static asset serving,
* and WebSocket request routing.
*
* @module Server
*/
import fs from "node:fs";
import http, { type IncomingMessage } from "node:http";
import path from "node:path";
import type { Duplex } from "node:stream";
import Mime from "@effect/platform-node/Mime";
import {
CommandId,
DEFAULT_CHAT_FILE_MIME_TYPE,
DEFAULT_PROVIDER_INTERACTION_MODE,
type ClientOrchestrationCommand,
type OrchestrationCommand,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
ProjectId,
ThreadId,
SME_WS_CHANNELS,
WS_CHANNELS,
WS_METHODS,
type WebSocketError,
WebSocketRequest,
type WsResponse as WsResponseMessage,
WsResponse,
type WsPushEnvelopeBase,
} from "@okcode/contracts";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import {
Cause,
Effect,
Exit,
FileSystem,
Fiber,
Layer,
Path,
Ref,
Result,
Schema,
Scope,
ServiceMap,
Stream,
Struct,
} from "effect";
import { WebSocketServer, type WebSocket } from "ws";
import { createLogger } from "./logger";
import { pickFolderNative } from "./nativeFolderPicker.ts";
import { GitManager } from "./git/Services/GitManager.ts";
import { TerminalManager } from "./terminal/Services/Manager.ts";
import { Keybindings } from "./keybindings";
import {
clearWorkspaceIndexCache,
listWorkspaceDirectory,
searchWorkspaceEntries,
} from "./workspaceEntries";
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
import { ProviderService } from "./provider/Services/ProviderService";
import { ProviderHealth } from "./provider/Services/ProviderHealth";
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
import { clamp } from "effect/Number";
import { Open, resolveAvailableEditors } from "./open";
import { ServerConfig } from "./config";
import { GitCore } from "./git/Services/GitCore.ts";
import { collectMergedWorktreeCleanupCandidates } from "./git/worktreeCleanup.ts";
import {
ATTACHMENTS_ROUTE_PREFIX,
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths";
import { buildPreviewDataUrl, containsBinaryBytes, resolveFilePreview } from "./filePreview";
import {
createAttachmentId,
resolveAttachmentPath,
resolveAttachmentPathById,
} from "./attachmentStore.ts";
import { parseBase64DataUrl } from "./imageMime.ts";
import { extractTextAttachmentContents } from "./attachmentText.ts";
import { expandHomePath } from "./os-jank.ts";
import { makeServerPushBus } from "./wsServer/pushBus.ts";
import { makeServerReadiness } from "./wsServer/readiness.ts";
import { decodeJsonResult, formatSchemaError } from "@okcode/shared/schemaJson";
import { redactSensitiveText, redactSensitiveValue } from "@okcode/shared/redaction";
import { PrReview } from "./prReview/Services/PrReview.ts";
import { GitHub } from "./github/Services/GitHub.ts";
import { GitActionExecutionError } from "./git/Errors.ts";
import { EnvironmentVariables } from "./persistence/Services/EnvironmentVariables.ts";
import { OpenclawGatewayConfig } from "./persistence/Services/OpenclawGatewayConfig.ts";
import { SkillService } from "./skills/SkillService.ts";
import { SmeChatService } from "./sme/Services/SmeChatService.ts";
import { TokenManager } from "./tokenManager.ts";
import { resolveRuntimeEnvironment, RuntimeEnv } from "./runtimeEnvironment.ts";
import { readCodexConfigSummary } from "./provider/codexConfig";
import { TerminalRuntimeEnvResolver } from "./terminal/Services/RuntimeEnvResolver.ts";
import { version as serverVersion } from "../package.json" with { type: "json" };
import { serverBuildInfo } from "./buildInfo";
import { runOpenclawGatewayTest } from "./openclawGatewayTest.ts";
import { createApiRouter } from "./api/router.ts";
// ── OpenClaw Gateway Connection Test ──────────────────────────────────
function testOpenclawGateway(input: import("@okcode/contracts").TestOpenclawGatewayInput) {
return Effect.tryPromise({
try: () => runOpenclawGatewayTest(input),
catch: (cause) =>
new RouteRequestError({
message: `OpenClaw gateway test failed: ${cause instanceof Error ? cause.message : String(cause)}`,
}),
});
}
const resolveCheckPath = Effect.fn(function* (input: string) {
return path.resolve(yield* expandHomePath(input.trim()));
});
/**
* Returns true if `a` is a strictly higher semver than `b`.
* Only handles `major.minor.patch` numeric segments; pre-release suffixes
* (e.g. `-beta.1`) are ignored. The `okcodes` npm package uses plain
* `x.y.z` releases so this is sufficient for update-check purposes.
*/
function isNewerSemver(a: string, b: string): boolean {
const pa = a.split(".").map(Number);
const pb = b.split(".").map(Number);
for (let i = 0; i < 3; i++) {
const va = pa[i] ?? 0;
const vb = pb[i] ?? 0;
if (va > vb) return true;
if (va < vb) return false;
}
return false;
}
function inferAttachmentContentType(filePath: string): string {
const mimeType = Mime.getType(filePath);
if (mimeType) {
return mimeType;
}
const normalizedPath = filePath.toLowerCase();
if (normalizedPath.endsWith(".patch") || normalizedPath.endsWith(".diff")) {
return "text/x-diff; charset=utf-8";
}
if (normalizedPath.endsWith(".md")) {
return "text/markdown; charset=utf-8";
}
if (normalizedPath.endsWith(".txt")) {
return "text/plain; charset=utf-8";
}
return "application/octet-stream";
}
/**
* Remote address from the HTTP upgrade (`request.socket`). The `ws` library often does not
* expose a reliable `socket.remoteAddress` when handling messages, so we capture it here.
*/
const remoteAddressByWebSocket = new WeakMap<WebSocket, string>();
function captureWebSocketRemoteAddress(ws: WebSocket, request: IncomingMessage): void {
const addr = request.socket?.remoteAddress;
if (typeof addr === "string" && addr.length > 0) {
remoteAddressByWebSocket.set(ws, addr);
}
}
function getWebSocketRemoteAddress(ws: WebSocket): string | undefined {
const fromUpgrade = remoteAddressByWebSocket.get(ws);
if (fromUpgrade !== undefined) {
return fromUpgrade;
}
const raw = ws as WebSocket & {
socket?: { remoteAddress?: string | undefined };
_socket?: { remoteAddress?: string | undefined };
};
return raw.socket?.remoteAddress ?? raw._socket?.remoteAddress;
}
function isLoopbackRemoteAddress(addr: string): boolean {
if (addr === "::1" || addr === "127.0.0.1" || addr === "::ffff:127.0.0.1") {
return true;
}
return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(addr);
}
function isLocalWebSocketClient(ws: WebSocket): boolean {
const addr = getWebSocketRemoteAddress(ws);
if (addr === undefined || addr.length === 0) {
return true;
}
return isLoopbackRemoteAddress(addr);
}
/**
* ServerShape - Service API for server lifecycle control.
*/
export interface ServerShape {
/**
* Start HTTP and WebSocket listeners.
*/
readonly start: Effect.Effect<
http.Server,
ServerLifecycleError,
Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
>;
/**
* Wait for process shutdown signals.
*/
readonly stopSignal: Effect.Effect<void, never>;
}
/**
* Server - Service tag for HTTP/WebSocket lifecycle management.
*/
export class Server extends ServiceMap.Service<Server, ServerShape>()("okcode/wsServer/Server") {}
const isServerNotRunningError = (error: Error): boolean => {
const maybeCode = (error as NodeJS.ErrnoException).code;
return (
maybeCode === "ERR_SERVER_NOT_RUNNING" || error.message.toLowerCase().includes("not running")
);
};
function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
socket.end(
`HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
"Connection: close\r\n" +
"Content-Type: text/plain\r\n" +
`Content-Length: ${Buffer.byteLength(message)}\r\n` +
"\r\n" +
message,
);
}
function websocketRawToString(raw: unknown): string | null {
if (typeof raw === "string") {
return raw;
}
if (raw instanceof Uint8Array) {
return Buffer.from(raw).toString("utf8");
}
if (raw instanceof ArrayBuffer) {
return Buffer.from(new Uint8Array(raw)).toString("utf8");
}
if (Array.isArray(raw)) {
const chunks: string[] = [];
for (const chunk of raw) {
if (typeof chunk === "string") {
chunks.push(chunk);
continue;
}
if (chunk instanceof Uint8Array) {
chunks.push(Buffer.from(chunk).toString("utf8"));
continue;
}
if (chunk instanceof ArrayBuffer) {
chunks.push(Buffer.from(new Uint8Array(chunk)).toString("utf8"));
continue;
}
return null;
}
return chunks.join("");
}
return null;
}
function toPosixRelativePath(input: string): string {
return input.replaceAll("\\", "/");
}
function resolveWorkspaceWritePath(params: {
workspaceRoot: string;
relativePath: string;
path: Path.Path;
}): Effect.Effect<{ absolutePath: string; relativePath: string }, RouteRequestError> {
const normalizedInputPath = params.relativePath.trim();
if (params.path.isAbsolute(normalizedInputPath)) {
return Effect.fail(
new RouteRequestError({
message: "Workspace file path must be relative to the project root.",
}),
);
}
const absolutePath = params.path.resolve(params.workspaceRoot, normalizedInputPath);
const relativeToRoot = toPosixRelativePath(
params.path.relative(params.workspaceRoot, absolutePath),
);
if (
relativeToRoot.length === 0 ||
relativeToRoot === "." ||
relativeToRoot.startsWith("../") ||
relativeToRoot === ".." ||
params.path.isAbsolute(relativeToRoot)
) {
return Effect.fail(
new RouteRequestError({
message: "Workspace file path must stay within the project root.",
}),
);
}
return Effect.succeed({
absolutePath,
relativePath: relativeToRoot,
});
}
function stripRequestTag<T extends { _tag: string }>(body: T) {
return Struct.omit(body, ["_tag"]);
}
const encodeWsResponse = Schema.encodeEffect(Schema.fromJsonString(WsResponse));
const decodeWebSocketRequest = decodeJsonResult(WebSocketRequest);
export type ServerCoreRuntimeServices =
| OrchestrationEngineService
| ProjectionSnapshotQuery
| CheckpointDiffQuery
| OrchestrationReactor
| ProviderService
| ProviderHealth;
export type ServerRuntimeServices =
| ServerCoreRuntimeServices
| GitManager
| GitCore
| PrReview
| GitHub
| TerminalManager
| TerminalRuntimeEnvResolver
| Keybindings
| SkillService
| SmeChatService
| Open
| EnvironmentVariables
| OpenclawGatewayConfig;
export class ServerLifecycleError extends Schema.TaggedErrorClass<ServerLifecycleError>()(
"ServerLifecycleError",
{
operation: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {}
class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("RouteRequestError", {
message: Schema.String,
}) {}
class GitActionStoppedError extends Schema.TaggedErrorClass<GitActionStoppedError>()(
"GitActionStoppedError",
{
message: Schema.String,
},
) {}
export const createServer = Effect.fn(function* (): Effect.fn.Return<
http.Server,
ServerLifecycleError,
Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
> {
const serverConfig = yield* ServerConfig;
const {
port,
cwd,
keybindingsConfigPath,
staticDir,
devUrl,
authToken,
host,
logWebSocketEvents,
autoBootstrapProjectFromCwd,
} = serverConfig;
const availableEditors = resolveAvailableEditors();
const tokenManager = new TokenManager(authToken);
const tryHandleApiRequest = createApiRouter({
authToken,
host,
port,
tokenManager,
});
const gitManager = yield* GitManager;
const terminalManager = yield* TerminalManager;
const keybindingsManager = yield* Keybindings;
const providerHealth = yield* ProviderHealth;
const openclawGatewayConfig = yield* OpenclawGatewayConfig;
const git = yield* GitCore;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* keybindingsManager.syncDefaultKeybindingsOnStartup.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to sync keybindings defaults on startup", {
path: error.configPath,
detail: error.detail,
cause: error.cause,
}),
),
);
let lastKnownProviderStatuses = yield* providerHealth.getStatuses;
const clients = yield* Ref.make(new Set<WebSocket>());
const logger = createLogger("ws");
const readiness = yield* makeServerReadiness;
type ActiveGitRequestKind = "pull" | "stacked_action";
type ActiveGitRequestHandle = {
readonly kind: ActiveGitRequestKind;
readonly cwd: string;
readonly actionId: string | null;
readonly fiber: Fiber.Fiber<unknown, unknown>;
};
const activeGitRequests = new WeakMap<WebSocket, Set<ActiveGitRequestHandle>>();
const registerActiveGitRequest = (ws: WebSocket, handle: ActiveGitRequestHandle) =>
Effect.sync(() => {
const handles = activeGitRequests.get(ws) ?? new Set<ActiveGitRequestHandle>();
handles.add(handle);
activeGitRequests.set(ws, handles);
});
const unregisterActiveGitRequest = (ws: WebSocket, handle: ActiveGitRequestHandle) =>
Effect.sync(() => {
const handles = activeGitRequests.get(ws);
if (!handles) {
return;
}
handles.delete(handle);
if (handles.size === 0) {
activeGitRequests.delete(ws);
}
});
const interruptActiveGitRequests = (ws: WebSocket) =>
Effect.gen(function* () {
const handles = Array.from(activeGitRequests.get(ws) ?? []);
activeGitRequests.delete(ws);
for (const handle of handles) {
yield* Fiber.interrupt(handle.fiber).pipe(Effect.ignore);
}
});
const stopActiveGitRequest = (
ws: WebSocket,
input: { cwd: string; actionId?: string | undefined },
) =>
Effect.gen(function* () {
const handles = Array.from(activeGitRequests.get(ws) ?? []);
const handle =
input.actionId != null
? handles.find(
(candidate) => candidate.cwd === input.cwd && candidate.actionId === input.actionId,
)
: handles.find((candidate) => candidate.cwd === input.cwd);
if (!handle) {
return;
}
yield* Fiber.interrupt(handle.fiber);
});
const runTrackedGitRequest = <A, E>(
ws: WebSocket,
meta: { kind: ActiveGitRequestKind; cwd: string; actionId?: string | undefined },
effect: Effect.Effect<A, E, never>,
interruptedMessage: string,
): Effect.Effect<A, E | GitActionStoppedError> =>
Effect.gen(function* () {
const fiber = yield* Effect.forkScoped(effect);
const handle: ActiveGitRequestHandle = {
kind: meta.kind,
cwd: meta.cwd,
actionId: meta.actionId ?? null,
fiber,
};
yield* registerActiveGitRequest(ws, handle);
const exit = yield* Fiber.await(fiber).pipe(
Effect.ensuring(unregisterActiveGitRequest(ws, handle)),
);
if (Exit.isSuccess(exit)) {
return exit.value;
}
if (Cause.hasInterruptsOnly(exit.cause)) {
return yield* new GitActionStoppedError({ message: interruptedMessage });
}
return yield* Effect.failCause(exit.cause as Cause.Cause<E>);
}) as Effect.Effect<A, E | GitActionStoppedError, never>;
function logOutgoingPush(push: WsPushEnvelopeBase, recipients: number) {
if (!logWebSocketEvents) return;
logger.event("outgoing push", {
channel: push.channel,
sequence: push.sequence,
recipients,
payload: push.data,
});
}
const pushBus = yield* makeServerPushBus({
clients,
logOutgoingPush,
logDeliveryFailure: (input) => {
logger.warn("failed to deliver websocket push", input);
},
});
const getProviderStatuses = () =>
providerHealth.getStatuses.pipe(
Effect.tap((statuses) =>
Effect.sync(() => {
lastKnownProviderStatuses = statuses;
}),
),
Effect.catch((cause) =>
Effect.logWarning("failed to refresh provider statuses", {
cause,
}).pipe(Effect.as(lastKnownProviderStatuses)),
),
);
yield* readiness.markPushBusReady;
yield* keybindingsManager.start.pipe(
Effect.mapError(
(cause) => new ServerLifecycleError({ operation: "keybindingsRuntimeStart", cause }),
),
);
yield* readiness.markKeybindingsReady;
const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
readonly command: ClientOrchestrationCommand;
}) {
const normalizeProjectWorkspaceRoot = Effect.fnUntraced(function* (workspaceRoot: string) {
const normalizedWorkspaceRoot = path.resolve(yield* expandHomePath(workspaceRoot.trim()));
const workspaceStat = yield* fileSystem
.stat(normalizedWorkspaceRoot)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!workspaceStat) {
return yield* new RouteRequestError({
message: `Project directory does not exist: ${normalizedWorkspaceRoot}`,
});
}
if (workspaceStat.type !== "Directory") {
return yield* new RouteRequestError({
message: `Project path is not a directory: ${normalizedWorkspaceRoot}`,
});
}
return normalizedWorkspaceRoot;
});
if (input.command.type === "project.create") {
return {
...input.command,
workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot),
} satisfies OrchestrationCommand;
}
if (input.command.type === "project.meta.update" && input.command.workspaceRoot !== undefined) {
return {
...input.command,
workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot),
} satisfies OrchestrationCommand;
}
if (input.command.type !== "thread.turn.start") {
return input.command as OrchestrationCommand;
}
const turnStartCommand = input.command;
const normalizedAttachments = yield* Effect.forEach(
turnStartCommand.message.attachments,
(attachment) =>
Effect.gen(function* () {
const parsed = parseBase64DataUrl(attachment.dataUrl);
if (!parsed) {
return yield* new RouteRequestError({
message: `Invalid attachment payload for '${attachment.name}'.`,
});
}
const bytes = Buffer.from(parsed.base64, "base64");
const normalizedMimeType =
parsed.mimeType.trim().toLowerCase() || DEFAULT_CHAT_FILE_MIME_TYPE;
if (attachment.type === "image") {
if (!normalizedMimeType.startsWith("image/")) {
return yield* new RouteRequestError({
message: `Invalid image attachment payload for '${attachment.name}'.`,
});
}
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
return yield* new RouteRequestError({
message: `Image attachment '${attachment.name}' is empty or too large.`,
});
}
} else {
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
return yield* new RouteRequestError({
message: `File attachment '${attachment.name}' is empty or too large.`,
});
}
const extractedText = extractTextAttachmentContents({
mimeType: normalizedMimeType,
fileName: attachment.name,
bytes,
});
if (extractedText === null) {
return yield* new RouteRequestError({
message: `Unsupported file attachment '${attachment.name}'. Attach UTF-8 text files or images.`,
});
}
}
const attachmentId = createAttachmentId(turnStartCommand.threadId);
if (!attachmentId) {
return yield* new RouteRequestError({
message: "Failed to create a safe attachment id.",
});
}
const persistedAttachment =
attachment.type === "image"
? {
type: "image" as const,
id: attachmentId,
name: attachment.name,
mimeType: normalizedMimeType,
sizeBytes: bytes.byteLength,
}
: {
type: "file" as const,
id: attachmentId,
name: attachment.name,
mimeType: normalizedMimeType,
sizeBytes: bytes.byteLength,
};
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment: persistedAttachment,
});
if (!attachmentPath) {
return yield* new RouteRequestError({
message: `Failed to resolve persisted path for '${attachment.name}'.`,
});
}
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
Effect.mapError(
() =>
new RouteRequestError({
message: `Failed to create attachment directory for '${attachment.name}'.`,
}),
),
);
yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
Effect.mapError(
() =>
new RouteRequestError({
message: `Failed to persist attachment '${attachment.name}'.`,
}),
),
);
return persistedAttachment;
}),
{ concurrency: 1 },
);
return {
...turnStartCommand,
message: {
...turnStartCommand.message,
attachments: normalizedAttachments,
},
} satisfies OrchestrationCommand;
});
// HTTP server — serves static files or redirects to Vite dev server
const httpServer = http.createServer(async (req, res) => {
const respond = (
statusCode: number,
headers: Record<string, string>,
body?: string | Uint8Array,
) => {
res.writeHead(statusCode, headers);
res.end(body);
};
void Effect.runPromise(
Effect.gen(function* () {
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
if (yield* Effect.promise(() => tryHandleApiRequest(req, res, url))) {
return;
}
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
if (!normalizedRelativePath) {
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
return;
}
const isIdLookup =
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
const filePath = isIdLookup
? resolveAttachmentPathById({
attachmentsDir: serverConfig.attachmentsDir,
attachmentId: normalizedRelativePath,
})
: resolveAttachmentRelativePath({
attachmentsDir: serverConfig.attachmentsDir,
relativePath: normalizedRelativePath,
});
if (!filePath) {
respond(
isIdLookup ? 404 : 400,
{ "Content-Type": "text/plain" },
isIdLookup ? "Not Found" : "Invalid attachment path",
);
return;
}
const fileInfo = yield* fileSystem
.stat(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
respond(404, { "Content-Type": "text/plain" }, "Not Found");
return;
}
const contentType = inferAttachmentContentType(filePath);
res.writeHead(200, {
"Content-Type": contentType,
"Cache-Control": "public, max-age=31536000, immutable",
});
const streamExit = yield* Stream.runForEach(fileSystem.stream(filePath), (chunk) =>
Effect.sync(() => {
if (!res.destroyed) {
res.write(chunk);
}
}),
).pipe(Effect.exit);
if (Exit.isFailure(streamExit)) {
if (!res.destroyed) {
res.destroy();
}
return;
}
if (!res.writableEnded) {
res.end();
}
return;
}
// In dev mode, redirect to Vite dev server
if (devUrl) {
respond(302, { Location: devUrl.href });
return;
}
// Serve static files from the web app build
if (!staticDir) {
respond(
503,
{ "Content-Type": "text/plain" },
"No static directory configured and no dev URL set.",
);
return;
}
const staticRoot = path.resolve(staticDir);
const staticRequestPath = url.pathname === "/" ? "/index.html" : url.pathname;
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
const hasPathTraversalSegment = staticRelativePath.startsWith("..");
if (
staticRelativePath.length === 0 ||
hasRawLeadingParentSegment ||
hasPathTraversalSegment ||
staticRelativePath.includes("\0")
) {
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
return;
}
const isWithinStaticRoot = (candidate: string) =>
candidate === staticRoot ||
candidate.startsWith(
staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`,
);
let filePath = path.resolve(staticRoot, staticRelativePath);
if (!isWithinStaticRoot(filePath)) {
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
return;
}
const ext = path.extname(filePath);
if (!ext) {
filePath = path.resolve(filePath, "index.html");
if (!isWithinStaticRoot(filePath)) {
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
return;
}
}
const fileInfo = yield* fileSystem
.stat(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
const indexPath = path.resolve(staticRoot, "index.html");
const indexData = yield* fileSystem
.readFile(indexPath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!indexData) {
respond(404, { "Content-Type": "text/plain" }, "Not Found");
return;
}
respond(200, { "Content-Type": "text/html; charset=utf-8" }, indexData);
return;
}
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
const data = yield* fileSystem
.readFile(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!data) {
respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
return;
}
respond(200, { "Content-Type": contentType }, data);
}),
).catch(() => {
if (!res.headersSent) {
respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
}
});
});
// WebSocket server — upgrades from the HTTP server
const wss = new WebSocketServer({ noServer: true });
const closeWebSocketServer = Effect.callback<void, ServerLifecycleError>((resume) => {
wss.close((error) => {
if (error && !isServerNotRunningError(error)) {
resume(
Effect.fail(
new ServerLifecycleError({ operation: "closeWebSocketServer", cause: error }),
),
);
} else {
resume(Effect.void);
}
});
});
const closeAllClients = Ref.get(clients).pipe(
Effect.flatMap(Effect.forEach((client) => Effect.sync(() => client.close()))),
Effect.flatMap(() => Ref.set(clients, new Set())),
);
const listenOptions = host ? { host, port } : { port };
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
const checkpointDiffQuery = yield* CheckpointDiffQuery;
const orchestrationReactor = yield* OrchestrationReactor;
const prReview = yield* PrReview;
const github = yield* GitHub;
const terminalRuntimeEnvResolver = yield* TerminalRuntimeEnvResolver;
const { openInEditor, openInFileManager, revealInFileManager } = yield* Open;
const environmentVariables = yield* EnvironmentVariables;
const skillService = yield* SkillService;
const smeChatService = yield* SmeChatService;
const subscriptionsScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void));
yield* Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) =>
pushBus.publishAll(ORCHESTRATION_WS_CHANNELS.domainEvent, event),
).pipe(Effect.forkIn(subscriptionsScope));
yield* Stream.runForEach(keybindingsManager.streamChanges, (event) =>
getProviderStatuses().pipe(
Effect.flatMap((providers) =>
pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
issues: event.issues,
providers,
}),
),
),
).pipe(Effect.forkIn(subscriptionsScope));
const publishServerConfigUpdated = () =>
Effect.gen(function* () {
const keybindingsConfig = yield* keybindingsManager.loadConfigState;
const providers = yield* getProviderStatuses();
yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
issues: keybindingsConfig.issues,
providers,
});
});
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
yield* readiness.markOrchestrationSubscriptionsReady;
let welcomeBootstrapProjectId: ProjectId | undefined;
let welcomeBootstrapThreadId: ThreadId | undefined;
if (autoBootstrapProjectFromCwd) {
yield* Effect.gen(function* () {
const snapshot = yield* projectionReadModelQuery.getSnapshot();
const existingProject = snapshot.projects.find(
(project) => project.workspaceRoot === cwd && project.deletedAt === null,
);
let bootstrapProjectId: ProjectId;
let bootstrapProjectDefaultModel: string;
if (!existingProject) {
const createdAt = new Date().toISOString();
bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
const bootstrapProjectTitle = path.basename(cwd) || "project";
bootstrapProjectDefaultModel = "gpt-5-codex";
yield* orchestrationEngine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
projectId: bootstrapProjectId,
title: bootstrapProjectTitle,
workspaceRoot: cwd,
defaultModel: bootstrapProjectDefaultModel,
createdAt,
});
} else {
bootstrapProjectId = existingProject.id;
bootstrapProjectDefaultModel = existingProject.defaultModel ?? "gpt-5-codex";
}
const existingThread = snapshot.threads.find(
(thread) => thread.projectId === bootstrapProjectId && thread.deletedAt === null,
);
if (!existingThread) {
const createdAt = new Date().toISOString();
const threadId = ThreadId.makeUnsafe(crypto.randomUUID());
yield* orchestrationEngine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
threadId,
projectId: bootstrapProjectId,
title: "New thread",
model: bootstrapProjectDefaultModel,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
});
welcomeBootstrapProjectId = bootstrapProjectId;
welcomeBootstrapThreadId = threadId;
} else {
welcomeBootstrapProjectId = bootstrapProjectId;
welcomeBootstrapThreadId = existingThread.id;
}
}).pipe(
Effect.mapError(
(cause) => new ServerLifecycleError({ operation: "autoBootstrapProject", cause }),
),
);
}
const runtimeServices = yield* Effect.services<
ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
>();
const runPromise = Effect.runPromiseWith(runtimeServices);
const unsubscribeTerminalEvents = yield* terminalManager.subscribe(
(event) => void Effect.runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)),
);
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
yield* readiness.markTerminalSubscriptionsReady;
// ── File tree watcher ──────────────────────────────────────────────
// Watch the workspace directory for file system changes and push
// notifications so the client can refresh the file tree automatically.
const FILE_TREE_DEBOUNCE_MS = 300;
const IGNORED_WATCHER_DIRS = new Set([