forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbridgeMain.ts
More file actions
2999 lines (2809 loc) · 113 KB
/
Copy pathbridgeMain.ts
File metadata and controls
2999 lines (2809 loc) · 113 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 { feature } from 'bun:bundle'
import { randomUUID } from 'crypto'
import { hostname, tmpdir } from 'os'
import { basename, join, resolve } from 'path'
import { getRemoteSessionUrl } from '../constants/product.js'
import { shutdownDatadog } from '../services/analytics/datadog.js'
import { shutdown1PEventLogging } from '../services/analytics/firstPartyEventLogger.js'
import { checkGate_CACHED_OR_BLOCKING } from '../services/analytics/growthbook.js'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
logEventAsync,
} from '../services/analytics/index.js'
import { isInBundledMode } from '../utils/bundledMode.js'
import { logForDebugging } from '../utils/debug.js'
import { logForDiagnosticsNoPII } from '../utils/diagLogs.js'
import { isEnvTruthy, isInProtectedNamespace } from '../utils/envUtils.js'
import { errorMessage } from '../utils/errors.js'
import { truncateToWidth } from '../utils/format.js'
import { logError } from '../utils/log.js'
import { sleep } from '../utils/sleep.js'
import { createAgentWorktree, removeAgentWorktree } from '../utils/worktree.js'
import {
BridgeFatalError,
createBridgeApiClient,
isExpiredErrorType,
isSuppressible403,
validateBridgeId,
} from './bridgeApi.js'
import { formatDuration } from './bridgeStatusUtil.js'
import { createBridgeLogger } from './bridgeUI.js'
import { createCapacityWake } from './capacityWake.js'
import { describeAxiosError } from './debugUtils.js'
import { createTokenRefreshScheduler } from './jwtUtils.js'
import { getPollIntervalConfig } from './pollConfig.js'
import { toCompatSessionId, toInfraSessionId } from './sessionIdCompat.js'
import { createSessionSpawner, safeFilenameId } from './sessionRunner.js'
import { getTrustedDeviceToken } from './trustedDevice.js'
import {
BRIDGE_LOGIN_ERROR,
type BridgeApiClient,
type BridgeConfig,
type BridgeLogger,
DEFAULT_SESSION_TIMEOUT_MS,
type SessionDoneStatus,
type SessionHandle,
type SessionSpawner,
type SessionSpawnOpts,
type SpawnMode,
} from './types.js'
import {
buildCCRv2SdkUrl,
buildSdkUrl,
decodeWorkSecret,
registerWorker,
sameSessionId,
} from './workSecret.js'
export type BackoffConfig = {
connInitialMs: number
connCapMs: number
connGiveUpMs: number
generalInitialMs: number
generalCapMs: number
generalGiveUpMs: number
/** SIGTERM→SIGKILL grace period on shutdown. Default 30s. */
shutdownGraceMs?: number
/** stopWorkWithRetry base delay (1s/2s/4s backoff). Default 1000ms. */
stopWorkBaseDelayMs?: number
}
const DEFAULT_BACKOFF: BackoffConfig = {
connInitialMs: 2_000,
connCapMs: 120_000, // 2 minutes
connGiveUpMs: 600_000, // 10 minutes
generalInitialMs: 500,
generalCapMs: 30_000,
generalGiveUpMs: 600_000, // 10 minutes
}
/** Status update interval for the live display (ms). */
const STATUS_UPDATE_INTERVAL_MS = 1_000
const SPAWN_SESSIONS_DEFAULT = 32
/**
* GrowthBook gate for multi-session spawn modes (--spawn / --capacity / --create-session-in-dir).
* Sibling of tengu_ccr_bridge_multi_environment (multiple envs per host:dir) —
* this one enables multiple sessions per environment.
* Rollout staged via targeting rules: ants first, then gradual external.
*
* Uses the blocking gate check so a stale disk-cache miss doesn't unfairly
* deny access. The fast path (cache has true) is still instant; only the
* cold-start path awaits the server fetch, and that fetch also seeds the
* disk cache for next time.
*/
async function isMultiSessionSpawnEnabled(): Promise<boolean> {
return checkGate_CACHED_OR_BLOCKING('tengu_ccr_bridge_multi_session')
}
/**
* Returns the threshold for detecting system sleep/wake in the poll loop.
* Must exceed the max backoff cap — otherwise normal backoff delays trigger
* false sleep detection (resetting the error budget indefinitely). Using
* 2× the connection backoff cap, matching the pattern in WebSocketTransport
* and replBridge.
*/
function pollSleepDetectionThresholdMs(backoff: BackoffConfig): number {
return backoff.connCapMs * 2
}
/**
* Returns the args that must precede CLI flags when spawning a child claude
* process. In compiled binaries, process.execPath is the claude binary itself
* and args go directly to it. In npm installs (node running cli.js),
* process.execPath is the node runtime — the child spawn must pass the script
* path as the first arg, otherwise node interprets --sdk-url as a node option
* and exits with "bad option: --sdk-url". See anthropics/claude-code#28334.
*/
function spawnScriptArgs(): string[] {
if (isInBundledMode() || !process.argv[1]) {
return []
}
return [process.argv[1]]
}
/** Attempt to spawn a session; returns error string if spawn throws. */
function safeSpawn(
spawner: SessionSpawner,
opts: SessionSpawnOpts,
dir: string,
): SessionHandle | string {
try {
return spawner.spawn(opts, dir)
} catch (err) {
const errMsg = errorMessage(err)
logError(new Error(`Session spawn failed: ${errMsg}`))
return errMsg
}
}
export async function runBridgeLoop(
config: BridgeConfig,
environmentId: string,
environmentSecret: string,
api: BridgeApiClient,
spawner: SessionSpawner,
logger: BridgeLogger,
signal: AbortSignal,
backoffConfig: BackoffConfig = DEFAULT_BACKOFF,
initialSessionId?: string,
getAccessToken?: () => string | undefined | Promise<string | undefined>,
): Promise<void> {
// Local abort controller so that onSessionDone can stop the poll loop.
// Linked to the incoming signal so external aborts also work.
const controller = new AbortController()
if (signal.aborted) {
controller.abort()
} else {
signal.addEventListener('abort', () => controller.abort(), { once: true })
}
const loopSignal = controller.signal
const activeSessions = new Map<string, SessionHandle>()
const sessionStartTimes = new Map<string, number>()
const sessionWorkIds = new Map<string, string>()
// Compat-surface ID (session_*) computed once at spawn and cached so
// cleanup and status-update ticks use the same key regardless of whether
// the tengu_bridge_repl_v2_cse_shim_enabled gate flips mid-session.
const sessionCompatIds = new Map<string, string>()
// Session ingress JWTs for heartbeat auth, keyed by sessionId.
// Stored separately from handle.accessToken because the token refresh
// scheduler overwrites that field with the OAuth token (~3h55m in).
const sessionIngressTokens = new Map<string, string>()
const sessionTimers = new Map<string, ReturnType<typeof setTimeout>>()
const completedWorkIds = new Set<string>()
const sessionWorktrees = new Map<
string,
{
worktreePath: string
worktreeBranch?: string
gitRoot?: string
hookBased?: boolean
}
>()
// Track sessions killed by the timeout watchdog so onSessionDone can
// distinguish them from server-initiated or shutdown interrupts.
const timedOutSessions = new Set<string>()
// Sessions that already have a title (server-set or bridge-derived) so
// onFirstUserMessage doesn't clobber a user-assigned --name / web rename.
// Keyed by compatSessionId to match logger.setSessionTitle's key.
const titledSessions = new Set<string>()
// Signal to wake the at-capacity sleep early when a session completes,
// so the bridge can immediately accept new work.
const capacityWake = createCapacityWake(loopSignal)
/**
* Heartbeat all active work items.
* Returns 'ok' if at least one heartbeat succeeded, 'auth_failed' if any
* got a 401/403 (JWT expired — re-queued via reconnectSession so the next
* poll delivers fresh work), or 'failed' if all failed for other reasons.
*/
async function heartbeatActiveWorkItems(): Promise<
'ok' | 'auth_failed' | 'fatal' | 'failed'
> {
let anySuccess = false
let anyFatal = false
const authFailedSessions: string[] = []
for (const [sessionId] of activeSessions) {
const workId = sessionWorkIds.get(sessionId)
const ingressToken = sessionIngressTokens.get(sessionId)
if (!workId || !ingressToken) {
continue
}
try {
await api.heartbeatWork(environmentId, workId, ingressToken)
anySuccess = true
} catch (err) {
logForDebugging(
`[bridge:heartbeat] Failed for sessionId=${sessionId} workId=${workId}: ${errorMessage(err)}`,
)
if (err instanceof BridgeFatalError) {
logEvent('tengu_bridge_heartbeat_error', {
status:
err.status as unknown as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
error_type: (err.status === 401 || err.status === 403
? 'auth_failed'
: 'fatal') as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
if (err.status === 401 || err.status === 403) {
authFailedSessions.push(sessionId)
} else {
// 404/410 = environment expired or deleted — no point retrying
anyFatal = true
}
}
}
}
// JWT expired → trigger server-side re-dispatch. Without this, work stays
// ACK'd out of the Redis PEL and poll returns empty forever (CC-1263).
// The existingHandle path below delivers the fresh token to the child.
// sessionId is already in the format /bridge/reconnect expects: it comes
// from work.data.id, which matches the server's EnvironmentInstance store
// (cse_* under the compat gate, session_* otherwise).
for (const sessionId of authFailedSessions) {
logger.logVerbose(
`Session ${sessionId} token expired — re-queuing via bridge/reconnect`,
)
try {
await api.reconnectSession(environmentId, sessionId)
logForDebugging(
`[bridge:heartbeat] Re-queued sessionId=${sessionId} via bridge/reconnect`,
)
} catch (err) {
logger.logError(
`Failed to refresh session ${sessionId} token: ${errorMessage(err)}`,
)
logForDebugging(
`[bridge:heartbeat] reconnectSession(${sessionId}) failed: ${errorMessage(err)}`,
{ level: 'error' },
)
}
}
if (anyFatal) {
return 'fatal'
}
if (authFailedSessions.length > 0) {
return 'auth_failed'
}
return anySuccess ? 'ok' : 'failed'
}
// Sessions spawned with CCR v2 env vars. v2 children cannot use OAuth
// tokens (CCR worker endpoints validate the JWT's session_id claim,
// register_worker.go:32), so onRefresh triggers server re-dispatch
// instead — the next poll delivers fresh work with a new JWT via the
// existingHandle path below.
const v2Sessions = new Set<string>()
// Proactive token refresh: schedules a timer 5min before the session
// ingress JWT expires. v1 delivers OAuth directly; v2 calls
// reconnectSession to trigger server re-dispatch (CC-1263: without
// this, v2 daemon sessions silently die at ~5h since the server does
// not auto-re-dispatch ACK'd work on lease expiry).
const tokenRefresh = getAccessToken
? createTokenRefreshScheduler({
getAccessToken,
onRefresh: (sessionId, oauthToken) => {
const handle = activeSessions.get(sessionId)
if (!handle) {
return
}
if (v2Sessions.has(sessionId)) {
logger.logVerbose(
`Refreshing session ${sessionId} token via bridge/reconnect`,
)
void api
.reconnectSession(environmentId, sessionId)
.catch((err: unknown) => {
logger.logError(
`Failed to refresh session ${sessionId} token: ${errorMessage(err)}`,
)
logForDebugging(
`[bridge:token] reconnectSession(${sessionId}) failed: ${errorMessage(err)}`,
{ level: 'error' },
)
})
} else {
handle.updateAccessToken(oauthToken)
}
},
label: 'bridge',
})
: null
const loopStartTime = Date.now()
// Track all in-flight cleanup promises (stopWork, worktree removal) so
// the shutdown sequence can await them before process.exit().
const pendingCleanups = new Set<Promise<unknown>>()
function trackCleanup(p: Promise<unknown>): void {
pendingCleanups.add(p)
void p.finally(() => pendingCleanups.delete(p))
}
let connBackoff = 0
let generalBackoff = 0
let connErrorStart: number | null = null
let generalErrorStart: number | null = null
let lastPollErrorTime: number | null = null
let statusUpdateTimer: ReturnType<typeof setInterval> | null = null
// Set by BridgeFatalError and give-up paths so the shutdown block can
// skip the resume message (resume is impossible after env expiry/auth
// failure/sustained connection errors).
let fatalExit = false
logForDebugging(
`[bridge:work] Starting poll loop spawnMode=${config.spawnMode} maxSessions=${config.maxSessions} environmentId=${environmentId}`,
)
logForDiagnosticsNoPII('info', 'bridge_loop_started', {
max_sessions: config.maxSessions,
spawn_mode: config.spawnMode,
})
// For ant users, show where session debug logs will land so they can tail them.
// sessionRunner.ts uses the same base path. File appears once a session spawns.
if (process.env.USER_TYPE === 'ant') {
let debugGlob: string
if (config.debugFile) {
const ext = config.debugFile.lastIndexOf('.')
debugGlob =
ext > 0
? `${config.debugFile.slice(0, ext)}-*${config.debugFile.slice(ext)}`
: `${config.debugFile}-*`
} else {
debugGlob = join(tmpdir(), 'claude', 'bridge-session-*.log')
}
logger.setDebugLogPath(debugGlob)
}
logger.printBanner(config, environmentId)
// Seed the logger's session count + spawn mode before any render. Without
// this, setAttached() below renders with the logger's default sessionMax=1,
// showing "Capacity: 0/1" until the status ticker kicks in (which is gated
// by !initialSessionId and only starts after the poll loop picks up work).
logger.updateSessionCount(0, config.maxSessions, config.spawnMode)
// If an initial session was pre-created, show its URL from the start so
// the user can click through immediately (matching /remote-control behavior).
if (initialSessionId) {
logger.setAttached(initialSessionId)
}
/** Refresh the inline status display. Shows idle or active depending on state. */
function updateStatusDisplay(): void {
// Push the session count (no-op when maxSessions === 1) so the
// next renderStatusLine tick shows the current count.
logger.updateSessionCount(
activeSessions.size,
config.maxSessions,
config.spawnMode,
)
// Push per-session activity into the multi-session display.
for (const [sid, handle] of activeSessions) {
const act = handle.currentActivity
if (act) {
logger.updateSessionActivity(sessionCompatIds.get(sid) ?? sid, act)
}
}
if (activeSessions.size === 0) {
logger.updateIdleStatus()
return
}
// Show the most recently started session that is still actively working.
// Sessions whose current activity is 'result' or 'error' are between
// turns — the CLI emitted its result but the process stays alive waiting
// for the next user message. Skip updating so the status line keeps
// whatever state it had (Attached / session title).
const [sessionId, handle] = [...activeSessions.entries()].pop()!
const startTime = sessionStartTimes.get(sessionId)
if (!startTime) return
const activity = handle.currentActivity
if (!activity || activity.type === 'result' || activity.type === 'error') {
// Session is between turns — keep current status (Attached/titled).
// In multi-session mode, still refresh so bullet-list activities stay current.
if (config.maxSessions > 1) logger.refreshDisplay()
return
}
const elapsed = formatDuration(Date.now() - startTime)
// Build trail from recent tool activities (last 5)
const trail = handle.activities
.filter(a => a.type === 'tool_start')
.slice(-5)
.map(a => a.summary)
logger.updateSessionStatus(sessionId, elapsed, activity, trail)
}
/** Start the status display update ticker. */
function startStatusUpdates(): void {
stopStatusUpdates()
// Call immediately so the first transition (e.g. Connecting → Ready)
// happens without delay, avoiding concurrent timer races.
updateStatusDisplay()
statusUpdateTimer = setInterval(
updateStatusDisplay,
STATUS_UPDATE_INTERVAL_MS,
)
}
/** Stop the status display update ticker. */
function stopStatusUpdates(): void {
if (statusUpdateTimer) {
clearInterval(statusUpdateTimer)
statusUpdateTimer = null
}
}
function onSessionDone(
sessionId: string,
startTime: number,
handle: SessionHandle,
): (status: SessionDoneStatus) => void {
return (rawStatus: SessionDoneStatus): void => {
const workId = sessionWorkIds.get(sessionId)
activeSessions.delete(sessionId)
sessionStartTimes.delete(sessionId)
sessionWorkIds.delete(sessionId)
sessionIngressTokens.delete(sessionId)
const compatId = sessionCompatIds.get(sessionId) ?? sessionId
sessionCompatIds.delete(sessionId)
logger.removeSession(compatId)
titledSessions.delete(compatId)
v2Sessions.delete(sessionId)
// Clear per-session timeout timer
const timer = sessionTimers.get(sessionId)
if (timer) {
clearTimeout(timer)
sessionTimers.delete(sessionId)
}
// Clear token refresh timer
tokenRefresh?.cancel(sessionId)
// Wake the at-capacity sleep so the bridge can accept new work immediately
capacityWake.wake()
// If the session was killed by the timeout watchdog, treat it as a
// failed session (not a server/shutdown interrupt) so we still call
// stopWork and archiveSession below.
const wasTimedOut = timedOutSessions.delete(sessionId)
const status: SessionDoneStatus =
wasTimedOut && rawStatus === 'interrupted' ? 'failed' : rawStatus
const durationMs = Date.now() - startTime
logForDebugging(
`[bridge:session] sessionId=${sessionId} workId=${workId ?? 'unknown'} exited status=${status} duration=${formatDuration(durationMs)}`,
)
logEvent('tengu_bridge_session_done', {
status:
status as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
duration_ms: durationMs,
})
logForDiagnosticsNoPII('info', 'bridge_session_done', {
status,
duration_ms: durationMs,
})
// Clear the status display before printing final log
logger.clearStatus()
stopStatusUpdates()
// Build error message from stderr if available
const stderrSummary =
handle.lastStderr.length > 0 ? handle.lastStderr.join('\n') : undefined
let failureMessage: string | undefined
switch (status) {
case 'completed':
logger.logSessionComplete(sessionId, durationMs)
break
case 'failed':
// Skip failure log during shutdown — the child exits non-zero when
// killed, which is expected and not a real failure.
// Also skip for timeout-killed sessions — the timeout watchdog
// already logged a clear timeout message.
if (!wasTimedOut && !loopSignal.aborted) {
failureMessage = stderrSummary ?? 'Process exited with error'
logger.logSessionFailed(sessionId, failureMessage)
logError(new Error(`Bridge session failed: ${failureMessage}`))
}
break
case 'interrupted':
logger.logVerbose(`Session ${sessionId} interrupted`)
break
}
// Notify the server that this work item is done. Skip for interrupted
// sessions — interrupts are either server-initiated (the server already
// knows) or caused by bridge shutdown (which calls stopWork() separately).
if (status !== 'interrupted' && workId) {
trackCleanup(
stopWorkWithRetry(
api,
environmentId,
workId,
logger,
backoffConfig.stopWorkBaseDelayMs,
),
)
completedWorkIds.add(workId)
}
// Clean up worktree if one was created for this session
const wt = sessionWorktrees.get(sessionId)
if (wt) {
sessionWorktrees.delete(sessionId)
trackCleanup(
removeAgentWorktree(
wt.worktreePath,
wt.worktreeBranch,
wt.gitRoot,
wt.hookBased,
).catch((err: unknown) =>
logger.logVerbose(
`Failed to remove worktree ${wt.worktreePath}: ${errorMessage(err)}`,
),
),
)
}
// Lifecycle decision: in multi-session mode, keep the bridge running
// after a session completes. In single-session mode, abort the poll
// loop so the bridge exits cleanly.
if (status !== 'interrupted' && !loopSignal.aborted) {
if (config.spawnMode !== 'single-session') {
// Multi-session: archive the completed session so it doesn't linger
// as stale in the web UI. archiveSession is idempotent (409 if already
// archived), so double-archiving at shutdown is safe.
// sessionId arrived as cse_* from the work poll (infrastructure-layer
// tag). archiveSession hits /v1/sessions/{id}/archive which is the
// compat surface and validates TagSession (session_*). Re-tag — same
// UUID underneath.
trackCleanup(
api
.archiveSession(compatId)
.catch((err: unknown) =>
logger.logVerbose(
`Failed to archive session ${sessionId}: ${errorMessage(err)}`,
),
),
)
logForDebugging(
`[bridge:session] Session ${status}, returning to idle (multi-session mode)`,
)
} else {
// Single-session: coupled lifecycle — tear down environment
logForDebugging(
`[bridge:session] Session ${status}, aborting poll loop to tear down environment`,
)
controller.abort()
return
}
}
if (!loopSignal.aborted) {
startStatusUpdates()
}
}
}
// Start the idle status display immediately — unless we have a pre-created
// session, in which case setAttached() already set up the display and the
// poll loop will start status updates when it picks up the session.
if (!initialSessionId) {
startStatusUpdates()
}
while (!loopSignal.aborted) {
// Fetched once per iteration — the GrowthBook cache refreshes every
// 5 min, so a loop running at the at-capacity rate picks up config
// changes within one sleep cycle.
const pollConfig = getPollIntervalConfig()
try {
const work = await api.pollForWork(
environmentId,
environmentSecret,
loopSignal,
pollConfig.reclaim_older_than_ms,
)
// Log reconnection if we were previously disconnected
const wasDisconnected =
connErrorStart !== null || generalErrorStart !== null
if (wasDisconnected) {
const disconnectedMs =
Date.now() - (connErrorStart ?? generalErrorStart ?? Date.now())
logger.logReconnected(disconnectedMs)
logForDebugging(
`[bridge:poll] Reconnected after ${formatDuration(disconnectedMs)}`,
)
logEvent('tengu_bridge_reconnected', {
disconnected_ms: disconnectedMs,
})
}
connBackoff = 0
generalBackoff = 0
connErrorStart = null
generalErrorStart = null
lastPollErrorTime = null
// Null response = no work available in the queue.
// Add a minimum delay to avoid hammering the server.
if (!work) {
// Use live check (not a snapshot) since sessions can end during poll.
const atCap = activeSessions.size >= config.maxSessions
if (atCap) {
const atCapMs = pollConfig.multisession_poll_interval_ms_at_capacity
// Heartbeat loops WITHOUT polling. When at-capacity polling is also
// enabled (atCapMs > 0), the loop tracks a deadline and breaks out
// to poll at that interval — heartbeat and poll compose instead of
// one suppressing the other. We break out to poll when:
// - Poll deadline reached (atCapMs > 0 only)
// - Auth fails (JWT expired → poll refreshes tokens)
// - Capacity wake fires (session ended → poll for new work)
// - Loop aborted (shutdown)
if (pollConfig.non_exclusive_heartbeat_interval_ms > 0) {
logEvent('tengu_bridge_heartbeat_mode_entered', {
active_sessions: activeSessions.size,
heartbeat_interval_ms:
pollConfig.non_exclusive_heartbeat_interval_ms,
})
// Deadline computed once at entry — GB updates to atCapMs don't
// shift an in-flight deadline (next entry picks up the new value).
const pollDeadline = atCapMs > 0 ? Date.now() + atCapMs : null
let hbResult: 'ok' | 'auth_failed' | 'fatal' | 'failed' = 'ok'
let hbCycles = 0
while (
!loopSignal.aborted &&
activeSessions.size >= config.maxSessions &&
(pollDeadline === null || Date.now() < pollDeadline)
) {
// Re-read config each cycle so GrowthBook updates take effect
const hbConfig = getPollIntervalConfig()
if (hbConfig.non_exclusive_heartbeat_interval_ms <= 0) break
// Capture capacity signal BEFORE the async heartbeat call so
// a session ending during the HTTP request is caught by the
// subsequent sleep (instead of being lost to a replaced controller).
const cap = capacityWake.signal()
hbResult = await heartbeatActiveWorkItems()
if (hbResult === 'auth_failed' || hbResult === 'fatal') {
cap.cleanup()
break
}
hbCycles++
await sleep(
hbConfig.non_exclusive_heartbeat_interval_ms,
cap.signal,
)
cap.cleanup()
}
// Determine exit reason for telemetry
const exitReason =
hbResult === 'auth_failed' || hbResult === 'fatal'
? hbResult
: loopSignal.aborted
? 'shutdown'
: activeSessions.size < config.maxSessions
? 'capacity_changed'
: pollDeadline !== null && Date.now() >= pollDeadline
? 'poll_due'
: 'config_disabled'
logEvent('tengu_bridge_heartbeat_mode_exited', {
reason:
exitReason as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
heartbeat_cycles: hbCycles,
active_sessions: activeSessions.size,
})
if (exitReason === 'poll_due') {
// bridgeApi throttles empty-poll logs (EMPTY_POLL_LOG_INTERVAL=100)
// so the once-per-10min poll_due poll is invisible at counter=2.
// Log it here so verification runs see both endpoints in the debug log.
logForDebugging(
`[bridge:poll] Heartbeat poll_due after ${hbCycles} cycles — falling through to pollForWork`,
)
}
// On auth_failed or fatal, sleep before polling to avoid a tight
// poll+heartbeat loop. Auth_failed: heartbeatActiveWorkItems
// already called reconnectSession — the sleep gives the server
// time to propagate the re-queue. Fatal (404/410): may be a
// single work item GCd while the environment is still valid.
// Use atCapMs if enabled, else the heartbeat interval as a floor
// (guaranteed > 0 here) so heartbeat-only configs don't tight-loop.
if (hbResult === 'auth_failed' || hbResult === 'fatal') {
const cap = capacityWake.signal()
await sleep(
atCapMs > 0
? atCapMs
: pollConfig.non_exclusive_heartbeat_interval_ms,
cap.signal,
)
cap.cleanup()
}
} else if (atCapMs > 0) {
// Heartbeat disabled: slow poll as liveness signal.
const cap = capacityWake.signal()
await sleep(atCapMs, cap.signal)
cap.cleanup()
}
} else {
const interval =
activeSessions.size > 0
? pollConfig.multisession_poll_interval_ms_partial_capacity
: pollConfig.multisession_poll_interval_ms_not_at_capacity
await sleep(interval, loopSignal)
}
continue
}
// At capacity — we polled to keep the heartbeat alive, but cannot
// accept new work right now. We still enter the switch below so that
// token refreshes for existing sessions are processed (the case
// 'session' handler checks for existing sessions before the inner
// capacity guard).
const atCapacityBeforeSwitch = activeSessions.size >= config.maxSessions
// Skip work items that have already been completed and stopped.
// The server may re-deliver stale work before processing our stop
// request, which would otherwise cause a duplicate session spawn.
if (completedWorkIds.has(work.id)) {
logForDebugging(
`[bridge:work] Skipping already-completed workId=${work.id}`,
)
// Respect capacity throttle — without a sleep here, persistent stale
// redeliveries would tight-loop at poll-request speed (the !work
// branch above is the only sleep, and work != null skips it).
if (atCapacityBeforeSwitch) {
const cap = capacityWake.signal()
if (pollConfig.non_exclusive_heartbeat_interval_ms > 0) {
await heartbeatActiveWorkItems()
await sleep(
pollConfig.non_exclusive_heartbeat_interval_ms,
cap.signal,
)
} else if (pollConfig.multisession_poll_interval_ms_at_capacity > 0) {
await sleep(
pollConfig.multisession_poll_interval_ms_at_capacity,
cap.signal,
)
}
cap.cleanup()
} else {
await sleep(1000, loopSignal)
}
continue
}
// Decode the work secret for session spawning and to extract the JWT
// used for the ack call below.
let secret
try {
secret = decodeWorkSecret(work.secret)
} catch (err) {
const errMsg = errorMessage(err)
logger.logError(
`Failed to decode work secret for workId=${work.id}: ${errMsg}`,
)
logEvent('tengu_bridge_work_secret_failed', {})
// Can't ack (needs the JWT we failed to decode). stopWork uses OAuth,
// so it's callable here — prevents XAUTOCLAIM from re-delivering this
// poisoned item every reclaim_older_than_ms cycle.
completedWorkIds.add(work.id)
trackCleanup(
stopWorkWithRetry(
api,
environmentId,
work.id,
logger,
backoffConfig.stopWorkBaseDelayMs,
),
)
// Respect capacity throttle before retrying — without a sleep here,
// repeated decode failures at capacity would tight-loop at
// poll-request speed (work != null skips the !work sleep above).
if (atCapacityBeforeSwitch) {
const cap = capacityWake.signal()
if (pollConfig.non_exclusive_heartbeat_interval_ms > 0) {
await heartbeatActiveWorkItems()
await sleep(
pollConfig.non_exclusive_heartbeat_interval_ms,
cap.signal,
)
} else if (pollConfig.multisession_poll_interval_ms_at_capacity > 0) {
await sleep(
pollConfig.multisession_poll_interval_ms_at_capacity,
cap.signal,
)
}
cap.cleanup()
}
continue
}
// Explicitly acknowledge after committing to handle the work — NOT
// before. The at-capacity guard inside case 'session' can break
// without spawning; acking there would permanently lose the work.
// Ack failures are non-fatal: server re-delivers, and existingHandle
// / completedWorkIds paths handle the dedup.
const ackWork = async (): Promise<void> => {
logForDebugging(`[bridge:work] Acknowledging workId=${work.id}`)
try {
await api.acknowledgeWork(
environmentId,
work.id,
secret.session_ingress_token,
)
} catch (err) {
logForDebugging(
`[bridge:work] Acknowledge failed workId=${work.id}: ${errorMessage(err)}`,
)
}
}
const workType: string = work.data.type
switch (work.data.type) {
case 'healthcheck':
await ackWork()
logForDebugging('[bridge:work] Healthcheck received')
logger.logVerbose('Healthcheck received')
break
case 'session': {
const sessionId = work.data.id
try {
validateBridgeId(sessionId, 'session_id')
} catch {
await ackWork()
logger.logError(`Invalid session_id received: ${sessionId}`)
break
}
// If the session is already running, deliver the fresh token so
// the child process can reconnect its WebSocket with the new
// session ingress token. This handles the case where the server
// re-dispatches work for an existing session after the WS drops.
const existingHandle = activeSessions.get(sessionId)
if (existingHandle) {
existingHandle.updateAccessToken(secret.session_ingress_token)
sessionIngressTokens.set(sessionId, secret.session_ingress_token)
sessionWorkIds.set(sessionId, work.id)
// Re-schedule next refresh from the fresh JWT's expiry. onRefresh
// branches on v2Sessions so both v1 and v2 are safe here.
tokenRefresh?.schedule(sessionId, secret.session_ingress_token)
logForDebugging(
`[bridge:work] Updated access token for existing sessionId=${sessionId} workId=${work.id}`,
)
await ackWork()
break
}
// At capacity — token refresh for existing sessions is handled
// above, but we cannot spawn new ones. The post-switch capacity
// sleep will throttle the loop; just break here.
if (activeSessions.size >= config.maxSessions) {
logForDebugging(
`[bridge:work] At capacity (${activeSessions.size}/${config.maxSessions}), cannot spawn new session for workId=${work.id}`,
)
break
}
await ackWork()
const spawnStartTime = Date.now()
// CCR v2 path: register this bridge as the session worker, get the
// epoch, and point the child at /v1/code/sessions/{id}. The child
// already has the full v2 client (SSETransport + CCRClient) — same
// code path environment-manager launches in containers.
//
// v1 path: Session-Ingress WebSocket. Uses config.sessionIngressUrl
// (not secret.api_base_url, which may point to a remote proxy tunnel
// that doesn't know about locally-created sessions).
let sdkUrl: string
let useCcrV2 = false
let workerEpoch: number | undefined
// Server decides per-session via the work secret; env var is the
// ant-dev override (e.g. forcing v2 before the server flag is on).
if (
secret.use_code_sessions === true ||
isEnvTruthy(process.env.CLAUDE_BRIDGE_USE_CCR_V2)
) {
sdkUrl = buildCCRv2SdkUrl(config.apiBaseUrl, sessionId)
// Retry once on transient failure (network blip, 500) before
// permanently giving up and killing the session.
for (let attempt = 1; attempt <= 2; attempt++) {
try {
workerEpoch = await registerWorker(
sdkUrl,
secret.session_ingress_token,
)
useCcrV2 = true
logForDebugging(
`[bridge:session] CCR v2: registered worker sessionId=${sessionId} epoch=${workerEpoch} attempt=${attempt}`,
)
break
} catch (err) {
const errMsg = errorMessage(err)
if (attempt < 2) {
logForDebugging(
`[bridge:session] CCR v2: registerWorker attempt ${attempt} failed, retrying: ${errMsg}`,
)
await sleep(2_000, loopSignal)
if (loopSignal.aborted) break
continue
}
logger.logError(
`CCR v2 worker registration failed for session ${sessionId}: ${errMsg}`,
)
logError(new Error(`registerWorker failed: ${errMsg}`))
completedWorkIds.add(work.id)
trackCleanup(
stopWorkWithRetry(
api,
environmentId,
work.id,
logger,
backoffConfig.stopWorkBaseDelayMs,
),
)
}
}
if (!useCcrV2) break
} else {
sdkUrl = buildSdkUrl(config.sessionIngressUrl, sessionId)
}
// In worktree mode, on-demand sessions get an isolated git worktree
// so concurrent sessions don't interfere with each other's file
// changes. The pre-created initial session (if any) runs in
// config.dir so the user's first session lands in the directory they
// invoked `rc` from — matching the old single-session UX.
// In same-dir and single-session modes, all sessions share config.dir.
// Capture spawnMode before the await below — the `w` key handler
// mutates config.spawnMode directly, and createAgentWorktree can
// take 1-2s, so reading config.spawnMode after the await can
// produce contradictory analytics (spawn_mode:'same-dir', in_worktree:true).
const spawnModeAtDecision = config.spawnMode
let sessionDir = config.dir
let worktreeCreateMs = 0
if (
spawnModeAtDecision === 'worktree' &&
(initialSessionId === undefined ||
!sameSessionId(sessionId, initialSessionId))
) {
const wtStart = Date.now()
try {
const wt = await createAgentWorktree(
`bridge-${safeFilenameId(sessionId)}`,
)
worktreeCreateMs = Date.now() - wtStart
sessionWorktrees.set(sessionId, {
worktreePath: wt.worktreePath,
worktreeBranch: wt.worktreeBranch,
gitRoot: wt.gitRoot,
hookBased: wt.hookBased,
})
sessionDir = wt.worktreePath
logForDebugging(
`[bridge:session] Created worktree for sessionId=${sessionId} at ${wt.worktreePath}`,
)
} catch (err) {
const errMsg = errorMessage(err)
logger.logError(
`Failed to create worktree for session ${sessionId}: ${errMsg}`,