forked from sanbuphy/learn-coding-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplBridge.ts
More file actions
2406 lines (2267 loc) · 98.2 KB
/
replBridge.ts
File metadata and controls
2406 lines (2267 loc) · 98.2 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 assist/source/organizeImports: ANT-ONLY import markers must not be reordered
import { randomUUID } from 'crypto'
import {
createBridgeApiClient,
BridgeFatalError,
isExpiredErrorType,
isSuppressible403,
} from './bridgeApi.js'
import type { BridgeConfig, BridgeApiClient } from './types.js'
import { logForDebugging } from '../utils/debug.js'
import { logForDiagnosticsNoPII } from '../utils/diagLogs.js'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from '../services/analytics/index.js'
import { registerCleanup } from '../utils/cleanupRegistry.js'
import {
handleIngressMessage,
handleServerControlRequest,
makeResultMessage,
isEligibleBridgeMessage,
extractTitleText,
BoundedUUIDSet,
} from './bridgeMessaging.js'
import {
decodeWorkSecret,
buildSdkUrl,
buildCCRv2SdkUrl,
sameSessionId,
} from './workSecret.js'
import { toCompatSessionId, toInfraSessionId } from './sessionIdCompat.js'
import { updateSessionBridgeId } from '../utils/concurrentSessions.js'
import { getTrustedDeviceToken } from './trustedDevice.js'
import { HybridTransport } from '../cli/transports/HybridTransport.js'
import {
type ReplBridgeTransport,
createV1ReplTransport,
createV2ReplTransport,
} from './replBridgeTransport.js'
import { updateSessionIngressAuthToken } from '../utils/sessionIngressAuth.js'
import { isEnvTruthy, isInProtectedNamespace } from '../utils/envUtils.js'
import { validateBridgeId } from './bridgeApi.js'
import {
describeAxiosError,
extractHttpStatus,
logBridgeSkip,
} from './debugUtils.js'
import type { Message } from '../types/message.js'
import type { SDKMessage } from '../entrypoints/agentSdkTypes.js'
import type { PermissionMode } from '../utils/permissions/PermissionMode.js'
import type {
SDKControlRequest,
SDKControlResponse,
} from '../entrypoints/sdk/controlTypes.js'
import { createCapacityWake, type CapacitySignal } from './capacityWake.js'
import { FlushGate } from './flushGate.js'
import {
DEFAULT_POLL_CONFIG,
type PollIntervalConfig,
} from './pollConfigDefaults.js'
import { errorMessage } from '../utils/errors.js'
import { sleep } from '../utils/sleep.js'
import {
wrapApiForFaultInjection,
registerBridgeDebugHandle,
clearBridgeDebugHandle,
injectBridgeFault,
} from './bridgeDebug.js'
export type ReplBridgeHandle = {
bridgeSessionId: string
environmentId: string
sessionIngressUrl: string
writeMessages(messages: Message[]): void
writeSdkMessages(messages: SDKMessage[]): void
sendControlRequest(request: SDKControlRequest): void
sendControlResponse(response: SDKControlResponse): void
sendControlCancelRequest(requestId: string): void
sendResult(): void
teardown(): Promise<void>
}
export type BridgeState = 'ready' | 'connected' | 'reconnecting' | 'failed'
/**
* Explicit-param input to initBridgeCore. Everything initReplBridge reads
* from bootstrap state (cwd, session ID, git, OAuth) becomes a field here.
* A daemon caller (Agent SDK, PR 4) that never runs main.tsx fills these
* in itself.
*/
export type BridgeCoreParams = {
dir: string
machineName: string
branch: string
gitRepoUrl: string | null
title: string
baseUrl: string
sessionIngressUrl: string
/**
* Opaque string sent as metadata.worker_type. Use BridgeWorkerType for
* the two CLI-originated values; daemon callers may send any string the
* backend recognizes (it's just a filter key on the web side).
*/
workerType: string
getAccessToken: () => string | undefined
/**
* POST /v1/sessions. Injected because `createSession.ts` lazy-loads
* `auth.ts`/`model.ts`/`oauth/client.ts` and `bun --outfile` inlines
* dynamic imports — the lazy-load doesn't help, the whole REPL tree ends
* up in the Agent SDK bundle.
*
* REPL wrapper passes `createBridgeSession` from `createSession.ts`.
* Daemon wrapper passes `createBridgeSessionLean` from `sessionApi.ts`
* (HTTP-only, orgUUID+model supplied by the daemon caller).
*
* Receives `gitRepoUrl`+`branch` so the REPL wrapper can build the git
* source/outcome for claude.ai's session card. Daemon ignores them.
*/
createSession: (opts: {
environmentId: string
title: string
gitRepoUrl: string | null
branch: string
signal: AbortSignal
}) => Promise<string | null>
/**
* POST /v1/sessions/{id}/archive. Same injection rationale. Best-effort;
* the callback MUST NOT throw.
*/
archiveSession: (sessionId: string) => Promise<void>
/**
* Invoked on reconnect-after-env-lost to refresh the title. REPL wrapper
* reads session storage (picks up /rename); daemon returns the static
* title. Defaults to () => title.
*/
getCurrentTitle?: () => string
/**
* Converts internal Message[] → SDKMessage[] for writeMessages() and the
* initial-flush/drain paths. REPL wrapper passes the real toSDKMessages
* from utils/messages/mappers.ts. Daemon callers that only use
* writeSdkMessages() and pass no initialMessages can omit this — those
* code paths are unreachable.
*
* Injected rather than imported because mappers.ts transitively pulls in
* src/commands.ts via messages.ts → api.ts → prompts.ts, dragging the
* entire command registry + React tree into the Agent SDK bundle.
*/
toSDKMessages?: (messages: Message[]) => SDKMessage[]
/**
* OAuth 401 refresh handler passed to createBridgeApiClient. REPL wrapper
* passes handleOAuth401Error; daemon passes its AuthManager's handler.
* Injected because utils/auth.ts transitively pulls in the command
* registry via config.ts → file.ts → permissions/filesystem.ts →
* sessionStorage.ts → commands.ts.
*/
onAuth401?: (staleAccessToken: string) => Promise<boolean>
/**
* Poll interval config getter for the work-poll heartbeat loop. REPL
* wrapper passes the GrowthBook-backed getPollIntervalConfig (allows ops
* to live-tune poll rates fleet-wide). Daemon passes a static config
* with a 60s heartbeat (5× headroom under the 300s work-lease TTL).
* Injected because growthbook.ts transitively pulls in the command
* registry via the same config.ts chain.
*/
getPollIntervalConfig?: () => PollIntervalConfig
/**
* Max initial messages to replay on connect. REPL wrapper reads from the
* tengu_bridge_initial_history_cap GrowthBook flag. Daemon passes no
* initialMessages so this is never read. Default 200 matches the flag
* default.
*/
initialHistoryCap?: number
// Same REPL-flush machinery as InitBridgeOptions — daemon omits these.
initialMessages?: Message[]
previouslyFlushedUUIDs?: Set<string>
onInboundMessage?: (msg: SDKMessage) => void
onPermissionResponse?: (response: SDKControlResponse) => void
onInterrupt?: () => void
onSetModel?: (model: string | undefined) => void
onSetMaxThinkingTokens?: (maxTokens: number | null) => void
/**
* Returns a policy verdict so this module can emit an error control_response
* without importing the policy checks itself (bootstrap-isolation constraint).
* The callback must guard `auto` (isAutoModeGateEnabled) and
* `bypassPermissions` (isBypassPermissionsModeDisabled AND
* isBypassPermissionsModeAvailable) BEFORE calling transitionPermissionMode —
* that function's internal auto-gate check is a defensive throw, not a
* graceful guard, and its side-effect order is setAutoModeActive(true) then
* throw, which corrupts the 3-way invariant documented in src/CLAUDE.md if
* the callback lets the throw escape here.
*/
onSetPermissionMode?: (
mode: PermissionMode,
) => { ok: true } | { ok: false; error: string }
onStateChange?: (state: BridgeState, detail?: string) => void
/**
* Fires on each real user message to flow through writeMessages() until
* the callback returns true (done). Mirrors remoteBridgeCore.ts's
* onUserMessage so the REPL bridge can derive a session title from early
* prompts when none was set at init time (e.g. user runs /remote-control
* on an empty conversation, then types). Tool-result wrappers, meta
* messages, and display-tag-only messages are skipped. Receives
* currentSessionId so the wrapper can PATCH the title without a closure
* dance to reach the not-yet-returned handle. The caller owns the
* derive-at-count-1-and-3 policy; the transport just keeps calling until
* told to stop. Not fired for the writeSdkMessages daemon path (daemon
* sets its own title at init). Distinct from SessionSpawnOpts's
* onFirstUserMessage (spawn-bridge, PR #21250), which stays fire-once.
*/
onUserMessage?: (text: string, sessionId: string) => boolean
/** See InitBridgeOptions.perpetual. */
perpetual?: boolean
/**
* Seeds lastTransportSequenceNum — the SSE event-stream high-water mark
* that's carried across transport swaps within one process. Daemon callers
* pass the value they persisted at shutdown so the FIRST SSE connect of a
* fresh process sends from_sequence_num and the server doesn't replay full
* history. REPL callers omit (fresh session each run → 0 is correct).
*/
initialSSESequenceNum?: number
}
/**
* Superset of ReplBridgeHandle. Adds getSSESequenceNum for daemon callers
* that persist the SSE seq-num across process restarts and pass it back as
* initialSSESequenceNum on the next start.
*/
export type BridgeCoreHandle = ReplBridgeHandle & {
/**
* Current SSE sequence-number high-water mark. Updates as transports
* swap. Daemon callers persist this on shutdown and pass it back as
* initialSSESequenceNum on next start.
*/
getSSESequenceNum(): number
}
/**
* Poll error recovery constants. When the work poll starts failing (e.g.
* server 500s), we use exponential backoff and give up after this timeout.
* This is deliberately long — the server is the authority on when a session
* is truly dead. As long as the server accepts our poll, we keep waiting
* for it to re-dispatch the work item.
*/
const POLL_ERROR_INITIAL_DELAY_MS = 2_000
const POLL_ERROR_MAX_DELAY_MS = 60_000
const POLL_ERROR_GIVE_UP_MS = 15 * 60 * 1000
// Monotonically increasing counter for distinguishing init calls in logs
let initSequence = 0
/**
* Bootstrap-free core: env registration → session creation → poll loop →
* ingress WS → teardown. Reads nothing from bootstrap/state or
* sessionStorage — all context comes from params. Caller (initReplBridge
* below, or a daemon in PR 4) has already passed entitlement gates and
* gathered git/auth/title.
*
* Returns null on registration or session-creation failure.
*/
export async function initBridgeCore(
params: BridgeCoreParams,
): Promise<BridgeCoreHandle | null> {
const {
dir,
machineName,
branch,
gitRepoUrl,
title,
baseUrl,
sessionIngressUrl,
workerType,
getAccessToken,
createSession,
archiveSession,
getCurrentTitle = () => title,
toSDKMessages = () => {
throw new Error(
'BridgeCoreParams.toSDKMessages not provided. Pass it if you use writeMessages() or initialMessages — daemon callers that only use writeSdkMessages() never hit this path.',
)
},
onAuth401,
getPollIntervalConfig = () => DEFAULT_POLL_CONFIG,
initialHistoryCap = 200,
initialMessages,
previouslyFlushedUUIDs,
onInboundMessage,
onPermissionResponse,
onInterrupt,
onSetModel,
onSetMaxThinkingTokens,
onSetPermissionMode,
onStateChange,
onUserMessage,
perpetual,
initialSSESequenceNum = 0,
} = params
const seq = ++initSequence
// bridgePointer import hoisted: perpetual mode reads it before register;
// non-perpetual writes it after session create; both use clear at teardown.
const { writeBridgePointer, clearBridgePointer, readBridgePointer } =
await import('./bridgePointer.js')
// Perpetual mode: read the crash-recovery pointer and treat it as prior
// state. The pointer is written unconditionally after session create
// (crash-recovery for all sessions); perpetual mode just skips the
// teardown clear so it survives clean exits too. Only reuse 'repl'
// pointers — a crashed standalone bridge (`claude remote-control`)
// writes source:'standalone' with a different workerType.
const rawPrior = perpetual ? await readBridgePointer(dir) : null
const prior = rawPrior?.source === 'repl' ? rawPrior : null
logForDebugging(
`[bridge:repl] initBridgeCore #${seq} starting (initialMessages=${initialMessages?.length ?? 0}${prior ? ` perpetual prior=env:${prior.environmentId}` : ''})`,
)
// 5. Register bridge environment
const rawApi = createBridgeApiClient({
baseUrl,
getAccessToken,
runnerVersion: MACRO.VERSION,
onDebug: logForDebugging,
onAuth401,
getTrustedDeviceToken,
})
// Ant-only: interpose so /bridge-kick can inject poll/register/heartbeat
// failures. Zero cost in external builds (rawApi passes through unchanged).
const api =
process.env.USER_TYPE === 'ant' ? wrapApiForFaultInjection(rawApi) : rawApi
const bridgeConfig: BridgeConfig = {
dir,
machineName,
branch,
gitRepoUrl,
maxSessions: 1,
spawnMode: 'single-session',
verbose: false,
sandbox: false,
bridgeId: randomUUID(),
workerType,
environmentId: randomUUID(),
reuseEnvironmentId: prior?.environmentId,
apiBaseUrl: baseUrl,
sessionIngressUrl,
}
let environmentId: string
let environmentSecret: string
try {
const reg = await api.registerBridgeEnvironment(bridgeConfig)
environmentId = reg.environment_id
environmentSecret = reg.environment_secret
} catch (err) {
logBridgeSkip(
'registration_failed',
`[bridge:repl] Environment registration failed: ${errorMessage(err)}`,
)
// Stale pointer may be the cause (expired/deleted env) — clear it so
// the next start doesn't retry the same dead ID.
if (prior) {
await clearBridgePointer(dir)
}
onStateChange?.('failed', errorMessage(err))
return null
}
logForDebugging(`[bridge:repl] Environment registered: ${environmentId}`)
logForDiagnosticsNoPII('info', 'bridge_repl_env_registered')
logEvent('tengu_bridge_repl_env_registered', {})
/**
* Reconnect-in-place: if the just-registered environmentId matches what
* was requested, call reconnectSession to force-stop stale workers and
* re-queue the session. Used at init (perpetual mode — env is alive but
* idle after clean teardown) and in doReconnect() Strategy 1 (env lost
* then resurrected). Returns true on success; caller falls back to
* fresh session creation on false.
*/
async function tryReconnectInPlace(
requestedEnvId: string,
sessionId: string,
): Promise<boolean> {
if (environmentId !== requestedEnvId) {
logForDebugging(
`[bridge:repl] Env mismatch (requested ${requestedEnvId}, got ${environmentId}) — cannot reconnect in place`,
)
return false
}
// The pointer stores what createBridgeSession returned (session_*,
// compat/convert.go:41). /bridge/reconnect is an environments-layer
// endpoint — once the server's ccr_v2_compat_enabled gate is on it
// looks sessions up by their infra tag (cse_*) and returns "Session
// not found" for the session_* costume. We don't know the gate state
// pre-poll, so try both; the re-tag is a no-op if the ID is already
// cse_* (doReconnect Strategy 1 path — currentSessionId never mutates
// to cse_* but future-proof the check).
const infraId = toInfraSessionId(sessionId)
const candidates =
infraId === sessionId ? [sessionId] : [sessionId, infraId]
for (const id of candidates) {
try {
await api.reconnectSession(environmentId, id)
logForDebugging(
`[bridge:repl] Reconnected session ${id} in place on env ${environmentId}`,
)
return true
} catch (err) {
logForDebugging(
`[bridge:repl] reconnectSession(${id}) failed: ${errorMessage(err)}`,
)
}
}
logForDebugging(
'[bridge:repl] reconnectSession exhausted — falling through to fresh session',
)
return false
}
// Perpetual init: env is alive but has no queued work after clean
// teardown. reconnectSession re-queues it. doReconnect() has the same
// call but only fires on poll 404 (env dead);
// here the env is alive but idle.
const reusedPriorSession = prior
? await tryReconnectInPlace(prior.environmentId, prior.sessionId)
: false
if (prior && !reusedPriorSession) {
await clearBridgePointer(dir)
}
// 6. Create session on the bridge. Initial messages are NOT included as
// session creation events because those use STREAM_ONLY persistence and
// are published before the CCR UI subscribes, so they get lost. Instead,
// initial messages are flushed via the ingress WebSocket once it connects.
// Mutable session ID — updated when the environment+session pair is
// re-created after a connection loss.
let currentSessionId: string
if (reusedPriorSession && prior) {
currentSessionId = prior.sessionId
logForDebugging(
`[bridge:repl] Perpetual session reused: ${currentSessionId}`,
)
// Server already has all initialMessages from the prior CLI run. Mark
// them as previously-flushed so the initial flush filter excludes them
// (previouslyFlushedUUIDs is a fresh Set on every CLI start). Duplicate
// UUIDs cause the server to kill the WebSocket.
if (initialMessages && previouslyFlushedUUIDs) {
for (const msg of initialMessages) {
previouslyFlushedUUIDs.add(msg.uuid)
}
}
} else {
const createdSessionId = await createSession({
environmentId,
title,
gitRepoUrl,
branch,
signal: AbortSignal.timeout(15_000),
})
if (!createdSessionId) {
logForDebugging(
'[bridge:repl] Session creation failed, deregistering environment',
)
logEvent('tengu_bridge_repl_session_failed', {})
await api.deregisterEnvironment(environmentId).catch(() => {})
onStateChange?.('failed', 'Session creation failed')
return null
}
currentSessionId = createdSessionId
logForDebugging(`[bridge:repl] Session created: ${currentSessionId}`)
}
// Crash-recovery pointer: written now so a kill -9 at any point after
// this leaves a recoverable trail. Cleared in teardown (non-perpetual)
// or left alone (perpetual mode — pointer survives clean exit too).
// `claude remote-control --continue` from the same directory will detect
// it and offer to resume.
await writeBridgePointer(dir, {
sessionId: currentSessionId,
environmentId,
source: 'repl',
})
logForDiagnosticsNoPII('info', 'bridge_repl_session_created')
logEvent('tengu_bridge_repl_started', {
has_initial_messages: !!(initialMessages && initialMessages.length > 0),
inProtectedNamespace: isInProtectedNamespace(),
})
// UUIDs of initial messages. Used for dedup in writeMessages to avoid
// re-sending messages that were already flushed on WebSocket open.
const initialMessageUUIDs = new Set<string>()
if (initialMessages) {
for (const msg of initialMessages) {
initialMessageUUIDs.add(msg.uuid)
}
}
// Bounded ring buffer of UUIDs for messages we've already sent to the
// server via the ingress WebSocket. Serves two purposes:
// 1. Echo filtering — ignore our own messages bouncing back on the WS.
// 2. Secondary dedup in writeMessages — catch race conditions where
// the hook's index-based tracking isn't sufficient.
//
// Seeded with initialMessageUUIDs so that when the server echoes back
// the initial conversation context over the ingress WebSocket, those
// messages are recognized as echoes and not re-injected into the REPL.
//
// Capacity of 2000 covers well over any realistic echo window (echoes
// arrive within milliseconds) and any messages that might be re-encountered
// after compaction. The hook's lastWrittenIndexRef is the primary dedup;
// this is a safety net.
const recentPostedUUIDs = new BoundedUUIDSet(2000)
for (const uuid of initialMessageUUIDs) {
recentPostedUUIDs.add(uuid)
}
// Bounded set of INBOUND prompt UUIDs we've already forwarded to the REPL.
// Defensive dedup for when the server re-delivers prompts (seq-num
// negotiation failure, server edge cases, transport swap races). The
// seq-num carryover below is the primary fix; this is the safety net.
const recentInboundUUIDs = new BoundedUUIDSet(2000)
// 7. Start poll loop for work items — this is what makes the session
// "live" on claude.ai. When a user types there, the backend dispatches
// a work item to our environment. We poll for it, get the ingress token,
// and connect the ingress WebSocket.
//
// The poll loop keeps running: when work arrives it connects the ingress
// WebSocket, and if the WebSocket drops unexpectedly (code != 1000) it
// resumes polling to get a fresh ingress token and reconnect.
const pollController = new AbortController()
// Adapter over either HybridTransport (v1: WS reads + POST writes to
// Session-Ingress) or SSETransport+CCRClient (v2: SSE reads + POST
// writes to CCR /worker/*). The v1/v2 choice is made in onWorkReceived:
// server-driven via secret.use_code_sessions, with CLAUDE_BRIDGE_USE_CCR_V2
// as an ant-dev override.
let transport: ReplBridgeTransport | null = null
// Bumped on every onWorkReceived. Captured in createV2ReplTransport's .then()
// closure to detect stale resolutions: if two calls race while transport is
// null, both registerWorker() (bumping server epoch), and whichever resolves
// SECOND is the correct one — but the transport !== null check gets this
// backwards (first-to-resolve installs, second discards). The generation
// counter catches it independent of transport state.
let v2Generation = 0
// SSE sequence-number high-water mark carried across transport swaps.
// Without this, each new SSETransport starts at 0, sends no
// from_sequence_num / Last-Event-ID on its first connect, and the server
// replays the entire session event history — every prompt ever sent
// re-delivered as fresh inbound messages on every onWorkReceived.
//
// Seed only when we actually reconnected the prior session. If
// `reusedPriorSession` is false we fell through to `createSession()` —
// the caller's persisted seq-num belongs to a dead session and applying
// it to the fresh stream (starting at 1) silently drops events. Same
// hazard as doReconnect Strategy 2; same fix as the reset there.
let lastTransportSequenceNum = reusedPriorSession ? initialSSESequenceNum : 0
// Track the current work ID so teardown can call stopWork
let currentWorkId: string | null = null
// Session ingress JWT for the current work item — used for heartbeat auth.
let currentIngressToken: string | null = null
// Signal to wake the at-capacity sleep early when the transport is lost,
// so the poll loop immediately switches back to fast polling for new work.
const capacityWake = createCapacityWake(pollController.signal)
const wakePollLoop = capacityWake.wake
const capacitySignal = capacityWake.signal
// Gates message writes during the initial flush to prevent ordering
// races where new messages arrive at the server interleaved with history.
const flushGate = new FlushGate<Message>()
// Latch for onUserMessage — flips true when the callback returns true
// (policy says "done deriving"). If no callback, skip scanning entirely
// (daemon path — no title derivation needed).
let userMessageCallbackDone = !onUserMessage
// Shared counter for environment re-creations, used by both
// onEnvironmentLost and the abnormal-close handler.
const MAX_ENVIRONMENT_RECREATIONS = 3
let environmentRecreations = 0
let reconnectPromise: Promise<boolean> | null = null
/**
* Recover from onEnvironmentLost (poll returned 404 — env was reaped
* server-side). Tries two strategies in order:
*
* 1. Reconnect-in-place: idempotent re-register with reuseEnvironmentId
* → if the backend returns the same env ID, call reconnectSession()
* to re-queue the existing session. currentSessionId stays the same;
* the URL on the user's phone stays valid; previouslyFlushedUUIDs is
* preserved so history isn't re-sent.
*
* 2. Fresh session fallback: if the backend returns a different env ID
* (original TTL-expired, e.g. laptop slept >4h) or reconnectSession()
* throws, archive the old session and create a new one on the
* now-registered env. Old behavior before #20460 primitives landed.
*
* Uses a promise-based reentrancy guard so concurrent callers share the
* same reconnection attempt.
*/
async function reconnectEnvironmentWithSession(): Promise<boolean> {
if (reconnectPromise) {
return reconnectPromise
}
reconnectPromise = doReconnect()
try {
return await reconnectPromise
} finally {
reconnectPromise = null
}
}
async function doReconnect(): Promise<boolean> {
environmentRecreations++
// Invalidate any in-flight v2 handshake — the environment is being
// recreated, so a stale transport arriving post-reconnect would be
// pointed at a dead session.
v2Generation++
logForDebugging(
`[bridge:repl] Reconnecting after env lost (attempt ${environmentRecreations}/${MAX_ENVIRONMENT_RECREATIONS})`,
)
if (environmentRecreations > MAX_ENVIRONMENT_RECREATIONS) {
logForDebugging(
`[bridge:repl] Environment reconnect limit reached (${MAX_ENVIRONMENT_RECREATIONS}), giving up`,
)
return false
}
// Close the stale transport. Capture seq BEFORE close — if Strategy 1
// (tryReconnectInPlace) succeeds we keep the SAME session, and the
// next transport must resume where this one left off, not replay from
// the last transport-swap checkpoint.
if (transport) {
const seq = transport.getLastSequenceNum()
if (seq > lastTransportSequenceNum) {
lastTransportSequenceNum = seq
}
transport.close()
transport = null
}
// Transport is gone — wake the poll loop out of its at-capacity
// heartbeat sleep so it can fast-poll for re-dispatched work.
wakePollLoop()
// Reset flush gate so writeMessages() hits the !transport guard
// instead of silently queuing into a dead buffer.
flushGate.drop()
// Release the current work item (force=false — we may want the session
// back). Best-effort: the env is probably gone, so this likely 404s.
if (currentWorkId) {
const workIdBeingCleared = currentWorkId
await api
.stopWork(environmentId, workIdBeingCleared, false)
.catch(() => {})
// When doReconnect runs concurrently with the poll loop (ws_closed
// handler case — void-called, unlike the awaited onEnvironmentLost
// path), onWorkReceived can fire during the stopWork await and set
// a fresh currentWorkId. If it did, the poll loop has already
// recovered on its own — defer to it rather than proceeding to
// archiveSession, which would destroy the session its new
// transport is connected to.
if (currentWorkId !== workIdBeingCleared) {
logForDebugging(
'[bridge:repl] Poll loop recovered during stopWork await — deferring to it',
)
environmentRecreations = 0
return true
}
currentWorkId = null
currentIngressToken = null
}
// Bail out if teardown started while we were awaiting
if (pollController.signal.aborted) {
logForDebugging('[bridge:repl] Reconnect aborted by teardown')
return false
}
// Strategy 1: idempotent re-register with the server-issued env ID.
// If the backend resurrects the same env (fresh secret), we can
// reconnect the existing session. If it hands back a different ID, the
// original env is truly gone and we fall through to a fresh session.
const requestedEnvId = environmentId
bridgeConfig.reuseEnvironmentId = requestedEnvId
try {
const reg = await api.registerBridgeEnvironment(bridgeConfig)
environmentId = reg.environment_id
environmentSecret = reg.environment_secret
} catch (err) {
bridgeConfig.reuseEnvironmentId = undefined
logForDebugging(
`[bridge:repl] Environment re-registration failed: ${errorMessage(err)}`,
)
return false
}
// Clear before any await — a stale value would poison the next fresh
// registration if doReconnect runs again.
bridgeConfig.reuseEnvironmentId = undefined
logForDebugging(
`[bridge:repl] Re-registered: requested=${requestedEnvId} got=${environmentId}`,
)
// Bail out if teardown started while we were registering
if (pollController.signal.aborted) {
logForDebugging(
'[bridge:repl] Reconnect aborted after env registration, cleaning up',
)
await api.deregisterEnvironment(environmentId).catch(() => {})
return false
}
// Same race as above, narrower window: poll loop may have set up a
// transport during the registerBridgeEnvironment await. Bail before
// tryReconnectInPlace/archiveSession kill it server-side.
if (transport !== null) {
logForDebugging(
'[bridge:repl] Poll loop recovered during registerBridgeEnvironment await — deferring to it',
)
environmentRecreations = 0
return true
}
// Strategy 1: same helper as perpetual init. currentSessionId stays
// the same on success; URL on mobile/web stays valid;
// previouslyFlushedUUIDs preserved (no re-flush).
if (await tryReconnectInPlace(requestedEnvId, currentSessionId)) {
logEvent('tengu_bridge_repl_reconnected_in_place', {})
environmentRecreations = 0
return true
}
// Env differs → TTL-expired/reaped; or reconnect failed.
// Don't deregister — we have a fresh secret for this env either way.
if (environmentId !== requestedEnvId) {
logEvent('tengu_bridge_repl_env_expired_fresh_session', {})
}
// Strategy 2: fresh session on the now-registered environment.
// Archive the old session first — it's orphaned (bound to a dead env,
// or reconnectSession rejected it). Don't deregister the env — we just
// got a fresh secret for it and are about to use it.
await archiveSession(currentSessionId)
// Bail out if teardown started while we were archiving
if (pollController.signal.aborted) {
logForDebugging(
'[bridge:repl] Reconnect aborted after archive, cleaning up',
)
await api.deregisterEnvironment(environmentId).catch(() => {})
return false
}
// Re-read the current title in case the user renamed the session.
// REPL wrapper reads session storage; daemon wrapper returns the
// original title (nothing to refresh).
const currentTitle = getCurrentTitle()
// Create a new session on the now-registered environment
const newSessionId = await createSession({
environmentId,
title: currentTitle,
gitRepoUrl,
branch,
signal: AbortSignal.timeout(15_000),
})
if (!newSessionId) {
logForDebugging(
'[bridge:repl] Session creation failed during reconnection',
)
return false
}
// Bail out if teardown started during session creation (up to 15s)
if (pollController.signal.aborted) {
logForDebugging(
'[bridge:repl] Reconnect aborted after session creation, cleaning up',
)
await archiveSession(newSessionId)
return false
}
currentSessionId = newSessionId
// Re-publish to the PID file so peer dedup (peerRegistry.ts) picks up the
// new ID — setReplBridgeHandle only fires at init/teardown, not reconnect.
void updateSessionBridgeId(toCompatSessionId(newSessionId)).catch(() => {})
// Reset per-session transport state IMMEDIATELY after the session swap,
// before any await. If this runs after `await writeBridgePointer` below,
// there's a window where handle.bridgeSessionId already returns session B
// but getSSESequenceNum() still returns session A's seq — a daemon
// persistState() in that window writes {bridgeSessionId: B, seq: OLD_A},
// which PASSES the session-ID validation check and defeats it entirely.
//
// The SSE seq-num is scoped to the session's event stream — carrying it
// over leaves the transport's lastSequenceNum stuck high (seq only
// advances when received > last), and its next internal reconnect would
// send from_sequence_num=OLD_SEQ against a stream starting at 1 → all
// events in the gap silently dropped. Inbound UUID dedup is also
// session-scoped.
lastTransportSequenceNum = 0
recentInboundUUIDs.clear()
// Title derivation is session-scoped too: if the user typed during the
// createSession await above, the callback fired against the OLD archived
// session ID (PATCH lost) and the new session got `currentTitle` captured
// BEFORE they typed. Reset so the next prompt can re-derive. Self-
// correcting: if the caller's policy is already done (explicit title or
// count ≥ 3), it returns true on the first post-reset call and re-latches.
userMessageCallbackDone = !onUserMessage
logForDebugging(`[bridge:repl] Re-created session: ${currentSessionId}`)
// Rewrite the crash-recovery pointer with the new IDs so a crash after
// this point resumes the right session. (The reconnect-in-place path
// above doesn't touch the pointer — same session, same env.)
await writeBridgePointer(dir, {
sessionId: currentSessionId,
environmentId,
source: 'repl',
})
// Clear flushed UUIDs so initial messages are re-sent to the new session.
// UUIDs are scoped per-session on the server, so re-flushing is safe.
previouslyFlushedUUIDs?.clear()
// Reset the counter so independent reconnections hours apart don't
// exhaust the limit — it guards against rapid consecutive failures,
// not lifetime total.
environmentRecreations = 0
return true
}
// Helper: get the current OAuth access token for session ingress auth.
// Unlike the JWT path, OAuth tokens are refreshed by the standard OAuth
// flow — no proactive scheduler needed.
function getOAuthToken(): string | undefined {
return getAccessToken()
}
// Drain any messages that were queued during the initial flush.
// Called after writeBatch completes (or fails) so queued messages
// are sent in order after the historical messages.
function drainFlushGate(): void {
const msgs = flushGate.end()
if (msgs.length === 0) return
if (!transport) {
logForDebugging(
`[bridge:repl] Cannot drain ${msgs.length} pending message(s): no transport`,
)
return
}
for (const msg of msgs) {
recentPostedUUIDs.add(msg.uuid)
}
const sdkMessages = toSDKMessages(msgs)
const events = sdkMessages.map(sdkMsg => ({
...sdkMsg,
session_id: currentSessionId,
}))
logForDebugging(
`[bridge:repl] Drained ${msgs.length} pending message(s) after flush`,
)
void transport.writeBatch(events)
}
// Teardown reference — set after definition below. All callers are async
// callbacks that run after assignment, so the reference is always valid.
let doTeardownImpl: (() => Promise<void>) | null = null
function triggerTeardown(): void {
void doTeardownImpl?.()
}
/**
* Body of the transport's setOnClose callback, hoisted to initBridgeCore
* scope so /bridge-kick can fire it directly. setOnClose wraps this with
* a stale-transport guard; debugFireClose calls it bare.
*
* With autoReconnect:true, this only fires on: clean close (1000),
* permanent server rejection (4001/1002/4003), or 10-min budget
* exhaustion. Transient drops are retried internally by the transport.
*/
function handleTransportPermanentClose(closeCode: number | undefined): void {
logForDebugging(
`[bridge:repl] Transport permanently closed: code=${closeCode}`,
)
logEvent('tengu_bridge_repl_ws_closed', {
code: closeCode,
})
// Capture SSE seq high-water mark before nulling. When called from
// setOnClose the guard guarantees transport !== null; when fired from
// /bridge-kick it may already be null (e.g. fired twice) — skip.
if (transport) {
const closedSeq = transport.getLastSequenceNum()
if (closedSeq > lastTransportSequenceNum) {
lastTransportSequenceNum = closedSeq
}
transport = null
}
// Transport is gone — wake the poll loop out of its at-capacity
// heartbeat sleep so it's fast-polling by the time the reconnect
// below completes and the server re-queues work.
wakePollLoop()
// Reset flush state so writeMessages() hits the !transport guard
// (with a warning log) instead of silently queuing into a buffer
// that will never be drained. Unlike onWorkReceived (which
// preserves pending messages for the new transport), onClose is
// a permanent close — no new transport will drain these.
const dropped = flushGate.drop()
if (dropped > 0) {
logForDebugging(
`[bridge:repl] Dropping ${dropped} pending message(s) on transport close (code=${closeCode})`,
{ level: 'warn' },
)
}
if (closeCode === 1000) {
// Clean close — session ended normally. Tear down the bridge.
onStateChange?.('failed', 'session ended')
pollController.abort()
triggerTeardown()
return
}
// Transport reconnect budget exhausted or permanent server
// rejection. By this point the env has usually been reaped
// server-side (BQ 2026-03-12: ~98% of ws_closed never recover
// via poll alone). stopWork(force=false) can't re-dispatch work
// from an archived env; reconnectEnvironmentWithSession can
// re-activate it via POST /bridge/reconnect, or fall through
// to a fresh session if the env is truly gone. The poll loop
// (already woken above) picks up the re-queued work once
// doReconnect completes.
onStateChange?.(
'reconnecting',
`Remote Control connection lost (code ${closeCode})`,
)
logForDebugging(
`[bridge:repl] Transport reconnect budget exhausted (code=${closeCode}), attempting env reconnect`,
)
void reconnectEnvironmentWithSession().then(success => {
if (success) return
// doReconnect has four abort-check return-false sites for
// teardown-in-progress. Don't pollute the BQ failure signal
// or double-teardown when the user just quit.
if (pollController.signal.aborted) return
// doReconnect returns false (never throws) on genuine failure.
// The dangerous case: registerBridgeEnvironment succeeded (so
// environmentId now points at a fresh valid env) but
// createSession failed — poll loop would poll a sessionless
// env getting null work with no errors, never hitting any
// give-up path. Tear down explicitly.
logForDebugging(
'[bridge:repl] reconnectEnvironmentWithSession resolved false — tearing down',
)
logEvent('tengu_bridge_repl_reconnect_failed', {
close_code: closeCode,
})
onStateChange?.('failed', 'reconnection failed')
triggerTeardown()
})
}
// Ant-only: SIGUSR2 → force doReconnect() for manual testing. Skips the
// ~30s poll wait — fire-and-observe in the debug log immediately.
// Windows has no USR signals; `process.on` would throw there.
let sigusr2Handler: (() => void) | undefined
if (process.env.USER_TYPE === 'ant' && process.platform !== 'win32') {
sigusr2Handler = () => {
logForDebugging(
'[bridge:repl] SIGUSR2 received — forcing doReconnect() for testing',
)
void reconnectEnvironmentWithSession()
}
process.on('SIGUSR2', sigusr2Handler)
}
// Ant-only: /bridge-kick fault injection. handleTransportPermanentClose
// is defined below and assigned into this slot so the slash command can
// invoke it directly — the real setOnClose callback is buried inside
// wireTransport which is itself inside onWorkReceived.
let debugFireClose: ((code: number) => void) | null = null
if (process.env.USER_TYPE === 'ant') {
registerBridgeDebugHandle({
fireClose: code => {
if (!debugFireClose) {
logForDebugging('[bridge:debug] fireClose: no transport wired yet')
return
}
logForDebugging(`[bridge:debug] fireClose(${code}) — injecting`)
debugFireClose(code)
},
forceReconnect: () => {
logForDebugging('[bridge:debug] forceReconnect — injecting')
void reconnectEnvironmentWithSession()
},