File size: 5,852 Bytes
4e23b01 | 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 | import { assign, createActor, fromPromise, setup, waitFor } from '@moonshot-ai/agent-core-v2/human/xstate2';
import { startRemoteControl, type RemoteControlHandle } from './remote-control';
export type RemoteControlState = 'off' | 'starting' | 'on' | 'stopping';
export interface RemoteControlStatusInfo {
readonly enabled: boolean;
readonly state: RemoteControlState;
readonly url?: string;
readonly deviceId?: string;
readonly deviceName?: string;
readonly error?: string;
}
export interface RemoteControlManager {
status(): RemoteControlStatusInfo;
enable(): Promise<RemoteControlStatusInfo>;
disable(): Promise<RemoteControlStatusInfo>;
close(): Promise<void>;
}
export interface RemoteControlManagerOptions {
readonly homeDir: string;
readonly localOrigin: () => string;
readonly localServerToken: () => string;
readonly clientVersion: string;
readonly relayOrigin?: string;
readonly stderr?: Pick<NodeJS.WriteStream, 'write'>;
}
interface RemoteControlMachineContext {
readonly handle?: RemoteControlHandle;
readonly error?: unknown;
}
type RemoteControlMachineEvent = { type: 'enable' } | { type: 'disable' } | { type: 'tunnel.exited' };
function createRemoteControlMachine(
options: RemoteControlManagerOptions,
onTunnelStarted: (handle: RemoteControlHandle) => void,
) {
return setup({
types: {
context: {} as RemoteControlMachineContext,
events: {} as RemoteControlMachineEvent,
},
actors: {
startTunnel: fromPromise<RemoteControlHandle, void>(async () => {
const handle = await startRemoteControl({
homeDir: options.homeDir,
localOrigin: options.localOrigin(),
localServerToken: options.localServerToken,
clientVersion: options.clientVersion,
relayOrigin: options.relayOrigin,
stderr: options.stderr,
});
onTunnelStarted(handle);
return handle;
}),
stopTunnel: fromPromise<void, RemoteControlHandle | undefined>(async ({ input }) => {
await input?.close();
}),
},
}).createMachine({
id: 'remoteControl',
initial: 'off',
context: { handle: undefined, error: undefined },
states: {
off: {
on: { enable: 'starting', 'tunnel.exited': {} },
},
starting: {
on: { enable: {} },
invoke: {
src: 'startTunnel',
onDone: {
target: 'on',
actions: assign({ handle: ({ event }) => event.output, error: undefined }),
},
onError: {
target: 'off',
actions: assign({ handle: undefined, error: ({ event }) => event.error }),
},
},
},
on: {
on: {
disable: 'stopping',
'tunnel.exited': { target: 'off', actions: assign({ handle: undefined }) },
},
},
stopping: {
on: { disable: {}, 'tunnel.exited': {} },
invoke: {
src: 'stopTunnel',
input: ({ context }) => context.handle,
onDone: { target: 'off', actions: assign({ handle: undefined }) },
onError: {
target: 'off',
actions: assign({ handle: undefined, error: ({ event }) => event.error }),
},
},
},
},
});
}
export function createRemoteControlManager(
options: RemoteControlManagerOptions,
): RemoteControlManager {
const actor = createActor(
createRemoteControlMachine(options, (handle) => {
void handle.closed.then(
() => {
actor.send({ type: 'tunnel.exited' });
},
(error) => {
options.stderr?.write(`remote-control lock release failed: ${errorMessage(error)}\n`);
actor.send({ type: 'tunnel.exited' });
},
);
}),
);
actor.start();
const status = (): RemoteControlStatusInfo => {
const snap = actor.getSnapshot();
const state = snap.value as RemoteControlState;
const handle = snap.context.handle;
const error = snap.context.error;
return {
enabled: state === 'on',
state,
url: handle?.url,
deviceId: handle?.deviceId,
deviceName: handle?.deviceName,
error: error === undefined ? undefined : errorMessage(error),
};
};
const settle = () =>
waitFor(actor, (snap) => snap.value === 'on' || snap.value === 'off');
const enable = async (): Promise<RemoteControlStatusInfo> => {
const snap = actor.getSnapshot();
if (snap.value === 'on') return status();
if (snap.value === 'stopping') {
await waitFor(actor, (s) => s.value === 'off');
} else if (snap.value === 'starting') {
const settled = await settle();
if (settled.value === 'on') return status();
throw settled.context.error;
}
actor.send({ type: 'enable' });
const settled = await settle();
if (settled.value === 'on') return status();
throw settled.context.error;
};
const disable = async (): Promise<RemoteControlStatusInfo> => {
const snap = actor.getSnapshot();
if (snap.value === 'off') return status();
if (snap.value === 'starting') {
const settled = await settle();
if (settled.value === 'off') return status();
} else if (snap.value === 'stopping') {
await waitFor(actor, (s) => s.value === 'off');
return status();
}
actor.send({ type: 'disable' });
await waitFor(actor, (s) => s.value === 'off');
return status();
};
const close = async (): Promise<void> => {
try {
await disable();
} catch (error) {
options.stderr?.write(`remote-control shutdown failed: ${errorMessage(error)}\n`);
} finally {
actor.stop();
}
};
return { status, enable, disable, close };
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
|