-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathforge-session-attach.ts
More file actions
382 lines (355 loc) · 15.4 KB
/
forge-session-attach.ts
File metadata and controls
382 lines (355 loc) · 15.4 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
import type { createOpencodeClient as createV2Client } from '@opencode-ai/sdk/v2'
import type { Logger } from '../types'
import type { ForgeExecutionServiceDeps, PlanSource } from '../services/execution'
import { attachLoopToSession } from '../services/execution'
import { resolveSandboxContextForLoop } from '../sandbox/context'
import { classifyForgeWorkspace, isPendingAttachWorkspace } from '../workspace/classify-stale'
import { removeForgeWorkspaceWithContext } from '../workspace/remove-with-context'
import { getForgeWorkspaceLoopName } from '../workspace/forge-worktree'
export interface ForgeSessionAttachHookDeps {
v2: ReturnType<typeof createV2Client>
execDeps: ForgeExecutionServiceDeps
projectId: string
directory: string
logger: Logger
attachLoopToSession?: typeof attachLoopToSession
}
interface WorkspaceEntry {
id: string
type: string
directory?: string | undefined
extra?: Record<string, unknown> | undefined
}
export function createForgeSessionAttachHook(deps: ForgeSessionAttachHookDeps) {
return async (eventInput: { event: { type: string; properties?: Record<string, unknown> } }) => {
if (eventInput.event.type !== 'session.created') return
const sessionInfo = eventInput.event.properties?.info as Record<string, unknown> | undefined
const sessionId = sessionInfo?.id as string | undefined
const workspaceId = sessionInfo?.workspaceID as string | undefined
const sessionDirectory = sessionInfo?.directory as string | undefined
const sessionProjectId = (sessionInfo?.projectID as string | undefined) ?? deps.projectId
if (!sessionId || !workspaceId) return
await attachForgeSession(deps, {
sessionId,
workspaceId,
sessionDirectory,
sessionProjectId,
sendInitialPrompt: true,
selectSession: true,
})
}
}
export function createForgeSessionMessageAttachHook(deps: ForgeSessionAttachHookDeps) {
return async (input: { sessionID: string }) => {
const sessionId = input.sessionID
if (!sessionId) return
const sessionResult = await deps.v2.session?.get?.({ sessionID: sessionId }).catch(() => null)
const sessionInfo = (sessionResult?.data ?? null) as Record<string, unknown> | null
const workspaceId = sessionInfo?.workspaceID as string | undefined
if (!workspaceId) return
await attachForgeSession(deps, {
sessionId,
workspaceId,
sessionDirectory: sessionInfo?.directory as string | undefined,
sessionProjectId: (sessionInfo?.projectID as string | undefined) ?? deps.projectId,
sendInitialPrompt: false,
selectSession: false,
})
}
}
async function attachForgeSession(
deps: ForgeSessionAttachHookDeps,
input: {
sessionId: string
workspaceId: string
sessionDirectory?: string
sessionProjectId: string
sendInitialPrompt: boolean
selectSession: boolean
},
): Promise<void> {
const { sessionId, workspaceId, sessionDirectory, sessionProjectId, sendInitialPrompt, selectSession } = input
let ws = await findWorkspaceById(deps, workspaceId, sessionDirectory)
if (!ws) {
await new Promise<void>((r) => setTimeout(r, 100))
ws = await findWorkspaceById(deps, workspaceId, sessionDirectory)
if (!ws) {
deps.logger.log(
`[forge-session-attach] skip session=${sessionId}: workspace ${workspaceId} not found ` +
`via experimental.workspace.list directory=${sessionDirectory ?? '(none)'} ` +
`(cross-project or sync lag)`,
)
if (sessionDirectory) {
publishAttachFailureToast(
deps,
sessionDirectory,
`Forge loop (workspace ${workspaceId})`,
'Workspace not visible from this plugin instance — open the TUI in the loop\'s project.',
)
}
return
}
}
if (ws.type !== 'forge') {
deps.logger.log(`[forge-session-attach] skip session=${sessionId} workspace=${workspaceId} reason=non-forge-type type=${ws.type}`)
return
}
const loopName = getForgeWorkspaceLoopName(ws)
if (!loopName) {
const extraKeys = ws.extra ? Object.keys(ws.extra) : []
deps.logger.log(`[forge-session-attach] skip session=${sessionId} workspace=${workspaceId} reason=no-loop-name extraKeys=[${extraKeys.join(',')}]`)
return
}
const cfg = (ws.extra ?? {}).forgeLoop as {
hostSessionId?: string
title?: string
executionModel?: string
auditorModel?: string
executionVariant?: string
auditorVariant?: string
planSource?: 'stored' | 'inline'
planText?: string
initialPromptOwner?: 'server' | 'tui'
maxIterations?: number
sandboxEnabled?: boolean
sandboxContainer?: string
} | undefined
if (cfg?.initialPromptOwner === 'tui' && sendInitialPrompt) {
deps.logger.log(`[forge-session-attach] skip session=${sessionId} loop=${loopName} reason=tui-owned-initial-prompt`)
return
}
// Build a synthetic entry for classification. If extra.projectDirectory is missing,
// synthesize it from ws.directory so the classifier can still check the loop row.
// This ensures the attach hook handles workspaces created by older code paths that
// didn't stamp extra.projectDirectory.
const ws_extra_proj = (ws.extra ?? {}).projectDirectory as string | undefined
const projectDirectory = ws_extra_proj ?? ws.directory ?? deps.directory
const classifyEntry = {
id: workspaceId,
type: ws.type,
extra: ws_extra_proj
? (ws.extra ?? {})
: { ...(ws.extra ?? {}), projectDirectory },
}
const action = classifyForgeWorkspace(
classifyEntry,
deps.execDeps.loopsRepo,
sessionProjectId,
projectDirectory,
)
if (action.action === 'keep' && action.reason !== 'running' && action.reason !== 'pending-attach') {
// bad config or wrong-project — toast and bail, do not attach
deps.logger.log(
`[forge-session-attach] skip session=${sessionId} workspace=${workspaceId} reason=${action.reason}`,
)
return
}
if ((action.action === 'remove-fully' && action.reason === 'missing-row') || (action.action === 'keep' && action.reason === 'pending-attach')) {
// Fresh attach (no loop row yet) - proceed to attach
if (!cfg) {
if (action.action === 'remove-fully') {
await removeForgeWorkspaceWithContext(
{ v2: deps.v2, pendingTeardowns: deps.execDeps.pendingTeardowns, logger: deps.logger },
{ workspaceId, loopName, action: 'remove-fully', reasonLabel: 'attach-missing-row-no-config' },
)
publishAttachFailureToast(
deps,
ws.directory ?? deps.directory,
`Forge loop "${loopName}"`,
'Loop metadata missing. Removed stale workspace registration.',
)
} else {
const extraKeys = ws.extra ? Object.keys(ws.extra) : []
deps.logger.log(`[forge-session-attach] skip session=${sessionId} workspace=${workspaceId} reason=no-forgeLoop-config extraKeys=[${extraKeys.join(',')}]`)
}
return
}
if (action.action === 'remove-fully' && cfg.initialPromptOwner === 'tui' && !isPendingAttachWorkspace(classifyEntry)) {
await removeForgeWorkspaceWithContext(
{ v2: deps.v2, pendingTeardowns: deps.execDeps.pendingTeardowns, logger: deps.logger },
{ workspaceId, loopName, action: 'remove-fully', reasonLabel: 'attach-expired-pending' },
)
publishAttachFailureToast(
deps,
ws.directory ?? deps.directory,
`Forge loop "${loopName}"`,
'Loop attach window expired. Run a new plan to start fresh.',
)
return
}
deps.logger.log(`[forge-session-attach] session=${sessionId} loop=${loopName} projectId=${sessionProjectId} proceeding (fresh-attach)`)
} else if (action.action === 'keep' && action.reason === 'running') {
// Running loop but no in-memory state: this is the plugin-reload recovery case
// However, the loop is already running, so we should NOT re-attach
deps.logger.log(`[forge-session-attach] skip session=${sessionId} loop=${loopName} reason=already-running`)
return
} else if (action.action === 'remove-fully' && action.reason === 'completed') {
// Completed loop: remove workspace + toast
await removeForgeWorkspaceWithContext(
{ v2: deps.v2, pendingTeardowns: deps.execDeps.pendingTeardowns, logger: deps.logger },
{ workspaceId, loopName, action: 'remove-fully', reasonLabel: 'attach-safety-net-completed' },
)
publishAttachFailureToast(
deps,
ws.directory ?? deps.directory,
`Forge loop "${loopName}"`,
'Loop already completed. Run a new plan to start fresh.',
)
return
} else if (action.action === 'remove-registration-only') {
// Restartable (cancelled/errored/stalled): remove registration, preserve worktree for manual restart
await removeForgeWorkspaceWithContext(
{ v2: deps.v2, pendingTeardowns: deps.execDeps.pendingTeardowns, logger: deps.logger },
{ workspaceId, loopName, action: 'remove-registration-only', reasonLabel: 'attach-safety-net-restartable' },
)
publishAttachFailureToast(
deps,
ws.directory ?? deps.directory,
`Forge loop "${loopName}"`,
`Loop "${loopName}" is in terminal status. Use Loop-status restart to resume.`,
)
return
} else {
// Fallback: should not reach here
deps.logger.log(`[forge-session-attach] skip session=${sessionId} loop=${loopName} reason=unexpected-classification`)
return
}
if (!cfg) return
const resolvedHostSessionId = cfg.hostSessionId && cfg.hostSessionId.length > 0
? cfg.hostSessionId
: sessionId
const planSource: PlanSource =
cfg.planSource === 'inline' && cfg.planText
? { kind: 'inline', planText: cfg.planText }
: { kind: 'stored', sessionId: resolvedHostSessionId }
let planText: string
if (planSource.kind === 'inline') {
planText = planSource.planText
} else {
const row = deps.execDeps.plansRepo.getForSession(sessionProjectId, planSource.sessionId)
if (!row) {
deps.logger.error(`[forge-session-attach] plan not found for session=${planSource.sessionId} loop=${loopName} workspace=${workspaceId}`)
publishAttachFailureToast(deps, ws.directory ?? deps.directory, `Forge loop "${loopName}"`, 'No stored plan found for this loop. Re-run "Execute → Loop" from a session that has a captured plan.')
await removeForgeWorkspaceWithContext(
{ v2: deps.v2, pendingTeardowns: deps.execDeps.pendingTeardowns, logger: deps.logger },
{ workspaceId, loopName, action: 'remove-fully', reasonLabel: 'attach-no-plan' },
)
return
}
planText = row.content
}
try {
const sandbox = await resolveAttachSandbox(deps, cfg, loopName, ws.directory ?? deps.directory)
const loopFn = deps.attachLoopToSession ?? attachLoopToSession
const result = await loopFn(
deps.execDeps,
{ surface: 'tui', projectId: sessionProjectId, directory: ws.directory ?? deps.directory },
{
sessionId,
workspaceId,
worktreeDir: ws.directory ?? '',
loopName,
displayName: cfg.title ?? loopName,
executionName: loopName,
hostSessionId: resolvedHostSessionId,
executionModel: cfg.executionModel,
auditorModel: cfg.auditorModel,
executionVariant: cfg.executionVariant,
auditorVariant: cfg.auditorVariant,
maxIterations: cfg.maxIterations ?? 50,
sandboxEnabled: sandbox.enabled,
sandboxContainer: sandbox.containerName,
planText,
selectSession,
selectSessionTiming: 'after-prompt',
startWatchdog: true,
sendInitialPrompt,
},
)
if (!result.ok && result.code === 'conflict') {
const row = deps.execDeps.loopsRepo.get(sessionProjectId, loopName)
const removalAction = row?.status === 'cancelled' || row?.status === 'errored' || row?.status === 'stalled'
? 'remove-registration-only'
: 'remove-fully'
publishAttachFailureToast(
deps,
ws.directory ?? deps.directory,
`Forge loop "${loopName}"`,
removalAction === 'remove-registration-only'
? `Loop "${loopName}" is in terminal status. Use Loop-status restart to resume.`
: `Failed to start loop: ${result.message}`,
)
await removeForgeWorkspaceWithContext(
{ v2: deps.v2, pendingTeardowns: deps.execDeps.pendingTeardowns, logger: deps.logger },
{ workspaceId, loopName, action: removalAction, reasonLabel: 'attach-conflict-terminal' },
)
} else if (!result.ok && result.code !== 'already_attached') {
publishAttachFailureToast(deps, ws.directory ?? deps.directory, `Forge loop "${loopName}"`, `Failed to start loop: ${result.message}`)
await removeForgeWorkspaceWithContext(
{ v2: deps.v2, pendingTeardowns: deps.execDeps.pendingTeardowns, logger: deps.logger },
{ workspaceId, loopName, action: 'remove-fully', reasonLabel: 'attach-failed' },
)
}
} catch (err) {
deps.logger.error('[forge-session-attach] attachLoopToSession threw', err)
publishAttachFailureToast(deps, ws.directory ?? deps.directory, `Forge loop "${loopName}"`, 'Failed to start loop (unexpected error). Check forge logs.')
await removeForgeWorkspaceWithContext(
{ v2: deps.v2, pendingTeardowns: deps.execDeps.pendingTeardowns, logger: deps.logger },
{ workspaceId, loopName, action: 'remove-fully', reasonLabel: 'attach-error' },
)
}
}
async function resolveAttachSandbox(
deps: ForgeSessionAttachHookDeps,
cfg: { sandboxEnabled?: boolean; sandboxContainer?: string } | undefined,
loopName: string,
worktreeDir: string | undefined,
): Promise<{ enabled: boolean; containerName?: string }> {
if (cfg?.sandboxEnabled === false) return { enabled: false }
const sandbox = await resolveSandboxContextForLoop(
deps.execDeps.sandboxManager,
{ loopName, active: true, sandbox: true, worktreeDir },
deps.logger,
{ throwOnRestoreError: true },
)
if (sandbox) {
return { enabled: true, containerName: sandbox.containerName }
}
if (!deps.execDeps.sandboxManager || !worktreeDir) {
return { enabled: cfg?.sandboxEnabled ?? false, containerName: cfg?.sandboxContainer }
}
return { enabled: cfg?.sandboxEnabled ?? false, containerName: cfg?.sandboxContainer }
}
function publishAttachFailureToast(
deps: ForgeSessionAttachHookDeps,
directory: string,
title: string,
message: string,
): void {
const tui = deps.v2.tui
if (!tui || typeof tui.publish !== 'function') return
tui.publish({
directory,
body: {
type: 'tui.toast.show',
properties: { title, message, variant: 'error', duration: 6000 },
},
}).catch((err) => {
deps.logger.error('[forge-session-attach] failed to publish toast', err)
})
}
async function findWorkspaceById(
deps: ForgeSessionAttachHookDeps,
workspaceId: string,
directory?: string,
): Promise<WorkspaceEntry | null> {
try {
const result = await deps.v2.experimental.workspace.list(
directory ? { directory } : undefined,
)
const entries = (result.data ?? []) as WorkspaceEntry[]
return entries.find((e) => e.id === workspaceId) ?? null
} catch {
return null
}
}