-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsyncRemoteCommandService.ts
More file actions
4597 lines (4312 loc) · 215 KB
/
Copy pathsyncRemoteCommandService.ts
File metadata and controls
4597 lines (4312 loc) · 215 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 fs from "node:fs";
import path from "node:path";
import { createHash, randomUUID } from "node:crypto";
import { fileURLToPath } from "node:url";
import type {
AgentChatCreateArgs,
AgentChatArchiveArgs,
AgentChatClaudePermissionMode,
AgentChatTranscriptEntry,
AgentChatEventHistorySnapshot,
AgentChatApproveArgs,
AgentChatCodexApprovalPolicy,
AgentChatCodexConfigSource,
AgentChatCodexSandbox,
AgentChatCodexClearGoalArgs,
AgentChatCodexGetGoalArgs,
AgentChatCodexSetGoalArgs,
AgentChatCodexSetGoalStatusArgs,
AgentChatContextUsageArgs,
AgentChatDroidPermissionMode,
AgentChatFileRef,
AgentChatGetSummaryArgs,
AgentChatGetTurnFileDiffArgs,
AgentChatHandoffArgs,
AgentChatLaunchArgs,
AgentChatListArgs,
AgentChatMainTranscriptArgs,
AgentChatModelCatalogArgs,
AgentChatSuggestLaneNameArgs,
AgentChatModelCatalogMode,
AgentChatModelCatalogRefreshProvider,
AgentChatOpenCodePermissionMode,
AgentChatParallelLaunchState,
AgentChatParallelLaunchStateArgs,
AgentChatPermissionMode,
AgentChatProvider,
AgentChatRewindFilesArgs,
AgentChatRespondToInputArgs,
AgentChatSendArgs,
AgentChatSetParallelLaunchStateArgs,
AgentChatSession,
AgentChatSessionSummary,
AgentChatSlashCommandsArgs,
AgentChatSteerArgs,
AgentChatSubagentListArgs,
AgentChatSubagentTranscriptArgs,
AgentChatCancelSteerArgs,
AgentChatEditSteerArgs,
AgentChatDispatchSteerArgs,
AgentChatCancelDispatchedSteerArgs,
AgentChatInterruptArgs,
AgentChatRecoverCodexTurnArgs,
AgentChatUpdateSessionArgs,
AddPrCommentArgs,
AiReviewSummaryArgs,
ApplyLaneTemplateArgs,
ArchiveLaneArgs,
AttachLaneArgs,
ChatTerminalActiveForChatArgs,
ChatTerminalListArgs,
ClosePrArgs,
CancelQueueAutomationArgs,
CleanupPrBranchArgs,
CtoIdentity,
CreateChildLaneArgs,
CommitIntegrationArgs,
CreateQueuePrsArgs,
CreateLaneArgs,
CreateLaneFromPrBranchArgs,
CreateLaneFromUnstagedArgs,
CreatePrFromLaneArgs,
CreateIntegrationLaneForProposalArgs,
CleanupIntegrationWorkflowArgs,
DeleteLaneArgs,
DeletePrArgs,
DeleteIntegrationProposalArgs,
DismissIntegrationCleanupArgs,
DraftPrDescriptionArgs,
GetDiffChangesArgs,
GetFileDiffArgs,
GitBatchFileActionArgs,
GitCherryPickArgs,
GitCommitArgs,
GitCreateTagArgs,
GitFileActionArgs,
GitGenerateCommitMessageArgs,
GitGetCommitMessageArgs,
GitGetFileHistoryArgs,
GitCheckoutBranchArgs,
GitListBranchesArgs,
GitListCommitFilesArgs,
GitPullArgs,
GitPullMode,
GitPushArgs,
GitResetCommitArgs,
GitRevertArgs,
GitGetUserIdentityArgs,
GitHubRepoRef,
GitHubStatus,
GitStashPushArgs,
GitStashRefArgs,
GitSyncArgs,
ImportBranchLaneArgs,
LandPrArgs,
LandQueueNextArgs,
PauseQueueAutomationArgs,
PersonalChatScopeContract,
PrGithubCoords,
PublishProjectInput,
PublishProjectResult,
ProjectConfigCandidate,
LaneEnvInitConfig,
LaneEnvInitProgress,
LaneDetailPayload,
LaneListSnapshot,
LaneOverlayOverrides,
LaneStateSnapshotSummary,
ListLanesArgs,
ListIntegrationWorkflowsArgs,
ListOperationsArgs,
ListSessionsArgs,
LinkPrToLaneArgs,
PostPrReviewCommentArgs,
PrAgentPermissionMode,
PrAiResolutionContext,
PrAiResolutionGetSessionArgs,
PrAiResolutionGetSessionResult,
PrAiResolutionSessionInfo,
PrAiResolutionSessionStatus,
PrAiResolutionStartArgs,
PrAiResolutionStartResult,
RebasePushArgs,
RebaseStartArgs,
RenameLaneArgs,
ReopenPrArgs,
RecheckIntegrationStepArgs,
ReactToPrCommentArgs,
ReplyToPrReviewThreadArgs,
ReparentLaneArgs,
RequestPrReviewersArgs,
ReorderQueuePrsArgs,
ResumeQueueAutomationArgs,
RerunPrChecksArgs,
SetPrLabelsArgs,
SetPrReviewThreadResolvedArgs,
SimulateIntegrationArgs,
StartIntegrationResolutionArgs,
StartQueueAutomationArgs,
SubmitPrReviewArgs,
ExternalSessionImportArgs,
ExternalSessionImportResult,
ExternalSessionListArgs,
ExternalSessionProvider,
ExternalSessionSummary,
SyncImportExternalSessionArgs,
SyncImportExternalSessionResult,
SyncListExternalSessionsArgs,
SyncListExternalSessionsResult,
SyncCommandPayload,
SyncRemoteCommandAction,
SyncRemoteCommandDescriptor,
SyncRemoteCommandPolicy,
SyncPairingConnectInfo,
SyncSendToSessionArgs,
SyncSendToSessionResult,
SyncStartCliSessionArgs,
SyncStartCliSessionResult,
SyncWebPairingInfo,
SyncRunQuickCommandArgs,
UpdateSessionMetaArgs,
UpdateIntegrationProposalArgs,
TerminalToolType,
UpdateBranchArgs,
UpdateLaneAppearanceArgs,
UpdatePrBodyArgs,
UpdatePrTitleArgs,
WriteTextAtomicArgs,
} from "../../../../desktop/src/shared/types";
import { isAdeUsageRangePreset, isAdeUsageScope } from "../../../../desktop/src/shared/types";
import type { OrchestrationRunCreateRequest } from "../../../../desktop/src/shared/types/orchestration";
import { PERSONAL_CHAT_ACTIONS, isPersonalChatActionQueueable } from "../../../../desktop/src/shared/types/personalChats";
import {
buildTrackedCliLaunchCommand,
deriveTrackedCliInitialInputSessionMeta,
isLaunchProfile,
isTrackedCliPermissionMode,
LAUNCH_PROFILE_TITLE,
LAUNCH_PROFILE_TOOL_TYPE,
resolveCleanShellLaunchFields,
validateLaunchProfilePermissionMode,
type TrackedCliLaunchCommand,
} from "../../../../desktop/src/shared/cliLaunch";
import { parseDeeplink, type ParseError } from "../../../../desktop/src/shared/deeplinks";
import { buildPairingQrPayload } from "../../../../desktop/src/shared/pairingQr";
import { buildWebClientPairUrl } from "../../../../desktop/src/shared/webClientUrl";
import { buildPrAiResolutionContextKey } from "../../../../desktop/src/shared/types";
import { getModelById } from "../../../../desktop/src/shared/modelRegistry";
import {
PUSH_GET_STATUS_ACTION,
PUSH_REGISTER_DEVICE_ACTION,
PUSH_REPORT_LIVE_ACTIVITY_TOKEN_ACTION,
PUSH_SET_PREFS_ACTION,
PUSH_UNREGISTER_DEVICE_ACTION,
type PushDeliveryStatus,
type PushDeviceRegistration,
type PushLiveActivityTokenReport,
type PushNotificationPrefs,
type PushQuietHours,
} from "../../../../desktop/src/shared/types/push";
import type { PushPublisherService } from "../push/pushPublisherService";
import { deriveDeterministicLaneNameFromPrompt } from "../../../../desktop/src/shared/laneNameFallback";
import { resolveLaneCreateRemoteBase } from "../laneCreateRemoteBase";
import { normalizePrCreationStrategy } from "../../../../desktop/src/shared/prStrategy";
import { readImageFileAndSniffMime, saveImageTempAttachment } from "../imageAttachment";
import { buildAiSettingsStatus, getUnavailableAiStatus, isDatabaseClosedError } from "../../../../desktop/src/main/services/ai/aiSettingsStatus";
import type { createAiIntegrationService } from "../../../../desktop/src/main/services/ai/aiIntegrationService";
import type { createAgentChatService } from "../../../../desktop/src/main/services/chat/agentChatService";
import { resolveCodexComputerUseMcpConfig } from "../../../../desktop/src/main/utils/codexComputerUse";
import type { createCtoStateService } from "../../../../desktop/src/main/services/cto/ctoStateService";
import type { CtoMemoryService } from "../../../../desktop/src/main/services/cto/ctoMemoryService";
import type { createLinearCredentialService } from "../../../../desktop/src/main/services/cto/linearCredentialService";
import type { createLinearIssueTracker } from "../../../../desktop/src/main/services/cto/linearIssueTracker";
import { matchLaneOverlayPolicies } from "../../../../desktop/src/main/services/config/laneOverlayMatcher";
import type { createProjectConfigService } from "../../../../desktop/src/main/services/config/projectConfigService";
import type { createConflictService } from "../../../../desktop/src/main/services/conflicts/conflictService";
import { appendDiffTruncationNotice, MAX_DIFF_SIDE_TEXT_BYTES, type createDiffService } from "../../../../desktop/src/main/services/diffs/diffService";
import type { createFileService } from "../../../../desktop/src/main/services/files/fileService";
import { runGit } from "../../../../desktop/src/main/services/git/git";
import type { createGitOperationsService } from "../../../../desktop/src/main/services/git/gitOperationsService";
import type { createGithubService } from "../../../../desktop/src/main/services/github/githubService";
import type { createOperationService } from "../../../../desktop/src/main/services/history/operationService";
import type { createAutoRebaseService } from "../../../../desktop/src/main/services/lanes/autoRebaseService";
import type { createLaneEnvironmentService } from "../../../../desktop/src/main/services/lanes/laneEnvironmentService";
import type { createLaneService } from "../../../../desktop/src/main/services/lanes/laneService";
import type { createLaneTemplateService } from "../../../../desktop/src/main/services/lanes/laneTemplateService";
import type { createPortAllocationService } from "../../../../desktop/src/main/services/lanes/portAllocationService";
import type { createRebaseSuggestionService } from "../../../../desktop/src/main/services/lanes/rebaseSuggestionService";
import type { createProcessService } from "../../../../desktop/src/main/services/processes/processService";
import type { Logger } from "../../../../desktop/src/main/services/logging/logger";
import { createOrchestrationDomainService } from "../../../../desktop/src/main/services/orchestration/orchestrationDomain";
import type { createOrchestrationService } from "../../../../desktop/src/main/services/orchestration/orchestrationService";
import type { createPrService } from "../../../../desktop/src/main/services/prs/prService";
import type { createPrSummaryService } from "../../../../desktop/src/main/services/prs/prSummaryService";
import type { createQueueLandingService } from "../../../../desktop/src/main/services/prs/queueLandingService";
import type { createPtyService } from "../../../../desktop/src/main/services/pty/ptyService";
import type { createUsageTrackingService } from "../../../../desktop/src/main/services/usage/usageTrackingService";
import { deleteTerminalSessionWithRuntimeCleanup } from "../../../../desktop/src/main/services/sessions/deleteTerminalSession";
import type { createSessionDeltaService } from "../../../../desktop/src/main/services/sessions/sessionDeltaService";
import type { createSessionService } from "../../../../desktop/src/main/services/sessions/sessionService";
import { getSharedModelPickerStore, type ModelPickerStore } from "../modelPickerStore";
import type { AdeDb } from "../../../../desktop/src/main/services/state/kvDb";
import { getErrorMessage, resolvePathWithinRoot } from "../../../../desktop/src/main/services/shared/utils";
import { sanitizeResumeTargetId } from "../../../../desktop/src/main/utils/terminalSessionSignals";
import type { SyncPinStore } from "./syncPinStore";
export type ExternalSessionsRemoteService = {
list(args?: ExternalSessionListArgs): Promise<ExternalSessionSummary[]>;
importExternalSession(args: ExternalSessionImportArgs): Promise<ExternalSessionImportResult>;
};
const EXTERNAL_SESSION_PROVIDERS = new Set<ExternalSessionProvider>([
"claude",
"codex",
"cursor",
"droid",
"opencode",
]);
type SyncRemoteCommandServiceArgs = {
/**
* Per-project cr-sqlite DB. Source of truth for the model-picker store
* (favorites + recents) when no explicit `getModelPickerStore` accessor is
* wired, so the sync host never falls back to an empty store in production.
* Optional only so unit tests that never touch `modelPicker.*` can omit it;
* production callers (bootstrap, syncHostService) always pass it.
*/
db?: AdeDb;
usageTrackingService?: ReturnType<typeof createUsageTrackingService> | null;
projectRoot?: string;
laneService: ReturnType<typeof createLaneService>;
prService: ReturnType<typeof createPrService>;
prSummaryService?: ReturnType<typeof createPrSummaryService> | null;
queueLandingService?: ReturnType<typeof createQueueLandingService> | null;
ptyService: ReturnType<typeof createPtyService>;
sessionService: ReturnType<typeof createSessionService>;
sessionDeltaService?: ReturnType<typeof createSessionDeltaService> | null;
fileService: ReturnType<typeof createFileService>;
gitService?: ReturnType<typeof createGitOperationsService>;
githubService?: ReturnType<typeof createGithubService> | null;
diffService?: ReturnType<typeof createDiffService>;
conflictService?: ReturnType<typeof createConflictService>;
operationService?: ReturnType<typeof createOperationService> | null;
aiIntegrationService?: ReturnType<typeof createAiIntegrationService> | null;
agentChatService?: ReturnType<typeof createAgentChatService>;
personalChatScope?: Pick<PersonalChatScopeContract, "call" | "streamEvents">;
orchestrationService?: ReturnType<typeof createOrchestrationService> | null;
ctoStateService?: ReturnType<typeof createCtoStateService> | null;
ctoMemoryService?: CtoMemoryService | null;
linearCredentialService?: ReturnType<typeof createLinearCredentialService> | null;
/**
* Resolvers for services created after createSyncService in main.ts.
* Router handlers read them lazily so init order is not load-bearing.
*/
getLinearIssueTracker?: () => ReturnType<typeof createLinearIssueTracker> | null;
projectConfigService?: ReturnType<typeof createProjectConfigService>;
processService?: ReturnType<typeof createProcessService> | null;
portAllocationService?: ReturnType<typeof createPortAllocationService> | null;
laneEnvironmentService?: ReturnType<typeof createLaneEnvironmentService> | null;
laneTemplateService?: ReturnType<typeof createLaneTemplateService> | null;
rebaseSuggestionService?: ReturnType<typeof createRebaseSuggestionService> | null;
autoRebaseService?: ReturnType<typeof createAutoRebaseService> | null;
externalSessionsService?: ExternalSessionsRemoteService | null;
getExternalSessionsService?: () => ExternalSessionsRemoteService | null;
/**
* Deterministic stamp of the sync host's in-memory lane presence
* (`devicesOpen`). The host decorates lane list/detail payloads with
* presence AFTER this service builds them, so the conditional-response
* signatures fold the stamp in — otherwise a presence-only change (another
* device opening a lane) would keep matching `ifNoneMatch` and the client
* would hold a stale presence indicator until an unrelated lane change.
*/
getLanePresenceStamp?: () => string;
/**
* Lazy accessor for the model picker store (favorites + recents, backed by
* the per-project cr-sqlite DB). iOS hits these via the `modelPicker.*` sync
* commands so favorites/recents stay in sync with desktop + TUI. Optional —
* when unset, handlers fall back to the per-db shared store built from
* `args.db`, so the sync host always reads/writes the real DB rather than an
* empty stub.
*/
getModelPickerStore?: () => ModelPickerStore | null;
/**
* Optional handler for the `deeplinks.open` sync command. iOS uses this to
* bounce a cross-machine `ade://...` or `https://ade-app.dev/open?...` URL
* to the paired desktop ("Send to your Mac"). Desktop main.ts wires this up
* to parseDeeplink +
* appNavigationService; in the ade-cli/runtime context (no desktop windows
* present) the handler is intentionally unset and the command returns a
* clear "not available" error.
*/
dispatchDeeplinkUrl?: (url: string) => Promise<{ ok: boolean; message?: string }>;
/**
* Brain→push-relay publisher. When present, the `push.*` runtime commands
* hand device registrations / prefs / Live Activity tokens to it; when absent
* (e.g. sync host with push publishing off) the commands no-op with a clear
* error so the phone can surface "push publishing is not running".
*/
pushPublisherService?: PushPublisherService | null;
/**
* Machine-level pairing PIN store. Required by `sync.getWebPairingInfo`,
* which only runs after the paired command channel is authenticated.
*/
syncPinStore?: SyncPinStore | null;
/**
* Builds the same connect info advertised by sync status / pairing QR,
* including direct address candidates and the optional relay candidate.
*/
getPairingConnectInfo?: () => SyncPairingConnectInfo | null;
/** Issues a short-lived one-time grant for the desktop runtime channels. */
issueRuntimeHostPairingGrant?: () => string;
/** Effective relay kill-switch state for the machine-level cloud tunnel. */
isCloudRelayEnabled?: () => boolean;
logger: Logger;
};
type RegisteredRemoteCommand = {
descriptor: SyncRemoteCommandDescriptor;
handler: (args: Record<string, unknown>) => Promise<unknown>;
};
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function asTrimmedString(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
function formatDeeplinkParseError(error: ParseError): string {
switch (error.kind) {
case "malformed":
return error.reason;
case "unsupported_scheme":
return `unsupported scheme '${error.scheme}'`;
case "unsupported_host":
return `unsupported host '${error.host}'`;
case "unknown_type":
return `unknown type '${error.type}'`;
case "empty":
return error.kind;
}
}
function asOptionalBoolean(value: unknown): boolean | undefined {
return typeof value === "boolean" ? value : undefined;
}
function asOptionalNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function payloadSignature(value: unknown): string {
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
}
/**
* Conditional-response envelope shared by the lane list/detail commands: when
* the caller's ifNoneMatch equals the current payload signature, return the
* lightweight notModified shell instead of the full payload. The full payload
* is still computed (the signature comes from it), so this saves transport and
* client decode/DB work, not host compute.
*/
function respondWithSignature<T extends object, E extends object>(
response: T,
ifNoneMatch: string | null | undefined,
emptyResponse: E,
signatureSalt = "",
): (T | E) & { signature: string; notModified: boolean } {
// The salt folds host-decorated state (lane presence) into the signature so
// a presence-only change invalidates the client's cached copy even though
// the undecorated payload is byte-identical.
const signature = payloadSignature(signatureSalt ? { response, signatureSalt } : response);
if (ifNoneMatch && ifNoneMatch === signature) {
return { ...emptyResponse, signature, notModified: true };
}
return { ...response, signature, notModified: false };
}
function asConfidenceThreshold(value: unknown): number | undefined {
const numeric = asOptionalNumber(value);
if (numeric == null) return undefined;
if (numeric < 0 || numeric > 1) return undefined;
return numeric;
}
function asNullableTrimmedString(value: unknown): string | null | undefined {
if (value === null) return null;
if (value === undefined) return undefined;
return asTrimmedString(value) ?? undefined;
}
function asStringArray(value: unknown): string[] {
if (!Array.isArray(value)) return [];
return value.map((entry) => asTrimmedString(entry)).filter((entry): entry is string => Boolean(entry));
}
function emptyLinearQuickView(connection: Record<string, unknown>) {
return {
connection,
organization: null,
viewer: null,
projects: [],
teams: [],
assignedIssues: [],
recentIssues: [],
fetchedAt: new Date().toISOString(),
sdk: { packageName: "@linear/sdk", surfaces: [] },
};
}
async function getConnectedLinearIssueTracker(
args: SyncRemoteCommandServiceArgs,
): Promise<ReturnType<typeof createLinearIssueTracker> | null> {
const credentialStatus = args.linearCredentialService?.getStatus() ?? {
tokenStored: false,
};
if (!credentialStatus.tokenStored) return null;
const linearIssueTracker = args.getLinearIssueTracker?.() ?? null;
if (!linearIssueTracker) return null;
const status = await linearIssueTracker.getConnectionStatus().catch(() => null);
return status?.connected ? linearIssueTracker : null;
}
function asStringRecord(value: unknown): Record<string, string> | undefined {
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
const entries = Object.entries(value)
.map(([key, entry]) => [key.trim(), typeof entry === "string" ? entry.trim() : ""] as const)
.filter(([key, entry]) => key.length > 0 && entry.length > 0);
return entries.length ? Object.fromEntries(entries) : undefined;
}
function parseAgentChatFileRefs(value: unknown): AgentChatFileRef[] | undefined {
if (!Array.isArray(value)) return undefined;
const attachments: AgentChatFileRef[] = [];
for (const entry of value) {
if (!isRecord(entry)) continue;
const path = asTrimmedString(entry.path);
let type: "image" | "file" | null = null;
if (entry.type === "image") type = "image";
else if (entry.type === "file") type = "file";
if (!path || !type) continue;
attachments.push({ path, type });
}
return attachments;
}
function parseCursorConfigValues(
value: unknown,
): AgentChatUpdateSessionArgs["cursorConfigValues"] | AgentChatCreateArgs["cursorConfigValues"] {
if (value == null) return null;
if (!isRecord(value)) return {};
return Object.fromEntries(
Object.entries(value)
.filter((entry): entry is [string, string | boolean | number] => (
typeof entry[1] === "string"
|| typeof entry[1] === "boolean"
|| (typeof entry[1] === "number" && Number.isFinite(entry[1]))
))
.map(([key, entryValue]): [string, string | boolean | number] => [key.trim(), entryValue])
.filter(([key]) => key.length > 0),
);
}
function requireString(value: unknown, message: string): string {
const parsed = asTrimmedString(value);
if (!parsed) throw new Error(message);
return parsed;
}
function requireStringArray(value: unknown, message: string): string[] {
const parsed = asStringArray(value);
if (parsed.length === 0) throw new Error(message);
return parsed;
}
function requireService<T>(value: T | null | undefined, message: string): T {
if (value == null) throw new Error(message);
return value;
}
function parseGetWebPairingInfoArgs(_value: Record<string, unknown>): Record<string, never> {
return {};
}
function parsePublishCurrentProjectArgs(value: Record<string, unknown>): PublishProjectInput {
const owner = asTrimmedString(value.owner);
const description = asTrimmedString(value.description);
return {
...(owner ? { owner } : {}),
name: requireString(value.name, "github.publishCurrentProject requires name."),
...(description ? { description } : {}),
isPrivate: asOptionalBoolean(value.isPrivate) ?? true,
};
}
function requireProjectRoot(args: SyncRemoteCommandServiceArgs, action: string): string {
return requireString(args.projectRoot, `${action} requires a project root.`);
}
function parseSessionIdArgs(value: Record<string, unknown>, action: string): { sessionId: string } {
return {
sessionId: requireString(value.sessionId, `${action} requires sessionId.`),
};
}
function parseAgentChatContextUsageArgs(value: Record<string, unknown>): AgentChatContextUsageArgs {
return parseSessionIdArgs(value, "chat.getContextUsage");
}
function parseAgentChatRewindFilesArgs(value: Record<string, unknown>): AgentChatRewindFilesArgs {
return {
sessionId: requireString(value.sessionId, "chat.rewindFiles requires sessionId."),
userMessageId: requireString(value.userMessageId, "chat.rewindFiles requires userMessageId."),
dryRun: asOptionalBoolean(value.dryRun),
};
}
function parseAgentChatTurnFileDiffArgs(value: Record<string, unknown>): AgentChatGetTurnFileDiffArgs {
return {
sessionId: requireString(value.sessionId, "chat.getTurnFileDiff requires sessionId."),
beforeSha: requireString(value.beforeSha, "chat.getTurnFileDiff requires beforeSha."),
afterSha: requireString(value.afterSha, "chat.getTurnFileDiff requires afterSha."),
filePath: requireString(value.filePath, "chat.getTurnFileDiff requires filePath."),
};
}
function parseAgentChatSlashCommandsArgs(value: Record<string, unknown>): AgentChatSlashCommandsArgs {
return {
...(asTrimmedString(value.sessionId) ? { sessionId: asTrimmedString(value.sessionId)! } : {}),
...("laneId" in value ? { laneId: value.laneId == null ? null : asTrimmedString(value.laneId) ?? null } : {}),
...("provider" in value ? { provider: value.provider == null ? null : asTrimmedString(value.provider) as AgentChatProvider | null } : {}),
...("projectRoot" in value ? { projectRoot: value.projectRoot == null ? null : asTrimmedString(value.projectRoot) ?? null } : {}),
};
}
function parseAgentChatParallelLaunchStateArgs(value: Record<string, unknown>): AgentChatParallelLaunchStateArgs {
return {
projectRoot: requireString(value.projectRoot, "chat.getParallelLaunchState requires projectRoot."),
parentLaneId: requireString(value.parentLaneId, "chat.getParallelLaunchState requires parentLaneId."),
};
}
function sanitizeParallelLaunchLaneIds(value: unknown): string[] {
if (!Array.isArray(value)) return [];
return Array.from(new Set(
value
.map((entry) => (typeof entry === "string" ? entry.trim() : ""))
.filter(Boolean),
));
}
function normalizeAgentChatParallelLaunchState(
value: unknown,
parentLaneIdFallback: string,
): AgentChatParallelLaunchState | null {
if (!isRecord(value)) return null;
const parentLaneId = asTrimmedString(value.parentLaneId) ?? parentLaneIdFallback;
const createdLaneIds = sanitizeParallelLaunchLaneIds(value.createdLaneIds);
if (createdLaneIds.length === 0) return null;
const sentLaneIds = sanitizeParallelLaunchLaneIds(value.sentLaneIds)
.filter((laneId) => createdLaneIds.includes(laneId));
const status = value.status === "creating_lanes"
|| value.status === "sending"
|| value.status === "completed"
|| value.status === "cleanup_pending"
? value.status
: sentLaneIds.length >= createdLaneIds.length
? "completed"
: "creating_lanes";
return {
parentLaneId,
createdLaneIds,
sentLaneIds,
status,
updatedAt: asTrimmedString(value.updatedAt) ?? new Date(0).toISOString(),
lastError: asTrimmedString(value.lastError),
};
}
function parseAgentChatSetParallelLaunchStateArgs(value: Record<string, unknown>): AgentChatSetParallelLaunchStateArgs {
const parsed = parseAgentChatParallelLaunchStateArgs(value);
return {
...parsed,
state: normalizeAgentChatParallelLaunchState(value.state, parsed.parentLaneId),
};
}
function agentChatParallelLaunchStateKey(projectRoot: string, parentLaneId: string): string {
return `agent-chat-parallel-launch:${projectRoot}:${parentLaneId}`;
}
function parseAgentChatHandoffArgs(value: Record<string, unknown>): AgentChatHandoffArgs {
const handoffNote = asTrimmedString(value.handoffNote);
return {
...(value as AgentChatHandoffArgs),
sourceSessionId: requireString(value.sourceSessionId, "chat.handoff requires sourceSessionId."),
targetModelId: requireString(value.targetModelId, "chat.handoff requires targetModelId.") as AgentChatHandoffArgs["targetModelId"],
...(handoffNote ? { handoffNote } : {}),
};
}
function parseAgentChatLaunchArgs(value: Record<string, unknown>): AgentChatLaunchArgs {
return {
...parseAgentChatCreateArgs(value),
kickoffText: requireString(value.kickoffText, "chat.launch requires kickoffText."),
...(asTrimmedString(value.kickoffDisplayText) ? { kickoffDisplayText: asTrimmedString(value.kickoffDisplayText)! } : {}),
...(Array.isArray(value.contextAttachments) ? { contextAttachments: value.contextAttachments as AgentChatLaunchArgs["contextAttachments"] } : {}),
};
}
function parseWarmupModelArgs(value: Record<string, unknown>): { sessionId: string; modelId: string } {
return {
sessionId: requireString(value.sessionId, "chat.warmupModel requires sessionId."),
modelId: requireString(value.modelId, "chat.warmupModel requires modelId."),
};
}
function parseTerminalRecord(value: Record<string, unknown>): Record<string, unknown> {
return isRecord(value) ? value : {};
}
function optionalTerminalString(
record: Record<string, unknown>,
field: string,
maxLength = 4096,
trim = true,
): string | null | undefined {
const value = record[field];
if (value === undefined) return undefined;
if (value === null) return null;
if (typeof value !== "string") throw new Error(`Invalid terminal payload: ${field} must be a string`);
const text = trim ? value.trim() : value;
if (text.includes("\0")) throw new Error(`Invalid terminal payload: ${field} cannot contain null bytes`);
if (text.length > maxLength) throw new Error(`Invalid terminal payload: ${field} is too long`);
return text;
}
function optionalTerminalNumber(
record: Record<string, unknown>,
field: string,
min: number,
max: number,
): number | null | undefined {
const value = record[field];
if (value === undefined) return undefined;
if (value === null) return null;
if (typeof value !== "number" || !Number.isFinite(value)) {
throw new Error(`Invalid terminal payload: ${field} must be a finite number`);
}
const next = Math.floor(value);
if (next < min || next > max) throw new Error(`Invalid terminal payload: ${field} is out of range`);
return next;
}
function parseTerminalListArgs(value: Record<string, unknown>): ChatTerminalListArgs {
const record = parseTerminalRecord(value);
return {
chatSessionId: optionalTerminalString(record, "chatSessionId", 128),
laneId: optionalTerminalString(record, "laneId", 512),
limit: optionalTerminalNumber(record, "limit", 1, 500),
};
}
function parseTerminalActiveForChatArgs(value: Record<string, unknown>): ChatTerminalActiveForChatArgs {
const record = parseTerminalRecord(value);
const chatSessionId = optionalTerminalString(record, "chatSessionId", 128);
if (!chatSessionId) throw new Error("Invalid terminal payload: chatSessionId is required");
return { chatSessionId };
}
function parseGitUserIdentityArgs(value: Record<string, unknown>): GitGetUserIdentityArgs {
return {
laneId: requireString(value.laneId, "git.getUserIdentity requires laneId."),
};
}
function parseListOperationsArgs(value: Record<string, unknown>): ListOperationsArgs {
const status = asTrimmedString(value.status);
return {
...(asTrimmedString(value.laneId) ? { laneId: asTrimmedString(value.laneId)! } : {}),
...(asTrimmedString(value.kind) ? { kind: asTrimmedString(value.kind)! } : {}),
...(status === "running" || status === "succeeded" || status === "failed" || status === "canceled" ? { status } : {}),
...(asOptionalNumber(value.limit) != null ? { limit: asOptionalNumber(value.limit)! } : {}),
};
}
function parseDeletePrArgs(value: Record<string, unknown>): DeletePrArgs {
return {
prId: requirePrId(value, "prs.delete"),
closeOnGitHub: asOptionalBoolean(value.closeOnGitHub),
archiveLane: asOptionalBoolean(value.archiveLane),
};
}
function parseCleanupPrBranchArgs(value: Record<string, unknown>): CleanupPrBranchArgs {
return {
prId: requirePrId(value, "prs.cleanupBranch"),
deleteLocalBranch: asOptionalBoolean(value.deleteLocalBranch),
deleteRemoteBranch: asOptionalBoolean(value.deleteRemoteBranch),
...(asTrimmedString(value.remoteName) ? { remoteName: asTrimmedString(value.remoteName)! } : {}),
};
}
function parsePostPrReviewCommentArgs(value: Record<string, unknown>): PostPrReviewCommentArgs {
return {
prId: requirePrId(value, "prs.postReviewComment"),
threadId: requireString(value.threadId, "prs.postReviewComment requires threadId."),
body: requireString(value.body, "prs.postReviewComment requires body."),
};
}
function parseStartPrAiResolutionArgs(value: Record<string, unknown>): PrAiResolutionStartArgs {
return {
context: isRecord(value.context) ? value.context as PrAiResolutionContext : {} as PrAiResolutionContext,
model: requireString(value.model, "prs.aiResolutionStart requires model."),
...("reasoning" in value ? { reasoning: value.reasoning == null ? null : asTrimmedString(value.reasoning) ?? null } : {}),
...(asTrimmedString(value.permissionMode) ? { permissionMode: asTrimmedString(value.permissionMode)! as PrAgentPermissionMode } : {}),
...("additionalInstructions" in value
? { additionalInstructions: value.additionalInstructions == null ? null : asTrimmedString(value.additionalInstructions) ?? null }
: {}),
};
}
function parseGetPrAiResolutionSessionArgs(value: Record<string, unknown>): PrAiResolutionGetSessionArgs {
return {
context: isRecord(value.context) ? value.context as PrAiResolutionContext : {} as PrAiResolutionContext,
};
}
function parseProjectConfigSaveArgs(value: Record<string, unknown>): { candidate: ProjectConfigCandidate } {
if (!isRecord(value.candidate)) throw new Error("projectConfig.save requires candidate.");
return { candidate: value.candidate as ProjectConfigCandidate };
}
function parseOrchestrationRunCreateArgs(value: Record<string, unknown>): OrchestrationRunCreateRequest & { laneId: string } {
return {
...(value as OrchestrationRunCreateRequest & { laneId: string }),
laneId: requireString(value.laneId, "orchestration.runCreate requires laneId."),
};
}
function parseProcessLaneArgs(payload: Record<string, unknown>, action: string): { laneId: string } {
return {
laneId: requireString(payload.laneId, `${action} requires laneId.`),
};
}
function parseProcessActionArgs(payload: Record<string, unknown>, action: string): { laneId: string; processId: string; runId?: string } {
const parsed = {
laneId: requireString(payload.laneId, `${action} requires laneId.`),
processId: requireString(payload.processId, `${action} requires processId.`),
};
const runId = asTrimmedString(payload.runId);
return runId ? { ...parsed, runId } : parsed;
}
async function summarizeChatSessionForRemote(
agentChatService: ReturnType<typeof createAgentChatService>,
session: AgentChatSession,
): Promise<AgentChatSessionSummary> {
const summary = await agentChatService.getSessionSummary(session.id);
if (summary) return summary;
return {
sessionId: session.id,
laneId: session.laneId,
provider: session.provider,
model: session.model,
...(session.modelId ? { modelId: session.modelId } : {}),
...(session.sessionProfile ? { sessionProfile: session.sessionProfile } : {}),
reasoningEffort: session.reasoningEffort ?? null,
fastMode: session.fastMode === true,
executionMode: session.executionMode ?? null,
...(session.permissionMode ? { permissionMode: session.permissionMode } : {}),
...(session.interactionMode !== undefined ? { interactionMode: session.interactionMode } : {}),
...(session.claudePermissionMode ? { claudePermissionMode: session.claudePermissionMode } : {}),
...(session.claudeOutputStyle ? { claudeOutputStyle: session.claudeOutputStyle } : {}),
...(session.codexApprovalPolicy ? { codexApprovalPolicy: session.codexApprovalPolicy } : {}),
...(session.codexSandbox ? { codexSandbox: session.codexSandbox } : {}),
...(session.codexConfigSource ? { codexConfigSource: session.codexConfigSource } : {}),
...(session.opencodePermissionMode ? { opencodePermissionMode: session.opencodePermissionMode } : {}),
...(session.droidPermissionMode ? { droidPermissionMode: session.droidPermissionMode } : {}),
...(session.cursorModeSnapshot ? { cursorModeSnapshot: session.cursorModeSnapshot } : {}),
...(session.cursorModeId !== undefined ? { cursorModeId: session.cursorModeId } : {}),
...(session.cursorConfigValues ? { cursorConfigValues: session.cursorConfigValues } : {}),
...(session.identityKey ? { identityKey: session.identityKey } : {}),
...(session.surface ? { surface: session.surface } : {}),
automationId: session.automationId ?? null,
automationRunId: session.automationRunId ?? null,
...(session.capabilityMode ? { capabilityMode: session.capabilityMode } : {}),
completion: session.completion ?? null,
status: session.status,
idleSinceAt: session.idleSinceAt ?? null,
startedAt: session.createdAt,
endedAt: null,
lastActivityAt: session.lastActivityAt,
lastOutputPreview: null,
summary: null,
nextWakeAt: null,
...(session.threadId ? { threadId: session.threadId } : {}),
...(session.requestedCwd !== undefined ? { requestedCwd: session.requestedCwd } : {}),
};
}
function parsePushQuietHours(value: unknown): PushQuietHours | null {
if (!isRecord(value)) return null;
const start = asTrimmedString(value.start);
const end = asTrimmedString(value.end);
const timezone = asTrimmedString(value.timezone);
if (!start || !end || !timezone) return null;
return { start, end, timezone };
}
function parsePushPrefs(value: unknown): PushNotificationPrefs {
if (!isRecord(value)) {
return { enabled: true, liveActivitiesEnabled: true, mutedSessionIds: [], quietHours: null };
}
return {
enabled: value.enabled !== false,
liveActivitiesEnabled: value.liveActivitiesEnabled !== false,
mutedSessionIds: asStringArray(value.mutedSessionIds),
quietHours: parsePushQuietHours(value.quietHours),
};
}
function parsePushRegisterDeviceArgs(value: Record<string, unknown>): PushDeviceRegistration {
const apsEnvironmentRaw = asTrimmedString(value.apsEnvironment);
if (apsEnvironmentRaw !== "sandbox" && apsEnvironmentRaw !== "production") {
throw new Error("push.registerDevice requires apsEnvironment (sandbox|production).");
}
return {
deviceId: requireString(value.deviceId, "push.registerDevice requires deviceId."),
bundleId: requireString(value.bundleId, "push.registerDevice requires bundleId."),
apsEnvironment: apsEnvironmentRaw,
apnsToken: asTrimmedString(value.apnsToken),
pushToStartToken: asTrimmedString(value.pushToStartToken),
platform: asTrimmedString(value.platform),
deviceName: asTrimmedString(value.deviceName),
prefs: isRecord(value.prefs) ? parsePushPrefs(value.prefs) : null,
};
}
function parsePushLiveActivityTokenArgs(value: Record<string, unknown>): PushLiveActivityTokenReport {
return {
deviceId: requireString(value.deviceId, "push.reportLiveActivityToken requires deviceId."),
activityId: requireString(value.activityId, "push.reportLiveActivityToken requires activityId."),
token: asTrimmedString(value.token),
};
}
function parseListLanesArgs(value: Record<string, unknown>): ListLanesArgs {
return {
includeArchived: asOptionalBoolean(value.includeArchived),
includeStatus: asOptionalBoolean(value.includeStatus),
includeConflictStatus: asOptionalBoolean(value.includeConflictStatus),
includeRebaseSuggestions: asOptionalBoolean(value.includeRebaseSuggestions),
includeAutoRebaseStatus: asOptionalBoolean(value.includeAutoRebaseStatus),
};
}
function parseCreateLaneArgs(value: Record<string, unknown>): CreateLaneArgs {
return {
name: requireString(value.name, "lanes.create requires name."),
...(asTrimmedString(value.description) ? { description: asTrimmedString(value.description)! } : {}),
...(asTrimmedString(value.parentLaneId) ? { parentLaneId: asTrimmedString(value.parentLaneId)! } : {}),
...(asTrimmedString(value.baseBranch) ? { baseBranch: asTrimmedString(value.baseBranch)! } : {}),
...(asTrimmedString(value.branchName) ? { branchName: asTrimmedString(value.branchName)! } : {}),
...(asTrimmedString(value.startPoint) ? { startPoint: asTrimmedString(value.startPoint)! } : {}),
...(isRecord(value.linearIssue) ? { linearIssue: value.linearIssue as CreateLaneArgs["linearIssue"] } : {}),
};
}
function parseSuggestLaneNameArgs(value: Record<string, unknown>): AgentChatSuggestLaneNameArgs {
return {
prompt: requireString(value.prompt, "lanes.suggestName requires prompt."),
modelId: requireString(value.modelId, "lanes.suggestName requires modelId."),
laneId: requireString(value.laneId, "lanes.suggestName requires laneId."),
...(asTrimmedString(value.fallbackName) ? { fallbackName: asTrimmedString(value.fallbackName)! } : {}),
};
}
function parseCreateChildLaneArgs(value: Record<string, unknown>): CreateChildLaneArgs {
return {
name: requireString(value.name, "lanes.createChild requires name."),
parentLaneId: requireString(value.parentLaneId, "lanes.createChild requires parentLaneId."),
...(asTrimmedString(value.description) ? { description: asTrimmedString(value.description)! } : {}),
...(asTrimmedString(value.folder) ? { folder: asTrimmedString(value.folder)! } : {}),
...(asTrimmedString(value.baseBranchRef) ? { baseBranchRef: asTrimmedString(value.baseBranchRef)! } : {}),
...(asTrimmedString(value.branchName) ? { branchName: asTrimmedString(value.branchName)! } : {}),
...(isRecord(value.linearIssue) ? { linearIssue: value.linearIssue as CreateChildLaneArgs["linearIssue"] } : {}),
};
}
function parseCreateLaneFromUnstagedArgs(value: Record<string, unknown>): CreateLaneFromUnstagedArgs {
return {
name: requireString(value.name, "lanes.createFromUnstaged requires name."),
sourceLaneId: requireString(value.sourceLaneId, "lanes.createFromUnstaged requires sourceLaneId."),
};
}
function parseImportBranchArgs(value: Record<string, unknown>): ImportBranchLaneArgs {
return {
branchRef: requireString(value.branchRef, "lanes.importBranch requires branchRef."),
...(asTrimmedString(value.name) ? { name: asTrimmedString(value.name)! } : {}),
...(asTrimmedString(value.description) ? { description: asTrimmedString(value.description)! } : {}),
...(asTrimmedString(value.baseBranch) ? { baseBranch: asTrimmedString(value.baseBranch)! } : {}),
};
}
function parseAttachLaneArgs(value: Record<string, unknown>): AttachLaneArgs {
return {
name: requireString(value.name, "lanes.attach requires name."),
attachedPath: requireString(value.attachedPath, "lanes.attach requires attachedPath."),
...(asTrimmedString(value.description) ? { description: asTrimmedString(value.description)! } : {}),
};
}
function parseArchiveLaneArgs(value: Record<string, unknown>, action: string): ArchiveLaneArgs {
return {
laneId: requireString(value.laneId, `${action} requires laneId.`),
};
}
function parseDeleteLaneArgs(value: Record<string, unknown>): DeleteLaneArgs {
return {
laneId: requireString(value.laneId, "lanes.delete requires laneId."),
deleteBranch: asOptionalBoolean(value.deleteBranch),
deleteRemoteBranch: asOptionalBoolean(value.deleteRemoteBranch),
...(asTrimmedString(value.remoteName) ? { remoteName: asTrimmedString(value.remoteName)! } : {}),
force: asOptionalBoolean(value.force),
};
}
function parseRenameLaneArgs(value: Record<string, unknown>): RenameLaneArgs {
return {
laneId: requireString(value.laneId, "lanes.rename requires laneId."),
name: requireString(value.name, "lanes.rename requires name."),
};
}
function parseReparentLaneArgs(value: Record<string, unknown>): ReparentLaneArgs {
const stackBaseBranchRef = asTrimmedString(value.stackBaseBranchRef);
return {
laneId: requireString(value.laneId, "lanes.reparent requires laneId."),
newParentLaneId: requireString(value.newParentLaneId, "lanes.reparent requires newParentLaneId."),
...(stackBaseBranchRef ? { stackBaseBranchRef } : {}),
};
}
function parseUpdateLaneAppearanceArgs(value: Record<string, unknown>): UpdateLaneAppearanceArgs {