This repository was archived by the owner on Feb 14, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 282
Expand file tree
/
Copy pathapiMachine.ts
More file actions
330 lines (284 loc) · 13 KB
/
apiMachine.ts
File metadata and controls
330 lines (284 loc) · 13 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
/**
* WebSocket client for machine/daemon communication with Happy server
* Similar to ApiSessionClient but for machine-scoped connections
*/
import { io, Socket } from 'socket.io-client';
import { logger } from '@/ui/logger';
import { configuration } from '@/configuration';
import { MachineMetadata, DaemonState, Machine, Update, UpdateMachineBody } from './types';
import { registerCommonHandlers, SpawnSessionOptions, SpawnSessionResult } from '../modules/common/registerCommonHandlers';
import { encodeBase64, decodeBase64, encrypt, decrypt } from './encryption';
import { backoff } from '@/utils/time';
import { RpcHandlerManager } from './rpc/RpcHandlerManager';
interface ServerToDaemonEvents {
update: (data: Update) => void;
'rpc-request': (data: { method: string, params: string }, callback: (response: string) => void) => void;
'rpc-registered': (data: { method: string }) => void;
'rpc-unregistered': (data: { method: string }) => void;
'rpc-error': (data: { type: string, error: string }) => void;
auth: (data: { success: boolean, user: string }) => void;
error: (data: { message: string }) => void;
}
interface DaemonToServerEvents {
'machine-alive': (data: {
machineId: string;
time: number;
}) => void;
'machine-update-metadata': (data: {
machineId: string;
metadata: string; // Encrypted MachineMetadata
expectedVersion: number
}, cb: (answer: {
result: 'error'
} | {
result: 'version-mismatch'
version: number,
metadata: string
} | {
result: 'success',
version: number,
metadata: string
}) => void) => void;
'machine-update-state': (data: {
machineId: string;
daemonState: string; // Encrypted DaemonState
expectedVersion: number
}, cb: (answer: {
result: 'error'
} | {
result: 'version-mismatch'
version: number,
daemonState: string
} | {
result: 'success',
version: number,
daemonState: string
}) => void) => void;
'rpc-register': (data: { method: string }) => void;
'rpc-unregister': (data: { method: string }) => void;
'rpc-call': (data: { method: string, params: any }, callback: (response: {
ok: boolean
result?: any
error?: string
}) => void) => void;
}
type MachineRpcHandlers = {
spawnSession: (options: SpawnSessionOptions) => Promise<SpawnSessionResult>;
stopSession: (sessionId: string) => boolean;
requestShutdown: () => void;
}
export class ApiMachineClient {
private socket!: Socket<ServerToDaemonEvents, DaemonToServerEvents>;
private keepAliveInterval: NodeJS.Timeout | null = null;
private rpcHandlerManager: RpcHandlerManager;
constructor(
private token: string,
private machine: Machine
) {
// Initialize RPC handler manager
this.rpcHandlerManager = new RpcHandlerManager({
scopePrefix: this.machine.id,
encryptionKey: this.machine.encryptionKey,
encryptionVariant: this.machine.encryptionVariant,
logger: (msg, data) => logger.debug(msg, data)
});
registerCommonHandlers(this.rpcHandlerManager, process.cwd(), this.machine.id);
}
setRPCHandlers({
spawnSession,
stopSession,
requestShutdown
}: MachineRpcHandlers) {
// Register spawn session handler
this.rpcHandlerManager.registerHandler('spawn-happy-session', async (params: any) => {
const { directory, sessionId, machineId, approvedNewDirectoryCreation, agent, token, environmentVariables } = params || {};
logger.debug(`[API MACHINE] Spawning session with params: ${JSON.stringify(params)}`);
if (!directory) {
throw new Error('Directory is required');
}
const result = await spawnSession({ directory, sessionId, machineId, approvedNewDirectoryCreation, agent, token, environmentVariables });
switch (result.type) {
case 'success':
logger.debug(`[API MACHINE] Spawned session ${result.sessionId}`);
return { type: 'success', sessionId: result.sessionId };
case 'requestToApproveDirectoryCreation':
logger.debug(`[API MACHINE] Requesting directory creation approval for: ${result.directory}`);
return { type: 'requestToApproveDirectoryCreation', directory: result.directory };
case 'error':
throw new Error(result.errorMessage);
}
});
// Register stop session handler
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');
}
logger.debug(`[API MACHINE] Stopped session ${sessionId}`);
return { message: 'Session stopped' };
});
// Register stop daemon handler
this.rpcHandlerManager.registerHandler('stop-daemon', () => {
logger.debug('[API MACHINE] Received stop-daemon RPC request');
// Trigger shutdown callback after a delay
setTimeout(() => {
logger.debug('[API MACHINE] Initiating daemon shutdown from RPC');
requestShutdown();
}, 100);
return { message: 'Daemon stop request acknowledged, starting shutdown sequence...' };
});
}
/**
* Update machine metadata
* Currently unused, changes from the mobile client are more likely
* for example to set a custom name.
*/
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: encodeBase64(encrypt(this.machine.encryptionKey, this.machine.encryptionVariant, updated)),
expectedVersion: this.machine.metadataVersion
});
if (answer.result === 'success') {
this.machine.metadata = decrypt(this.machine.encryptionKey, this.machine.encryptionVariant, decodeBase64(answer.metadata));
this.machine.metadataVersion = answer.version;
logger.debug('[API MACHINE] Metadata updated successfully');
} else if (answer.result === 'version-mismatch') {
if (answer.version > this.machine.metadataVersion) {
this.machine.metadataVersion = answer.version;
this.machine.metadata = decrypt(this.machine.encryptionKey, this.machine.encryptionVariant, decodeBase64(answer.metadata));
}
throw new Error('Metadata version mismatch'); // Triggers retry
}
});
}
/**
* Update daemon state (runtime info) - similar to session updateAgentState
* Simplified without lock - relies on backoff for retry
*/
async updateDaemonState(handler: (state: DaemonState | null) => DaemonState): Promise<void> {
await backoff(async () => {
const updated = handler(this.machine.daemonState);
const answer = await this.socket.emitWithAck('machine-update-state', {
machineId: this.machine.id,
daemonState: encodeBase64(encrypt(this.machine.encryptionKey, this.machine.encryptionVariant, updated)),
expectedVersion: this.machine.daemonStateVersion
});
if (answer.result === 'success') {
this.machine.daemonState = decrypt(this.machine.encryptionKey, this.machine.encryptionVariant, decodeBase64(answer.daemonState));
this.machine.daemonStateVersion = answer.version;
logger.debug('[API MACHINE] Daemon state updated successfully');
} else if (answer.result === 'version-mismatch') {
if (answer.version > this.machine.daemonStateVersion) {
this.machine.daemonStateVersion = answer.version;
this.machine.daemonState = decrypt(this.machine.encryptionKey, this.machine.encryptionVariant, decodeBase64(answer.daemonState));
}
throw new Error('Daemon state version mismatch'); // Triggers retry
}
});
}
connect() {
const serverUrl = configuration.serverUrl.replace(/^http/, 'ws');
logger.debug(`[API MACHINE] Connecting to ${serverUrl}`);
this.socket = io(serverUrl, {
transports: ['websocket'],
auth: {
token: this.token,
clientType: 'machine-scoped' as const,
machineId: this.machine.id
},
path: '/v1/updates',
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000
});
this.socket.on('connect', () => {
logger.debug('[API MACHINE] Connected to server');
// Update daemon state to running
// We need to override previous state because the daemon (this process)
// has restarted with new PID & port
this.updateDaemonState((state) => ({
...state,
status: 'running',
pid: process.pid,
httpPort: this.machine.daemonState?.httpPort,
startedAt: Date.now()
}));
// Register all handlers
this.rpcHandlerManager.onSocketConnect(this.socket);
// Start keep-alive
this.startKeepAlive();
});
this.socket.on('disconnect', () => {
logger.debug('[API MACHINE] Disconnected from server');
this.rpcHandlerManager.onSocketDisconnect();
this.stopKeepAlive();
});
// Single consolidated RPC handler
this.socket.on('rpc-request', async (data: { method: string, params: string }, callback: (response: string) => void) => {
logger.debugLargeJson(`[API MACHINE] Received RPC request:`, data);
callback(await this.rpcHandlerManager.handleRequest(data));
});
// Handle update events from server
this.socket.on('update', (data: Update) => {
// Machine clients should only care about machine updates
if (data.body.t === 'update-machine' && (data.body as UpdateMachineBody).machineId === this.machine.id) {
// Handle machine metadata or daemon state updates from other clients (e.g., mobile app)
const update = data.body as UpdateMachineBody;
if (update.metadata) {
logger.debug('[API MACHINE] Received external metadata update');
this.machine.metadata = decrypt(this.machine.encryptionKey, this.machine.encryptionVariant, decodeBase64(update.metadata.value));
this.machine.metadataVersion = update.metadata.version;
}
if (update.daemonState) {
logger.debug('[API MACHINE] Received external daemon state update');
this.machine.daemonState = decrypt(this.machine.encryptionKey, this.machine.encryptionVariant, decodeBase64(update.daemonState.value));
this.machine.daemonStateVersion = update.daemonState.version;
}
} else {
logger.debug(`[API MACHINE] Received unknown update type: ${(data.body as any).t}`);
}
});
this.socket.on('connect_error', (error) => {
logger.debug(`[API MACHINE] Connection error: ${error.message}`);
});
this.socket.io.on('error', (error: any) => {
logger.debug('[API MACHINE] Socket error:', error);
});
}
private startKeepAlive() {
this.stopKeepAlive();
this.keepAliveInterval = setInterval(() => {
const payload = {
machineId: this.machine.id,
time: Date.now()
};
if (process.env.DEBUG) { // too verbose for production
logger.debugLargeJson(`[API MACHINE] Emitting machine-alive`, payload);
}
this.socket.emit('machine-alive', payload);
}, 20000);
logger.debug('[API MACHINE] Keep-alive started (20s interval)');
}
private stopKeepAlive() {
if (this.keepAliveInterval) {
clearInterval(this.keepAliveInterval);
this.keepAliveInterval = null;
logger.debug('[API MACHINE] Keep-alive stopped');
}
}
shutdown() {
logger.debug('[API MACHINE] Shutting down');
this.stopKeepAlive();
if (this.socket) {
this.socket.close();
logger.debug('[API MACHINE] Socket closed');
}
}
}