-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathsessionService.ts
More file actions
6125 lines (5647 loc) · 199 KB
/
Copy pathsessionService.ts
File metadata and controls
6125 lines (5647 loc) · 199 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
// biome-ignore-all lint/suspicious/noExplicitAny: SessionServiceDeps is the
// host seam for the ported renderer SessionService; the trpc/store/helper ports
// are satisfied by the desktop adapter and typed loosely at this boundary.
import type {
ContentBlock,
RequestPermissionRequest,
SessionConfigOption,
SessionConfigSelectGroup,
SessionConfigSelectOption,
SessionUpdate,
} from "@agentclientprotocol/sdk";
import {
type AcpMessage,
type Adapter,
type AgentSession,
type CloudRegion,
classifyGatewayLimitError,
type ExecutionMode,
flattenSelectOptions,
getBackoffDelay,
getCloudUrlFromRegion,
getConfigOptionByCategory,
isFatalSessionError,
isJsonRpcNotification,
isJsonRpcRequest,
isJsonRpcResponse,
isRateLimitError,
isTransientUpstreamError,
mergeConfigOptions,
type OptimisticItem,
type PermissionRequest,
type QueuedMessage,
resolveBypassRevertMode,
type StoredLogEntry,
sendableQueuePrefixLength,
sessionSupportsNativeSteer,
type TaskRunStatus,
} from "@posthog/shared";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
import {
type CloudTaskPermissionRequestUpdate,
type CloudTaskUpdatePayload,
type EffortLevel,
effortLevelSchema,
isTerminalStatus,
type Task,
} from "@posthog/shared/domain-types";
import type { SpeechKind, SpeechSource } from "../speech/identifiers";
import {
isNotification,
POSTHOG_NOTIFICATIONS,
SPEAK_TOOL_QUALIFIED_NAME,
} from "./acpNotifications";
import { createAppendOnlyTracker } from "./appendOnlyTracker";
import type {
CloudArtifactClient,
CloudSkillBundleRef,
} from "./cloudArtifactIdentifiers";
import { classifyCloudLogAppend } from "./cloudLogGap";
import { CloudLogGapReconciler } from "./cloudLogGapReconciler";
import { CloudRunIdleTracker } from "./cloudRunIdleTracker";
import {
type CloudRuntimeOptions,
getCloudPrAuthorshipMode,
getCloudRunSource,
getCloudRuntimeOptions,
} from "./cloudRunOptions";
import {
addMissingCloudRuntimeConfigOptions,
buildCloudDefaultConfigOptions,
extractLatestConfigOptionsFromEntries,
} from "./cloudSessionConfig";
import {
computeAutoRetryFinalState,
OFFLINE_SESSION_MESSAGE,
routeLocalConnect,
} from "./connectRouting";
import {
formatPermissionAnswerPrompt,
type PermissionSelectionPlan,
planPermissionResponse,
} from "./permissionResponse";
import {
convertStoredEntriesToEvents,
createUserShellExecuteEvent,
extractPromptText,
getUserShellExecutesSinceLastPrompt,
hasSessionPromptEvent,
isTurnCompleteEvent,
normalizePromptToBlocks,
promptReferencesAbsoluteFolder,
shellExecutesToContextBlocks,
} from "./sessionEvents";
import { selectSessionsToEvict } from "./sessionEviction";
import { createBaseSession } from "./sessionFactory";
import { type ParsedSessionLogs, parseSessionLogContent } from "./sessionLogs";
const LOCAL_SESSION_RECONNECT_ATTEMPTS = 3;
const LOCAL_SESSION_RECONNECT_BACKOFF = {
initialDelayMs: 1_000,
maxDelayMs: 5_000,
};
const LOCAL_SESSION_RECOVERY_MESSAGE =
"Lost connection to the agent. Reconnecting…";
const LOCAL_SESSION_RECOVERY_FAILED_MESSAGE =
"Connecting to to the agent has been lost. Retry, or start a new session.";
const GITHUB_AUTHORIZATION_REQUIRED_CODE = "github_authorization_required";
const AUTO_RETRY_MAX_ATTEMPTS = 2;
const AUTO_RETRY_DELAY_MS = 10_000;
const AUTH_RESTORE_MAX_RETRY_WAITS = 6;
const MAX_SUPERSEDED_RUN_IDS = 100;
const MAX_RESPONDED_PERMISSION_REQUEST_IDS = 500;
/**
* Streamed events are buffered and flushed on this cadence so a burst of tokens
* coalesces into one processing pass (and roughly one render) instead of one
* per event. Electron IPC delivers each event as its own task, so a microtask
* flush wouldn't batch across them — a short timer does. One frame is
* imperceptible for streamed text.
*/
const SESSION_EVENT_FLUSH_MS = 16;
/**
* A backgrounded session's transcript is freed this long after it stops being
* viewed, and reloaded from disk on return. Only disconnected (idle, no live
* subscription) sessions are eligible, so no streamed event can append to an
* evicted transcript.
*/
const SESSION_EVENT_EVICT_GRACE_MS = 20_000;
/**
* On open, paint the last this-many bytes of the log immediately so a big
* transcript shows its latest turns in tens of ms, while the authoritative
* full read + connect completes behind it. ~1.5MB is a few hundred entries —
* plenty for the initial (scrolled-to-bottom) view.
*/
const OPEN_TAIL_BYTES = 1_500_000;
class GitHubAuthorizationRequiredForCloudHandoffError extends Error {
constructor(
message = "Connect GitHub before continuing this task in cloud.",
) {
super(message);
this.name = "GitHubAuthorizationRequiredForCloudHandoffError";
}
}
type TrpcMutation = { mutate: (input?: any) => Promise<any> };
type TrpcQuery = { query: (input?: any) => Promise<any> };
type TrpcSubscription = {
subscribe: (
input: any,
handlers: { onData: (data: any) => void; onError?: (err: unknown) => void },
) => { unsubscribe: () => void };
};
export interface SessionTrpc {
agent: {
start: TrpcMutation;
reconnect: TrpcMutation;
cancel: TrpcMutation;
prompt: TrpcMutation;
cancelPrompt: TrpcMutation;
cancelPermission: TrpcMutation;
respondToPermission: TrpcMutation;
setConfigOption: TrpcMutation;
resetAll: TrpcMutation;
recordActivity: TrpcMutation;
getPreviewConfigOptions: TrpcQuery;
onSessionEvent: TrpcSubscription;
onPermissionRequest: TrpcSubscription;
onSessionIdleKilled: TrpcSubscription;
};
workspace: { verify: TrpcQuery };
cloudTask: {
watch: TrpcMutation;
unwatch: TrpcMutation;
retry: TrpcMutation;
sendCommand: TrpcMutation;
stop: TrpcMutation;
designateRelayedMcpServers: TrpcMutation;
onUpdate: TrpcSubscription;
};
handoff: {
execute: TrpcMutation;
executeToCloud: TrpcMutation;
preflight: TrpcQuery;
preflightToCloud: TrpcQuery;
};
logs: {
readLocalLogs: TrpcQuery;
/** Optional: merges superseded tool_call_update snapshots server-side so
* a tool-heavy log doesn't ship its full redundant history over IPC.
* Presence can't be trusted on proxy-based hosts (a tRPC client fabricates
* a query for any path), so callers fall back to `readLocalLogs` when the
* call itself fails. */
readLocalLogsCollapsed?: TrpcQuery;
/** Optional: only the Electron host exposes the tail read. Core feature-
* detects and falls back to a full read when it's absent. */
readLocalLogsTail?: TrpcQuery;
fetchS3Logs: TrpcQuery;
writeLocalLogs: TrpcMutation;
};
os: { openExternal: TrpcMutation };
}
export interface ISessionStore {
setSession(session: AgentSession): void;
removeSession(taskRunId: string): void;
updateSession(taskRunId: string, updates: Partial<AgentSession>): void;
appendEvents(
taskRunId: string,
events: AcpMessage[],
newLineCount?: number,
): void;
evictEvents(taskRunId: string): void;
restoreEvents(
taskRunId: string,
events: AcpMessage[],
lineCount: number,
): void;
updateCloudStatus(
taskRunId: string,
fields: {
status?: TaskRunStatus;
stage?: string | null;
output?: Record<string, unknown> | null;
errorMessage?: string | null;
branch?: string | null;
},
): void;
setPendingPermissions(
taskRunId: string,
permissions: Map<string, PermissionRequest>,
): void;
enqueueMessage(
taskId: string,
content: string,
rawPrompt?: string | ContentBlock[],
): void;
removeQueuedMessage(taskId: string, messageId: string): void;
updateQueuedMessage(
taskId: string,
messageId: string,
patch: { content: string; rawPrompt?: string | ContentBlock[] },
): void;
setEditingQueuedMessage(taskId: string, messageId: string): void;
clearEditingQueuedMessage(taskId: string): void;
clearMessageQueue(taskId: string): void;
dequeueMessagesAsText(
taskId: string,
options?: { stopAtEdited?: boolean; max?: number },
): string | null;
dequeueMessages(
taskId: string,
options?: { stopAtEdited?: boolean; max?: number },
): QueuedMessage[];
prependQueuedMessages(taskId: string, messages: QueuedMessage[]): void;
appendOptimisticItem(
taskRunId: string,
item: OptimisticItem extends infer T
? T extends { id: string }
? Omit<T, "id">
: never
: never,
): void;
clearOptimisticItems(taskRunId: string): void;
clearTailOptimisticItems(taskRunId: string): void;
replaceOptimisticWithEvent(taskRunId: string, event: AcpMessage): void;
getSessionByTaskId(taskId: string): AgentSession | undefined;
getSessions(): Record<string, AgentSession>;
}
export interface SessionServiceHelpers {
extractSkillButtonId: (...args: any[]) => any;
combineQueuedCloudPrompts: (...args: any[]) => any;
getCloudPromptTransport: (...args: any[]) => any;
resolveLocalSkillCommandPrompt?: (prompt: string) => Promise<string | null>;
uploadRunAttachments: (
client: CloudArtifactClient,
taskId: string,
runId: string,
filePaths: string[],
skillBundles?: CloudSkillBundleRef[],
) => Promise<string[]>;
uploadTaskStagedAttachments: (
client: CloudArtifactClient,
taskId: string,
filePaths: string[],
skillBundles?: CloudSkillBundleRef[],
) => Promise<string[]>;
}
export interface SessionServiceDeps {
trpc: SessionTrpc;
store: ISessionStore;
h: SessionServiceHelpers;
log: {
info(message: string, data?: unknown): void;
warn(message: string, data?: unknown): void;
error(message: string, data?: unknown): void;
debug(message: string, data?: unknown): void;
};
toast: {
error: (msg: any, opts?: any) => unknown;
info: (msg: any, opts?: any) => unknown;
};
track: (event: string, props?: Record<string, unknown>) => void;
buildPermissionToolMetadata: (...args: any[]) => any;
notifyPermissionRequest: (...args: any[]) => any;
notifyPromptComplete: (...args: any[]) => any;
enqueueSpeech: (request: {
text: string;
taskTitle: string;
taskId?: string;
kind: SpeechKind;
source: SpeechSource;
addressByName?: boolean;
}) => void;
getIsOnline: () => boolean;
fetchAuthState: () => Promise<any>;
getAuthenticatedClient: () => Promise<any>;
createAuthenticatedClient: (authState: any) => any;
getPersistedConfigOptions: (
taskRunId: string,
) => SessionConfigOption[] | undefined;
setPersistedConfigOptions: (
taskRunId: string,
options: SessionConfigOption[],
) => void;
removePersistedConfigOptions: (taskRunId: string) => void;
adapterStore: {
getAdapter(taskRunId: string): Adapter | undefined;
setAdapter(taskRunId: string, adapter: Adapter): void;
removeAdapter(taskRunId: string): void;
};
readonly settings: {
customInstructions?: string | null;
rtkEnabledLocal?: boolean;
rtkEnabledCloud?: boolean;
spokenNotifications?: boolean;
spokenNarrationEnabled?: boolean;
};
usageLimit: { show: (...args: any[]) => any };
readonly addDirectoryDialog: { open: boolean };
taskViewedApi: { markActivity(taskId: string): void };
queryClient: {
invalidateQueries: (filters?: any) => any;
refetchQueries: (filters?: any) => any;
};
DEFAULT_GATEWAY_MODEL: string;
WORKSPACE_QUERY_KEY: any;
}
type AuthClient = NonNullable<
Awaited<ReturnType<SessionServiceDeps["getAuthenticatedClient"]>>
>;
interface AuthCredentials {
apiHost: string;
projectId: number;
client: AuthClient;
}
type AuthCredentialsStatus =
| { kind: "ready"; auth: AuthCredentials }
| { kind: "restoring" }
| { kind: "missing" };
export interface ConnectParams {
task: Task;
repoPath: string;
initialPrompt?: ContentBlock[];
executionMode?: ExecutionMode;
adapter?: Adapter;
model?: string;
reasoningLevel?: string;
/**
* Session ID of an imported Claude Code CLI transcript already copied into
* the app's Claude config dir. The agent loads it and replays its history.
*/
importedSessionId?: string;
}
export interface CloudConnectionAuth {
status: string;
bootstrapComplete?: boolean;
projectId?: number | null;
cloudRegion?: CloudRegion | null;
}
export interface ReconcileSessionState {
taskRunId: string;
taskId: string;
taskTitle: string;
status: AgentSession["status"];
isCloud?: boolean;
idleKilled?: boolean;
eventCount: number;
}
export interface ReconcileTaskConnectionParams {
task: Task;
session: ReconcileSessionState | undefined;
repoPath: string | null;
isCloud: boolean;
isSuspended?: boolean;
isOnline: boolean;
cloudAuth: CloudConnectionAuth;
onCloudStatusChange?: () => void;
}
const ACTIVITY_HEARTBEAT_INTERVAL_MS = 5 * 60 * 1000;
export type SessionPlan = Extract<SessionUpdate, { sessionUpdate: "plan" }>;
export function selectLatestPlan(events: AcpMessage[]): SessionPlan | null {
let planIndex = -1;
let plan: SessionPlan | null = null;
let turnEndResponseIndex = -1;
for (let i = events.length - 1; i >= 0; i--) {
const msg = events[i].message;
if (
turnEndResponseIndex === -1 &&
isJsonRpcResponse(msg) &&
(msg.result as { stopReason?: string })?.stopReason !== undefined
) {
turnEndResponseIndex = i;
}
if (
planIndex === -1 &&
isJsonRpcNotification(msg) &&
msg.method === "session/update"
) {
const update = (msg.params as { update?: { sessionUpdate?: string } })
?.update;
if (update?.sessionUpdate === "plan") {
planIndex = i;
plan = update as SessionPlan;
}
}
if (planIndex !== -1 && turnEndResponseIndex !== -1) break;
}
if (turnEndResponseIndex > planIndex) return null;
return plan;
}
export function createLatestPlanTracker() {
return createAppendOnlyTracker<
{ plan: SessionPlan | null },
SessionPlan | null
>({
init: () => ({ plan: null }),
processEvent: (state, event) => {
const msg = event.message;
if (
isJsonRpcResponse(msg) &&
(msg.result as { stopReason?: string })?.stopReason !== undefined
) {
state.plan = null;
return;
}
if (isJsonRpcNotification(msg) && msg.method === "session/update") {
const update = (msg.params as { update?: { sessionUpdate?: string } })
?.update;
if (update?.sessionUpdate === "plan") {
state.plan = update as SessionPlan;
}
}
},
getResult: (state) => state.plan,
});
}
export const SESSION_SERVICE = Symbol.for("posthog.core.sessions.service");
type DerivedPermissionRequest = Pick<
CloudTaskPermissionRequestUpdate,
"requestId" | "toolCall" | "options"
>;
function getEntryTaskRunMarker(entry: StoredLogEntry): string | undefined {
const method = entry.notification?.method;
if (!method) return undefined;
const params = (entry.notification?.params ?? {}) as {
runId?: unknown;
taskRunId?: unknown;
};
if (
isNotification(method, POSTHOG_NOTIFICATIONS.SDK_SESSION) &&
typeof params.taskRunId === "string"
) {
return params.taskRunId;
}
if (
isNotification(method, POSTHOG_NOTIFICATIONS.RUN_STARTED) &&
typeof params.runId === "string"
) {
return params.runId;
}
return undefined;
}
function entriesScopedToTaskRun(
entries: StoredLogEntry[],
taskRunId: string | undefined,
): StoredLogEntry[] {
if (!taskRunId || !entries.some((entry) => getEntryTaskRunMarker(entry))) {
return entries;
}
let currentTaskRunId: string | undefined;
return entries.filter((entry) => {
const marker = getEntryTaskRunMarker(entry);
if (marker) {
currentTaskRunId = marker;
}
return currentTaskRunId === taskRunId;
});
}
export function derivePendingPermissionRequests(
entries: StoredLogEntry[],
options?: { taskRunId?: string },
): DerivedPermissionRequest[] {
const requests = new Map<string, DerivedPermissionRequest>();
const resolved = new Set<string>();
for (const entry of entriesScopedToTaskRun(entries, options?.taskRunId)) {
const method = entry.notification?.method;
if (!method) continue;
const params = (entry.notification?.params ?? {}) as {
requestId?: string;
toolCall?: CloudTaskPermissionRequestUpdate["toolCall"];
options?: CloudTaskPermissionRequestUpdate["options"];
};
if (typeof params.requestId !== "string") continue;
if (isNotification(method, POSTHOG_NOTIFICATIONS.PERMISSION_RESOLVED)) {
resolved.add(params.requestId);
} else if (
isNotification(method, POSTHOG_NOTIFICATIONS.PERMISSION_REQUEST) &&
typeof params.toolCall?.toolCallId === "string" &&
Array.isArray(params.options)
) {
requests.set(params.requestId, {
requestId: params.requestId,
toolCall: params.toolCall,
options: params.options,
});
}
}
return [...requests.values()].filter((r) => !resolved.has(r.requestId));
}
/**
* Whether a derived permission request has already been surfaced for this
* session. Snapshot replays re-deliver still-pending requests on every
* bootstrap and re-subscribe; only the first delivery should notify. A
* different requestId for the same tool call is a new ask and must notify.
*/
export function isPermissionRequestAlreadySurfaced(
pendingPermissions: ReadonlyMap<string, unknown>,
trackedRequestId: string | undefined,
update: DerivedPermissionRequest,
): boolean {
return (
trackedRequestId === update.requestId &&
pendingPermissions.has(update.toolCall.toolCallId)
);
}
/** The steering capability on a loosely-typed agent start/reconnect result. */
function readSteering(result: unknown): string | undefined {
return (result as { steering?: string } | undefined)?.steering;
}
function classifyTurnEventKind(
msg: AcpMessage["message"],
): "text" | "output" | "other" {
if (!("method" in msg) || msg.method !== "session/update") return "other";
const update = (msg as { params?: { update?: Record<string, unknown> } })
.params?.update;
if (!update) return "other";
const sessionUpdate = update.sessionUpdate;
if (sessionUpdate === "agent_message_chunk") {
const content = update.content as { type?: string } | undefined;
return content?.type === "text" ? "text" : "output";
}
if (
sessionUpdate === "agent_thought_chunk" ||
sessionUpdate === "tool_call" ||
sessionUpdate === "tool_call_update"
) {
return "output";
}
return "other";
}
export class SessionService {
private connectingTasks = new Map<string, Promise<void>>();
private reconcilingTasks = new Set<string>();
private reconcileSkipLogged = new Set<string>();
private taskCreationMarks = new Map<string, number>();
private static readonly TASK_CREATION_IN_FLIGHT_TTL_MS = 10 * 60 * 1000;
private activityHeartbeats = new Map<
string,
ReturnType<typeof setInterval>
>();
private localRepoPaths = new Map<string, string>();
private localRecoveryAttempts = new Map<string, Promise<boolean>>();
private sessionLastUsedAt = new Map<string, number>();
private mountedTaskCounts = new Map<string, number>();
/** Re-entrance guard for cloud queue dispatch (per taskId). */
private dispatchingCloudQueues = new Set<string>();
/** Coalesces deferred cloud queue flush timers (per taskId). */
private scheduledCloudQueueFlushes = new Set<string>();
private cloudRunIdleTracker: CloudRunIdleTracker;
private nextCloudTaskWatchToken = 0;
private supersededRunIds = new Set<string>();
// Spoken narration: the `speak` tool's { text, kind } args stream in across
// multiple tool_call_updates (partial input_json_delta), so early events carry
// a truncated text like "The quick b". Track speak tool calls by id and
// accumulate their latest args; enqueue once the call reaches a terminal
// status (full text), then delete the entry — which also dedupes re-fires.
// A `null` value means "identified as speak, args not streamed in yet".
// Keyed by taskRunId first so a session teardown can drop any of its
// still-streaming speak calls (see unsubscribeFromChannel); the inner map is
// keyed by toolCallId.
private speakCalls = new Map<
string,
Map<string, { text: string; kind: SpeechKind } | null>
>();
// When the agent last narrated `done`/`needs_input` per task run (event ts).
// The deterministic completion/needs-input backstops compare this against the
// turn's start so they don't double up on a moment the agent already voiced.
private agentSpokeAt = new Map<
string,
{ needs_input: number; done: number }
>();
private subscriptions = new Map<
string,
{
event: { unsubscribe: () => void };
permission?: { unsubscribe: () => void };
}
>();
/** Active cloud task watchers, keyed by taskId */
private cloudTaskWatchers = new Map<
string,
{
runId: string;
apiHost: string;
teamId: number;
startToken: number;
subscription: { unsubscribe: () => void };
onStatusChange?: () => void;
}
>();
private cloudLogGapReconciler: CloudLogGapReconciler;
/** Maps toolCallId → cloud requestId for routing permission responses */
private cloudPermissionRequestIds = new Map<string, string>();
/**
* Cloud permission requestIds the user has already responded to this app
* session. A stale snapshot (a resolved marker not yet flushed to storage)
* or a replayed stream frame can re-deliver an answered request; without
* this guard it would re-surface as a fresh pending card.
*/
private respondedCloudPermissionRequestIds = new Set<string>();
private liveTurnContent = new Map<
string,
{ startedAtTs: number; agentTextChunks: number; agentOutputEvents: number }
>();
private pendingPermissionHydratedRuns = new Set<string>();
private idleKilledSubscription: { unsubscribe: () => void } | null = null;
/**
* Cached preview-config-options responses keyed by `${apiHost}::${adapter}`.
* Shared across cloud sessions so switching model/adapter reuses the list.
*/
private previewConfigOptionsCache = new Map<
string,
{ promise: Promise<SessionConfigOption[]>; fetchedAt: number }
>();
/**
* Initial cloud prompt text (user message + any channel CONTEXT.md block),
* stashed by task creation keyed by taskId. The cloud sandbox takes seconds to
* boot and echo this back, so the optimistic placeholder would otherwise show
* the bare task description with no CONTEXT.md chip until the echo lands. Seed
* the placeholder with this richer text instead, then drop it once consumed.
*/
private initialCloudOptimisticPrompt = new Map<string, string>();
constructor(private readonly d: SessionServiceDeps) {
this.cloudRunIdleTracker = new CloudRunIdleTracker();
this.cloudLogGapReconciler = new CloudLogGapReconciler({
fetchLogs: (logUrl, taskRunId, minEntryCount) =>
this.fetchSessionLogs(logUrl, taskRunId, { minEntryCount }),
getSession: (taskRunId) => {
const session = d.store.getSessions()[taskRunId];
if (!session) return undefined;
return {
taskId: session.taskId,
processedLineCount: session.processedLineCount ?? 0,
logUrl: session.logUrl,
};
},
commit: (taskRunId, rawEntries, logUrl, processedLineCount) =>
this.commitReconciledCloudEvents(
taskRunId,
rawEntries,
logUrl,
processedLineCount,
),
logger: d.log,
});
this.idleKilledSubscription = d.trpc.agent.onSessionIdleKilled.subscribe(
undefined,
{
onData: (event: { taskRunId: string }) => {
const { taskRunId } = event;
d.log.info("Session idle-killed by main process", { taskRunId });
this.handleIdleKill(taskRunId);
},
onError: (err: unknown) => {
d.log.debug("Idle-killed subscription error", { error: err });
},
},
);
}
/**
* Connect to a task session.
* Uses locking to prevent duplicate concurrent connections.
*/
async connectToTask(params: ConnectParams): Promise<void> {
const { task } = params;
const taskId = task.id;
this.taskCreationMarks.delete(taskId);
this.localRepoPaths.set(taskId, params.repoPath);
this.sessionLastUsedAt.set(taskId, Date.now());
void this.evictIdleSessions(taskId);
// Return existing connection promise if already connecting
const existingPromise = this.connectingTasks.get(taskId);
if (existingPromise) {
return existingPromise;
}
// Check for existing connected session
const existingSession = this.d.store.getSessionByTaskId(taskId);
if (existingSession?.status === "connected") {
this.d.log.info("Already connected to task", { taskId });
return;
}
if (existingSession?.status === "connecting") {
this.d.log.info("Session already in connecting state", { taskId });
return;
}
// Create and store the connection promise
const connectPromise = this.doConnect(params).finally(() => {
this.connectingTasks.delete(taskId);
});
this.connectingTasks.set(taskId, connectPromise);
return connectPromise;
}
private stampRunConfig(session: AgentSession, params: ConnectParams): void {
session.adapter = params.adapter;
session.model = params.model;
session.executionMode = params.executionMode;
session.reasoningLevel = params.reasoningLevel;
if (params.initialPrompt?.length) {
session.initialPrompt = params.initialPrompt;
}
}
private async doConnect(params: ConnectParams): Promise<void> {
const {
task,
repoPath,
initialPrompt,
executionMode,
adapter,
model,
reasoningLevel,
importedSessionId,
} = params;
const { id: taskId, latest_run: latestRun } = task;
const taskTitle = task.title || task.description || "Task";
if (latestRun?.environment === "cloud") {
this.d.log.info("Skipping local session connect for cloud run", {
taskId,
taskRunId: latestRun.id,
});
return;
}
try {
const authStatus = await this.getAuthCredentialsStatus();
if (authStatus.kind === "restoring") {
throw new Error("Authentication is still restoring. Please wait.");
}
const auth = authStatus.kind === "ready" ? authStatus.auth : null;
const route = routeLocalConnect({
hasAuth: auth !== null,
latestRunId: latestRun?.id,
latestRunLogUrl: latestRun?.log_url,
});
if (route.kind === "no-auth" || !auth) {
this.d.log.error("Missing auth credentials");
const taskRunId = latestRun?.id ?? `error-${taskId}`;
const session = createBaseSession(taskRunId, taskId, taskTitle);
session.status = "error";
session.errorMessage =
"Authentication required. Please sign in to continue.";
this.stampRunConfig(session, params);
this.d.store.setSession(session);
return;
}
if (route.kind === "resume-existing") {
const { taskRunId: existingRunId, logUrl } = route;
if (!this.d.getIsOnline()) {
this.d.log.info("Skipping connection attempt - offline", { taskId });
const { rawEntries } = await this.fetchSessionLogs(
logUrl,
existingRunId,
);
const events = convertStoredEntriesToEvents(rawEntries);
const session = createBaseSession(existingRunId, taskId, taskTitle);
session.events = events;
session.logUrl = logUrl;
session.status = "disconnected";
session.errorMessage = OFFLINE_SESSION_MESSAGE;
this.d.store.setSession(session);
return;
}
// Paint the log tail immediately so a big transcript is visible in tens
// of ms; the full read + reconnect replace it with the authoritative
// session once everything below resolves.
const [workspaceResult, logResult] = await Promise.all([
this.d.trpc.workspace.verify.query({ taskId }),
this.fetchSessionLogs(logUrl, existingRunId),
this.paintTailFirst(existingRunId, taskId, taskTitle, logUrl),
]);
if (!workspaceResult.exists) {
this.d.log.warn("Workspace no longer exists, showing error state", {
taskId,
missingPath: workspaceResult.missingPath,
});
const events = convertStoredEntriesToEvents(logResult.rawEntries);
const session = createBaseSession(existingRunId, taskId, taskTitle);
session.events = events;
session.logUrl = logUrl;
session.status = "error";
session.errorMessage = workspaceResult.missingPath
? `Working directory no longer exists: ${workspaceResult.missingPath}`
: "The working directory for this task no longer exists. Please start a new session.";
this.d.store.setSession(session);
return;
}
await this.reconnectToLocalSession(
taskId,
existingRunId,
taskTitle,
logUrl,
repoPath,
auth,
logResult,
);
} else {
if (!this.d.getIsOnline()) {
this.d.log.info("Skipping connection attempt - offline", { taskId });
const taskRunId = latestRun?.id ?? `offline-${taskId}`;
const session = createBaseSession(taskRunId, taskId, taskTitle);
session.status = "disconnected";
session.errorMessage =
"No internet connection. Connect when you're back online.";
this.d.store.setSession(session);
return;
}
await this.createNewLocalSession(
taskId,
taskTitle,
repoPath,
auth,
initialPrompt,
executionMode,
adapter,
model,
reasoningLevel,
importedSessionId,
);
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.d.log.error("Failed to connect to task", { message });
const taskRunId = latestRun?.id ?? `error-${taskId}`;
const session = createBaseSession(taskRunId, taskId, taskTitle);
this.stampRunConfig(session, params);
if (latestRun?.log_url) {
try {
const { rawEntries } = await this.fetchSessionLogs(
latestRun.log_url,
latestRun.id,
);
session.events = convertStoredEntriesToEvents(rawEntries);
session.logUrl = latestRun.log_url;
} catch {
// Ignore log fetch errors
}
}
const shouldAutoRetry = this.d.getIsOnline();
session.status = shouldAutoRetry ? "connecting" : "error";
if (!shouldAutoRetry) {
session.errorTitle = "Failed to connect";
session.errorMessage = message;
}
this.d.store.setSession(session);
if (!shouldAutoRetry) return;
let lastRetryMessage = message;
let wentOffline = false;
let restoringWaits = 0;
let attempt = 0;
while (attempt < AUTO_RETRY_MAX_ATTEMPTS) {
await new Promise((resolve) =>
setTimeout(resolve, AUTO_RETRY_DELAY_MS),
);
if (!this.d.getIsOnline()) {
this.d.log.warn("Skipping retry — device went offline", { taskId });
wentOffline = true;
break;
}
// Wait out an in-flight restore instead of spending a retry on
// clearSessionError, which tears the connecting session down.
if (
restoringWaits < AUTH_RESTORE_MAX_RETRY_WAITS &&
(await this.getAuthCredentialsStatus()).kind === "restoring"
) {
restoringWaits++;
this.d.log.info("Auth still restoring; keeping session connecting", {
taskId,
restoringWaits,
});
continue;
}
attempt++;
this.d.log.warn("Auto-retrying failed connection", {
taskId,
attempt,
delayMs: AUTO_RETRY_DELAY_MS,
});
try {
await this.clearSessionError(taskId, repoPath);
return;
} catch (retryError) {
lastRetryMessage =
retryError instanceof Error
? retryError.message
: String(retryError);
this.d.log.error("Auto-retry via clearSessionError failed", {
taskId,
attempt,
error: lastRetryMessage,
});
}
}
const currentSession = this.d.store.getSessionByTaskId(taskId);
if (!currentSession) return;
this.d.store.updateSession(
currentSession.taskRunId,
computeAutoRetryFinalState({
wentOffline,
lastRetryMessage,
originalMessage: message,
}),
);
}