-
-
Notifications
You must be signed in to change notification settings - Fork 435
Expand file tree
/
Copy pathapiMachine.ts
More file actions
355 lines (313 loc) · 13.1 KB
/
apiMachine.ts
File metadata and controls
355 lines (313 loc) · 13.1 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
/**
* WebSocket client for machine/runner communication with hapi-hub
*/
import { io, type Socket } from 'socket.io-client'
import { stat } from 'node:fs/promises'
import { logger } from '@/ui/logger'
import { configuration } from '@/configuration'
import type { Update, UpdateMachineBody } from '@hapi/protocol'
import type { RunnerState, Machine, MachineMetadata } from './types'
import { RunnerStateSchema, MachineMetadataSchema } from './types'
import { backoff } from '@/utils/time'
import { getInvokedCwd } from '@/utils/invokedCwd'
import { RpcHandlerManager } from './rpc/RpcHandlerManager'
import { registerCommonHandlers } from '../modules/common/registerCommonHandlers'
import type {
RpcListImportableSessionsRequest,
RpcListImportableSessionsResponse,
SpawnSessionOptions,
SpawnSessionResult
} from '../modules/common/rpcTypes'
import { listImportableClaudeSessions } from '@/claude/utils/listImportableClaudeSessions'
import { listImportableCodexSessions } from '@/codex/utils/listImportableCodexSessions'
import { applyVersionedAck } from './versionedUpdate'
interface ServerToRunnerEvents {
update: (data: Update) => void
'rpc-request': (data: { method: string; params: string }, callback: (response: string) => void) => void
error: (data: { message: string }) => void
}
interface RunnerToServerEvents {
'machine-alive': (data: { machineId: string; time: number }) => void
'machine-update-metadata': (data: { machineId: string; metadata: unknown; expectedVersion: number }, cb: (answer: {
result: 'error'
} | {
result: 'version-mismatch'
version: number
metadata: unknown | null
} | {
result: 'success'
version: number
metadata: unknown | null
}) => void) => void
'machine-update-state': (data: { machineId: string; runnerState: unknown | null; expectedVersion: number }, cb: (answer: {
result: 'error'
} | {
result: 'version-mismatch'
version: number
runnerState: unknown | null
} | {
result: 'success'
version: number
runnerState: unknown | null
}) => void) => void
'rpc-register': (data: { method: string }) => void
'rpc-unregister': (data: { method: string }) => void
}
type MachineRpcHandlers = {
spawnSession: (options: SpawnSessionOptions) => Promise<SpawnSessionResult>
stopSession: (sessionId: string) => boolean
requestShutdown: () => void
}
interface PathExistsRequest {
paths: string[]
}
interface PathExistsResponse {
exists: Record<string, boolean>
}
export class ApiMachineClient {
private socket!: Socket<ServerToRunnerEvents, RunnerToServerEvents>
private keepAliveInterval: NodeJS.Timeout | null = null
private rpcHandlerManager: RpcHandlerManager
constructor(
private readonly token: string,
private readonly machine: Machine
) {
this.rpcHandlerManager = new RpcHandlerManager({
scopePrefix: this.machine.id,
logger: (msg, data) => logger.debug(msg, data)
})
registerCommonHandlers(this.rpcHandlerManager, getInvokedCwd())
this.registerMachineHandlers()
}
setRPCHandlers({ spawnSession, stopSession, requestShutdown }: MachineRpcHandlers): void {
this.rpcHandlerManager.registerHandler('spawn-happy-session', async (params: any) => {
const { directory, sessionId, resumeSessionId, machineId, approvedNewDirectoryCreation, agent, model, effort, modelReasoningEffort, yolo, token, sessionType, worktreeName } = params || {}
if (!directory) {
throw new Error('Directory is required')
}
const result = await spawnSession({
directory,
sessionId,
resumeSessionId,
machineId,
approvedNewDirectoryCreation,
agent,
model,
effort,
modelReasoningEffort,
yolo,
token,
sessionType,
worktreeName
})
switch (result.type) {
case 'success':
return { type: 'success', sessionId: result.sessionId }
case 'requestToApproveDirectoryCreation':
return { type: 'requestToApproveDirectoryCreation', directory: result.directory }
case 'error':
return { type: 'error', errorMessage: result.errorMessage }
}
})
this.rpcHandlerManager.registerHandler('stop-session', (params: any) => {
const { sessionId } = params || {}
if (!sessionId) {
throw new Error('Session ID is required')
}
const success = stopSession(sessionId)
if (!success) {
throw new Error('Session not found or failed to stop')
}
return { message: 'Session stopped' }
})
this.rpcHandlerManager.registerHandler('stop-runner', () => {
setTimeout(() => requestShutdown(), 100)
return { message: 'Runner stop request acknowledged' }
})
}
private registerMachineHandlers(): void {
this.rpcHandlerManager.registerHandler<PathExistsRequest, PathExistsResponse>('path-exists', async (params) => {
const rawPaths = Array.isArray(params?.paths) ? params.paths : []
const uniquePaths = Array.from(new Set(rawPaths.filter((path): path is string => typeof path === 'string')))
const exists: Record<string, boolean> = {}
await Promise.all(uniquePaths.map(async (path) => {
const trimmed = path.trim()
if (!trimmed) return
try {
const stats = await stat(trimmed)
exists[trimmed] = stats.isDirectory()
} catch {
exists[trimmed] = false
}
}))
return { exists }
})
this.rpcHandlerManager.registerHandler<RpcListImportableSessionsRequest, RpcListImportableSessionsResponse>(
'list-importable-sessions',
async (params) => {
if (params?.agent === 'codex') {
return await listImportableCodexSessions()
}
if (params?.agent === 'claude') {
return await listImportableClaudeSessions()
}
return { sessions: [] }
}
)
}
async updateMachineMetadata(handler: (metadata: MachineMetadata | null) => MachineMetadata): Promise<void> {
await backoff(async () => {
const updated = handler(this.machine.metadata)
const answer = await this.socket.emitWithAck('machine-update-metadata', {
machineId: this.machine.id,
metadata: updated,
expectedVersion: this.machine.metadataVersion
}) as unknown
applyVersionedAck(answer, {
valueKey: 'metadata',
parseValue: (value) => {
const parsed = MachineMetadataSchema.safeParse(value)
return parsed.success ? parsed.data : null
},
applyValue: (value) => {
this.machine.metadata = value
},
applyVersion: (version) => {
this.machine.metadataVersion = version
},
logInvalidValue: (context, version) => {
const suffix = context === 'success' ? 'ack' : 'version-mismatch ack'
logger.debug(`[API MACHINE] Ignoring invalid metadata value from ${suffix}`, { version })
},
invalidResponseMessage: 'Invalid machine-update-metadata response',
errorMessage: 'Machine metadata update failed',
versionMismatchMessage: 'Metadata version mismatch'
})
})
}
async updateRunnerState(handler: (state: RunnerState | null) => RunnerState): Promise<void> {
await backoff(async () => {
const updated = handler(this.machine.runnerState)
const answer = await this.socket.emitWithAck('machine-update-state', {
machineId: this.machine.id,
runnerState: updated,
expectedVersion: this.machine.runnerStateVersion
}) as unknown
applyVersionedAck(answer, {
valueKey: 'runnerState',
parseValue: (value) => {
const parsed = RunnerStateSchema.safeParse(value)
return parsed.success ? parsed.data : null
},
applyValue: (value) => {
this.machine.runnerState = value
},
applyVersion: (version) => {
this.machine.runnerStateVersion = version
},
logInvalidValue: (context, version) => {
const suffix = context === 'success' ? 'ack' : 'version-mismatch ack'
logger.debug(`[API MACHINE] Ignoring invalid runnerState value from ${suffix}`, { version })
},
invalidResponseMessage: 'Invalid machine-update-state response',
errorMessage: 'Machine state update failed',
versionMismatchMessage: 'Runner state version mismatch'
})
})
}
connect(): void {
this.socket = io(`${configuration.apiUrl}/cli`, {
transports: ['websocket'],
auth: {
token: this.token,
clientType: 'machine-scoped' as const,
machineId: this.machine.id
},
path: '/socket.io/',
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000
})
this.socket.on('connect', () => {
logger.debug('[API MACHINE] Connected to bot')
this.rpcHandlerManager.onSocketConnect(this.socket)
this.updateRunnerState((state) => ({
...(state ?? {}),
status: 'running',
pid: process.pid,
httpPort: this.machine.runnerState?.httpPort,
startedAt: Date.now()
})).catch((error) => {
logger.debug('[API MACHINE] Failed to update runner state on connect', error)
})
this.startKeepAlive()
})
this.socket.on('disconnect', () => {
logger.debug('[API MACHINE] Disconnected from bot')
this.rpcHandlerManager.onSocketDisconnect()
this.stopKeepAlive()
})
this.socket.on('rpc-request', async (data: { method: string; params: string }, callback: (response: string) => void) => {
callback(await this.rpcHandlerManager.handleRequest(data))
})
this.socket.on('update', (data: Update) => {
if (data.body.t !== 'update-machine') {
return
}
const update = data.body as UpdateMachineBody
if (update.machineId !== this.machine.id) {
return
}
if (update.metadata) {
const parsed = MachineMetadataSchema.safeParse(update.metadata.value)
if (parsed.success) {
this.machine.metadata = parsed.data
} else {
logger.debug('[API MACHINE] Ignoring invalid metadata update', { version: update.metadata.version })
}
this.machine.metadataVersion = update.metadata.version
}
if (update.runnerState) {
const next = update.runnerState.value
if (next == null) {
this.machine.runnerState = null
} else {
const parsed = RunnerStateSchema.safeParse(next)
if (parsed.success) {
this.machine.runnerState = parsed.data
} else {
logger.debug('[API MACHINE] Ignoring invalid runnerState update', { version: update.runnerState.version })
}
}
this.machine.runnerStateVersion = update.runnerState.version
}
})
this.socket.on('connect_error', (error) => {
logger.debug(`[API MACHINE] Connection error: ${error.message}`)
})
this.socket.on('error', (payload) => {
logger.debug('[API MACHINE] Socket error:', payload)
})
}
private startKeepAlive(): void {
this.stopKeepAlive()
this.keepAliveInterval = setInterval(() => {
this.socket.emit('machine-alive', {
machineId: this.machine.id,
time: Date.now()
})
}, 20_000)
}
private stopKeepAlive(): void {
if (this.keepAliveInterval) {
clearInterval(this.keepAliveInterval)
this.keepAliveInterval = null
}
}
shutdown(): void {
this.stopKeepAlive()
if (this.socket) {
this.socket.close()
}
}
}