-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexecution.ts
More file actions
1994 lines (1770 loc) · 71.5 KB
/
execution.ts
File metadata and controls
1994 lines (1770 loc) · 71.5 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
/**
* Forge Execution Service - Command Bus Interface
*
* Shared execution service for plan execution and loop lifecycle.
* Provides a unified interface for internal tools, API, and TUI surfaces.
*/
import type { PluginConfig, Logger } from '../types'
import type { OpencodeClient } from '@opencode-ai/sdk/v2'
import type { PlansRepo } from '../storage/repos/plans-repo'
import type { LoopsRepo } from '../storage/repos/loops-repo'
import type { createLoopEventHandler } from '../hooks'
import type { SandboxManager } from '../sandbox/manager'
import { extractPlanExecutionMetadata } from '../utils/plan-execution'
import { parseModelString, retryWithModelFallback } from '../utils/model-fallback'
import { formatLoopSessionTitle, formatPlanSessionTitle } from '../utils/session-titles'
import { buildLoopPermissionRuleset, buildAuditSessionPermissionRuleset } from '../constants/loop'
import { findPartialMatch } from '../utils/partial-match'
import { isSandboxEnabled } from '../sandbox/context'
import { createLoopSessionWithWorkspace, publishWorkspaceDetachedToast } from '../utils/loop-session'
import { aggregateToUsageSummary } from '../utils/loop-format'
import { join } from 'path'
import { existsSync } from 'fs'
import { decomposeDeterministically } from './deterministic-decomposer'
import { markPromptSent, clearPromptPending, terminationStatusFor, parseTerminationReasonString } from '../loop'
import {
withInFlightGuard,
ConcurrentPromptError,
type PromptAgent,
} from '../loop/in-flight-guard'
import { getRestartability, type RestartBlockedReason } from '../loop/restartability'
// ============================================================================
// Surface Types - Identifies the caller boundary
// ============================================================================
export type ForgeExecutionSurface = 'tool' | 'approval-hook' | 'api' | 'tui'
// ============================================================================
// Request Context
// ============================================================================
export interface ForgeExecutionRequestContext {
surface: ForgeExecutionSurface
projectId: string
directory: string
sourceSessionId?: string
requestId?: string
}
// ============================================================================
// Plan Source Types
// ============================================================================
export type PlanSource =
| { kind: 'inline'; planText: string }
| { kind: 'stored'; sessionId: string }
| { kind: 'loop-state'; loopName: string }
// ============================================================================
// Loop Extra / Attach Types
// ============================================================================
export interface ForgeLoopExtra {
hostSessionId?: string
title?: string
executionModel?: string
auditorModel?: string
executionVariant?: string
auditorVariant?: string
planSource: 'stored' | 'inline'
planText?: string
initialPromptOwner?: 'server' | 'tui'
pendingAttachStartedAt?: number
}
export interface AttachLoopInput {
sessionId: string
workspaceId?: string
worktreeDir: string
worktreeBranch?: string
loopName: string
displayName: string
executionName: string
hostSessionId?: string
executionModel?: string
auditorModel?: string
executionVariant?: string
auditorVariant?: string
maxIterations: number
sandboxEnabled: boolean
sandboxContainer?: string
planText: string
selectSession?: boolean
selectSessionTiming?: 'after-create' | 'after-prompt'
startWatchdog?: boolean
sendInitialPrompt?: boolean
abortSourceSessionOnSuccess?: boolean
onStarted?: (info: {
sessionId: string
loopName: string
displayName: string
worktreeDir?: string
workspaceId?: string
}) => void
}
// ============================================================================
// Loop Selector Types
// ============================================================================
export type LoopSelector =
| { kind: 'exact'; name: string }
| { kind: 'partial'; name: string }
| { kind: 'only-active' }
// ============================================================================
// Command Types - Discriminated Union
// ============================================================================
export interface ExecutePlanNewSessionCommand {
type: 'plan.execute.newSession'
source: PlanSource
title?: string
executionModel?: string
lifecycle?: {
selectSession?: boolean
selectSessionTiming?: 'after-create' | 'after-prompt'
abortSourceSession?: boolean
deleteSessionOnPromptFailure?: boolean
returnToSourceOnPromptFailure?: boolean
}
}
export interface ExecutePlanHereCommand {
type: 'plan.execute.here'
source: PlanSource
targetSessionId: string
title?: string
executionModel?: string
}
export interface StartLoopCommand {
type: 'loop.start'
source: PlanSource
title?: string
loopName?: string
maxIterations?: number
executionModel?: string
auditorModel?: string
executionVariant?: string
auditorVariant?: string
hostSessionId?: string
lifecycle?: {
selectSession?: boolean
selectSessionTiming?: 'after-create' | 'after-prompt'
startWatchdog?: boolean
abortSourceSessionOnSuccess?: boolean
onStarted?: (info: {
sessionId: string
loopName: string
displayName: string
worktreeDir?: string
workspaceId?: string
}) => void
}
}
export interface BuildStartLoopCommandInput {
source: PlanSource
title?: string
loopName?: string
maxIterations?: number
executionModel?: string
auditorModel?: string
executionVariant?: string
auditorVariant?: string
hostSessionId?: string
lifecycle?: StartLoopCommand['lifecycle']
}
export function buildStartLoopCommand(input: BuildStartLoopCommandInput): StartLoopCommand {
return {
type: 'loop.start',
source: input.source,
title: input.title,
loopName: input.loopName,
maxIterations: input.maxIterations,
executionModel: input.executionModel,
auditorModel: input.auditorModel,
executionVariant: input.executionVariant,
auditorVariant: input.auditorVariant,
hostSessionId: input.hostSessionId,
lifecycle: input.lifecycle,
}
}
export interface RestartLoopCommand {
type: 'loop.restart'
selector: LoopSelector
force?: boolean
}
export interface CancelLoopCommand {
type: 'loop.cancel'
selector?: LoopSelector
cleanupWorktree?: boolean
}
export interface GetLoopStatusCommand {
type: 'loop.status'
selector?: LoopSelector
includeRecent?: boolean
includeSessionOutput?: boolean
limit?: number
}
export type ForgeExecutionCommand =
| ExecutePlanNewSessionCommand
| ExecutePlanHereCommand
| StartLoopCommand
| RestartLoopCommand
| CancelLoopCommand
| GetLoopStatusCommand
// ============================================================================
// Response/Error Types
// ============================================================================
export interface ForgeExecutionError {
code: 'bad_request' | 'not_found' | 'conflict' | 'disabled' | 'prompt_failed' | 'lifecycle_failed' | 'internal_error'
status: number
message: string
candidates?: string[]
details?: Record<string, unknown>
}
export interface ForgeExecutionWarning {
code: string
message: string
}
export type ForgeExecutionResponse<T> =
| { ok: true; data: T; warnings?: ForgeExecutionWarning[] }
| { ok: false; error: ForgeExecutionError }
// ============================================================================
// Result Types per Command
// ============================================================================
export interface PlanExecutionStartedResult {
operation: 'plan.execute.newSession' | 'plan.execute.here'
mode: 'new-session' | 'execute-here'
sessionId: string
modelUsed: string | null
title: string
}
export interface LoopStartedResult {
operation: 'loop.start'
sessionId: string
loopName: string
displayName: string
executionName: string
worktreeDir?: string
worktreeBranch?: string
workspaceId?: string
hostSessionId?: string
modelUsed: string | null
maxIterations: number
deduped?: boolean
}
export interface LoopRestartedResult {
operation: 'loop.restart'
loopName: string
sessionId: string
previousSessionId: string
worktreeDir?: string
worktreeBranch?: string
worktree: boolean
sandbox: boolean
bindFailed: boolean
iteration: number
}
export interface LoopCancelledResult {
operation: 'loop.cancel'
loopName: string
sessionId: string
iteration: number
worktreeDir?: string
worktreeRemoved: boolean
worktree: boolean
worktreeBranch?: string
}
export interface LoopStatusView {
loopName: string
displayName: string
status: 'running' | 'completed' | 'cancelled' | 'errored' | 'stalled'
phase?: string
iteration: number
maxIterations: number
sessionId: string
active: boolean
startedAt: string
completedAt?: string
terminationReason?: string
worktree: boolean
worktreeDir?: string
worktreeBranch?: string
executionModel?: string
auditorModel?: string
workspaceId?: string
hostSessionId?: string
currentSectionIndex?: number
totalSections?: number
finalAuditDone?: boolean
usage?: import('../loop/token-usage').LoopUsageSummary
restartable: boolean
restartRequiresForce: boolean
restartBlockedReason?: RestartBlockedReason
restartBlockedMessage?: string
sections?: Array<{
index: number
title: string
status: string
attempts: number
startedAt?: number | null
completedAt?: number | null
summaryDone: string | null
summaryDeviations: string | null
summaryFollowUps: string | null
}>
}
export interface LoopStatusResult {
operation: 'loop.status'
loops: LoopStatusView[]
active: LoopStatusView[]
recent: LoopStatusView[]
}
// Type mapping from command to result
export type ForgeExecutionResult<C extends ForgeExecutionCommand> =
C extends ExecutePlanNewSessionCommand ? PlanExecutionStartedResult :
C extends ExecutePlanHereCommand ? PlanExecutionStartedResult :
C extends StartLoopCommand ? LoopStartedResult :
C extends RestartLoopCommand ? LoopRestartedResult :
C extends CancelLoopCommand ? LoopCancelledResult :
C extends GetLoopStatusCommand ? LoopStatusResult :
never
// ============================================================================
// Service Interface
// ============================================================================
export interface ForgeExecutionService {
dispatch<C extends ForgeExecutionCommand>(
ctx: ForgeExecutionRequestContext,
command: C,
): Promise<ForgeExecutionResponse<ForgeExecutionResult<C>>>
}
// ============================================================================
// Service Dependencies
// ============================================================================
export interface ForgeExecutionServiceDeps {
projectId: string
directory: string
config: PluginConfig
logger: Logger | Console
dataDir: string
v2: OpencodeClient
legacyClient?: import('@opencode-ai/sdk').OpencodeClient
plansRepo: PlansRepo
loopsRepo: LoopsRepo
loopHandler?: ReturnType<typeof createLoopEventHandler>
loop: import('../loop/runtime').Loop
sandboxManager?: SandboxManager | null
sectionPlansRepo?: import('../storage/repos/section-plans-repo').SectionPlansRepo
reviewFindingsRepo?: import('../storage/repos/review-findings-repo').ReviewFindingsRepo
loopSessionUsageRepo?: import('../storage/repos/loop-session-usage-repo').LoopSessionUsageRepo
workspaceStatusRegistry: import('../utils/workspace-status-registry').WorkspaceStatusRegistry
pendingTeardowns: import('../workspace/pending-teardown').PendingTeardownRegistry
}
// ============================================================================
// Helper Functions
// ============================================================================
function ok<T>(data: T, warnings?: ForgeExecutionWarning[]): ForgeExecutionResponse<T> {
return { ok: true, data, warnings }
}
function fail(
code: ForgeExecutionError['code'],
status: number,
message: string,
details?: Record<string, unknown>,
candidates?: string[]
): ForgeExecutionResponse<never> {
return {
ok: false,
error: { code, status, message, details, candidates }
}
}
// ============================================================================
// Plan Source Resolution
// ============================================================================
async function resolvePlanSource(
ctx: ForgeExecutionRequestContext,
source: PlanSource,
deps: ForgeExecutionServiceDeps,
): Promise<{ ok: true; planText: string } | { ok: false; error: ForgeExecutionError }> {
switch (source.kind) {
case 'inline': {
return { ok: true, planText: source.planText }
}
case 'stored': {
const planRow = deps.plansRepo.getForSession(ctx.projectId, source.sessionId)
if (!planRow) {
return {
ok: false,
error: {
code: 'not_found',
status: 404,
message: 'Plan not found for session',
}
}
}
return { ok: true, planText: planRow.content }
}
case 'loop-state': {
const planText = deps.loop.getPlanText(source.loopName, ctx.sourceSessionId ?? '')
if (planText) {
return { ok: true, planText }
}
return {
ok: false,
error: {
code: 'not_found',
status: 404,
message: 'Plan not found in loop state',
}
}
}
}
}
// ============================================================================
// Fallback Helpers for Legacy Plugin SDK
// ============================================================================
interface SessionCreateInput {
title: string
directory: string
permission?: ReturnType<typeof import('../constants/loop').buildLoopPermissionRuleset>
}
interface SessionCreateResult {
data?: { id: string }
error?: unknown
}
interface SessionPromptInput {
sessionID: string
directory: string
parts: Array<{ type: 'text'; text: string }>
agent: string
model?: { providerID: string; modelID: string }
workspace?: string
}
interface SessionPromptResult {
data?: unknown
error?: unknown
}
async function createSessionWithFallback(
deps: ForgeExecutionServiceDeps,
input: SessionCreateInput,
): Promise<SessionCreateResult> {
// Try v2 SDK first
try {
const result = await deps.v2.session.create({
title: input.title,
directory: input.directory,
...(input.permission ? { permission: input.permission } : {}),
})
if (result.data) {
return { data: result.data }
}
if (result.error) {
const errorMsg = result.error instanceof Error ? result.error.message : String(result.error)
if (errorMsg.includes('Unable to connect')) {
deps.logger.log('createSessionWithFallback: v2 SDK unavailable, falling back to legacy SDK')
} else {
deps.logger.error('createSessionWithFallback: v2 SDK error', result.error)
}
}
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err)
if (errorMsg.includes('Unable to connect')) {
deps.logger.log('createSessionWithFallback: v2 SDK threw connection error, falling back to legacy SDK')
} else {
deps.logger.error('createSessionWithFallback: v2 SDK threw error', err)
}
}
// Fallback to legacy SDK
if (!deps.legacyClient) {
deps.logger.error('createSessionWithFallback: no legacy SDK available')
return { error: new Error('No legacy SDK available') }
}
try {
const result = await deps.legacyClient.session.create({
body: {
title: input.title,
...(input.permission ? { permission: input.permission } : {}),
},
query: {
directory: input.directory,
},
} as Parameters<typeof deps.legacyClient.session.create>[0])
const session = result.data as { id?: string } | undefined
if (session?.id) {
return { data: { id: session.id } }
}
return { error: new Error('Legacy SDK returned no session ID') }
} catch (err) {
deps.logger.error('createSessionWithFallback: legacy SDK failed', err)
return { error: err }
}
}
async function promptSessionWithFallback(
deps: ForgeExecutionServiceDeps,
input: SessionPromptInput,
model?: { providerID: string; modelID: string },
): Promise<{ result: SessionPromptResult; usedModel?: typeof model }> {
// Try v2 SDK first
try {
const result = await deps.v2.session.promptAsync({
sessionID: input.sessionID,
directory: input.directory,
parts: input.parts,
agent: input.agent,
...(model ? { model } : {}),
...(input.workspace ? { workspace: input.workspace } : {}),
})
if (!result.error) {
return { result: { data: result.data }, usedModel: model }
}
const errorMsg = result.error instanceof Error ? result.error.message : String(result.error)
if (errorMsg.includes('Unable to connect')) {
deps.logger.log('promptSessionWithFallback: v2 SDK unavailable, falling back to legacy SDK')
} else {
deps.logger.error('promptSessionWithFallback: v2 SDK error', result.error)
}
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err)
if (errorMsg.includes('Unable to connect')) {
deps.logger.log('promptSessionWithFallback: v2 SDK threw connection error, falling back to legacy SDK')
} else {
deps.logger.error('promptSessionWithFallback: v2 SDK threw error', err)
}
}
// Fallback to legacy SDK
if (!deps.legacyClient) {
deps.logger.error('promptSessionWithFallback: no legacy SDK available')
return { result: { error: new Error('No legacy SDK available') }, usedModel: model }
}
try {
const legacyResult = await deps.legacyClient.session.promptAsync({
path: { id: input.sessionID },
query: {
directory: input.directory,
...(input.workspace ? { workspace: input.workspace } : {}),
},
body: {
agent: input.agent,
parts: input.parts,
...(model ? { model } : {}),
},
} as Parameters<typeof deps.legacyClient.session.promptAsync>[0])
// Legacy SDK returns { data, request, response }
const legacyData = legacyResult as { data?: unknown }
if (!legacyData.data) {
return { result: { error: new Error('Legacy SDK returned no data') }, usedModel: model }
}
return { result: { data: legacyData.data }, usedModel: model }
} catch (err) {
deps.logger.error('promptSessionWithFallback: legacy SDK failed', err)
return { result: { error: err }, usedModel: model }
}
}
async function selectSessionWithFallback(
deps: ForgeExecutionServiceDeps,
selection: { sessionID: string; workspace?: string },
): Promise<void> {
const maxAttempts = 3
const backoffMs = 250
async function attemptSelectSession(attempt: number): Promise<{ ok: boolean; retryable: boolean }> {
try {
await deps.v2.tui!.selectSession({
sessionID: selection.sessionID,
...(selection.workspace ? { workspace: selection.workspace } : {}),
})
deps.logger.log(`[warp] select.v2.selectSession ok attempt=${attempt}`)
return { ok: true, retryable: false }
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err)
deps.logger.log(`[warp] select.v2.selectSession failed attempt=${attempt} error="${errorMsg}"`)
const retryable = errorMsg.includes('Unable to connect')
if (retryable) {
deps.logger.log('selectSessionWithFallback: v2 TUI unavailable, will retry then fall back to publish')
} else {
deps.logger.error('selectSessionWithFallback: v2 TUI error', err)
}
return { ok: false, retryable }
}
}
if (deps.v2.tui) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const result = await attemptSelectSession(attempt)
if (result.ok) return
if (!result.retryable) break
if (attempt < maxAttempts) {
await new Promise(resolve => setTimeout(resolve, backoffMs))
}
}
} else {
deps.logger.log('[warp] select.v2.selectSession skipped reason=no-v2-tui')
}
try {
if (!deps.v2.tui) {
deps.logger.log('[warp] select.v2.publish skipped reason=no-v2-tui')
} else {
await deps.v2.tui.publish({
directory: deps.directory,
body: {
type: 'tui.session.select',
properties: {
sessionID: selection.sessionID,
...(selection.workspace ? { workspace: selection.workspace } : {}),
},
},
})
deps.logger.log('[warp] select.v2.publish ok')
return
}
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err)
deps.logger.log(`[warp] select.v2.publish failed error="${errorMsg}"`)
if (errorMsg.includes('Unable to connect')) {
deps.logger.log('selectSessionWithFallback: v2 TUI publish unavailable, falling back to legacy SDK')
} else {
deps.logger.error('selectSessionWithFallback: v2 TUI publish error', err)
}
}
if (!deps.legacyClient?.tui) {
deps.logger.log('[warp] select.legacy.publish skipped reason=no-legacy-tui')
deps.logger.error('selectSessionWithFallback: no legacy TUI available')
return
}
try {
await deps.legacyClient.tui.publish({
body: {
type: 'tui.session.select',
properties: {
sessionID: selection.sessionID,
...(selection.workspace ? { workspace: selection.workspace } : {}),
},
},
} as unknown as Parameters<typeof deps.legacyClient.tui.publish>[0])
deps.logger.log('[warp] select.legacy.publish ok')
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err)
deps.logger.log(`[warp] select.legacy.publish failed error="${errorMsg}"`)
deps.logger.error('selectSessionWithFallback: legacy TUI failed', err)
}
}
export interface SelectInitialWorktreeSessionOpts {
selectSession: boolean | undefined
logger: Logger | Console
workspaceStatusRegistry: import('../utils/workspace-status-registry').WorkspaceStatusRegistry
selectSessionFn: (selection: { sessionID: string; workspace?: string }) => Promise<void>
/** Maximum time to wait for selectSessionFn before falling through. Defaults to 2000ms. */
selectTimeoutMs?: number
}
export async function selectInitialWorktreeSession(
targetSessionId: string,
boundWorkspaceId: string | undefined,
context: string,
opts: SelectInitialWorktreeSessionOpts,
): Promise<void> {
opts.logger.log(`[warp] select.entry context="${context}" targetSessionId=${targetSessionId} workspaceId=${boundWorkspaceId ?? 'none'}`)
if (!opts.selectSession) {
opts.logger.log(`[warp] select.exit context="${context}" reason=no-select-session`)
return
}
if (!boundWorkspaceId) {
opts.logger.log(`[warp] select.exit context="${context}" reason=no-workspace`)
return
}
const totalStart = Date.now()
try {
const connectedResult = await opts.workspaceStatusRegistry.awaitConnected(boundWorkspaceId, {
timeoutMs: 5000,
logger: opts.logger as Logger,
})
const readyElapsedMs = Date.now() - totalStart
if (connectedResult.connected) {
opts.logger.log(
`[warp] select.ready context="${context}" source=${connectedResult.source} elapsedMs=${readyElapsedMs}`,
)
} else {
opts.logger.log(
`[warp] select.degraded context="${context}" reason="${connectedResult.reason ?? 'unknown'}" lastStatus="${connectedResult.lastStatus ?? 'none'}" elapsedMs=${readyElapsedMs}`,
)
}
const envTimeout = Number(process.env.FORGE_SELECT_TIMEOUT_MS)
const SELECT_TIMEOUT_MS = opts.selectTimeoutMs ?? (Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : 2000)
await Promise.race([
opts.selectSessionFn({ sessionID: targetSessionId, workspace: boundWorkspaceId }),
new Promise<void>((resolve) => setTimeout(resolve, SELECT_TIMEOUT_MS)),
])
const totalMs = Date.now() - totalStart
opts.logger.log(`[warp] select.complete context="${context}" totalMs=${totalMs}`)
} catch (err) {
const totalMs = Date.now() - totalStart
opts.logger.error(
`[warp] select.failed context="${context}" error="${err instanceof Error ? err.message : String(err)}" totalMs=${totalMs}`,
)
}
}
// ============================================================================
// attachLoopToSession
// ============================================================================
export async function attachLoopToSession(
deps: ForgeExecutionServiceDeps,
ctx: ForgeExecutionRequestContext,
input: AttachLoopInput,
): Promise<{ ok: true; loopName: string } | { ok: false; code: 'already_attached' | 'conflict' | 'internal_error' | 'prompt_failed'; message: string }> {
const {
sessionId,
workspaceId,
worktreeDir,
worktreeBranch,
loopName,
displayName,
executionModel,
auditorModel,
executionVariant,
auditorVariant,
maxIterations,
sandboxEnabled,
sandboxContainer,
planText,
selectSession,
selectSessionTiming,
startWatchdog,
sendInitialPrompt = true,
abortSourceSessionOnSuccess,
onStarted,
} = input
const loopModel = parseModelString(executionModel)
const existing = deps.loopsRepo.get(ctx.projectId, loopName)
if (existing) {
if (existing.status === 'running') {
deps.logger.log(`attachLoopToSession: loop ${loopName} already attached (running), skipping`)
return { ok: false, code: 'already_attached', message: `Loop ${loopName} is already attached` }
}
deps.logger.log(`attachLoopToSession: loop ${loopName} has terminal status ${existing.status}; refusing attach`)
return { ok: false, code: 'conflict', message: `Loop ${loopName} is terminal. Use loop restart to resume or start a new suffixed loop.` }
}
// Defensive purge of orphaned per-loop rows (section_plans cascade may not have fired
// historically; plans/review_findings have no FK). Idempotent.
try {
const removedSections = deps.sectionPlansRepo?.deleteAll(ctx.projectId, loopName) ?? 0
deps.plansRepo.deleteForLoop(ctx.projectId, loopName)
deps.reviewFindingsRepo?.deleteByLoopName(ctx.projectId, loopName)
if (removedSections > 0) {
deps.logger.log(`attachLoopToSession: purged ${removedSections} orphaned section_plans rows for ${loopName}`)
}
} catch (err) {
deps.logger.error(`attachLoopToSession: failed to purge orphaned per-loop rows for ${loopName}`, err)
// Non-fatal — proceed.
}
try {
// Persist loop state
const state: import('../loop/state').LoopState = {
active: true,
sessionId,
loopName,
worktreeDir: worktreeDir ?? ctx.directory,
projectDir: ctx.directory,
worktreeBranch,
iteration: 1,
maxIterations,
startedAt: new Date().toISOString(),
prompt: planText,
phase: 'coding',
errorCount: 0,
auditCount: 0,
status: 'running',
worktree: true,
sandbox: sandboxEnabled,
sandboxContainer: sandboxContainer ?? undefined,
executionModel,
auditorModel,
executionVariant,
auditorVariant,
workspaceId,
hostSessionId: input.hostSessionId,
currentSectionIndex: 0,
totalSections: 0,
finalAuditDone: false,
}
deps.loop.setState(loopName, state)
deps.loop.registerLoopSession(sessionId, loopName)
deps.logger.log(`attachLoopToSession: state stored for loop=${loopName}`)
onStarted?.({
sessionId,
loopName,
displayName,
worktreeDir,
workspaceId,
})
// === Section extraction ===
const maxSections = 12
const sections = decomposeDeterministically(planText, { maxSections })
let promptText: string
if (sections.length > 0 && deps.sectionPlansRepo) {
deps.sectionPlansRepo.bulkInsert({ projectId: ctx.projectId, loopName, sections })
deps.loopsRepo.setTotalSections(ctx.projectId, loopName, sections.length)
deps.loopsRepo.setCurrentSectionIndex(ctx.projectId, loopName, 0)
deps.sectionPlansRepo.setStatus(ctx.projectId, loopName, 0, 'in_progress')
deps.sectionPlansRepo.setStartedAt(ctx.projectId, loopName, 0, Date.now())
const updatedState = { ...state, phase: 'coding' as const, currentSectionIndex: 0, totalSections: sections.length }
promptText = deps.loop.buildSectionInitialPrompt(updatedState as import('../loop/state').LoopState)
} else {
deps.loopsRepo.setTotalSections(ctx.projectId, loopName, 0)
promptText = planText
}
// Wait for sandbox readiness in worktree+sandbox mode (after persistence)
if (sandboxEnabled && deps.sandboxManager && deps.dataDir) {
const dbPath = join(deps.dataDir, 'forge.db')
if (existsSync(dbPath)) {
const { waitForSandboxReady } = await import('../utils/sandbox-ready')
const waitResult = await waitForSandboxReady({
projectId: ctx.projectId,
loopName,
dbPath,
pollMs: 200,
timeoutMs: 15_000,
})
if (!waitResult.ready) {
deps.logger.error(`attachLoopToSession: sandbox not ready (${waitResult.reason})`)
try {
const { createDockerService } = await import('../sandbox/docker')
const docker = createDockerService(deps.logger as unknown as Console)
const cn = docker.containerName(loopName)
if (await docker.isRunning(cn)) {
await docker.removeContainer(cn)
}
} catch (cleanupErr) {
deps.logger.error('attachLoopToSession: failed to remove sandbox container after timeout', cleanupErr)
}
deps.loop.deleteState(loopName)
return { ok: false, code: 'internal_error', message: `Sandbox not ready: ${waitResult.reason}` }
}
deps.logger.log(`attachLoopToSession: sandbox ready (${waitResult.containerName})`)
}
}
// Navigate TUI if requested with early timing
if (selectSession && selectSessionTiming === 'after-create') {
const selection = workspaceId
? { workspace: workspaceId, sessionID: sessionId }
: { sessionID: sessionId }
selectSessionWithFallback(deps, selection).catch((err: unknown) => {
deps.logger.error('attachLoopToSession: failed to navigate TUI (early)', err as Error)
})
}
if (!sendInitialPrompt) {
if (startWatchdog && deps.loopHandler) {
deps.loopHandler.startWatchdog(loopName)
}
deps.logger.log(`attachLoopToSession: attached loop=${loopName} without sending initial prompt`)
return { ok: true, loopName }
}
// Send initial prompt with fallback
const sessionDir = worktreeDir
const promptParts = [{ type: 'text' as const, text: promptText }]
const workspaceParam = workspaceId ? { workspace: workspaceId } : {}
let promptResult: { result: SessionPromptResult; usedModel?: typeof loopModel }
if (loopModel) {
promptResult = await retryWithModelFallback(
async () => {
markPromptSent(loopName, sessionId, deps.logger)
const { result } = await promptSessionWithFallback(
deps,
{
sessionID: sessionId,
directory: sessionDir,
parts: promptParts,
agent: 'code',
...workspaceParam,
},
loopModel,
)
return result
},
async () => {
markPromptSent(loopName, sessionId, deps.logger)
const { result } = await promptSessionWithFallback(
deps,
{
sessionID: sessionId,
directory: sessionDir,
parts: promptParts,
agent: 'code',
...workspaceParam,
},
undefined,
)
return result
},
loopModel,
deps.logger as unknown as Console,
)
} else {
markPromptSent(loopName, sessionId, deps.logger)
promptResult = await promptSessionWithFallback(
deps,
{
sessionID: sessionId,
directory: sessionDir,
parts: promptParts,
agent: 'code',
...workspaceParam,
},
loopModel,
)
}