forked from pingdotgg/t3code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathws.ts
More file actions
1867 lines (1818 loc) · 76.4 KB
/
Copy pathws.ts
File metadata and controls
1867 lines (1818 loc) · 76.4 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
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import {
DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,
AuthAccessStreamError,
type AuthAccessStreamEvent,
type AuthEnvironmentScope,
AuthSessionId,
CommandId,
type DiscoveredLocalServerList,
type OrchestrationCommand,
type GitActionProgressEvent,
type GitManagerServiceError,
OrchestrationDispatchCommandError,
type OrchestrationEvent,
type OrchestrationShellStreamEvent,
type OrchestrationShellStreamItem,
type OrchestrationThreadStreamItem,
OrchestrationGetFullThreadDiffError,
OrchestrationGetSnapshotError,
OrchestrationSearchThreadsError,
OrchestrationGetTurnDiffError,
ORCHESTRATION_WS_METHODS,
type ProjectId,
type ProjectEntriesFailure,
type ProjectFileFailure,
type ProjectFileOperation,
ProjectListEntriesError,
ProjectReadFileError,
ProjectSearchContentsError,
ProjectSearchEntriesError,
ProjectWriteFileError,
RelayClientInstallFailedError,
type RelayClientInstallProgressEvent,
type ServerSelfUpdateError,
type ServerSelfUpdateProgressEvent,
type FilesystemBrowseFailure,
FilesystemBrowseError,
AssetWorkspaceContextNotFoundError,
AssetWorkspaceContextResolutionError,
RpcClientId,
EnvironmentAuthorizationError,
ThreadId,
type TerminalAttachStreamEvent,
type TerminalError,
type TerminalEvent,
type TerminalMetadataStreamEvent,
WS_METHODS,
WsRpcGroup,
} from "@t3tools/contracts";
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
import { HttpRouter, HttpServerRequest, HttpServerRespondable } from "effect/unstable/http";
import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
import * as ServerConfig from "./config.ts";
import * as Keybindings from "./keybindings.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import {
projectActivityEvent,
projectThreadDetailSnapshot,
} from "./orchestration/ActivityPayloadProjection.ts";
import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import * as ThreadBootstrap from "./orchestration/Services/ThreadBootstrap.ts";
import {
observeRpcEffect as instrumentRpcEffect,
observeRpcStream as instrumentRpcStream,
observeRpcStreamEffect as instrumentRpcStreamEffect,
} from "./observability/RpcInstrumentation.ts";
import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
import * as ServerSettings from "./serverSettings.ts";
import * as TerminalManager from "./terminal/Manager.ts";
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
import * as PreviewManager from "./preview/Manager.ts";
import { issueAssetUrl } from "./assets/AssetAccess.ts";
import * as PortScanner from "./preview/PortScanner.ts";
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
import * as ReviewService from "./review/ReviewService.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { requiredScopeForRpcMethod } from "./auth/RpcAuthorization.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts";
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";
import * as GitHubCli from "./sourceControl/GitHubCli.ts";
import * as GitLabCli from "./sourceControl/GitLabCli.ts";
import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
import * as VcsProcess from "./vcs/VcsProcess.ts";
import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
import * as SessionStore from "./auth/SessionStore.ts";
import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
import * as RelayClient from "@t3tools/shared/relayClient";
const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const EDITOR_DISCOVERY_TIMEOUT = Duration.seconds(5);
export const resolveAvailableEditorsForConfig = <A, E, R>(
discovery: Effect.Effect<ReadonlyArray<A>, E, R>,
) =>
discovery.pipe(
Effect.timeoutOption(EDITOR_DISCOVERY_TIMEOUT),
Effect.map(Option.getOrElse(() => [])),
);
function unexpectedCompatibilityError(error: never): never {
throw new Error(`Unhandled compatibility error: ${String(error)}`);
}
function projectEntriesFailureContext(error: WorkspaceEntries.WorkspaceEntriesError): {
readonly failure: ProjectEntriesFailure;
readonly normalizedCwd?: string;
readonly timeout?: string;
readonly detail?: string;
} {
switch (error._tag) {
case "WorkspaceRootNotExistsError":
return {
failure: "workspace_root_not_found",
normalizedCwd: error.normalizedWorkspaceRoot,
};
case "WorkspaceRootCreateFailedError":
return {
failure: "workspace_root_create_failed",
normalizedCwd: error.normalizedWorkspaceRoot,
};
case "WorkspaceRootStatFailedError":
return {
failure: "workspace_root_stat_failed",
normalizedCwd: error.normalizedWorkspaceRoot,
detail: error.phase,
};
case "WorkspaceRootNotDirectoryError":
return {
failure: "workspace_root_not_directory",
normalizedCwd: error.normalizedWorkspaceRoot,
};
case "WorkspaceSearchIndexCreateFailed":
return {
failure: "search_index_create_failed",
normalizedCwd: error.cwd,
detail: error.reason,
};
case "WorkspaceSearchIndexScanTimedOut":
return {
failure: "search_index_scan_timed_out",
normalizedCwd: error.cwd,
timeout: error.timeout,
};
case "WorkspaceSearchIndexSearchFailed":
return {
failure: "search_index_search_failed",
normalizedCwd: error.cwd,
detail: error.reason,
};
default:
return unexpectedCompatibilityError(error);
}
}
function filesystemBrowseFailureContext(error: WorkspaceEntries.WorkspaceEntriesBrowseError): {
readonly failure: FilesystemBrowseFailure;
readonly parentPath?: string;
readonly platform?: string;
} {
switch (error._tag) {
case "WorkspaceEntriesWindowsPathUnsupportedError":
return { failure: "windows_path_unsupported", platform: error.platform };
case "WorkspaceEntriesCurrentProjectRequiredError":
return { failure: "current_project_required" };
case "WorkspaceEntriesReadDirectoryError":
return { failure: "read_directory_failed", parentPath: error.parentPath };
default:
return unexpectedCompatibilityError(error);
}
}
function projectFileFailureContext(
error:
| WorkspaceFileSystem.WorkspaceFileSystemError
| WorkspacePaths.WorkspacePathOutsideRootError,
): {
readonly failure: ProjectFileFailure;
readonly resolvedPath?: string;
readonly resolvedWorkspaceRoot?: string;
readonly operation?: ProjectFileOperation;
readonly operationPath?: string;
} {
switch (error._tag) {
case "WorkspacePathOutsideRootError":
return { failure: "workspace_path_outside_root" };
case "WorkspaceFileSystemOperationError":
return {
failure: "operation_failed",
resolvedPath: error.resolvedPath,
operation: error.operation,
operationPath: error.operationPath,
};
case "WorkspaceFilePathEscapeError":
return {
failure: "resolved_path_outside_root",
resolvedPath: error.resolvedPath,
resolvedWorkspaceRoot: error.resolvedWorkspaceRoot,
};
case "WorkspacePathNotFileError":
return { failure: "path_not_file", resolvedPath: error.resolvedPath };
case "WorkspaceBinaryFileError":
return { failure: "binary_file", resolvedPath: error.resolvedPath };
default:
return unexpectedCompatibilityError(error);
}
}
function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
OrchestrationEvent,
{
type:
| "thread.message-sent"
| "thread.proposed-plan-upserted"
| "thread.activity-appended"
| "thread.turn-diff-completed"
| "thread.reverted"
| "thread.session-set";
}
> {
return (
event.type === "thread.message-sent" ||
event.type === "thread.proposed-plan-upserted" ||
event.type === "thread.activity-appended" ||
event.type === "thread.turn-diff-completed" ||
event.type === "thread.reverted" ||
event.type === "thread.session-set"
);
}
const PROVIDER_STATUS_DEBOUNCE_MS = 200;
// When a resuming client's cursor is more than this many events behind the
// current head, skip the per-event catch-up replay and send a fresh shell
// snapshot instead. Replaying each intervening event costs a shell refetch;
// past this gap a single O(active-threads) snapshot is cheaper and bounded.
// Matches the event store's default page size (DEFAULT_READ_FROM_SEQUENCE_LIMIT).
const SHELL_RESUME_MAX_GAP = 1_000;
function toAuthAccessStreamEvent(
change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange,
revision: number,
currentSessionId: AuthSessionId,
): AuthAccessStreamEvent {
switch (change.type) {
case "pairingLinkUpserted":
return {
version: 1,
revision,
type: "pairingLinkUpserted",
payload: change.pairingLink,
};
case "pairingLinkRemoved":
return {
version: 1,
revision,
type: "pairingLinkRemoved",
payload: { id: change.id },
};
case "clientUpserted":
return {
version: 1,
revision,
type: "clientUpserted",
payload: {
...change.clientSession,
current: change.clientSession.sessionId === currentSessionId,
},
};
case "clientRemoved":
return {
version: 1,
revision,
type: "clientRemoved",
payload: { sessionId: change.sessionId },
};
}
}
const makeWsRpcLayer = (
currentSession: EnvironmentAuth.AuthenticatedSession,
previewAutomationBroker: PreviewAutomationBroker.PreviewAutomationBroker["Service"],
) =>
WsRpcGroup.toLayer(
Effect.gen(function* () {
const currentSessionId = currentSession.sessionId;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
const threadBootstrap = yield* ThreadBootstrap.ThreadBootstrapService;
const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery;
const keybindings = yield* Keybindings.Keybindings;
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
const review = yield* ReviewService.ReviewService;
const vcsProvisioning = yield* VcsProvisioningService.VcsProvisioningService;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const terminalManager = yield* TerminalManager.TerminalManager;
const previewManager = yield* PreviewManager.PreviewManager;
const portDiscovery = yield* PortScanner.PortDiscovery;
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
const config = yield* ServerConfig.ServerConfig;
const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
const rpcClientIds = yield* Ref.make(new Set<RpcClientId>());
yield* Effect.addFinalizer(() =>
Ref.get(rpcClientIds).pipe(
Effect.flatMap((clientIds) =>
Effect.forEach(
clientIds,
(clientId) => backgroundPolicy.removeRpcClient(currentSessionId, clientId),
{
discard: true,
},
),
),
Effect.ignore,
),
);
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const sourceControlDiscovery = yield* SourceControlDiscovery.SourceControlDiscovery;
const automaticGitFetchInterval = serverSettings.getSettings.pipe(
Effect.map(
(settings) => resolveServerBackgroundActivitySettings(settings).automaticGitFetchInterval,
),
Effect.catch((cause) =>
Effect.logWarning("Failed to read automatic Git fetch interval setting", {
detail: cause.message,
}).pipe(Effect.as(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),
),
);
const sourceControlRepositories =
yield* SourceControlRepositoryService.SourceControlRepositoryService;
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
const sessions = yield* SessionStore.SessionStore;
const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor;
const resourceTelemetry = yield* ResourceTelemetry.ResourceTelemetry;
const relayClient = yield* RelayClient.RelayClient;
const authorizationError = (requiredScope: AuthEnvironmentScope) =>
new EnvironmentAuthorizationError({
message: `The authenticated token is missing required scope: ${requiredScope}.`,
requiredScope,
});
const authorizeEffect = <A, E, R>(
requiredScope: AuthEnvironmentScope,
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, E | EnvironmentAuthorizationError, R> =>
currentSession.scopes.includes(requiredScope)
? effect
: Effect.fail(authorizationError(requiredScope));
const authorizeStream = <A, E, R>(
requiredScope: AuthEnvironmentScope,
stream: Stream.Stream<A, E, R>,
): Stream.Stream<A, E | EnvironmentAuthorizationError, R> =>
currentSession.scopes.includes(requiredScope)
? stream
: Stream.fail(authorizationError(requiredScope));
const observeRpcEffect = <A, E, R>(
method: string,
effect: Effect.Effect<A, E, R>,
traceAttributes?: Readonly<Record<string, unknown>>,
) =>
instrumentRpcEffect(
method,
authorizeEffect(requiredScopeForRpcMethod(method), effect),
traceAttributes,
);
const observeRpcStream = <A, E, R>(
method: string,
stream: Stream.Stream<A, E, R>,
traceAttributes?: Readonly<Record<string, unknown>>,
) =>
instrumentRpcStream(
method,
authorizeStream(requiredScopeForRpcMethod(method), stream),
traceAttributes,
);
const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(
method: string,
effect: Effect.Effect<
Stream.Stream<A, StreamError, StreamContext>,
EffectError,
EffectContext
>,
traceAttributes?: Readonly<Record<string, unknown>>,
) =>
instrumentRpcStreamEffect(
method,
authorizeEffect(requiredScopeForRpcMethod(method), effect),
traceAttributes,
);
const toDispatchCommandError = (cause: unknown, fallbackMessage: string) =>
isOrchestrationDispatchCommandError(cause)
? cause
: new OrchestrationDispatchCommandError({
message: cause instanceof Error ? cause.message : fallbackMessage,
cause,
});
const loadAuthAccessSnapshot = () =>
Effect.all({
pairingLinks: serverAuth.listPairingLinks(),
clientSessions: serverAuth.listClientSessions(currentSessionId),
}).pipe(
Effect.mapError(
(error) =>
new AuthAccessStreamError({
message: error.message,
}),
),
);
const toShellStreamEvent = (
event: OrchestrationEvent,
): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> => {
switch (event.type) {
case "project.created":
case "project.meta-updated":
return projectUpsertOrRemove(event.payload.projectId, event.sequence);
case "project.deleted":
return Effect.succeed(
Option.some({
kind: "project-removed" as const,
sequence: event.sequence,
projectId: event.payload.projectId,
}),
);
case "thread.deleted":
case "thread.archived":
return Effect.succeed(
Option.some({
kind: "thread-removed" as const,
sequence: event.sequence,
threadId: event.payload.threadId,
}),
);
case "thread.unarchived":
return threadUpsertOrRemove(event.payload.threadId, event.sequence);
default:
if (event.aggregateKind !== "thread") {
return Effect.succeed(Option.none());
}
return threadUpsertOrRemove(ThreadId.make(event.aggregateId), event.sequence);
}
};
// Coalescing makes each projection read represent every event for that
// aggregate in the current window. Retry a typed persistence failure once
// so a brief read failure cannot strand the shell at its previous state.
// If both attempts fail, log and drop the stream item; treating an error as
// a missing row would incorrectly remove a still-active aggregate.
const retryShellProjectionRead = <A, E>(
aggregateKind: "project" | "thread",
aggregateId: string,
read: Effect.Effect<A, E>,
): Effect.Effect<Option.Option<A>, never, never> =>
read.pipe(
Effect.retry({ times: 1 }),
Effect.map(Option.some),
Effect.tapError((error) =>
Effect.logWarning("orchestration shell projection refetch failed", {
aggregateKind,
aggregateId,
error,
}),
),
Effect.orElseSucceed(() => Option.none()),
);
const projectUpsertOrRemove = (
projectId: ProjectId,
sequence: number,
): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> =>
retryShellProjectionRead(
"project",
projectId,
projectionSnapshotQuery.getProjectShellById(projectId),
).pipe(
Effect.map(
Option.flatMap((project) =>
Option.match(project, {
onNone: () =>
Option.some<OrchestrationShellStreamEvent>({
kind: "project-removed" as const,
sequence,
projectId,
}),
onSome: (nextProject) =>
Option.some<OrchestrationShellStreamEvent>({
kind: "project-upserted" as const,
sequence,
project: nextProject,
}),
}),
),
),
);
// Refetch a thread's shell and emit an upsert if it is still active, or a
// `thread-removed` if the projection has no active row for it. Emitting a
// removal on a `none` (rather than dropping the event) is what keeps
// coalescing correct: when a burst collapses a `thread.deleted`/`archived`
// into a later refetchable event for the same thread, the refetch returns
// `none` for the now-inactive row and this still tells the sidebar to drop
// it. A `thread-removed` the client does not have is a harmless no-op. The
// projection commits in the same transaction before the event publishes,
// so a `none` reliably means the thread is deleted or archived, not
// not-yet-persisted.
const threadUpsertOrRemove = (
threadId: ThreadId,
sequence: number,
): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> =>
retryShellProjectionRead(
"thread",
threadId,
projectionSnapshotQuery.getThreadShellById(threadId),
).pipe(
Effect.map(
Option.flatMap((thread) =>
Option.match(thread, {
onNone: () =>
Option.some<OrchestrationShellStreamEvent>({
kind: "thread-removed" as const,
sequence,
threadId,
}),
onSome: (nextThread) =>
Option.some<OrchestrationShellStreamEvent>({
kind: "thread-upserted" as const,
sequence,
thread: nextThread,
}),
}),
),
),
);
// Turn a batch of domain events into shell stream items, coalescing by
// aggregate first. `toShellStreamEvent` re-reads the *current* projected
// shell for an aggregate, so within a batch only the latest event per
// aggregate matters: a burst of streaming `thread.message-sent` deltas for
// one thread collapses into a single shell refetch, and an unrelated
// `thread.created` in the same batch is never stuck behind those DB reads.
//
// Input events arrive in ascending sequence; we keep the last (highest
// sequence) event per aggregate, then re-sort ascending before emitting so
// the client — which applies shell items strictly by increasing sequence
// and drops any `sequence <= snapshotSequence` — never skips a coalesced
// item. The refetch runs with bounded concurrency (order-preserving).
const SHELL_REFETCH_CONCURRENCY = 8;
const coalesceShellEvents = (
events: ReadonlyArray<OrchestrationEvent>,
): Effect.Effect<ReadonlyArray<OrchestrationShellStreamEvent>, never, never> =>
Effect.gen(function* () {
if (events.length === 0) {
return [];
}
const latestByAggregate = new Map<string, OrchestrationEvent>();
for (const event of events) {
latestByAggregate.set(`${event.aggregateKind}:${event.aggregateId}`, event);
}
const survivors = Array.from(latestByAggregate.values()).sort(
(left, right) => left.sequence - right.sequence,
);
const shellEvents = yield* Effect.forEach(survivors, toShellStreamEvent, {
concurrency: SHELL_REFETCH_CONCURRENCY,
});
return shellEvents.flatMap((option) => (Option.isSome(option) ? [option.value] : []));
});
// Small time/size window over which to coalesce shell events. The window
// bounds the worst-case added latency for a brand-new thread to appear in
// the sidebar (imperceptible), while collapsing high-frequency streaming
// traffic so it can't serialize the shell stream behind per-event DB reads.
const SHELL_COALESCE_WINDOW = Duration.millis(50);
const SHELL_COALESCE_MAX_CHUNK = 512;
const coalesceShellStream = <E, R>(
stream: Stream.Stream<OrchestrationEvent, E, R>,
): Stream.Stream<OrchestrationShellStreamEvent, E, R> =>
stream.pipe(
Stream.groupedWithin(SHELL_COALESCE_MAX_CHUNK, SHELL_COALESCE_WINDOW),
Stream.mapEffect(coalesceShellEvents),
Stream.flatMap((items) => Stream.fromIterable(items)),
);
type ShellLiveInput =
| { readonly kind: "event"; readonly event: OrchestrationEvent }
| { readonly kind: "synchronized" };
// A completion marker is queued alongside raw live events so it cannot
// overtake an event still waiting in the coalescing window. Split each
// batch at markers and coalesce only the event segments on either side.
const coalesceShellLiveInputs = (
inputs: ReadonlyArray<ShellLiveInput>,
): Effect.Effect<ReadonlyArray<OrchestrationShellStreamItem>, never, never> =>
Effect.gen(function* () {
const output: Array<OrchestrationShellStreamItem> = [];
let pendingEvents: Array<OrchestrationEvent> = [];
for (const input of inputs) {
if (input.kind === "event") {
pendingEvents.push(input.event);
continue;
}
output.push(...(yield* coalesceShellEvents(pendingEvents)));
pendingEvents = [];
output.push({ kind: "synchronized" });
}
output.push(...(yield* coalesceShellEvents(pendingEvents)));
return output;
});
const coalesceShellLiveStream = <E, R>(
stream: Stream.Stream<ShellLiveInput, E, R>,
): Stream.Stream<OrchestrationShellStreamItem, E, R> =>
stream.pipe(
Stream.groupedWithin(SHELL_COALESCE_MAX_CHUNK, SHELL_COALESCE_WINDOW),
Stream.mapEffect(coalesceShellLiveInputs),
Stream.flatMap((items) => Stream.fromIterable(items)),
);
const dispatchNormalizedCommand = (
normalizedCommand: OrchestrationCommand,
): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => {
const dispatchEffect =
normalizedCommand.type === "thread.turn.start" && normalizedCommand.bootstrap
? threadBootstrap.dispatchBootstrapTurnStart(normalizedCommand)
: orchestrationEngine
.dispatch(normalizedCommand)
.pipe(
Effect.mapError((cause) =>
toDispatchCommandError(cause, "Failed to dispatch orchestration command"),
),
);
return startup
.enqueueCommand(dispatchEffect)
.pipe(
Effect.mapError((cause) =>
toDispatchCommandError(cause, "Failed to dispatch orchestration command"),
),
);
};
const loadServerConfig = Effect.gen(function* () {
const keybindingsConfig = yield* keybindings.loadConfigState;
const providers = yield* providerRegistry.getProviders;
const settings = ServerSettings.redactServerSettingsForClient(
yield* serverSettings.getSettings,
);
const environment = yield* serverEnvironment.getDescriptor;
const auth = yield* serverAuth.getDescriptor();
return {
environment,
auth,
cwd: config.cwd,
keybindingsConfigPath: config.keybindingsConfigPath,
keybindings: keybindingsConfig.keybindings,
issues: keybindingsConfig.issues,
providers,
availableEditors: yield* resolveAvailableEditorsForConfig(
externalLauncher.resolveAvailableEditors(),
),
observability: {
logsDirectoryPath: config.logsDir,
localTracingEnabled: true,
...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}),
otlpTracesEnabled: config.otlpTracesUrl !== undefined,
...(config.otlpMetricsUrl !== undefined
? { otlpMetricsUrl: config.otlpMetricsUrl }
: {}),
otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,
},
settings,
shellResumeCompletionMarker: true,
threadResumeCompletionMarker: true,
};
});
const refreshGitStatus = (cwd: string) =>
vcsStatusBroadcaster
.refreshStatus(cwd)
.pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
return WsRpcGroup.of({
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.dispatchCommand,
Effect.gen(function* () {
const normalizedCommand = yield* normalizeDispatchCommand(command);
const shouldStopSessionAfterArchive =
normalizedCommand.type === "thread.archive"
? yield* projectionSnapshotQuery
.getThreadShellById(normalizedCommand.threadId)
.pipe(
Effect.map(
Option.match({
onNone: () => false,
onSome: (thread) =>
thread.session !== null && thread.session.status !== "stopped",
}),
),
Effect.orElseSucceed(() => false),
)
: false;
const result = yield* dispatchNormalizedCommand(normalizedCommand);
if (normalizedCommand.type === "thread.archive") {
if (shouldStopSessionAfterArchive) {
yield* Effect.gen(function* () {
const stopCommand = yield* normalizeDispatchCommand({
type: "thread.session.stop",
commandId: CommandId.make(
`session-stop-for-archive:${normalizedCommand.commandId}`,
),
threadId: normalizedCommand.threadId,
createdAt: yield* nowIso,
});
yield* dispatchNormalizedCommand(stopCommand);
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("failed to stop provider session during archive", {
threadId: normalizedCommand.threadId,
cause,
}),
),
);
}
yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to close thread terminals after archive", {
threadId: normalizedCommand.threadId,
error: error.message,
}),
),
);
}
return result;
}).pipe(
Effect.mapError((cause) =>
isOrchestrationDispatchCommandError(cause)
? cause
: new OrchestrationDispatchCommandError({
message: "Failed to dispatch orchestration command",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getTurnDiff,
checkpointDiffQuery.getTurnDiff(input).pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetTurnDiffError({
message: "Failed to load turn diff",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getFullThreadDiff,
checkpointDiffQuery.getFullThreadDiff(input).pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetFullThreadDiffError({
message: "Failed to load full thread diff",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.searchThreads]: (input) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.searchThreads,
projectionSnapshotQuery.searchThreads(input).pipe(
Effect.mapError(
(cause) =>
new OrchestrationSearchThreadsError({
message: "Failed to search threads",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.subscribeShell]: (input) =>
observeRpcStreamEffect(
ORCHESTRATION_WS_METHODS.subscribeShell,
Effect.gen(function* () {
// Coalesce the live shell stream per aggregate over a small window
// so bursts of high-frequency events (streaming message deltas,
// activity appends) collapse into a single shell refetch and never
// serialize a brand-new thread's `thread.created` behind hundreds
// of per-event DB reads. See coalesceShellStream.
// Attach live delivery into a scope-bound buffer BEFORE loading any
// snapshot or draining catch-up, otherwise an event published while
// the snapshot query is in flight is lost (it is past the snapshot's
// sequence but the live subscription is not attached yet). Every
// path below emits from this same buffered live tail. Overlapping
// events are deduped by sequence on the client.
const liveBuffer = yield* Queue.unbounded<ShellLiveInput>();
yield* Effect.forkScoped(
orchestrationEngine.streamDomainEvents.pipe(
Stream.runForEach((event) =>
Queue.offer(liveBuffer, { kind: "event" as const, event }),
),
),
{ startImmediately: true },
);
const bufferedLiveStream = coalesceShellLiveStream(Stream.fromQueue(liveBuffer));
const loadSnapshot = projectionSnapshotQuery.getShellSnapshot().pipe(
Effect.tapError((cause) =>
Effect.logError("orchestration shell snapshot load failed", { cause }),
),
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to load orchestration shell snapshot",
cause,
}),
),
);
// Offer the completion marker into the same queue as live events.
// Anything buffered while snapshot/replay work was in flight is
// therefore delivered before the client is told it is synchronized.
const synchronizedThenLive =
input.requestCompletionMarker === true
? Stream.concat(
Stream.fromEffect(
Queue.offer(liveBuffer, { kind: "synchronized" as const }).pipe(
Effect.andThen(Queue.takeAll(liveBuffer)),
Effect.flatMap(coalesceShellLiveInputs),
),
).pipe(Stream.flatMap((items) => Stream.fromIterable(items))),
bufferedLiveStream,
)
: bufferedLiveStream;
// When the client already holds a shell snapshot (cached, or loaded
// over HTTP) it passes that snapshot's sequence, and we resume by
// replaying shell events after it instead of re-sending the whole
// projects/threads list over the socket. If the client is too far
// behind, we fall back to a fresh snapshot instead of an unbounded
// replay (see below).
if (input.afterSequence !== undefined) {
const afterSequence = input.afterSequence;
const headSequence = yield* orchestrationEngine.latestSequence;
const replayGap = headSequence - afterSequence;
// Gap too large: replaying every intervening event (each a shell
// refetch) is far more expensive than a single O(active-threads)
// snapshot. A cursor ahead of this engine's authoritative state
// is also invalid, so reset it with a snapshot. Send the snapshot
// followed by the buffered live tail, exactly as the
// no-afterSequence path does.
if (replayGap < 0 || replayGap > SHELL_RESUME_MAX_GAP) {
const snapshot = yield* loadSnapshot;
return Stream.concat(
Stream.make({ kind: "snapshot" as const, snapshot }),
synchronizedThenLive,
);
}
const catchUpStream = coalesceShellStream(
// Replay only through the head captured above. Newer events
// are already covered by the live subscription, so this bound
// cannot chase a moving event-store head or grow the live
// buffer indefinitely while waiting for an empty page.
orchestrationEngine.readEvents(afterSequence, replayGap),
).pipe(
Stream.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to replay orchestration shell events",
cause,
}),
),
);
return Stream.concat(catchUpStream, synchronizedThenLive);
}
const snapshot = yield* loadSnapshot;
return Stream.concat(
Stream.make({
kind: "snapshot" as const,
snapshot,
}),
synchronizedThenLive,
);
}),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]: (_input) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot,
projectionSnapshotQuery.getArchivedShellSnapshot().pipe(
Effect.tapError((cause) =>
Effect.logError("orchestration archived shell snapshot load failed", { cause }),
),
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to load archived orchestration shell snapshot",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.subscribeThread]: (input) =>
observeRpcStreamEffect(
ORCHESTRATION_WS_METHODS.subscribeThread,
Effect.gen(function* () {
const isThisThreadDetailEvent = (event: OrchestrationEvent) =>
event.aggregateKind === "thread" &&
event.aggregateId === input.threadId &&
isThreadDetailEvent(event);
const liveStream = orchestrationEngine.streamDomainEvents.pipe(
Stream.filter(isThisThreadDetailEvent),
Stream.map((event) => ({
kind: "event" as const,
event: projectActivityEvent(event),
})),
);
// Attach live delivery before reading either replay or snapshot state.
// Otherwise an event published while the snapshot is loading is lost.
const liveBuffer = yield* Queue.unbounded<OrchestrationThreadStreamItem>();
yield* Effect.forkScoped(
liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),
);
const bufferedLiveStream = Stream.fromQueue(liveBuffer);
// When the client already loaded the snapshot over HTTP it passes
// that snapshot's sequence, and we resume the live subscription by
// replaying persisted events after it instead of re-sending the
// (potentially multi-KB) snapshot frame over the socket.
//
// The live PubSub subscription must be attached *before* draining
// the catch-up replay, otherwise events published during the replay
// window are dropped (they are past the persisted tail the replay
// read, but the live stream is not yet subscribed). So fork the
// live stream into a buffer bound to this stream's scope, then emit
// catch-up followed by the buffered/ongoing live events. Overlapping
// events are deduped by sequence on the client.
//
// Read the full range after the cursor (not the store's default
// page-bounded limit): the range is normally tiny (a fresh HTTP
// snapshot sequence) and the per-thread filter runs after reading,