-
-
Notifications
You must be signed in to change notification settings - Fork 432
Expand file tree
/
Copy pathapiMachine.ts
More file actions
566 lines (496 loc) · 22.2 KB
/
apiMachine.ts
File metadata and controls
566 lines (496 loc) · 22.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
/**
* WebSocket client for machine/runner communication with hapi-hub
*/
import { io, type Socket } from 'socket.io-client'
import { readdir, realpath, stat } from 'node:fs/promises'
import { realpathSync } from 'node:fs'
import { basename, dirname, isAbsolute, join, relative, resolve as resolvePath } from 'node:path'
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 {
listOpencodeModelsForCwd,
type ListOpencodeModelsForCwdRequest,
type ListOpencodeModelsForCwdResponse
} from '../modules/common/opencodeModels'
import type { SpawnSessionOptions, SpawnSessionResult } from '../modules/common/rpcTypes'
import { applyVersionedAck } from './versionedUpdate'
import { buildSocketIoExtraHeaderOptions } from './hubExtraHeaders'
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>
}
interface ListMachineDirectoryRequest {
path: string
}
interface ListMachineDirectoryEntry {
name: string
type: 'file' | 'directory' | 'other'
size?: number
modified?: number
isGitRepo?: boolean
}
interface ListMachineDirectoryResponse {
success: boolean
entries?: ListMachineDirectoryEntry[]
error?: string
}
function normalizeWorkspaceRoots(paths?: string[]): string[] | undefined {
if (!paths?.length) {
return undefined
}
const normalized = Array.from(new Set(paths.map((path) => {
try {
return realpathSync(path)
} catch {
return resolvePath(path)
}
})))
return normalized.length > 0 ? normalized : undefined
}
function workspaceRootsEqual(left?: string[], right?: string[]): boolean {
const normalizedLeft = left ?? []
const normalizedRight = right ?? []
if (normalizedLeft.length !== normalizedRight.length) {
return false
}
return normalizedLeft.every((value, index) => value === normalizedRight[index])
}
function formatWorkspaceRoots(paths?: string[]): string {
return paths?.length ? paths.join(', ') : '(none)'
}
export class ApiMachineClient {
private socket!: Socket<ServerToRunnerEvents, RunnerToServerEvents>
private keepAliveInterval: NodeJS.Timeout | null = null
private rpcHandlerManager: RpcHandlerManager
private readonly normalizedWorkspaceRoots: string[] | undefined
constructor(
private readonly token: string,
private readonly machine: Machine,
private readonly workspaceRoots?: string[]
) {
// Realpath roots once so all subsequent comparisons are against
// canonical, symlink-resolved locations. Falls back to lexical
// resolution if realpath fails so we still get protection.
this.normalizedWorkspaceRoots = normalizeWorkspaceRoots(workspaceRoots)
this.rpcHandlerManager = new RpcHandlerManager({
scopePrefix: this.machine.id,
logger: (msg, data) => logger.debug(msg, data)
})
registerCommonHandlers(this.rpcHandlerManager, getInvokedCwd())
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<ListMachineDirectoryRequest, ListMachineDirectoryResponse>('list-directory', async (params) => {
if (!this.normalizedWorkspaceRoots?.length) {
return { success: false, error: 'Workspace browsing is not enabled for this machine' }
}
const rawPath = typeof params?.path === 'string' ? params.path.trim() : ''
if (!rawPath) {
return { success: false, error: 'Path is required' }
}
const targetPath = await this.resolveForWorkspaceCheck(rawPath)
if (!this.isWithinWorkspaceRoots(targetPath)) {
return { success: false, error: 'Path is outside workspace roots' }
}
try {
const dirStat = await stat(targetPath)
if (!dirStat.isDirectory()) {
return { success: false, error: 'Path is not a directory' }
}
const dirEntries = await readdir(targetPath, { withFileTypes: true })
const entries: ListMachineDirectoryEntry[] = []
await Promise.all(dirEntries.map(async (entry) => {
if (entry.name.startsWith('.')) return
const fullPath = join(targetPath, entry.name)
let type: 'file' | 'directory' | 'other' = 'other'
let size: number | undefined
let modified: number | undefined
let isGitRepo = false
if (entry.isDirectory()) {
type = 'directory'
try {
const gitStat = await stat(join(fullPath, '.git'))
isGitRepo = gitStat.isDirectory() || gitStat.isFile()
} catch {
// not a git repo
}
} else if (entry.isFile()) {
type = 'file'
}
if (!entry.isSymbolicLink()) {
try {
const stats = await stat(fullPath)
size = stats.size
modified = stats.mtime.getTime()
} catch {
// ignore stat errors
}
}
entries.push({ name: entry.name, type, size, modified, isGitRepo })
}))
entries.sort((a, b) => {
if (a.type === 'directory' && b.type !== 'directory') return -1
if (a.type !== 'directory' && b.type === 'directory') return 1
return a.name.localeCompare(b.name)
})
return { success: true, entries }
} catch (error) {
return { success: false, error: error instanceof Error ? error.message : 'Failed to list directory' }
}
})
// OpenCode model discovery spawns an `opencode acp` subprocess scoped to the
// requested cwd, so it must obey the same workspace-root containment as
// `list-directory` and `spawn-happy-session`. Re-register the handler that
// `registerCommonHandlers` installed unguarded with a guarded version that
// resolves symlinks and rejects paths outside the configured root before
// delegating to the lower-level probe. This intentionally overwrites the
// earlier registration on the same scoped method name.
this.rpcHandlerManager.registerHandler<ListOpencodeModelsForCwdRequest, ListOpencodeModelsForCwdResponse>(
'listOpencodeModelsForCwd',
async (params) => {
const rawCwd = typeof params?.cwd === 'string' ? params.cwd.trim() : ''
if (!rawCwd) {
return { success: false, error: 'cwd is required' }
}
const resolvedCwd = await this.resolveForWorkspaceCheck(rawCwd)
if (!this.isWithinWorkspaceRoots(resolvedCwd)) {
return { success: false, error: 'Path is outside workspace roots' }
}
return await listOpencodeModelsForCwd(resolvedCwd)
}
)
}
private isWithinWorkspaceRoots(absolutePath: string): boolean {
if (!this.normalizedWorkspaceRoots?.length) return true
return this.normalizedWorkspaceRoots.some((workspaceRoot) => {
const rel = relative(workspaceRoot, absolutePath)
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
})
}
/**
* Canonicalize a path for workspace-root containment checks. Resolves
* symlinks via realpath so a symlink such as `/safe/out -> /etc` cannot
* be used to escape the configured root with a lexical-only check.
*
* If the path doesn't exist (e.g. a session is being spawned in a
* directory we'll create), walks up to the nearest existing ancestor
* and realpaths *that*, joining the missing tail back on. This way the
* check still runs against the real on-disk location once any
* intermediate symlink in the parent chain has been resolved.
*/
private async resolveForWorkspaceCheck(path: string): Promise<string> {
const absolute = resolvePath(path)
try {
return await realpath(absolute)
} catch {
const missing: string[] = []
let cursor = absolute
while (cursor !== dirname(cursor)) {
missing.unshift(basename(cursor))
cursor = dirname(cursor)
try {
return join(await realpath(cursor), ...missing)
} catch {
// keep walking to the nearest existing parent
}
}
return absolute
}
}
setRPCHandlers({ spawnSession, stopSession, requestShutdown }: MachineRpcHandlers): void {
this.rpcHandlerManager.registerHandler('spawn-happy-session', async (params: any) => {
const { directory, sessionId, resumeSessionId, forkSessionId, forkHistory, machineId, approvedNewDirectoryCreation, agent, model, effort, modelReasoningEffort, yolo, permissionMode, token, sessionType, worktreeName } = params || {}
if (!directory) {
throw new Error('Directory is required')
}
const resolvedDirectory = await this.resolveForWorkspaceCheck(directory)
if (!this.isWithinWorkspaceRoots(resolvedDirectory)) {
return { type: 'error', errorMessage: 'Directory is outside this machine\'s workspace roots' }
}
const result = await spawnSession({
directory,
sessionId,
resumeSessionId,
forkSessionId,
forkHistory,
machineId,
approvedNewDirectoryCreation,
agent,
model,
effort,
modelReasoningEffort,
yolo,
permissionMode,
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' }
})
}
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,
...buildSocketIoExtraHeaderOptions()
})
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)
})
const hubWorkspaceRoots = this.machine.metadata?.workspaceRoots
const desiredWorkspaceRoots = this.workspaceRoots
if (!workspaceRootsEqual(desiredWorkspaceRoots, hubWorkspaceRoots)) {
if (desiredWorkspaceRoots?.length) {
console.log(`[HAPI] Syncing workspace roots to hub: ${formatWorkspaceRoots(desiredWorkspaceRoots)} (current hub value: ${formatWorkspaceRoots(hubWorkspaceRoots)})`)
} else {
console.log(`[HAPI] Clearing workspace roots on hub (was: ${formatWorkspaceRoots(hubWorkspaceRoots)})`)
}
this.updateMachineMetadata((current) => {
const base = current ?? this.machine.metadata
if (!base) {
return { workspaceRoots: desiredWorkspaceRoots } as MachineMetadata
}
if (desiredWorkspaceRoots?.length) {
return { ...base, workspaceRoots: desiredWorkspaceRoots }
}
const { workspaceRoot: _legacyWorkspaceRoot, workspaceRoots: _workspaceRoots, ...rest } = base as MachineMetadata & {
workspaceRoot?: string
}
return rest as MachineMetadata
}).then(() => {
console.log(`[HAPI] Workspace roots synced: ${formatWorkspaceRoots(this.machine.metadata?.workspaceRoots)}`)
}).catch((error) => {
console.error('[HAPI] Failed to sync workspace roots:', error instanceof Error ? error.message : error)
})
} else if (desiredWorkspaceRoots?.length) {
console.log(`[HAPI] Workspace roots already up to date on hub: ${formatWorkspaceRoots(desiredWorkspaceRoots)}`)
}
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()
}
}
}